From witham.ian at gmail.com Wed Aug 1 00:51:33 2007 From: witham.ian at gmail.com (Ian Witham) Date: Wed, 1 Aug 2007 10:51:33 +1200 Subject: [Tutor] Which GUI? In-Reply-To: <46AFAB4A.2020103@rogers.com> References: <002001c7d0ad$034ac5a0$4cfce004@JSLAPTOP> <46AFAB4A.2020103@rogers.com> Message-ID: Hi Scott, I'm no expert (yet) but I have come across this fun online tool which helps you choose a GUI toolkit for Python: Choose Your GUI Toolkit I had no problem installing WxPython from the Ubuntu repos, and I have heard that is is one of the top choices for cross-platform GUI development. If you are only interested in developing for Linux then there is PyGTK. I haven't used this though so I couldn't comment on its ease of use. Ian On 8/1/07, scott wrote: > > Hi, > > I have been doing some research on the GUI's and noticed it is a > very > difficult choice to make which one to write with. It seems to be even > more difficult than choosing which programming language to use. > > If you don't mind I have a few questions to ask about selecting > the > right GUI to program with. > > 1: I know many people suggest learning more than one programming > language when writing programs and use each programming language like a > tool on a toolbox. Should one also learn more than one GUI and select > the correct one for each individual program? > > 2: How have you come to select your favourite GUI(s)? > > 3: Is there a GUI that is better for developing for Linux? > > 4: I have read that WxPython is difficult to install on Linux from a > couple different sources. I have personally never found that a problem. > Is this true? Is WxPython a poor choice for a Linux developer? > > Thank you for any help you can give me :) > > -- > Your friend, > Scott > > Sent to you from a Linux computer using Ubuntu Version 7.04 (Feisty Fawn) > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070801/d643013d/attachment.html From carroll at tjc.com Wed Aug 1 01:59:55 2007 From: carroll at tjc.com (Terry Carroll) Date: Tue, 31 Jul 2007 16:59:55 -0700 (PDT) Subject: [Tutor] Which GUI? In-Reply-To: Message-ID: On Wed, 1 Aug 2007, Ian Witham wrote: > I'm no expert (yet) but I have come across this fun online tool which helps > you choose a GUI toolkit for Python: > > Choose Your GUI Toolkit I think it's rigged. I answered it honestly, and it suggested wxPython, which is no surprise; I came to the same conclusion myself based on my needs and preferences. But no matter how I adjusted the parameters, it always suggested wxPython. I just input a 1 on every factor, except "Popularity, installed base", where I put in 100. Surely that should suggest Tkinter, which comes pre-installed with Python,right? Nope. "wxPython is the GUI for you!" From fiveholiday55 at hotmail.com Wed Aug 1 02:12:33 2007 From: fiveholiday55 at hotmail.com (Alondt Yauk) Date: Wed, 1 Aug 2007 01:12:33 +0100 Subject: [Tutor] C program Message-ID: Hello people of the world. This question is not a Python related question, but I thought I might just throw it in here and see if there are any C old-timers who could help out. I have a string with space and I would like to remove the space before comparing but I don't know how to go about doing it. Here is the code int result = strcmp("yes","yes ");//trailing space on the second yes this should give me '0' meaning they are both the same, but with the space, it gives me '-1' Please note: those arguments can be supplied by the user, and when they do, I want to strip off the trailing space. Any helps is highly appreciated. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070801/af4e9c43/attachment.htm From keridee at jayco.net Wed Aug 1 04:20:41 2007 From: keridee at jayco.net (Tiger12506) Date: Tue, 31 Jul 2007 21:20:41 -0500 Subject: [Tutor] C program References: Message-ID: <002001c7d3e2$c9c66300$f054e104@JSLAPTOP> Hello people of the world. This question is not a Python related question, but I thought I might just throw it in here and see if there are any C old-timers who could help out. I have a string with space and I would like to remove the space before comparing but I don't know how to go about doing it. Here is the code int result = strcmp("yes","yes ");//trailing space on the second yes this should give me '0' meaning they are both the same, but with the space, it gives me '-1' Please note: those arguments can be supplied by the user, and when they do, I want to strip off the trailing space. Any helps is highly appreciated. --------------------- I doubt if this is the best way, but you can do this. /*--------------------------------------------------*/ #include #include char s[20] = "yes"; char s2[20] = "yes "; void rstrip(char *c) { while (*c++!=0); c--; while (*--c==' ') *c = 0; } int main() { rstrip(s2); int result = strcmp(s, s2); printf("%d\n",result); system("pause"); } /*------------------------------------------------------*/ JS PS - This *is* a python list. Usually the tutors don't like people who post off-topic stuff. (And C is pretty off-topic) From john at fouhy.net Wed Aug 1 04:40:35 2007 From: john at fouhy.net (John Fouhy) Date: Wed, 1 Aug 2007 14:40:35 +1200 Subject: [Tutor] passing form data into a class In-Reply-To: References: <5e58f2e40707302127j29416a5cved2b9ade63708960@mail.gmail.com> Message-ID: <5e58f2e40707311940p73561178i5677e01282543d47@mail.gmail.com> On 01/08/07, tpc247 at gmail.com wrote: > John, I spent the last two hours trying to understand what you wrote, and I > feel I'm missing something: > > >>> a_dict = {'one':1, 'two':2, 'three':3} > >>> class A(object): > def __init__(self, **kwargs): > for var in kwargs: > setattr(self, var, locals()[var]) Well, that's one risk of using something like locals() -- it can be fragile with respect to transformations that wouldn't otherwise make much difference. Try this: a_dict = {'one':11, 'two':22} class A(object): def __init__(self, one=1, two=2): print locals() A(**a_dict) And this: class B(object): def __init__(self, **kwargs): print locals() B(**a_dict) Do you see the difference? With B, you could write: class B(object): def __init__(self, **kwargs): for var in kwargs: setattr(self, var, kwargs[var]) Although, as Kent points out, you can more simply write 'self.__dict__.update(kwargs)'. > >>> class A(object): > def __init__(self, **kwargs): > for var in locals(): > setattr(self, var, locals()[var]) > >>> a_inst = A(**a_dict) > RuntimeError: dictionary changed size during iteration And that illustrates another risk of using locals() (and a risk of not testing my code before posting it). What's happening is that python is inserting 'var' into locals() immediately after starting the loop, which is breaking iteration. You could fix this by saying: for var in locals().keys(): # etc But a few other people have weighed in with suggestions that should be less fragile, so you may want to go with their ideas instead. -- John. From rabidpoobear at gmail.com Wed Aug 1 05:36:47 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Tue, 31 Jul 2007 22:36:47 -0500 Subject: [Tutor] Which GUI? In-Reply-To: References: Message-ID: <46AFFFCF.9010801@gmail.com> Terry Carroll wrote: > On Wed, 1 Aug 2007, Ian Witham wrote: > > >> I'm no expert (yet) but I have come across this fun online tool which helps >> you choose a GUI toolkit for Python: >> >> Choose Your GUI Toolkit >> > > I think it's rigged. I answered it honestly, and it suggested wxPython, > which is no surprise; I came to the same conclusion myself based on my > needs and preferences. > > But no matter how I adjusted the parameters, it always suggested wxPython. > > I just input a 1 on every factor, except "Popularity, installed base", > where I put in 100. Surely that should suggest Tkinter, which comes > pre-installed with Python,right? > > Nope. "wxPython is the GUI for you!" > A quick view of the source code of the page finds the relative weights in the javascript: var scorePyGUI = (easelearning * 50) + (maturity * 10) + (pop * 30) + (paint * 10) + (windows * 10) + (linux * 100) + (mac * 100) + (pda * 10); var scoreTkinter = (easelearning * 30) + (maturity * 100) + (pop * 100) + (paint * 50) + (windows * 50) + (linux * 80) + (mac * 70) + (pda * 0); var scoreEasygui = (easelearning * 100) + (maturity * 10) + (pop * 10) + (paint * 10) + (windows * 50) + (linux * 70) + (mac * 70) + (pda * 0); var scorewxPython = (easelearning * 33) + (maturity * 100) + (pop * 120) + (paint * 100) + (windows * 100) + (linux * 100) + (mac * 90) + (pda * 10); var scorePythonCard = (easelearning * 90) + (maturity * 30) + (pop * 40) + (paint * 10) + (windows * 100) + (linux * 50) + (mac * 50) + (pda * 0); var scorepyQt = (easelearning * 20) + (maturity * 100) + (pop * 60) + (paint * 50) + (windows * 70) + (linux * 100) + (mac * 20) + (pda * 70); var scorepyGtk = (easelearning * 20) + (maturity * 100) + (pop * 60) + (paint * 90) + (windows * 40) + (linux * 80) + (mac * 25) + (pda * 0); var scoreJython = (easelearning * 25) + (maturity * 75) + (pop * 50) + (paint * 10) + (windows * 80) + (linux * 80) + (mac * 80) + (pda * 100); var scoreAnygui = (easelearning * 40) + (maturity * 20) + (pop * 10) + (paint * 10) + (windows * 90) + (linux * 90) + (mac * 50) + (pda * 10); var scorefxPy = (easelearning * 20) + (maturity * 50 ) + (pop * 20) + (paint * 0) + (windows * 75) + (linux * 90) + (mac * 20) + (pda * 0); var scorepyFLTK = (easelearning * 50) + (maturity * 35) + (pop * 10) + (paint * 0) + (windows * 75) + (linux * 90) + (mac * 20) + (pda * 0); Seems like wxPython's scores are a little biased, maybe. Especially that 120 for popularity, when no other GUI toolkit got more than 100 for any other category. Interpret this as you will :) > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From alan.gauld at btinternet.com Wed Aug 1 06:31:52 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 1 Aug 2007 05:31:52 +0100 Subject: [Tutor] Which GUI? References: <002001c7d0ad$034ac5a0$4cfce004@JSLAPTOP> <46AFAB4A.2020103@rogers.com> Message-ID: "scott" wrote > 1: I know many people suggest learning more than one programming > language when writing programs and use each programming language > like a > tool on a toolbox. Should one also learn more than one GUI and > select > the correct one for each individual program? I would say not. There is little advantage of one over the other. Unfortunately you will often be required to learn new GUIs because the choice for any given project may already have been made, either because the project is already underway, or its the 'house style' or because some key component only works with a given GUI. > 2: How have you come to select your favourite GUI(s)? History and experience. The ones that are most 'intuitive' to use and use least lines of code or have good GUI builders - something lacking in most open-source GUIs at present... > 3: Is there a GUI that is better for developing for Linux? > > 4: I have read that WxPython is difficult to install on Linux from a > couple different sources. I've never found any problem, but I've only done it twice... > Is this true? Is WxPython a poor choice for a Linux developer? I don't think so, Linux seems to be the main development OS from what little I've seen. Alan G. From alan.gauld at btinternet.com Wed Aug 1 06:42:21 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 1 Aug 2007 05:42:21 +0100 Subject: [Tutor] C program References: <002001c7d3e2$c9c66300$f054e104@JSLAPTOP> Message-ID: "Tiger12506" wrote > I have a string with space and I would like to remove the space > before > comparing but I don't know how to go about doing it. Here is the > code Look at strrchr()... > void rstrip(char *c) { > while (*c++!=0); > c--; > while (*--c==' ') *c = 0; > } Or roll your own... :-) This is probably easiest if you only want to catch spaces... Alan G. From anotequaltob at gmail.com Wed Aug 1 03:55:46 2007 From: anotequaltob at gmail.com (Kyle Brooks) Date: Tue, 31 Jul 2007 21:55:46 -0400 Subject: [Tutor] Textual Captchas: Would like to show that bots can crack a simple text captcha Message-ID: Hi. My name is Kyle Brooks, and I hereby introduce myself with this post. I have seen a lot of text captchas. A text captcha is the logical opposite of a image captcha. That is, among other qualities: image captchas are inaccessible, while text captchas are, and image captchas cannot be easily read by bots, while text captchas can be because they are clearly embedded in forms for all to visibly see. Therein lies the problem. You see, text captchas can be insecure! But there are too many people that think text captchas are secure, that they are a panacea. So, I would like to show that a bot can crack a simple textual captcha that involves math, like 1 + 1. I want to generate a captcha, show it, and have the user (in this case, me) submit the answer. Then I would like to write an automated bot that goes to the webpage, reads the captcha, evaluates it, puts it in, and submits it. I would like some suggestions on how to do both stages. In advance, thanks for any help that you may give. - Kyle From fiveholiday55 at hotmail.com Wed Aug 1 10:35:33 2007 From: fiveholiday55 at hotmail.com (Alondt Yauk) Date: Wed, 1 Aug 2007 09:35:33 +0100 Subject: [Tutor] C program References: <002001c7d3e2$c9c66300$f054e104@JSLAPTOP> Message-ID: Thanks very much, I will try it out and use your idea. Am sorry I posted the question in this forum, just wanted to get ideas from you guys. Ciao ----- Original Message ----- From: "Tiger12506" To: Sent: Wednesday, August 01, 2007 3:20 AM Subject: Re: [Tutor] C program > Hello people of the world. > > This question is not a Python related question, but I thought I might just > throw it in here and see if there are any C old-timers who could help out. > > I have a string with space and I would like to remove the space before > comparing but I don't know how to go about doing it. Here is the code > > int result = strcmp("yes","yes ");//trailing space on the second yes > this should give me '0' meaning they are both the same, but with the > space, > it gives me '-1' > > Please note: those arguments can be supplied by the user, and when they > do, > I want to strip off the trailing space. > > Any helps is highly appreciated. > --------------------- > > I doubt if this is the best way, but you can do this. > > > /*--------------------------------------------------*/ > #include > #include > > char s[20] = "yes"; > char s2[20] = "yes "; > > void rstrip(char *c) { > while (*c++!=0); > c--; > while (*--c==' ') *c = 0; > } > > int main() { > rstrip(s2); > int result = strcmp(s, s2); > printf("%d\n",result); > system("pause"); > } > /*------------------------------------------------------*/ > > > JS > > PS - This *is* a python list. Usually the tutors don't like people who > post > off-topic stuff. (And C is pretty off-topic) > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From rabidpoobear at gmail.com Wed Aug 1 13:32:17 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Wed, 01 Aug 2007 06:32:17 -0500 Subject: [Tutor] Textual Captchas: Would like to show that bots can crack a simple text captcha In-Reply-To: References: Message-ID: <46B06F41.3090301@gmail.com> Kyle Brooks wrote: > Hi. > > My name is Kyle Brooks, and I hereby introduce myself with this post. > > I have seen a lot of text captchas. A text captcha is the logical > opposite of a image captcha. That is, among other qualities: image > captchas are inaccessible, while text captchas are, and image captchas > cannot be easily read by bots, while text captchas can be because they > are clearly embedded in forms for all to visibly see. > > Therein lies the problem. You see, text captchas can be insecure! But > there are too many people that think text captchas are secure, that > they are a panacea. So, I would like to show that a bot can crack a > simple textual captcha that involves math, like 1 + 1. > Essentially, if you generate these questions programmatically, and they're all math-based, then you're right, this is trivially easy to crack. If, however, you had questions such as "what color is the sky?" "do cats meow or bark?" and such, like that, thrown in with the math questions, it becomes slightly more difficult to crack these. > I want to generate a captcha, show it, and have the user (in this > case, me) submit the answer. You could write a simple CGI script to do this. You'll obviously have to have a webserver with CGI running on your local machine. > Then I would like to write an automated > bot that goes to the webpage, reads the captcha, evaluates it, puts it > in, and submits it. > > I would like some suggestions on how to do both stages. > First, install Apache. Then get CGI working. Then, figure out a way to generate your captchas and their answers. Here's a very hackish and simple way to do this: ops = ['%s +','%s -','%s *','%s /'] import random temp = ' '.join([random.choice(ops) for x in range(random.randrange(3,6))]) temp += ' %s' vals = [] while 1: try: finalstr = temp % tuple(vals) break except TypeError: vals.append(random.randrange(30)) print "The answer to the captcha :",finalstr finalanswer = eval(finalstr) print "should be :",finalanswer I must confess, I just woke up a few minutes ago and I didn't take the time to come up with a good solution to your problem, so there's almost definitely a better way to do this. You might want to throw some random text into the finalstr, such as "what is the answer to " + finalstr + "?" so that your naysayers won't say "but my captchas have other text!" etc. As far as automating reading the captcha, use BeautifulSoup to parse the HTML, figure out where on their page the captcha lies. Automating the form submission is pretty easy. Especially if it's a submit form, instead of a post, or something, you just submit by making a query with the form data attached to the end. For example, if I wanted to submit the values "q = 2000" and "x = 100" I would do this: http://www.example.com/captcha.html?q=2000&x=100 If this is the case, you don't even have to deal with the HTML. Just use urllib to load this web address, and save the page locally, so you can check if it says "YOU SOLVED IT" or "YOU SUCK" or whatever. > In advance, thanks for any help that you may give. > > - Kyle > -Luke From astroultraman at gmail.com Wed Aug 1 14:46:17 2007 From: astroultraman at gmail.com (Robert William Hanks) Date: Wed, 1 Aug 2007 09:46:17 -0300 Subject: [Tutor] gotoxy Message-ID: <6be1291e0708010546k150e6349ud76d17ad588a89c@mail.gmail.com> hi folks, is there in python a gotoxy like in pascal so i can print stuff in other parts of the screen? what about some thing like it for the gui in windows? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070801/7b7a4d66/attachment.html From slewin at rogers.com Wed Aug 1 14:54:00 2007 From: slewin at rogers.com (scott) Date: Wed, 01 Aug 2007 08:54:00 -0400 Subject: [Tutor] Which GUI? In-Reply-To: References: Message-ID: <46B08268.7090201@rogers.com> Terry Carroll wrote: > I think it's rigged. I answered it honestly, and it suggested wxPython, > which is no surprise; I came to the same conclusion myself based on my > needs and preferences. I thought the same, it always came up with WxPython for me. This is what I meant by it being difficult to decide :) I am thinking about starting with Tkinter then trying WxPython because WxPython seems to be the most highly suggested and seems to have the best documentation and selection of software/RADs. -- Your friend, Scott Sent to you from a Linux computer using Ubuntu Version 7.04 (Feisty Fawn) From clsdaniel at gmail.com Wed Aug 1 14:59:10 2007 From: clsdaniel at gmail.com (Carlos Daniel Ruvalcaba Valenzuela) Date: Wed, 1 Aug 2007 05:59:10 -0700 Subject: [Tutor] gotoxy In-Reply-To: <6be1291e0708010546k150e6349ud76d17ad588a89c@mail.gmail.com> References: <6be1291e0708010546k150e6349ud76d17ad588a89c@mail.gmail.com> Message-ID: <4fae7dfa0708010559n362c639q3d2ea2c8e938548c@mail.gmail.com> You should have a look at the curses module, basically gotoxy is a borland think, in linux and other unix systems there is the curses library for working with text screens. Module documentation: http://docs.python.org/lib/module-curses.html Some tutorials: http://www.amk.ca/python/howto/curses/ http://www.ibm.com/developerworks/linux/library/l-python6.html Checkout window objects, there is functions for all that you want to do (move cursor, print, read, etc). Good Luck! Carlos Ruvalcaba Valenzuela On 8/1/07, Robert William Hanks wrote: > > hi folks, is there in python a gotoxy like in pascal so i can print stuff > in other parts of the screen? > what about some thing like it for the gui in windows? > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From kent37 at tds.net Wed Aug 1 15:10:53 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 01 Aug 2007 09:10:53 -0400 Subject: [Tutor] gotoxy In-Reply-To: <6be1291e0708010546k150e6349ud76d17ad588a89c@mail.gmail.com> References: <6be1291e0708010546k150e6349ud76d17ad588a89c@mail.gmail.com> Message-ID: <46B0865D.3050909@tds.net> Robert William Hanks wrote: > > hi folks, is there in python a gotoxy like in pascal so i can print > stuff in other parts of the screen? curses for the systems that support it http://effbot.org/zone/console-handbook.htm for Windows > what about some thing like it for the gui in windows? Which GUI are you talking about? If you want to write GUI programs to run under windows, look at Tkinter or wxPython or you can use pywin32 to code to the native Windows GUI. Kent From kent37 at tds.net Wed Aug 1 15:14:53 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 01 Aug 2007 09:14:53 -0400 Subject: [Tutor] Which GUI? In-Reply-To: <46B08268.7090201@rogers.com> References: <46B08268.7090201@rogers.com> Message-ID: <46B0874D.3060603@tds.net> scott wrote: I am thinking about > starting with Tkinter then trying WxPython because WxPython seems to be > the most highly suggested and seems to have the best documentation and > selection of software/RADs. I think that is a good plan, Tkinter is pretty easy to learn but harder to use to create polished, high-function interfaces. wxPython comes with a lot more in the box. BTW you eliminated PyQt because you want an open source solution but Qt 4 and PyQt 4 are available under GPL for all supported platforms. Kent From slewin at rogers.com Wed Aug 1 15:24:45 2007 From: slewin at rogers.com (scott) Date: Wed, 01 Aug 2007 09:24:45 -0400 Subject: [Tutor] Which GUI? In-Reply-To: <46B0874D.3060603@tds.net> References: <46B08268.7090201@rogers.com> <46B0874D.3060603@tds.net> Message-ID: <46B0899D.2040007@rogers.com> Kent Johnson wrote: > BTW you eliminated PyQt because you want an open source solution but Qt > 4 and PyQt 4 are available under GPL for all supported platforms. I know that most likely everything I develop will be released under the GPL, but, I like the freedom to choose. I don't like how Qt is only open source if you release under the GPL. Unless Qt 4 will be released only under LGPL and/or GPL, no matter how you decide to release your product. I actually moved from Kubuntu using KDE to Ubuntu using Gnome when I found out about the Qt licence. -- Your friend, Scott Sent to you from a Linux computer using Ubuntu Version 7.04 (Feisty Fawn) From bgailer at alum.rpi.edu Wed Aug 1 16:12:24 2007 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Wed, 01 Aug 2007 07:12:24 -0700 Subject: [Tutor] Textual Captchas: Would like to show that bots can crack a simple text captcha In-Reply-To: References: Message-ID: <46B094C8.7010700@alum.rpi.edu> Kyle Brooks wrote: > Hi. > > My name is Kyle Brooks, and I hereby introduce myself with this post. > > I have seen a lot of text captchas. > I wonder how a computer program would respond to the previous sentence? Could it simulate the path I took? "captcha"? Did he mean "capture"? Is this one more poster who does not know how to spell? But the rest of the email is good english! Oh yes - ask Google. *visualizae me reading the wikipedia article on captchas. Light bulbs and ahas going on.* Oh yes this is a really good question. Should I respond? What would I say? Why would I say it? *visualize me typing the above and hitting send From anotequaltob at gmail.com Wed Aug 1 16:17:49 2007 From: anotequaltob at gmail.com (Kyle Brooks) Date: Wed, 1 Aug 2007 10:17:49 -0400 Subject: [Tutor] Textual Captchas: Would like to show that bots can crack a simple text captcha In-Reply-To: <46B094C8.7010700@alum.rpi.edu> References: <46B094C8.7010700@alum.rpi.edu> Message-ID: Hi. Please look up captcha... I did not mean capture. Your response is hilarious, frankly, but not appropriate for this list :-) - Kyle Brooks On 8/1/07, Bob Gailer wrote: > Kyle Brooks wrote: > > Hi. > > > > My name is Kyle Brooks, and I hereby introduce myself with this post. > > > > I have seen a lot of text captchas. > > > I wonder how a computer program would respond to the previous sentence? > Could it simulate the path I took? > > "captcha"? Did he mean "capture"? Is this one more poster who does not > know how to spell? > But the rest of the email is good english! > Oh yes - ask Google. > *visualizae me reading the wikipedia article on captchas. Light bulbs > and ahas going on.* > Oh yes this is a really good question. > Should I respond? What would I say? Why would I say it? > *visualize me typing the above and hitting send > > From kent37 at tds.net Wed Aug 1 16:33:32 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 01 Aug 2007 10:33:32 -0400 Subject: [Tutor] Textual Captchas: Would like to show that bots can crack a simple text captcha In-Reply-To: References: <46B094C8.7010700@alum.rpi.edu> Message-ID: <46B099BC.3050703@tds.net> Kyle Brooks wrote: > Hi. > > Please look up captcha... I did not mean capture. > > Your response is hilarious, frankly, but not appropriate for this list :-) Oh, all of a sudden we are not allowed to go OT or have fun here? Who died and made you the moderator? ;-) A bit more on track to actually answering your question... ISTM making your own web site with a text captcha and then cracking it is not a very impressive demonstration. Hoping that you are not actually a spammer looking for help on cracking sites with text captchas, I'll point you to urllib2 - to fetch the content of a web page http://docs.python.org/lib/module-urllib2.html BeautifulSoup - to parse the content of a web page http://www.crummy.com/software/BeautifulSoup/documentation.html eval() - to evaluate expressions http://docs.python.org/lib/built-in-funcs.html#l2h-25 safe eval - so eval can't erase your hard disk http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/364469 Kent From anotequaltob at gmail.com Wed Aug 1 16:54:10 2007 From: anotequaltob at gmail.com (Kyle Brooks) Date: Wed, 1 Aug 2007 10:54:10 -0400 Subject: [Tutor] Textual Captchas: Would like to show that bots can crack a simple text captcha In-Reply-To: <46B099BC.3050703@tds.net> References: <46B094C8.7010700@alum.rpi.edu> <46B099BC.3050703@tds.net> Message-ID: Hi. I am not a spammer! I just want to demonstrate something :-) Thanks for the resources! You guys are great :-) - Kyle On 8/1/07, Kent Johnson wrote: > Kyle Brooks wrote: > > Hi. > > > > Please look up captcha... I did not mean capture. > > > > Your response is hilarious, frankly, but not appropriate for this list :-) > > Oh, all of a sudden we are not allowed to go OT or have fun here? Who > died and made you the moderator? ;-) > > A bit more on track to actually answering your question... > > ISTM making your own web site with a text captcha and then cracking it > is not a very impressive demonstration. > > Hoping that you are not actually a spammer looking for help on cracking > sites with text captchas, I'll point you to > > urllib2 - to fetch the content of a web page > http://docs.python.org/lib/module-urllib2.html > > BeautifulSoup - to parse the content of a web page > http://www.crummy.com/software/BeautifulSoup/documentation.html > > eval() - to evaluate expressions > http://docs.python.org/lib/built-in-funcs.html#l2h-25 > > safe eval - so eval can't erase your hard disk > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/364469 > > Kent > From brunson at brunson.com Wed Aug 1 17:10:01 2007 From: brunson at brunson.com (Eric Brunson) Date: Wed, 01 Aug 2007 09:10:01 -0600 Subject: [Tutor] Textual Captchas: Would like to show that bots can crack a simple text captcha In-Reply-To: References: <46B094C8.7010700@alum.rpi.edu> Message-ID: <46B0A249.5010704@brunson.com> Kyle Brooks wrote: > Hi. > > Please look up captcha... I did not mean capture. > > Your response is hilarious, frankly, but not appropriate for this list :-) > Seeing that a) this is your second post here and b) you are the one asking the list for help, I don't think it's your place to decide what is and isn't appropriate for this list. Also, I'm pretty sure he *did* look up captcha and was using the process through which he researched and replied as a metaphor for how your program might work. > - Kyle Brooks > > On 8/1/07, Bob Gailer wrote: > >> Kyle Brooks wrote: >> >>> Hi. >>> >>> My name is Kyle Brooks, and I hereby introduce myself with this post. >>> >>> I have seen a lot of text captchas. >>> >>> >> I wonder how a computer program would respond to the previous sentence? >> Could it simulate the path I took? >> >> "captcha"? Did he mean "capture"? Is this one more poster who does not >> know how to spell? >> But the rest of the email is good english! >> Oh yes - ask Google. >> *visualizae me reading the wikipedia article on captchas. Light bulbs >> and ahas going on.* >> Oh yes this is a really good question. >> Should I respond? What would I say? Why would I say it? >> *visualize me typing the above and hitting send >> >> >> > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From carroll at tjc.com Wed Aug 1 23:19:55 2007 From: carroll at tjc.com (Terry Carroll) Date: Wed, 1 Aug 2007 14:19:55 -0700 (PDT) Subject: [Tutor] Which GUI? In-Reply-To: <46B0874D.3060603@tds.net> Message-ID: On Wed, 1 Aug 2007, Kent Johnson wrote: > I think that is a good plan, Tkinter is pretty easy to learn but harder > to use to create polished, high-function interfaces. wxPython comes with > a lot more in the box. I've heard "Tkinter is easier to learn" before, and I think I would once have agreed. But now that there's a good book on wxPython, I think wxPython's pretty easy to learn, and is now even better documented than Tkinter. As I was learning wxPython, most of my learning gotchas were noting differences from the Tkinter approach (including terminology). I think if I were approaching wxPython with no prior GUI knowledge, it would be approximately as easy to learn as Tkinter. All this is assuming access to a copy of "wxPython in Action"; without the book, you're back to a dearth of tutorials, and yes, Tkinter would be easier to learn. From witham.ian at gmail.com Wed Aug 1 23:46:00 2007 From: witham.ian at gmail.com (Ian Witham) Date: Thu, 2 Aug 2007 09:46:00 +1200 Subject: [Tutor] Filemaker interactions Message-ID: Hello, I'm hoping someone here can put me on the right track with some broad concepts here. I've cross-posted this email to the comp.lang.python, I hope that's acceptable. What I am hoping to achieve is a simple HTML page to be served over our company LAN, into which the users (Real Estate Agents) can enter a property address or reference number. My next thought was to have a Python CGI script query our filemaker database of property listings, construct a PDF from the relevant information, and finally return this PDF to the user. At no stage do I want the user to have unfettered access to the database or the ability to alter/delete records. My question is: what is the most appropriate way for my script to interact with Filemaker? Can this be done with Filemaker Pro 6? According to the Filemaker Help, the "Local Data Access Companion" shares the FileMaker Pro database with ODBC-compliant applications on the same computer. Is this the right option? Can my CGI script be an ODBC client? How? Would it need to be Filemaker specific code or does ODBC have a standardised format? I'm grateful for any advice and a nudge in the right direction. Ian. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070802/ad5140b0/attachment.html From ranpra at gmail.com Wed Aug 1 17:01:36 2007 From: ranpra at gmail.com (Pradeep Kumar) Date: Wed, 1 Aug 2007 19:01:36 +0400 Subject: [Tutor] Design Pattern + Wxpython Message-ID: <76b198110708010801p5c1d9474g6b5e8d66f07b8884@mail.gmail.com> I am new to this and wants to do a project for Autoparts industry (Trading) with backend SQL Server 2000. 1. Which Design Pattern is suitable for me. Pradeep~~ -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070801/4c91c9a0/attachment.html From kent37 at tds.net Thu Aug 2 03:03:08 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 01 Aug 2007 21:03:08 -0400 Subject: [Tutor] Design Pattern + Wxpython In-Reply-To: <76b198110708010801p5c1d9474g6b5e8d66f07b8884@mail.gmail.com> References: <76b198110708010801p5c1d9474g6b5e8d66f07b8884@mail.gmail.com> Message-ID: <46B12D4C.3090404@tds.net> Pradeep Kumar wrote: > I am new to this and wants to do a project for Autoparts industry > (Trading) with backend SQL Server 2000. > > 1. Which Design Pattern is suitable for me. This one clearly applies: http://catb.org/~esr/faqs/smart-questions.html Kent From winglion1 at 163.com Thu Aug 2 03:45:31 2007 From: winglion1 at 163.com (Yang) Date: Thu, 2 Aug 2007 09:45:31 +0800 Subject: [Tutor] operator * of the list and tuple Message-ID: <46B13AF1.0D2179.15191@m12-15.163.com> tutor-request: I found this interesting question in a local forum, and want to get a more detail explain of it: >>> a = [[]]*5 >>> a [[], [], [], [], []] >>> a[0].append(3) >>> a [[3], [3], [3], [3], [3]] >>> b = [[] for i in range(5)] >>> b [[], [], [], [], []] >>> b[0].append(3) >>> b [[3], [], [], [], []] This look something like pointer! I found it also work for tuple ! >>> l1=((1,2),(2,3))*5 >>> l1 ((1, 2), (2, 3), (1, 2), (2, 3), (1, 2), (2, 3), (1, 2), (2, 3), (1, 2), (2, 3)) So, can somebody tell me how the * operator of list and tuple work, and how can we make use of it? ????????????????Yang ????????????????winglion1 at 163.com ????????????????????2007-08-02 From zeliboba at mail.ru Wed Aug 1 17:02:00 2007 From: zeliboba at mail.ru (Maxim Loginov) Date: Wed, 01 Aug 2007 22:02:00 +0700 Subject: [Tutor] tree-like functions call to find dependencies Message-ID: <871weni9hz.fsf@mail.ru> hi all! my problem is: I have (for example) 2 sets of quantity set(A,B,C) or set(A,B,D). I need to calculate another quantity E which is function of A,B,C or A,F. but F in turn is function of (A,B,D). I want to write one function that checks the supplied set if it possible to calculate requested the value depending on the set of values supplied, it should check what input data it needs and call functions in tree-like manner to check which quantity can they provide. In reality dependecies of course deeper sets are longer and data are very big arrays (do not fit into memory of my machine), another reason is easy to extend the program if I will need a function indirectly depending on already existed. the question is: maybe there is a design template for this? what I invented now is bit ugly... thanks Maxim Loginov From queprime at gmail.com Thu Aug 2 06:51:17 2007 From: queprime at gmail.com (Que Prime) Date: Wed, 1 Aug 2007 21:51:17 -0700 Subject: [Tutor] gendata.py Message-ID: <17285ccf0708012151m395a95bbwee5b9b8ac33c4554@mail.gmail.com> This script appears to be written for Unix systems. Is there a way to get it to work for PythonWin? from random import randint, choice from string import lowercase from sys import maxint from time import ctime doms = ( 'com', 'edu', 'net', 'org', 'gov' ) for i in range(randint(5, 10)): dtint = randint(0, maxint-1) #pick date dtstr = ctime(dtint) #date string shorter = randint(4,7) #login shorter em = '' for j in range(shorter): #generate login em += choice(lowercase) longer = randint(shorter, 12) #domain longer dn = '' for j in range(longer): #create domain dn += choice(lowercase) print '%s::%s@%s.%s::%d-%d-%d' % (dtstr, em, dn, choice(doms), dtint, shorter, longer) -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070801/b84770df/attachment.html From brunson at brunson.com Thu Aug 2 07:17:40 2007 From: brunson at brunson.com (Eric Brunson) Date: Wed, 01 Aug 2007 23:17:40 -0600 Subject: [Tutor] gendata.py In-Reply-To: <17285ccf0708012151m395a95bbwee5b9b8ac33c4554@mail.gmail.com> References: <17285ccf0708012151m395a95bbwee5b9b8ac33c4554@mail.gmail.com> Message-ID: <46B168F4.60505@brunson.com> What is it that you think makes it Unix specific? Que Prime wrote: > > This script appears to be written for Unix systems. Is there a way to > get it to work for PythonWin? > > from random import randint, choice > from string import lowercase > from sys import maxint > from time import ctime > > doms = ( 'com', 'edu', 'net', 'org', 'gov' ) > > for i in range(randint(5, 10)): > dtint = randint(0, maxint-1) #pick date > dtstr = ctime(dtint) #date string > > > shorter = randint(4,7) #login shorter > em = '' > for j in range(shorter): #generate login > em += choice(lowercase) > > longer = randint(shorter, 12) #domain longer > dn = '' > for j in range(longer): #create domain > dn += choice(lowercase) > > print '%s::%s@%s.%s::%d-%d-%d' % (dtstr, em, dn, choice(doms), > dtint, shorter, longer) > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From maseriyer at yahoo.com Thu Aug 2 07:55:08 2007 From: maseriyer at yahoo.com (Iyer) Date: Wed, 1 Aug 2007 22:55:08 -0700 (PDT) Subject: [Tutor] os.path.exists(path) returns false when the path actually exists! In-Reply-To: <46AE9429.2070708@alum.rpi.edu> Message-ID: <213508.28357.qm@web50706.mail.re2.yahoo.com> Is there any chance the file has an extension that Windows is hiding? Can you get True for other files in the folder? So, it was the extensions all the way ! Apparently the file extension was hidden by Windows! It now works. Thank you all for your suggestions and help. -iyer --------------------------------- Shape Yahoo! in your own image. Join our Network Research Panel today! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070801/daa4e524/attachment.htm From carroll at tjc.com Thu Aug 2 08:46:20 2007 From: carroll at tjc.com (Terry Carroll) Date: Wed, 1 Aug 2007 23:46:20 -0700 (PDT) Subject: [Tutor] sqlite: does "?" work in PRAGMA commands? Message-ID: I'm using sqlite for the first time, so I'm not sure whether I'm trying to do something unsupported. or whether I'm trying to do something that's supported, but doing it wrong. I want to get information about a table in my database. The variable tablename holds the name of the table, and self.dbconn.execute is a valid connection object. This works: GET_TABLE_INFO_COMMAND = "PRAGMA TABLE_INFO(%s)" pragma_cmd = GET_TABLE_INFO_COMMAND % tablename field_data = self.dbconn.execute(pragma_cmd) But I'm mindful of the warning ("# Never do this -- insecure!") at http://docs.python.org/lib/module-sqlite3.html, and I'd like to get into the habit of doing that; so instead I tried it this way (and many variations of it): GET_TABLE_INFO_COMMAND = "PRAGMA TABLE_INFO(?)" pragma_cmd = GET_TABLE_INFO_COMMAND field_data = self.dbconn.execute(pragma_cmd, (tablename)) I get the error: sqlite3.OperationalError: near "?": syntax error Some of the variations included using "tablename" or "(tablename,)" for the second parameter; it made no difference. Does the "?" approach not work with PRAGMA commands or something; or am I doing this wrong? From john at fouhy.net Thu Aug 2 09:22:19 2007 From: john at fouhy.net (John Fouhy) Date: Thu, 2 Aug 2007 19:22:19 +1200 Subject: [Tutor] sqlite: does "?" work in PRAGMA commands? In-Reply-To: References: Message-ID: <5e58f2e40708020022x70ae00bev788a651e3ca133e7@mail.gmail.com> I'm not sure about PRAGMA, but you can do introspection in sqlite by examining the table 'sqlite_master'. -- John. From kent37 at tds.net Thu Aug 2 13:22:46 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 02 Aug 2007 07:22:46 -0400 Subject: [Tutor] Filemaker interactions In-Reply-To: References: Message-ID: <46B1BE86.8090803@tds.net> Ian Witham wrote: > Can my CGI script be an ODBC client? How? Yes mxODBC is a payware ODBC driver: http://www.egenix.com/products/python/mxODBC/ Here is an example of connecting to ODBC on Windows: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/303667 which apparently has been replaced by this: http://unipex.it/vario/RealPyOdbc.py > Would it need to be > Filemaker specific code or does ODBC have a standardised format? Probably a bit of each. I'm not familiar with ODBC but typically each database has its own quirks and database-specific behaviour. Kent From kent37 at tds.net Thu Aug 2 13:25:30 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 02 Aug 2007 07:25:30 -0400 Subject: [Tutor] operator * of the list and tuple In-Reply-To: <46B13AF1.0D2179.15191@m12-15.163.com> References: <46B13AF1.0D2179.15191@m12-15.163.com> Message-ID: <46B1BF2A.4090204@tds.net> Yang wrote: > So, can somebody tell me how the * operator of list and tuple work, > and how can we make use of it? A bit more here: http://docs.python.org/lib/typesseq.html See especially note (2) Kent From kent37 at tds.net Thu Aug 2 13:29:44 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 02 Aug 2007 07:29:44 -0400 Subject: [Tutor] shelves behaving badly In-Reply-To: References: Message-ID: <46B1C028.7070201@tds.net> Luke Jordan wrote: > i've implemented a database as a shelve of record class instances. some > of the fields in each record are dictionaries. > > i needed to parse info from 3 different reports into the dictionary > fields in each record instance. i wrote the code to do this and tinkered > it to fit the different reports (i.e. information being in different > columns, etc.). for 2 of the reports, it runs fine. the required info > turns up in the shelve after i run the code, and i can exit and reenter > python, open the shelve, and it's all still there, where it should be. > i've quadruple checked the code for the third report, and it looks like > it should work. in fact it runs, and reports back that it did everything > i told it to do; this includes checking results as they occur at > runtime. however, when i reopen the shelve, none of that data is there. > writeback is set to True, and I didn't forget to close the shelve at the > end of my code. > > Now, if I open the shelve in the same shell as the script ran in, right > after I run it, I get the updated shelve. but any other method of > opening the shelve results in the shelve missing the data from the third > report. > > Any ideas what's going on here? It's pretty hard to say without seeing the code. I wonder if you are saving the third shelve in a different location than you think you are, and opening an old one in the other programs? Maybe check the full path of the file you save (use os.path.abspath()) and check the modified date of the one you open. Kent From anotequaltob at gmail.com Thu Aug 2 14:53:39 2007 From: anotequaltob at gmail.com (Kyle Brooks) Date: Thu, 2 Aug 2007 08:53:39 -0400 Subject: [Tutor] operator * of the list and tuple In-Reply-To: <46B1BF2A.4090204@tds.net> References: <46B13AF1.0D2179.15191@m12-15.163.com> <46B1BF2A.4090204@tds.net> Message-ID: Hi. The explanation on that page may be a bit confusing, so I will add to it. If you think of L * n as something similiar to doing a shallow copy of the list L n times, then it makes some sense: >>> a = [] >>> L = [[]] >>> for i in xrange(5): ... a.append(L[:][0]) has the same (or similiar) effect as >>> a = [[]]*5 Both have the side effect noted in the text: that >>> a[0].append(42) modifies a single list, as you can see if you ask for a unique identifier: >>> [id(e) for e in L] [number repeated 5 times] The alternative way: >>> L = [[] for i in xrange(5)] works because the code "[]", which creates a new empty list, is executed 5 times, and creates 5 different lists. On 8/2/07, Kent Johnson wrote: > Yang wrote: > > So, can somebody tell me how the * operator of list and tuple work, > > and how can we make use of it? > > A bit more here: > http://docs.python.org/lib/typesseq.html > > See especially note (2) > > Kent > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From anotequaltob at gmail.com Thu Aug 2 14:57:26 2007 From: anotequaltob at gmail.com (Kyle Brooks) Date: Thu, 2 Aug 2007 08:57:26 -0400 Subject: [Tutor] gendata.py In-Reply-To: <46B168F4.60505@brunson.com> References: <17285ccf0708012151m395a95bbwee5b9b8ac33c4554@mail.gmail.com> <46B168F4.60505@brunson.com> Message-ID: Hi. If you think time.ctime is Unix specific, it is not. - Kyle On 8/2/07, Eric Brunson wrote: > > What is it that you think makes it Unix specific? > > Que Prime wrote: > > > > This script appears to be written for Unix systems. Is there a way to > > get it to work for PythonWin? > > > > from random import randint, choice > > from string import lowercase > > from sys import maxint > > from time import ctime > > > > doms = ( 'com', 'edu', 'net', 'org', 'gov' ) > > > > for i in range(randint(5, 10)): > > dtint = randint(0, maxint-1) #pick date > > dtstr = ctime(dtint) #date string > > > > > > shorter = randint(4,7) #login shorter > > em = '' > > for j in range(shorter): #generate login > > em += choice(lowercase) > > > > longer = randint(shorter, 12) #domain longer > > dn = '' > > for j in range(longer): #create domain > > dn += choice(lowercase) > > > > print '%s::%s@%s.%s::%d-%d-%d' % (dtstr, em, dn, choice(doms), > > dtint, shorter, longer) > > ------------------------------------------------------------------------ > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From slewin at rogers.com Thu Aug 2 15:11:20 2007 From: slewin at rogers.com (scott) Date: Thu, 02 Aug 2007 09:11:20 -0400 Subject: [Tutor] Which GUI? In-Reply-To: References: Message-ID: <46B1D7F8.9000806@rogers.com> Terry Carroll wrote: >> I think that is a good plan, Tkinter is pretty easy to learn but harder >> to use to create polished, high-function interfaces. wxPython comes with >> a lot more in the box. > > I've heard "Tkinter is easier to learn" before, and I think I would once > have agreed. But now that there's a good book on wxPython, I think > wxPython's pretty easy to learn, and is now even better documented than > Tkinter. > > As I was learning wxPython, most of my learning gotchas were noting > differences from the Tkinter approach (including terminology). I think if > I were approaching wxPython with no prior GUI knowledge, it would be > approximately as easy to learn as Tkinter. > > All this is assuming access to a copy of "wxPython in Action"; without the > book, you're back to a dearth of tutorials, and yes, Tkinter would be > easier to learn. I was thinking about finding a copy of that book, so maybe starting WxPython would be easier then and not worry about Tkinter. Is "WxPython in Action" a very good book? -- Your friend, Scott Sent to you from a Linux computer using Ubuntu Version 7.04 (Feisty Fawn) From rfquerin at gmail.com Thu Aug 2 15:34:00 2007 From: rfquerin at gmail.com (Richard Querin) Date: Thu, 2 Aug 2007 09:34:00 -0400 Subject: [Tutor] Which GUI? In-Reply-To: <46B1D7F8.9000806@rogers.com> References: <46B1D7F8.9000806@rogers.com> Message-ID: <7d81675b0708020634r5aba7eb7p97f71536c04e57d2@mail.gmail.com> On 8/2/07, scott wrote: > I was thinking about finding a copy of that book, so maybe starting > WxPython would be easier then and not worry about Tkinter. Is "WxPython > in Action" a very good book? > I'm no programmer by trade, but dabble in Python/wxPython for fun and bought the book several months ago. I've found it to be very good. There are a lot of good online tutorials as well, but I was never sure if they were up to date with the later versions of the framework - so the book was blessing to me. I found the book to be very useful and clearly written. It's no reference manual (the online docs serve that purpose) but I think it really helped me get a good foundation in how to program with wxPython. IMO a good book is still more useful and efficient than online articles or tutorials for a newbie (like me) most of the time. It's nice to be able to thumb through and study some concept without flipping back and forth to some web page. I own a lot of computer books, and I've found Learning Python (an O'Reilly Book) and wxPython in Action to be my two most useful ones. RQ From jeff at san-dc.com Thu Aug 2 16:52:18 2007 From: jeff at san-dc.com (Jeff Johnson) Date: Thu, 2 Aug 2007 07:52:18 -0700 Subject: [Tutor] Which GUI? In-Reply-To: <46AA63AB.3080209@rogers.com> Message-ID: <004b01c7d514$b94d94c0$5f01a8c0@dcsoftware.local> > -----Original Message----- > From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf > Of scott > Sent: Friday, July 27, 2007 2:29 PM > To: tutor at python.org > Subject: [Tutor] Which GUI? > > Hi, > > now that I have a very basic understanding of Python I would like to > take a look at programming in a GUI. Which GUI is generally the easiest > to learn? > > -- > Your friend, > Scott > I am using Dabo. -- http://dabodev.com and for a mailing list: http://leafe.com/mailman/listinfo/dabo-users It is basically a wxpython wrapper with a whole lot more. Jeff Jeff Johnson jeff at san-dc.com 623-582-0323 Fax 623-869-0675 -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 4232 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20070802/a3f4ad89/attachment.bin From brunson at brunson.com Thu Aug 2 17:11:43 2007 From: brunson at brunson.com (Eric Brunson) Date: Thu, 02 Aug 2007 09:11:43 -0600 Subject: [Tutor] Which GUI? In-Reply-To: <7d81675b0708020634r5aba7eb7p97f71536c04e57d2@mail.gmail.com> References: <46B1D7F8.9000806@rogers.com> <7d81675b0708020634r5aba7eb7p97f71536c04e57d2@mail.gmail.com> Message-ID: <46B1F42F.4040108@brunson.com> Richard Querin wrote: > On 8/2/07, scott wrote: > > >> I was thinking about finding a copy of that book, so maybe starting >> WxPython would be easier then and not worry about Tkinter. Is "WxPython >> in Action" a very good book? >> >> > > I'm no programmer by trade, but dabble in Python/wxPython for fun and > bought the book several months ago. I've found it to be very good. > There are a lot of good online tutorials as well, but I was never sure > if they were up to date with the later versions of the framework - so > the book was blessing to me. I found the book to be very useful and > clearly written. It's no reference manual (the online docs serve that > purpose) but I think it really helped me get a good foundation in how > to program with wxPython. Switching gears from linear to event driven programming is a pretty significant paradigm shift. Will this book help him get his head around that? > IMO a good book is still more useful and > efficient than online articles or tutorials for a newbie (like me) > most of the time. It's nice to be able to thumb through and study some > concept without flipping back and forth to some web page. > > I own a lot of computer books, and I've found Learning Python (an > O'Reilly Book) and wxPython in Action to be my two most useful ones. > > > RQ > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From carroll at tjc.com Thu Aug 2 17:16:34 2007 From: carroll at tjc.com (Terry Carroll) Date: Thu, 2 Aug 2007 08:16:34 -0700 (PDT) Subject: [Tutor] sqlite: does "?" work in PRAGMA commands? In-Reply-To: <5e58f2e40708020022x70ae00bev788a651e3ca133e7@mail.gmail.com> Message-ID: On Thu, 2 Aug 2007, John Fouhy wrote: > I'm not sure about PRAGMA, but you can do introspection in sqlite by > examining the table 'sqlite_master'. Thanks. That's how I get the table names, actually. But it doesn't give the column names. It does give the SQL used to create the table, so I could theoretically parse that out. I suppose I don't actually have a risk in this particular case by using the python-based "%" substitution, rather than the DB API "?" substitution. The table names come directly out of the schema, with no opportunity for a user-driven SQL injection. I'd just like to use good habits from the start. From rfquerin at gmail.com Thu Aug 2 17:28:45 2007 From: rfquerin at gmail.com (Richard Querin) Date: Thu, 2 Aug 2007 11:28:45 -0400 Subject: [Tutor] Which GUI? In-Reply-To: <46B1F42F.4040108@brunson.com> References: <46B1D7F8.9000806@rogers.com> <7d81675b0708020634r5aba7eb7p97f71536c04e57d2@mail.gmail.com> <46B1F42F.4040108@brunson.com> Message-ID: <7d81675b0708020828qfcf9cd6n61a517cacc4e6782@mail.gmail.com> On 8/2/07, Eric Brunson wrote: > Switching gears from linear to event driven programming is a pretty > significant paradigm shift. Will this book help him get his head around > that? > That's one of the main reasons why I bought it actually. I couldn't grasp in any significant way how it worked. I could build a working wxpython program based on tutorials etc. but didn't really know why/how it worked. There are early sections in the book dealing with the basics of the event-driven paradigm as well as a section discussing the Model-View-Controller pattern too. It's not exhaustive on the subject by any means, but cleared up a lot of questions for me. It doesn't just throw you into building a detailed wxpython app without any background as to how it works - although it does get you going immediately with some small hello world type stuff to immediately build a little confidence. ;) RQ From brunson at brunson.com Thu Aug 2 17:39:43 2007 From: brunson at brunson.com (Eric Brunson) Date: Thu, 02 Aug 2007 09:39:43 -0600 Subject: [Tutor] Which GUI? In-Reply-To: <7d81675b0708020828qfcf9cd6n61a517cacc4e6782@mail.gmail.com> References: <46B1D7F8.9000806@rogers.com> <7d81675b0708020634r5aba7eb7p97f71536c04e57d2@mail.gmail.com> <46B1F42F.4040108@brunson.com> <7d81675b0708020828qfcf9cd6n61a517cacc4e6782@mail.gmail.com> Message-ID: <46B1FABF.8070406@brunson.com> Richard Querin wrote: > On 8/2/07, Eric Brunson wrote: > > >> Switching gears from linear to event driven programming is a pretty >> significant paradigm shift. Will this book help him get his head around >> that? >> >> > > That's one of the main reasons why I bought it actually. I couldn't > grasp in any significant way how it worked. I could build a working > wxpython program based on tutorials etc. but didn't really know > why/how it worked. There are early sections in the book dealing with > the basics of the event-driven paradigm as well as a section > discussing the Model-View-Controller pattern too. It's not exhaustive > on the subject by any means, but cleared up a lot of questions for me. > > It doesn't just throw you into building a detailed wxpython app > without any background as to how it works - although it does get you > going immediately with some small hello world type stuff to > immediately build a little confidence. ;) > Sounds like a good book, I wish I'd had something similar 15 years ago when I was learning to program on Mac OS. Thanks for the review, I hope it helps the original poster. e. From carroll at tjc.com Thu Aug 2 18:07:26 2007 From: carroll at tjc.com (Terry Carroll) Date: Thu, 2 Aug 2007 09:07:26 -0700 (PDT) Subject: [Tutor] Which GUI? In-Reply-To: <46B1D7F8.9000806@rogers.com> Message-ID: On Thu, 2 Aug 2007, scott wrote: > I was thinking about finding a copy of that book, so maybe starting > WxPython would be easier then and not worry about Tkinter. Is "WxPython > in Action" a very good book? I can say that it's the best book on wxPython that I'm aware of. Of course, it's the only book on wxPython that I'm aware of. Actually, I like it a lot. It's usually clear, and gets you going step-by-step. Because this is the only available wxPython book, I probably want too much. What I really would have liked is a reference-like chapter, at least listing out all the controls, maybe categorized by type, with a graphic showing what each looks like. I would gladly have swapped Chapter 4 (which talks about PyCrust, a cool-looking Python shell that comes with wxPython, but is not needed to use the GUI) for that. It's more important with wxPython than many other things, because much of wxPython documentation is not wxPython documentation, per se, as it is wxWidgets documentation, expressed in C++ rather than Python. I'm an avid user of my local public library, and if you're not sure you want to shell out the bucks for it (and assuming you're in the US), I'd suggest you do what I did: try to borrow a copy through your library. My library did not have it, but could get it for me on inter-library loan from another local library. http://www.worldcat.org/ shows that there are 121 library copies in the U.S., so give it a shot. From carroll at tjc.com Thu Aug 2 18:12:19 2007 From: carroll at tjc.com (Terry Carroll) Date: Thu, 2 Aug 2007 09:12:19 -0700 (PDT) Subject: [Tutor] Which GUI? In-Reply-To: <46B1F42F.4040108@brunson.com> Message-ID: On Thu, 2 Aug 2007, Eric Brunson wrote: > Switching gears from linear to event driven programming is a pretty > significant paradigm shift. Will this book help him get his head around > that? Hard to say. It does have a chapter, Chapter 3, devoted to that. From etrade.griffiths at dsl.pipex.com Thu Aug 2 17:51:58 2007 From: etrade.griffiths at dsl.pipex.com (eShopping) Date: Thu, 02 Aug 2007 16:51:58 +0100 Subject: [Tutor] Which GUI? In-Reply-To: References: Message-ID: <20070802155200.546D4E0003A9@astro.systems.pipex.net> >Richard Querin wrote: > > On 8/2/07, scott wrote: > > > > > >> I was thinking about finding a copy of that book, so maybe starting > >> WxPython would be easier then and not worry about Tkinter. Is "WxPython > >> in Action" a very good book? > >> > >> > > > > I'm no programmer by trade, but dabble in Python/wxPython for fun and > > bought the book several months ago. I've found it to be very good. > > There are a lot of good online tutorials as well, but I was never sure > > if they were up to date with the later versions of the framework - so > > the book was blessing to me. I found the book to be very useful and > > clearly written. It's no reference manual (the online docs serve that > > purpose) but I think it really helped me get a good foundation in how > > to program with wxPython. > >Switching gears from linear to event driven programming is a pretty >significant paradigm shift. Will this book help him get his head around >that? Chapter 3 of WPIA gives a nice introduction to event driven programming. But event driven programming is implicit in all GUIs (isn't it?) so this he will have to do this regardless of which GUI he uses. > > IMO a good book is still more useful and > > efficient than online articles or tutorials for a newbie (like me) > > most of the time. It's nice to be able to thumb through and study some > > concept without flipping back and forth to some web page. > > > > I own a lot of computer books, and I've found Learning Python (an > > O'Reilly Book) and wxPython in Action to be my two most useful ones. > > I have both books and agree that they are both excellent. After a couple of evenings flicking through WPIA and playing the code, I had a not-too-simple WinApp up and running Alun Griffiths From kent37 at tds.net Thu Aug 2 18:33:17 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 02 Aug 2007 12:33:17 -0400 Subject: [Tutor] sqlite: does "?" work in PRAGMA commands? In-Reply-To: References: Message-ID: <46B2074D.1070008@tds.net> Terry Carroll wrote: > GET_TABLE_INFO_COMMAND = "PRAGMA TABLE_INFO(?)" > pragma_cmd = GET_TABLE_INFO_COMMAND > field_data = self.dbconn.execute(pragma_cmd, (tablename)) > > I get the error: > > sqlite3.OperationalError: near "?": syntax error > > Some of the variations included using "tablename" or "(tablename,)" for > the second parameter; it made no difference. FWIW (tablename,) or [tablename] is the correct spelling, the parameter argument must be a sequence. Kent From slewin at rogers.com Thu Aug 2 18:43:16 2007 From: slewin at rogers.com (scott) Date: Thu, 02 Aug 2007 12:43:16 -0400 Subject: [Tutor] [Bulk] Re: Which GUI? In-Reply-To: <46B1FABF.8070406@brunson.com> References: <46B1D7F8.9000806@rogers.com> <7d81675b0708020634r5aba7eb7p97f71536c04e57d2@mail.gmail.com> <46B1F42F.4040108@brunson.com> <7d81675b0708020828qfcf9cd6n61a517cacc4e6782@mail.gmail.com> <46B1FABF.8070406@brunson.com> Message-ID: <46B209A4.6070400@rogers.com> Eric Brunson wrote: > Thanks for the review, I hope > it helps the original poster. Yes, defiantly. Everyone haves been a great help in choosing which GUI. My mind is much clearer now and I know what I want to do. I'm going to try and get a copy of the WxPython book and then go through some of the tutorials after to re-enforce my knowledge. I did something similar when I was first Learning Python and it worked out well. -- Your friend, Scott Sent to you from a Linux computer using Ubuntu Version 7.04 (Feisty Fawn) From slewin at rogers.com Thu Aug 2 18:48:05 2007 From: slewin at rogers.com (scott) Date: Thu, 02 Aug 2007 12:48:05 -0400 Subject: [Tutor] Which GUI? In-Reply-To: References: Message-ID: <46B20AC5.6030903@rogers.com> Terry Carroll wrote: > I'm an avid user of my local public library, and if you're not sure you > want to shell out the bucks for it (and assuming you're in the US), I'd > suggest you do what I did: try to borrow a copy through your library. My > library did not have it, but could get it for me on inter-library loan > from another local library. http://www.worldcat.org/ shows that there are > 121 library copies in the U.S., so give it a shot. I'm a Canadian and I don't Live in a City; I live in a town. My local library is not bad for most subjects, but its programming section is fairly nasty. Not many books and most of the few books they have are worthless. We do have a inter-library exchange here as well, but I have never used it and don't know much about it. I'll take a trip to the library sometime to ask. -- Your friend, Scott Sent to you from a Linux computer using Ubuntu Version 7.04 (Feisty Fawn) From Barry.Carroll at datalogic.com Thu Aug 2 18:56:04 2007 From: Barry.Carroll at datalogic.com (Carroll, Barry) Date: Thu, 2 Aug 2007 09:56:04 -0700 Subject: [Tutor] Design Pattern + Wxpython In-Reply-To: Message-ID: <2BBAEE949D384D40A2B851287ADB6A4307A23E5F@eugsrv400.psc.pscnet.com> > -----Original Message----- > Message: 4 > Date: Wed, 1 Aug 2007 19:01:36 +0400 > From: "Pradeep Kumar" > Subject: [Tutor] Design Pattern + Wxpython > To: tutor at python.org > Message-ID: > <76b198110708010801p5c1d9474g6b5e8d66f07b8884 at mail.gmail.com> > Content-Type: text/plain; charset="iso-8859-1" > > I am new to this and wants to do a project for Autoparts industry > (Trading) > with backend SQL Server 2000. > > 1. Which Design Pattern is suitable for me. > > Pradeep~~ > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: > http://mail.python.org/pipermail/tutor/attachments/20070801/4c91c9a0/att ac > hment-0001.html > > ------------------------------ > > Message: 5 > Date: Wed, 01 Aug 2007 21:03:08 -0400 > From: Kent Johnson > Subject: Re: [Tutor] Design Pattern + Wxpython > To: Pradeep Kumar > Cc: tutor at python.org > Message-ID: <46B12D4C.3090404 at tds.net> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > Pradeep Kumar wrote: > > I am new to this and wants to do a project for Autoparts industry > > (Trading) with backend SQL Server 2000. > > > > 1. Which Design Pattern is suitable for me. > > This one clearly applies: > http://catb.org/~esr/faqs/smart-questions.html > > Kent > > > ------------------------------ "Ouch!" True and appropriate, but "ouch" all the same. ;-) Regards, Barry barry.carroll at datalogic.com 541-302-1107 ________________________ We who cut mere stones must always be envisioning cathedrals. -Quarry worker's creed From bgailer at alum.rpi.edu Thu Aug 2 19:12:47 2007 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Thu, 02 Aug 2007 10:12:47 -0700 Subject: [Tutor] os.path.exists(path) returns false when the path actually exists! In-Reply-To: <213508.28357.qm@web50706.mail.re2.yahoo.com> References: <213508.28357.qm@web50706.mail.re2.yahoo.com> Message-ID: <46B2108F.6080803@alum.rpi.edu> Iyer wrote: > So, it was the extensions all the way ! Apparently the file extension > was hidden by Windows! It now works. I have never understood Microsoft changing things from one release to another. In the beginning extensions were IIRC always visible. Every time I configure a computer I have to spend a lot of time undoing the initial settings so my users can get their work done! -- Bob Gailer 510-978-4454 Oakland, CA 919-636-4239 Chapel Hill, NC From keridee at jayco.net Thu Aug 2 21:49:15 2007 From: keridee at jayco.net (Tiger12506) Date: Thu, 2 Aug 2007 14:49:15 -0500 Subject: [Tutor] os.path.exists(path) returns false when the path actually exists! References: <213508.28357.qm@web50706.mail.re2.yahoo.com> <46B2108F.6080803@alum.rpi.edu> Message-ID: <012501c7d53e$38af9c30$4ffce004@JSLAPTOP> > I have never understood Microsoft changing things from one release to > another. In the beginning extensions were IIRC always visible. > > Every time I configure a computer I have to spend a lot of time undoing > the initial settings so my users can get their work done! Even though I completely agree with you and detest Microsoft's decisions in these matters, here are the basic reasons: Computers are becoming more and more available for use amongst non-tech-savy individuals. Individuals who previously did not have to work with computers may now have to use them in their job for whatever reason. Microsoft would make less money if so called non-user-friendly attributes remained in their operating system. Consider: A potential computer user looks at the listing in a folder. Not quite understanding why things look the way they do, not quite understanding how these so called folders and files are supposed to look like the old paper file cabinet systems that they are used to. He sees these files with periods and strange letters. What do they mean? A file extension? What?! I don't get it, he says. You explain that the letters tell Windows which program is supposed to open the file. That doesn't make sense to him. He wonders why Windows can't just see that this is a spreadsheet, I mean look at it. It's obviously a spreadsheet! So to circumvent this confusion they hide the file extensions. Consider some other UI changes. The places bar, for example. Most programs save documents in My Documents. So where is it? Most people don't realize where they are. The file cabinets that they knew had folders yes, but never folders within folders. So Microsoft, in order to aid the new computer user provided a flattened view so that they could more easily find and understand where they are. Granted, all of these are just visual sugar and are completely worthless. But they have provided Microsoft with much money because more useless people can use computers. It is because these people do not wish to learn, do not have the capacity, or just plain would rather pay through their teeth. They would rather have Microsoft make obfuscate things, to make it "easier" for them, than to try to understand themselves. JS From alan.gauld at btinternet.com Thu Aug 2 20:53:39 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 2 Aug 2007 19:53:39 +0100 Subject: [Tutor] Which GUI? References: <20070802155200.546D4E0003A9@astro.systems.pipex.net> Message-ID: "eShopping" wrote >>Switching gears from linear to event driven programming is a pretty >>significant paradigm shift. Will this book help him get his head >>around >>that? > > Chapter 3 of WPIA gives a nice introduction to event driven > programming. But event driven programming is implicit in > all GUIs (isn't it?) Not quite, there are non Event Driven GuUIs - in fact the Python easyGUI is not Event Driven - but most are. Thats why I cover event driven programming as a sepsaate precursor to GUII porogramming in my tutorial. >> > I own a lot of computer books, and I've found Learning Python (an >> > O'Reilly Book) and wxPython in Action to be my two most useful >> > ones. I agree with most of the comments in this thread - I've been away for a few days - however I still prefer Tkinter and find it both conceptually easier and more concise in coding terms than wxPython. With the addition of Tix to the standard library there is less to choose between them in widget coverage, although wxPython definitely still has an edge. As to Tkinter documentation, there is a llarge number of books on Tk and it is fairly easy to translate from Tk speak to Tkinter. There are fewer books on wxWidgets. However the new wxPython book covers most of the ground pretty well. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From luke.jordan at gmail.com Thu Aug 2 20:51:24 2007 From: luke.jordan at gmail.com (Luke Jordan) Date: Thu, 2 Aug 2007 13:51:24 -0500 Subject: [Tutor] shelves behaving badly In-Reply-To: <46B1C028.7070201@tds.net> References: <46B1C028.7070201@tds.net> Message-ID: i think that some form of that is going on. actually there is only one shelve; that's the confusing part, there are dictionaries in that shelve though. i think it has to do with running things in IDLE and losing track of what versions of shelves and modules are active in what shell, etc etc, because i ran it again and it worked fine. it must be something to do with i screwed something up in testing and forgot about it. i haven't found a definitive answer to why it behaves this way, but so far the solution has been to confine myself to one shell and to close out and reopen everytime edits/reruns are made. thanks for the tip on checking things with os. On 8/2/07, Kent Johnson wrote: > > Luke Jordan wrote: > > i've implemented a database as a shelve of record class instances. some > > of the fields in each record are dictionaries. > > > > i needed to parse info from 3 different reports into the dictionary > > fields in each record instance. i wrote the code to do this and tinkered > > it to fit the different reports (i.e. information being in different > > columns, etc.). for 2 of the reports, it runs fine. the required info > > turns up in the shelve after i run the code, and i can exit and reenter > > python, open the shelve, and it's all still there, where it should be. > > i've quadruple checked the code for the third report, and it looks like > > it should work. in fact it runs, and reports back that it did everything > > i told it to do; this includes checking results as they occur at > > runtime. however, when i reopen the shelve, none of that data is there. > > writeback is set to True, and I didn't forget to close the shelve at the > > end of my code. > > > > Now, if I open the shelve in the same shell as the script ran in, right > > after I run it, I get the updated shelve. but any other method of > > opening the shelve results in the shelve missing the data from the third > > report. > > > > Any ideas what's going on here? > > It's pretty hard to say without seeing the code. I wonder if you are > saving the third shelve in a different location than you think you are, > and opening an old one in the other programs? Maybe check the full path > of the file you save (use os.path.abspath()) and check the modified date > of the one you open. > > Kent > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070802/fa79e6a6/attachment.html From alan.gauld at btinternet.com Thu Aug 2 21:04:35 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 2 Aug 2007 20:04:35 +0100 Subject: [Tutor] gotoxy References: <6be1291e0708010546k150e6349ud76d17ad588a89c@mail.gmail.com> Message-ID: "Robert William Hanks" wrote > hi folks, is there in python a gotoxy like in pascal so i can print > stuff > in other parts of the screen? Yes there is a port of the Borland Pascal conio library module available on the Vaults of Parnassus. Dunno how up to date it is though - it claims to work with Python 2.2... http://newcenturycomputers.net/projects/wconio.html. > what about some thing like it for the gui in windows? In a GUI go to X,Y is usually done in the context of a graphics widget like a canvas. Most GUI toolkits offer such a method. But in a GUI its less like the Pascal example in that you normally go to a widget that has been created at a location. The location may be specified as an X,Y location or more commonly in a relative location using a layout manager. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Thu Aug 2 21:05:46 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 2 Aug 2007 20:05:46 +0100 Subject: [Tutor] Design Pattern + Wxpython References: <76b198110708010801p5c1d9474g6b5e8d66f07b8884@mail.gmail.com> Message-ID: "Pradeep Kumar" wrote >I am new to this and wants to do a project for Autoparts industry >(Trading) > with backend SQL Server 2000. > > 1. Which Design Pattern is suitable for me. Most of them, but I'd consider the MVC as a starter. Alan G From anotequaltob at gmail.com Thu Aug 2 21:10:54 2007 From: anotequaltob at gmail.com (Kyle Brooks) Date: Thu, 2 Aug 2007 15:10:54 -0400 Subject: [Tutor] os.path.exists(path) returns false when the path actually exists! In-Reply-To: <012501c7d53e$38af9c30$4ffce004@JSLAPTOP> References: <213508.28357.qm@web50706.mail.re2.yahoo.com> <46B2108F.6080803@alum.rpi.edu> <012501c7d53e$38af9c30$4ffce004@JSLAPTOP> Message-ID: Hi. > Granted, all of these are just visual sugar and are completely worthless. > But they have provided Microsoft with much money because more useless people > can use computers. It is because these people do not wish to learn, do not > have the capacity, or just plain would rather pay through their teeth. They > would rather have Microsoft make obfuscate things, to make it "easier" for > them, than to try to understand themselves. > > JS Why are you making out people and Microsoft in such a negative way? Also, how is it "harder" for them when things like file extensions are obfuscated? - Kyle From alan.gauld at btinternet.com Thu Aug 2 21:11:05 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 2 Aug 2007 20:11:05 +0100 Subject: [Tutor] tree-like functions call to find dependencies References: <871weni9hz.fsf@mail.ru> Message-ID: "Maxim Loginov" wrote > my problem is: I have (for example) 2 sets of quantity set(A,B,C) or > set(A,B,D). I need to calculate another quantity E which is function > of A,B,C or A,F. but F in turn is function of (A,B,D). ... > In reality dependecies of > course deeper sets are longer and data are very big arrays ... > I will need a function indirectly depending on already > existed. I'm not sure whether it applies or not but one approach would be to use a dictionary where the keys are the required data sets and the values are the functions. Another approach is to use higher order functions that can analyse the input data set and generate a function capable of processing it. A third option might enable the use of OOP and polymorphism, provided the data can be categorized into a Liskoff compliant type heirarchy. Unfortunately its difficult to be sure without a lot more detail about the rules, the size of data and the types of data. Alan G From carroll at tjc.com Thu Aug 2 21:43:02 2007 From: carroll at tjc.com (Terry Carroll) Date: Thu, 2 Aug 2007 12:43:02 -0700 (PDT) Subject: [Tutor] [OT] Re: os.path.exists(path) returns false when the path actually exists! In-Reply-To: <012501c7d53e$38af9c30$4ffce004@JSLAPTOP> Message-ID: On Thu, 2 Aug 2007, Tiger12506 wrote: > But they have provided Microsoft with much money because more useless > people can use computers. That's a little harsh, isn't it? A person using a computer is not useless by virtue of not wanting to program or understand technical details, but rather just wanting to use it for its functional purpose. There are people in my Finance department who know much more about finance than I do, and more, I suspect, than you do. They are very useful to me and my employer by virtue of that knowledge, and if some of them don't know about Microsoft Windows file extension, well, quite frankly, who cares? They know what's important. I don't want to have to know the details of what makes my car run. All I want to do is drive it from one location to another. > It is because these people do not wish to learn, do not have the > capacity, Why should they have to learn? They just want to use the spreadsheet, for example. Why should they have to learn that the magic sequence of ".XLS", when appended to a file name, make the file work a certain way? In most contexts, the name of a thing does not determine how it works. The name is just a name. I suppose I could have a television that would require me to know to tune it to a frequency of about 69Mhz to watch a particular program; but it's just so much more convenient to me to turn to channel 4. I see that hiding of the technical details as an improvement, not a hindrance. Why should people adapt themselves to software instead of having the software adapt to them? I'm cribbing a bit from George Bernard Shaw here, who wrote something like, "The reasonable man adapts to the world; the unreasonable man adapts the world to himself. Therefore, all progress depends on the unreasonable man." From alan.gauld at btinternet.com Thu Aug 2 21:53:45 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 2 Aug 2007 20:53:45 +0100 Subject: [Tutor] os.path.exists(path) returns false when the pathactually exists! References: <213508.28357.qm@web50706.mail.re2.yahoo.com><46B2108F.6080803@alum.rpi.edu><012501c7d53e$38af9c30$4ffce004@JSLAPTOP> Message-ID: "Kyle Brooks" wrote >> would rather have Microsoft make obfuscate things, to make it >> "easier" for >> them, than to try to understand themselves. >> > Why are you making out people and Microsoft in such a negative way? JS is reflecting a commonly held view of Microsoft and their "contribution" to computing among the computing community who do not use Microsoft! I agree it is a little harsh since Microsoft are following a publickly declared policy to bring a PC to every home, but... > Also, how is it "harder" for them when things like file extensions > are > obfuscated? Its harder in the sense that by dumbing down the user experience they are making Windows less predictable to use. As was seen in this thread when a filename turned out to be bogus because there was really an extension attached. MS have brought this particular "problem" on themselves by insisting on using file extensions to associate files with applications, in fact this is not necessary and Unix, for example, can associate files with apps even with no extension. The technology to do that has been there for at least 30 years but MS persist on using their own brain-dead scheme and then trying to "fix" it for the user by hiding bits of the name. Its a bad solution to a problem which should not exist in the first place. The OS should not need to use extensions, and then the users could name the files as intuitively as they liked. I have no problem with non techie users not liking extensions, but Microsoft should have done a better fix. But Microsoft do not have a good track record of adopting good ideas from elsewhere. They are very much a "Not Invented Here" type of company and that is bad for users and bad for the industry because MS nearly always introiduce inferior alternatives to existing technologies and use their marketing dominance to force them into wide use. Leaving poor programmers like us to work with multiple standards and the users having to deal with incompatible applications and computers. Microsoft like to portray themselves as a leading light of computer development when in fact their contribution has been minimal and frequently negative. The only positive contributions I can think of offhand are the ergonomic keyboard (is it really an improvement?) and the scroll-wheel control in mice (I think most accept it as a good idea). But in software(*) and OS their added value is mostly marketing hype! I hope that explains some of the hostility often expressed by programmers towards Micro$oft. (*) Actually it could be argued that their early advocacy of Component Based software (ie COM) being superior to OOP based software has proved to be correct, but there are plenty who would disagree, or at least contend that they are complementary and not competing technologies. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From keridee at jayco.net Thu Aug 2 23:50:26 2007 From: keridee at jayco.net (Tiger12506) Date: Thu, 2 Aug 2007 16:50:26 -0500 Subject: [Tutor] os.path.exists(path) returns false when the path actually exists! References: <213508.28357.qm@web50706.mail.re2.yahoo.com> <46B2108F.6080803@alum.rpi.edu> <012501c7d53e$38af9c30$4ffce004@JSLAPTOP> Message-ID: <000c01c7d54f$26c69670$4ffce004@JSLAPTOP> >> Granted, all of these are just visual sugar and are completely worthless. >> But they have provided Microsoft with much money because more useless >> people >> can use computers. It is because these people do not wish to learn, do >> not >> have the capacity, or just plain would rather pay through their teeth. >> They >> would rather have Microsoft make obfuscate things, to make it "easier" >> for >> them, than to try to understand themselves. >> >> JS > > Why are you making out people and Microsoft in such a negative way? > Also, how is it "harder" for them when things like file extensions are > obfuscated? They would rather have Microsoft obfuscate things, to make it "easier" for *the people* not Microsoft. Why am I being negative about it? Very simply: The necessary code and provisions it takes to implement UI devices like Hiding file extensions is a waste of space, time, resources, and too many other things to count. Windows Vista is the newest OS out from Microsoft. One look at the size of the installation should be enough to tell anyone that enough is enough. Another problem I have with Windows is the paradigm "There are only 500,000 ways to do it." For example, you can change network adapter configuration by going to Control Panel, by using the SysTray icon, by using the StartMenu shortcut, by navigating to the program itself, by using Device Manager, add especially dangerous - indirectly by using the network setup wizard, etc. All of these routes waste space, and only provide minimal advantage, but manage to provide serious breaches of understanding. I know I am not the only one who has tried to find why a network adapter doesn't work, only to find that an important setting was comprimised when running one of the handy "It does everything!" UIs. I don't know if you are one of those people that loves those all-in-one screwdrivers, but I find that pieces of them get lost, they are bulky, and when it comes right down to it, all I want to do is use the simple, light, and specialised screwdrivers. Why? Because they are faster, stronger, and more stable. Is that good enough? Why am I upset with people? Because they want "ease of use", I must buy bigger hard drives, and more ram. Because Microsoft has determined that media is more important to the mass population than performance, I have to fight to get my Windows installation to stop initiating the time-consuming Autoplay feature, or I have to jump through hoops to cut off the Windows Messenger just because I don't want to use it. Or I have to search through numerous wizards and settings to try to find where I can shut-up Windows Update. Yes, maybe I want it to update, but I don't want it to bother me! I have work to do. No I don't need "troubleshooting help". Give me a damn RFC. No, there is no big massive error, I just need to find where my program is using an invalid pointer. Why can't these changes be something useful? A great example. Such and such module is linked to missing export such and such. Okay. But you are preventing me from using the program! The Windows Loader provides API addresses at load time anyway, so why isn't there an option to redirect the API? It would take a hell of a lot less resource space than implementing some of the visual junk that makes "managing media" "so easy". I apologize for my bringing up these beliefs on this list. They are better placed in a blog somewhere, or more efficiently, in a zip file of ASCII text as small and as neat as possible. JS From keridee at jayco.net Fri Aug 3 00:35:21 2007 From: keridee at jayco.net (Tiger12506) Date: Thu, 2 Aug 2007 17:35:21 -0500 Subject: [Tutor] [OT] Re: os.path.exists(path) returns false when the path actually exists! References: Message-ID: <001f01c7d555$6d0be120$4ffce004@JSLAPTOP> >> But they have provided Microsoft with much money because more useless >> people can use computers. > > That's a little harsh, isn't it? A person using a computer is not useless > by virtue of not wanting to program or understand technical details, but > rather just wanting to use it for its functional purpose. There are > people in my Finance department who know much more about finance than I > do, and more, I suspect, than you do. They are very useful to me and my > employer by virtue of that knowledge, and if some of them don't know > about Microsoft Windows file extension, well, quite frankly, who cares? > They know what's important. Very well. > I don't want to have to know the details of what makes my car run. All I > want to do is drive it from one location to another. And one day your car doesn't start. So you blindly take it to a car mechanic (or even the dealership~shudder) where they hook it up to a battery charger, send it back and charge you $300. Right. Not important to you. I wish I could throw away that kind of security. >> It is because these people do not wish to learn, do not have the >> capacity, > > Why should they have to learn? They just want to use the spreadsheet, for > example. Why should they have to learn that the magic sequence of ".XLS", > when appended to a file name, make the file work a certain way? In most > contexts, the name of a thing does not determine how it works. The name > is just a name. Why? Because it's a good idea. The name of the thing does not determine how it works. But it does determine how it works in Windows. I do not expect them to understand *why* the magic sequence of .xls causing this file to open in Excel. I expect them to overlook it. I expect them to accept them. I do not think it's appropriate that Microsoft should baby them by hiding the extensions by default. > I suppose I could have a television that would require me to know to tune > it to a frequency of about 69Mhz to watch a particular program; but it's > just so much more convenient to me to turn to channel 4. I see that > hiding of the technical details as an improvement, not a hindrance. Did I say I wanted people to know just what extension is what? Did I say that they have to parse the .xls file for Excel? No. I ask that they learn to accept it. Just like I would ask them to accept a slip of paper taped to the TV that lists all of the frequencies mapped to the channels. I would not ask them to use the table of frequencies to tune the TV. They may use the channels. But the table would be there, visible, not hidden away where potentially someone who needs it might not be able to find it. On the other hand, do you want a neural transmitter installed in you so that you can more easily change the channel? Hey ~ you wouldn't even have to know which channel you want to watch. All you would have to do is know *what* you want to watch. Wouldn't that be excellent? It's like looking all over the living room for the TV remote because you don't know how to change the channel using the TV. > Why should people adapt themselves to software instead of having the > software adapt to them? I'm cribbing a bit from George Bernard Shaw here, > who wrote something like, "The reasonable man adapts to the world; the > unreasonable man adapts the world to himself. Therefore, all progress > depends on the unreasonable man." Why should computer people have to adapt to user-friendly software? From dkuhlman at rexx.com Thu Aug 2 23:55:31 2007 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Thu, 2 Aug 2007 14:55:31 -0700 Subject: [Tutor] Which GUI? In-Reply-To: <46B20AC5.6030903@rogers.com> References: <46B20AC5.6030903@rogers.com> Message-ID: <20070802215531.GB24269@cutter.rexx.com> On Thu, Aug 02, 2007 at 12:48:05PM -0400, scott wrote: > > We do have a inter-library exchange here as well, but I have never used > it and don't know much about it. I'll take a trip to the library > sometime to ask. > For sure, even if you *don't* need the wxPython book, check into the inter-library or inter-branch transfer program. And, also ask about Internet access. Here in Sacramento, California, USA, when I need a book, my first action is to go to http://saclibrary.org/ and do a search. If the book is not at my local (small) branch library but is in the Sacramento county library system, I click on request and tell them which branch to deliver it to. I believe that they have a truck that is constantly traveling between branches to deliver the inter-branch transfers. It's a super system. I visited the libraries in Vancouver, B.C. and Victoria, B.C. several years ago, and they were at least as advanced as ours here. Be sure to check that out. Wherever you are in Canada, be sure to check into it. By the way, my librarian tells me that they do this because it both saves them money (by not having to have copies at all branches) and enables them to afford to offer more titles. (Sorry for off-topic post. I'm a library "true believer".) Dave > -- > Your friend, > Scott > > Sent to you from a Linux computer using Ubuntu Version 7.04 (Feisty Fawn) > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Dave Kuhlman http://www.rexx.com/~dkuhlman From kent37 at tds.net Thu Aug 2 23:57:28 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 02 Aug 2007 17:57:28 -0400 Subject: [Tutor] os.path.exists(path) returns false when the path actually exists! In-Reply-To: <000c01c7d54f$26c69670$4ffce004@JSLAPTOP> References: <213508.28357.qm@web50706.mail.re2.yahoo.com> <46B2108F.6080803@alum.rpi.edu> <012501c7d53e$38af9c30$4ffce004@JSLAPTOP> <000c01c7d54f$26c69670$4ffce004@JSLAPTOP> Message-ID: <46B25348.3060902@tds.net> Tiger12506 wrote: > I apologize for my bringing up these beliefs on this list. They are better > placed in a blog somewhere, or more efficiently, in a zip file of ASCII text > as small and as neat as possible. Yes, thanks. Could we stop the Microsoft bashing - or whatever you want to call it - please? There are plenty of other places for such discussions. Thanks, Kent From john at fouhy.net Fri Aug 3 00:07:58 2007 From: john at fouhy.net (John Fouhy) Date: Fri, 3 Aug 2007 10:07:58 +1200 Subject: [Tutor] sqlite: does "?" work in PRAGMA commands? In-Reply-To: References: <5e58f2e40708020022x70ae00bev788a651e3ca133e7@mail.gmail.com> Message-ID: <5e58f2e40708021507w6de5eb2ela5c65fbfc7bbea48@mail.gmail.com> On 03/08/07, Terry Carroll wrote: > On Thu, 2 Aug 2007, John Fouhy wrote: > > > I'm not sure about PRAGMA, but you can do introspection in sqlite by > > examining the table 'sqlite_master'. > > Thanks. That's how I get the table names, actually. But it doesn't give > the column names. It gives you the CREATE statement; you could just parse that :-) -- John. From keridee at jayco.net Fri Aug 3 02:23:21 2007 From: keridee at jayco.net (Tiger12506) Date: Thu, 2 Aug 2007 19:23:21 -0500 Subject: [Tutor] Which GUI? References: <46B20AC5.6030903@rogers.com> <20070802215531.GB24269@cutter.rexx.com> Message-ID: <000601c7d564$85c67450$32fce004@JSLAPTOP> I did that once for a very good fiction book I wanted to read. <$2. for transfer. It was worth it to me. Agreed. Definitely a good system. JS > On Thu, Aug 02, 2007 at 12:48:05PM -0400, scott wrote: >> >> We do have a inter-library exchange here as well, but I have never used >> it and don't know much about it. I'll take a trip to the library >> sometime to ask. >> > > For sure, even if you *don't* need the wxPython book, check into > the inter-library or inter-branch transfer program. And, also ask > about Internet access. Here in Sacramento, California, USA, when I > need a book, my first action is to go to http://saclibrary.org/ and > do a search. If the book is not at my local (small) branch library > but is in the Sacramento county library system, I click on request > and tell them which branch to deliver it to. I believe that they > have a truck that is constantly traveling between branches to > deliver the inter-branch transfers. It's a super system. > > I visited the libraries in Vancouver, B.C. and Victoria, B.C. > several years ago, and they were at least as advanced as ours here. > Be sure to check that out. Wherever you are in Canada, be sure to > check into it. > > By the way, my librarian tells me that they do this because it both > saves them money (by not having to have copies at all branches) and > enables them to afford to offer more titles. > > (Sorry for off-topic post. I'm a library "true believer".) > > Dave > >> -- >> Your friend, >> Scott >> >> Sent to you from a Linux computer using Ubuntu Version 7.04 (Feisty Fawn) >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor > > -- > Dave Kuhlman > http://www.rexx.com/~dkuhlman > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From Andy.cheesman at bristol.ac.uk Fri Aug 3 11:35:11 2007 From: Andy.cheesman at bristol.ac.uk (Andy Cheesman) Date: Fri, 03 Aug 2007 10:35:11 +0100 Subject: [Tutor] Issue with iterating within lists, objects and functions Message-ID: <46B2F6CF.3050202@bristol.ac.uk> Dear people, Sorry for the vague title, I'm struggling to define the problem but an example will be better/clearer. If I've a list of strings, which relate to objects(lists) elsewhere in my code, I can call list action fine within the loop but I was wondering how do I apply an external function as shown below? e.g for thing in ["top", "right", "bottom", "left"]: eval("self." + thing).append("fish") eval("self." + thing +"_extra") eval("self." + thing) = external_function(eval("self." + thing)) #This falls Thanks for your help Andy From kent37 at tds.net Fri Aug 3 13:06:19 2007 From: kent37 at tds.net (Kent Johnson) Date: Fri, 03 Aug 2007 07:06:19 -0400 Subject: [Tutor] Issue with iterating within lists, objects and functions In-Reply-To: <46B2F6CF.3050202@bristol.ac.uk> References: <46B2F6CF.3050202@bristol.ac.uk> Message-ID: <46B30C2B.50105@tds.net> Andy Cheesman wrote: > for thing in ["top", "right", "bottom", "left"]: > eval("self." + thing).append("fish") You don't need to use eval() here, use getattr() instead: getattr(self, thing).append('fish') > eval("self." + thing +"_extra") > eval("self." + thing) = external_function(eval("self." + thing)) #This > falls It would help if you said *how* it fails - the specific error message and traceback. I guess it is failing on the left side of the assignment, not the function call. The result of eval("self." + thing) is the value of self.thing, not an assignable reference. You should use getattr() and setattr() here: new_value = external_function(getattr(self, thing)) setattr(self, thing, new_value) or in one line if you like: setattr(self, thing, external_function(getattr(self, thing))) http://docs.python.org/lib/built-in-funcs.html Kent From tony.sales at rncb.ac.uk Fri Aug 3 11:02:13 2007 From: tony.sales at rncb.ac.uk (Anthony Sales) Date: Fri, 3 Aug 2007 10:02:13 +0100 Subject: [Tutor] ossaudiodev, pygtk, and flushing buffers In-Reply-To: 20060511191552.593fa91c.klappnase@freenet.de Message-ID: <1186131733.7656.2.camel@drbongo-vaio> Matthew, I am also experimenting with ossaudiodev with python and was having the same problem on my laptop, but not on my desktop - the reset() method has solved this problem. However I want to be able to pause the played file before it ends, but all the controls seem to be locked until the sound has finished playing. Could you advise me of a way to interrupt the playing of a file? Tony Sales. From Andy.cheesman at bristol.ac.uk Fri Aug 3 14:20:53 2007 From: Andy.cheesman at bristol.ac.uk (Andy Cheesman) Date: Fri, 03 Aug 2007 13:20:53 +0100 Subject: [Tutor] Issue with iterating within lists, objects and functions In-Reply-To: <46B30C2B.50105@tds.net> References: <46B2F6CF.3050202@bristol.ac.uk> <46B30C2B.50105@tds.net> Message-ID: <46B31DA5.6090001@bristol.ac.uk> Thanks for your help Kent The error was that I was trying to assign to a non-assignable reference as you highlighted. Everything works now Thanks Andy Kent Johnson wrote: > Andy Cheesman wrote: >> for thing in ["top", "right", "bottom", "left"]: >> eval("self." + thing).append("fish") > > You don't need to use eval() here, use getattr() instead: > getattr(self, thing).append('fish') > >> eval("self." + thing +"_extra") >> eval("self." + thing) = external_function(eval("self." + thing)) >> #This >> falls > > It would help if you said *how* it fails - the specific error message > and traceback. I guess it is failing on the left side of the assignment, > not the function call. The result of eval("self." + thing) is the value > of self.thing, not an assignable reference. You should use getattr() and > setattr() here: > > new_value = external_function(getattr(self, thing)) > setattr(self, thing, new_value) > > or in one line if you like: > setattr(self, thing, external_function(getattr(self, thing))) > > http://docs.python.org/lib/built-in-funcs.html > > Kent > From rabidpoobear at gmail.com Fri Aug 3 15:23:18 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Fri, 03 Aug 2007 08:23:18 -0500 Subject: [Tutor] [OT] Re: os.path.exists(path) returns false when the path actually exists! In-Reply-To: <001f01c7d555$6d0be120$4ffce004@JSLAPTOP> References: <001f01c7d555$6d0be120$4ffce004@JSLAPTOP> Message-ID: <46B32C46.1010808@gmail.com> > >> I don't want to have to know the details of what makes my car run. All I >> want to do is drive it from one location to another. >> > > And one day your car doesn't start. So you blindly take it to a car mechanic > (or even the dealership~shudder) where they hook it up to a battery charger, > send it back and charge you $300. Right. Not important to you. I wish I > could throw away that kind of security. > That's not really the same at all. In the context of a large company, there is almost definitely an IT staff on retainer set up to fix the computers at all times with no cost to the individual. So the finance people's computer breaks, and someone comes to fix it for them. Yes, you could argue that if the staff were trained enough, the IT department wouldn't need to be as large, etc. etc. but the basic fact is that there are certain people who it's not cost-effective for companies to train to the level where they can fix any problem that arises in their use of the computer, and it's much cheaper to just train one guy (who can learn quickly) how to do the repairs quickly and efficiently and then have everyone defer to him. >>> It is because these people do not wish to learn, do not have the >>> capacity, >>> >> Why should they have to learn? They just want to use the spreadsheet, for >> example. Why should they have to learn that the magic sequence of ".XLS", >> when appended to a file name, make the file work a certain way? In most >> contexts, the name of a thing does not determine how it works. The name >> is just a name. >> > > Why? Because it's a good idea. The name of the thing does not determine how > it works. But it does determine how it works in Windows. I do not expect > them to understand *why* the magic sequence of .xls causing this file to > open in Excel. I expect them to overlook it. I expect them to accept them. I > do not think it's appropriate that Microsoft should baby them by hiding the > extensions by default. > I think this is similar to the backslash thing in Windows. First-time Windows developers get tripped up because backslashes are the chosen escape-sequence for strings, to encode ascii values in them. But forward-slashes could've been the escape sequence too. It's pretty arbitrary. They used backslashes in DOS, so they continued to use them in future versions of their OS. Or the carriage returns. \r means return to the beginning of the line, \n means go to the next line. So \r\n is a logical way to make a backslash, because it goes to the next line, and returns to the beginning (so you don't start typing off in space.) That's how Windows does it, but *nix does it using just \n, and Mac does it using just \r. People argue that Windows' way of doing it is worse, but really, it makes the most sense as far as the ascii control codes go. Yes, it's a few characters longer, but it's mostly irrelevant. Then, for file extensions: Microsoft chose to use file extensions to determine which program would run a given type of file. All of these things could be considered design flaws, but the point is that they were used in every version of Microsoft's operating system, and thus they need to continue to be consistent, or a whole lot of software will break. So Microsoft realizes that a majority of their users don't need to see the extensions. So they hide them by default in the GUI. That doesn't mean that developers don't have access to the full filename. Sure we do. It doesn't affect how our programs run. The only fault is believing that the GUI is a completely accurate representation of the filesystem. Which it's not. You might say "OH, BUT IT SHOULD BE!" well, when you're using a GUI file browser on a Linux system, it may not show you the write permissions to every file and directory. Or it may not differentiate between symbolic links and actual files. That's because, to the extent that the GUI is used, this knowledge is largely unnecessary. If you try to delete a file you don't have permission to, a little popup will come up saying "Sorry, you don't have permission to delete this file!" As for Windows, it may be easier for people to see launching a shortcut to 'Notepad' and then clicking 'File > Open' and choosing their file as analogous to just double-clicking the file in their GUI. And in this environment, this is represented by an icon of a notepad, just as the 'Notepad' shortcut is. Do you think that the 'Notepad' shortcut should say "%SystemRoot%\system32\notepad.exe" instead? I think that would confuse a lot of people! So a developer gets confused about the file path. This is an unfortunate side-effect. But if thousands of people find the computer more accessible in exchange for one developer getting confused and then realizing his mistake and never making it again, well, the choice is obviously (from a business standpoint) to hide the extension. >> I suppose I could have a television that would require me to know to tune >> it to a frequency of about 69Mhz to watch a particular program; but it's >> just so much more convenient to me to turn to channel 4. I see that >> hiding of the technical details as an improvement, not a hindrance. >> > > Did I say I wanted people to know just what extension is what? Did I say > that they have to parse the .xls file for Excel? No. I ask that they learn > to accept it. Just like I would ask them to accept a slip of paper taped to > the TV that lists all of the frequencies mapped to the channels. I would not > ask them to use the table of frequencies to tune the TV. They may use the > channels. But the table would be there, visible, not hidden away where > potentially someone who needs it might not be able to find it. > And should my stereo system come with a manual attached to it at all times that details soldering transistors and an explanation of electrical theory? Your argument can be extended to gross extremes, and it doesn't hold up. The interface I use to interact with my stereo, a system of knobs and such, is what I need to know in order to get my stereo to do what I need it to. If it breaks, maybe I go buy a service manual and fix it, or maybe I recognize that the time it would take me to learn the intricacies of the electronics is greater than the cost if I have a professional fix it. But largely, I just need to understand the interface. Not the technical implementation. Note that I just don't like your argument, not that I disagree with you. > On the other hand, do you want a neural transmitter installed in you so that > you can more easily change the channel? Hey ~ you wouldn't even have to know > which channel you want to watch. All you would have to do is know *what* you > want to watch. Wouldn't that be excellent? It's like looking all over the > living room for the TV remote because you don't know how to change the > channel using the TV. > You know, I can see a lot of people going for that. Hey, if I could just hook directly to a computer and 'think' what I wanted to program, and I didn't have to rapidly press a series of buttons for the computer to understand me, I'd be all for it. (The assumption here is that it's safe, etc.) But that's not the issue here. The reason you hate the extension-hiding is because it makes interacting with the computer at a lower level than the GUI confusing to you, when you are viewing the system at the level of the GUI. If you view the system at the same level as you're interacting with it, there is no issue here. That's the key idea. You're making faulty assumptions based on a view of the filesystem that's different from the view your program sees when it's running. Base your view on what your program sees and there will be no problem. >> Why should people adapt themselves to software instead of having the >> software adapt to them? I'm cribbing a bit from George Bernard Shaw here, >> who wrote something like, "The reasonable man adapts to the world; the >> unreasonable man adapts the world to himself. Therefore, all progress >> depends on the unreasonable man." >> > > Why should computer people have to adapt to user-friendly software? > Because you (singular) program the software for them (plural.) There are more users than developers. They are the ones who need to understand it. Why should the computer have to be able to compile your C++ code or interpret your Python code? Why shouldn't you have to speak to it in machine language? Terry's quote embodies these. The early Computer Science pioneers were disdainful of FORTRAN. "It'll never be able to craft assembly that's nearly as efficient as what WE write by hand." Then it turned out it did. Then when Python came along, some C programmers were heard saying "Ah, but it'll never run as fast as our C programs will!" But then the world came to realize that the fact remains that the computers are constantly increasing in speed of execution, and humans are not. So we've reached the level where the shift occurs from increasing computing efficiency to increasing user efficiency. And the more user-friendly the software is, the more user-efficient the resulting interaction will be. P.S. Why don't I ever see Linux-bashing on this list? -Luke From queprime at gmail.com Fri Aug 3 18:07:37 2007 From: queprime at gmail.com (Que Prime) Date: Fri, 3 Aug 2007 09:07:37 -0700 Subject: [Tutor] Parsing several files Message-ID: <17285ccf0708030907s32edc7b3p16a537efc5e4a69f@mail.gmail.com> With the help of a tutor I was able to get the following code to work the way I want, but I'd like for it to parse through several files in one folder and create one output file. I'm thinking I need to add something like: def grab_files(files = []): found = [] if files != None: Here is the original: import re infile = open("in.txt","r") outfile = open("out.txt","w") patt = re.compile(r'.*src=([\d\.]*) dst=(10.52.10.10.*)') for line in infile: m = patt.match(line) if m: outfile.write('src=%s dst=%s\n' % m.groups()) infile.close() outfile.close() -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070803/50793698/attachment.html From rabidpoobear at gmail.com Fri Aug 3 18:24:34 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Fri, 03 Aug 2007 11:24:34 -0500 Subject: [Tutor] Parsing several files In-Reply-To: <17285ccf0708030907s32edc7b3p16a537efc5e4a69f@mail.gmail.com> References: <17285ccf0708030907s32edc7b3p16a537efc5e4a69f@mail.gmail.com> Message-ID: <46B356C2.50902@gmail.com> Que Prime wrote: > > With the help of a tutor I was able to get the following code to work > the way I want, but I'd like for it to parse through several files in > one folder and create one output file. > > I'm thinking I need to add something like: > > def grab_files(files = []): Default values are created when the function object is created, not on each call. So given this: def test(a = []): a.append(5) print a it works how you'd think it would for a passed list: >>> x = [] >>> test(x) [5] >>> test(x) [5, 5] >>> x [5, 5] But when you don't pass it a value, >>> test() [5] >>> test() [5, 5] >>> test() [5, 5, 5] As you can see, the default value isn't constant at []. So if you do any operations on the default value, you should do something like this instead: def test(a=None): if a == None: a = [] which will give you the behavior you probably expected. Other than that, I would suggest doing it like this: files = ['a','b','c'] #construct this however you want outfile = open('output','w') for filename in files: for line in open(filename): #do your regular pattern matching stuff here. outfile.close() You can put this in a function but if this is all your code does then I don't see the point of making a function, it would just make the logic harder to follow. I believe that the 'for line in open(filename):' will automatically read in the file and then close the file stream, but you may want to check that it does close the file. Code untested. -Luke From alej0varas at gmail.com Fri Aug 3 19:33:43 2007 From: alej0varas at gmail.com (alejandro varas) Date: Fri, 3 Aug 2007 17:33:43 +0000 Subject: [Tutor] curses In-Reply-To: <629446A1-721A-4A7A-AF35-4226520D7A2B@gmail.com> References: <629446A1-721A-4A7A-AF35-4226520D7A2B@gmail.com> Message-ID: <84391c2a0708031033w720ac1cdl2ff5f181b8bd0228@mail.gmail.com> maybe dis is what you want to do. Ijust made some changes to the code. On 7/17/07, max baseman wrote: > > hello all sorry to bother I'm working on my first curses program ive > been wanting to learn curses for a while now and now that a have a > lop top with fedora core running in run level 3 ware im trying to > program all the tools i'll use but curses will be my only gui ALAN > has been helping me with this program > > import curses > from time import sleep > scr=curses.initscr() > population=0 > seconds=0 > try: > scr.nodelay(1) > scr.leaveok(0) > max_y, max_x = scr.getmaxyx() > while 1: > sleep(1) > second=seconds=+1 population=population+2.5 > scr.addstr(0,0,"seconds",seconds) scr.addch,max_y/2, max_x/2, str(population)[0] scr.refresh() > finally: > curses.endwin() > > > depending on ware i run this i get different results on may mac OSX > 10.4 i only get a wired second thing in the top left corner that > looks like this secooes > > and when i run this on fedora core 6 i get the seconds word in top > left but no number and i get a single digit in the midle that changes > i think the single digit is part of population but not all i cant > find out what is wrong > > > any help would be great :) > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Alejandro Varas G. T.N.S. en Redes de Computadores. http://alej0varas.googlepages.com +56984350861 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070803/957ad43e/attachment.html -------------- next part -------------- A non-text attachment was scrubbed... Name: asdf.py Type: text/x-python Size: 516 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20070803/957ad43e/attachment-0001.py From jjcrump at myuw.net Fri Aug 3 20:09:40 2007 From: jjcrump at myuw.net (Jon Crump) Date: Fri, 3 Aug 2007 11:09:40 -0700 (PDT) Subject: [Tutor] more encoding confusion Message-ID: I'm parsing a utf-8 encoded file with lines characterized by placenames in all caps thus: HEREFORD, Herefordshire. ..other lines.. H?RON (LE), Normandie. ..other lines.. I identify these lines for parsing using for line in data: if re.match(r'[A-Z]{2,}', line): but of course this catches HEREFORD, but not H?RON. What sort of re test can I do to catch lines whose defining characteristic is that they begin with two or more adjacent utf-8 encoded capital letters? From kent37 at tds.net Fri Aug 3 21:13:00 2007 From: kent37 at tds.net (Kent Johnson) Date: Fri, 03 Aug 2007 15:13:00 -0400 Subject: [Tutor] more encoding confusion In-Reply-To: References: Message-ID: <46B37E3C.6060905@tds.net> Jon Crump wrote: > I'm parsing a utf-8 encoded file with lines characterized by placenames > in all caps thus: > > HEREFORD, Herefordshire. > ..other lines.. > H?RON (LE), Normandie. > ..other lines.. > > I identify these lines for parsing using > > for line in data: > if re.match(r'[A-Z]{2,}', line): > > but of course this catches HEREFORD, but not H?RON. > > What sort of re test can I do to catch lines whose defining > characteristic is that they begin with two or more adjacent utf-8 > encoded capital letters? First you have to decode the file to a Unicode string. Then build the set of matching characters and build a regex. For example, something like this: data = open('data.txt').read().decode('utf-8').splitlines() uppers = u''.join(unichr(i) for i in xrange(sys.maxunicode) if unichr(i).isupper()) upperRe = u'^[%s]{2,}' % uppers for line in data: if re.match(upperRe, line): With a tip of the hat to http://tinyurl.com/yrl8cy Kent From pytutmail at gmail.com Fri Aug 3 21:43:26 2007 From: pytutmail at gmail.com (Toon Pieton) Date: Fri, 3 Aug 2007 21:43:26 +0200 Subject: [Tutor] Float and decimal spaces Message-ID: <7c3104d20708031243p5a527771hd9e93d2382da90ed@mail.gmail.com> Hey all! My memory seem to have a horrible leak. How does one limit the amount of decimal spaces for a float? I used to know that... Example: not 5.398042156, but 5.4 (if I decide to have only one place). Thanks in advance! Toon Pieton. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070803/350a9e95/attachment.htm From rabidpoobear at gmail.com Fri Aug 3 22:05:23 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Fri, 03 Aug 2007 15:05:23 -0500 Subject: [Tutor] Float and decimal spaces In-Reply-To: <7c3104d20708031243p5a527771hd9e93d2382da90ed@mail.gmail.com> References: <7c3104d20708031243p5a527771hd9e93d2382da90ed@mail.gmail.com> Message-ID: <46B38A83.3040406@gmail.com> Toon Pieton wrote: > Hey all! > > My memory seem to have a horrible leak. How does one limit the amount > of decimal spaces for a float? I used to know that... > > Example: not 5.398042156, but 5.4 (if I decide to have only one place). Usually you do this during display, while you leave the actual value untouched. >>> '%f' % 4.55 '4.550000' >>> '%.1f' % 4.55 '4.5' >>> '%.2f' % 4.55 '4.55' > > Thanks in advance! > Toon Pieton. > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Sat Aug 4 05:00:08 2007 From: kent37 at tds.net (Kent Johnson) Date: Fri, 03 Aug 2007 23:00:08 -0400 Subject: [Tutor] Issue with iterating within lists, objects and functions In-Reply-To: <46B3C345.1090703@bigfoot.com> References: <46B2F6CF.3050202@bristol.ac.uk> <46B30C2B.50105@tds.net> <46B3C345.1090703@bigfoot.com> Message-ID: <46B3EBB8.8080103@tds.net> Ricardo Ar?oz wrote: > Kent Johnson wrote: >> Andy Cheesman wrote: >>> for thing in ["top", "right", "bottom", "left"]: >>> eval("self." + thing).append("fish") >> You don't need to use eval() here, use getattr() instead: >> getattr(self, thing).append('fish') >> > > What if you want to do : > MyObj = 1 > myStr = 'MyObj' > eval('MyObj') = 125 Usually a dictionary is the right solution, instead of a named variable. values = {'MyObj' : 1} values[myStr] = 125 Kent From kent37 at tds.net Sat Aug 4 14:33:07 2007 From: kent37 at tds.net (Kent Johnson) Date: Sat, 04 Aug 2007 08:33:07 -0400 Subject: [Tutor] Float and decimal spaces In-Reply-To: <7c3104d20708031243p5a527771hd9e93d2382da90ed@mail.gmail.com> References: <7c3104d20708031243p5a527771hd9e93d2382da90ed@mail.gmail.com> Message-ID: <46B47203.4090806@tds.net> Toon Pieton wrote: > Hey all! > > My memory seem to have a horrible leak. How does one limit the amount of > decimal spaces for a float? I used to know that... > > Example: not 5.398042156, but 5.4 (if I decide to have only one place). For printing, use %.1f : In [2]: print '%.1f' % 5.398042156 5.4 If you want to limit the precision of computations maybe the Decimal module would help. Kent From sli1que at yahoo.com Sat Aug 4 15:43:49 2007 From: sli1que at yahoo.com (Eric Walker) Date: Sat, 4 Aug 2007 06:43:49 -0700 (PDT) Subject: [Tutor] Float and decimal spaces In-Reply-To: <46B47203.4090806@tds.net> Message-ID: <860634.70654.qm@web60124.mail.yahoo.com> --- Kent Johnson wrote: > Toon Pieton wrote: > > Hey all! > > > > My memory seem to have a horrible leak. How does > one limit the amount of > > decimal spaces for a float? I used to know that... > > > > Example: not 5.398042156, but 5.4 (if I decide to > have only one place). > > For printing, use %.1f : > > In [2]: print '%.1f' % 5.398042156 > 5.4 > > If you want to limit the precision of computations > maybe the Decimal > module would help. > > Kent > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor You can try this: >>> test 5.3980421559999998 >>> print '%.2f' % (test) 5.40 >>> The number gives the number of precision after the decimal. Eric ____________________________________________________________________________________ Moody friends. Drama queens. Your life? Nope! - their life, your story. Play Sims Stories at Yahoo! Games. http://sims.yahoo.com/ From tnoyeaux at msn.com Sat Aug 4 17:34:52 2007 From: tnoyeaux at msn.com (Tony Noyeaux) Date: Sat, 4 Aug 2007 11:34:52 -0400 Subject: [Tutor] Python Editors .. which do you reccomend for a amateur? Message-ID: I've been using Python IDLE,.. tried DrPython,.. had a try of ActiveState Komodo IDE, Active Python,... What is a good python editor to use. I've seen good and bad with all of the above from my newcomer perspective.. wondering what other feel is a good editor to use... when you're new to python? Tony Noyeaux _________________________________________________________________ Learn. Laugh. Share. Reallivemoms is right place! http://www.reallivemoms.com?ocid=TXT_TAGHM&loc=us -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070804/5db0339a/attachment.htm From rob.andrews at gmail.com Sat Aug 4 17:50:02 2007 From: rob.andrews at gmail.com (Rob Andrews) Date: Sat, 4 Aug 2007 10:50:02 -0500 Subject: [Tutor] Python Editors .. which do you reccomend for a amateur? In-Reply-To: References: Message-ID: <8d757d2e0708040850t705350b8oa2a5e740fe0971db@mail.gmail.com> A fair enough and frequently-asked question... I take it you're in a Windows environment? For basic editing purposes, I'm pretty crazy about IDLE after all these years, although I use Komodo IDE for most of my production code. When the other programmers in my department tasked me with picking a standard for use in the department this week, I settled on the standard Windows distro from python.org with IDLE because it's consistently straight-forward & predictable in behavior. For ease of use beyond a certain level of sophistication, however, I go straight to Komodo IDE without meaningful complaint. Part of my reasoning for that, though, is that it enables me to use the same familiar environment for python, perl, javascript & PHP. -Rob On 8/4/07, Tony Noyeaux wrote: > > I've been using Python IDLE,.. tried DrPython,.. had a try of ActiveState > Komodo IDE, Active Python,... > > What is a good python editor to use. I've seen good and bad with all of the > above from my newcomer perspective.. wondering what other feel is a good > editor to use... when you're new to python? > > > Tony Noyeaux From rabidpoobear at gmail.com Sat Aug 4 17:52:21 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sat, 04 Aug 2007 10:52:21 -0500 Subject: [Tutor] Python Editors .. which do you reccomend for a amateur? In-Reply-To: References: Message-ID: <46B4A0B5.5030501@gmail.com> Tony Noyeaux wrote: > I've been using Python IDLE,.. tried DrPython,.. had a try of > ActiveState Komodo IDE, Active Python,... > > What is a good python editor to use. I've seen good and bad with all > of the above from my newcomer perspective.. wondering what other feel > is a good editor to use... when you're new to python? Well, I've tried a few editors, but since I swicth computers a lot, some of which are Windows, where Vi and Emacs have to be installed separately, I usually end up using IDLE. Been using Python for 3 or 4 years now, and that's the editor that's by far seen the most use by me. I'm sure there are some features in other development tools that might speed up my programming a little bit, but since I'm in University right now, and all my classes use C++, I don't have the time to dedicate to Python to learn more powerful tools. > > > Tony Noyeaux > > ------------------------------------------------------------------------ > New home for Mom, no cleanup required. All starts here. > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at btinternet.com Sat Aug 4 20:54:34 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 4 Aug 2007 19:54:34 +0100 Subject: [Tutor] Python Editors .. which do you reccomend for a amateur? References: Message-ID: "Tony Noyeaux" wrote > I've been using Python IDLE,.. > tried DrPython,.. had a try of ActiveState Komodo IDE, > Active Python,... Of the basic editors I favour Pythonwin and AlaMode The former comes with the windows extensions (standard in the activepython distro) and the latter with wxpython. ALaMode is my current favourite because it has the wonderful PyCrust shell and tabbed editing windows, features which neither IDLE nor Pythonwin can support. And the editor is the fabulous Scintilla widget used in several other IDEs, including Pythonwin. I've played with PyDev on Eclipse and I lve the debugger but the lack of a >>> prompt is a limitation and its a slow starter and quite resource hungry. However for serious programming I'm still using my original setup of vim and a couple of OS shell windows, one for running the program and one for a >>> prompt. However I increasingly substitute PyCrust nstead of the vanilla >>> prompt. vim is just too powerful an editor compared to even scintilla that I can't live without the features for long (multi hour) sessions. PS There must be a FAQ page on this somewhere? It gets asked so often... HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From bgailer at alum.rpi.edu Sat Aug 4 21:11:26 2007 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Sat, 04 Aug 2007 12:11:26 -0700 Subject: [Tutor] Python Editors .. which do you reccomend for a amateur? In-Reply-To: References: Message-ID: <46B4CF5E.8040401@alum.rpi.edu> Alan Gauld wrote: > AlaMode > I have googled without success. Where do I find AlaMode? -- Bob Gailer 510-978-4454 Oakland, CA 919-636-4239 Chapel Hill, NC From seem at gazeta.pl Sat Aug 4 21:51:47 2007 From: seem at gazeta.pl (Lukasz) Date: Sat, 04 Aug 2007 21:51:47 +0200 Subject: [Tutor] Python Editors .. which do you reccomend for a amateur? In-Reply-To: <46B4CF5E.8040401@alum.rpi.edu> References: <46B4CF5E.8040401@alum.rpi.edu> Message-ID: <46B4D8D3.7060305@gazeta.pl> U?ytkownik Bob Gailer napisa?: > I have googled without success. Where do I find AlaMode? AlaMode is part of wxpython; for me it's valuable as a shell for interactive sessions, provides many informations how my program (and Python) really works, and have auto completion; very helpfull when I get stuck with stupid mistakes -- Opole - Miasto Bez Granic. http://www.opole.pl - tu znajdziesz nowe miejsca, nowe mozliwosci, nowe inspiracje... From dkuhlman at rexx.com Sat Aug 4 22:43:05 2007 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Sat, 4 Aug 2007 13:43:05 -0700 Subject: [Tutor] Python Editors .. which do you reccomend for a amateur? In-Reply-To: <46B4CF5E.8040401@alum.rpi.edu> References: <46B4CF5E.8040401@alum.rpi.edu> Message-ID: <20070804204305.GA97120@cutter.rexx.com> On Sat, Aug 04, 2007 at 12:11:26PM -0700, Bob Gailer wrote: > Alan Gauld wrote: > > AlaMode > > > I have googled without success. Where do I find AlaMode? This won't help you with AlaMode, but give you more choices than you want in the way of editors. The first link is Python-relevant and the second is Python-neutral. http://wiki.python.org/moin/PythonEditors http://en.wikipedia.org/wiki/Comparison_of_text_editors The Python Wiki, by the way, is hidden under the "Community" link at http://python.org. I'm a bit in Alan's mode. I use screen to create multiple sessions in a terminal window, and have a text editor open in one session, run tests in another, have an IPython prompt in the next, build documentation (using Docutils) in yet another session, etc. That's for one project. If I am working on another project concurrently, which is likely, then I have another set of sessions open for that project. For editing Python source and documentation text (reST: reStructuredText -- http://docutils.sourceforge.net/rst.html) I use Jed and sometimes Emacs. Jed and Emacs have very nice Python modes. Jed gives you a choice between an Emacs user-interface and several others. Jed runs on Linux and Windows. There is a MS Windows version of Emacs. Both Jed and Emacs take some time to get into, however, if you spend lots of time editing code, those start-up costs (whatever editor you chose) are likely well spent. http://www.jedsoft.org/jed/index.html http://www.xemacs.org/ If you want a GUI (graphical user interface) editor that you can start using as quickly as possible, SciTE is pretty nice: http://scintilla.sourceforge.net/SciTE.html And, if you decide to try SciTE, see the following for quick instructions on customizing SciTE for Python indentation: http://www.rexx.com/~dkuhlman/#scite-python-properties But, as you can see from the links above, you have lots of choices. I'm not sure which platform the original poster is on, but on my Linux box, the Eric IDE for Python runs well and has built-in debugging support. http://www.die-offenbachs.de/eric/index.html Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman From bgailer at alum.rpi.edu Sat Aug 4 23:02:11 2007 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Sat, 04 Aug 2007 14:02:11 -0700 Subject: [Tutor] Python Editors .. which do you reccomend for a amateur? In-Reply-To: <46B4D8D3.7060305@gazeta.pl> References: <46B4CF5E.8040401@alum.rpi.edu> <46B4D8D3.7060305@gazeta.pl> Message-ID: <46B4E953.8060700@alum.rpi.edu> Lukasz wrote: > U?ytkownik Bob Gailer napisa?: > >> I have googled without success. Where do I find AlaMode? >> > > AlaMode is part of wxpython OK I installed wxpython. Now what do I do to run alaMode? I found no useful documentation. -- Bob Gailer 510-978-4454 Oakland, CA 919-636-4239 Chapel Hill, NC From keridee at jayco.net Sun Aug 5 01:16:52 2007 From: keridee at jayco.net (Tiger12506) Date: Sat, 4 Aug 2007 18:16:52 -0500 Subject: [Tutor] Python Editors .. which do you reccomend for a amateur? References: <46B4CF5E.8040401@alum.rpi.edu><46B4D8D3.7060305@gazeta.pl> <46B4E953.8060700@alum.rpi.edu> Message-ID: <000801c7d6ed$8e87b4c0$65fce004@JSLAPTOP> It is found in python25\lib\site-packages\wx-2.6-msw-unicode\wx\py pyAlaMode.py I'm sure there are shortcuts, but that's where it is. JS From alan.gauld at btinternet.com Sun Aug 5 01:54:18 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 5 Aug 2007 00:54:18 +0100 Subject: [Tutor] Python Editors .. which do you reccomend for a amateur? References: <46B4CF5E.8040401@alum.rpi.edu><46B4D8D3.7060305@gazeta.pl> <46B4E953.8060700@alum.rpi.edu> Message-ID: "Bob Gailer" wrote > OK I installed wxpython. Now what do I do to run alaMode? I found no > useful documentation. The Py toolset is here: %PYTHON%\lib\site-packages\wx-2.6-msw-unicode\wx\py Just drag a shortcut to the file into the menu or onto the desktop. It is fairly intuitive to operate and some exploration reveals the rest. Its basically a demo of the wxPython text editing widget plus the PyCrust shell. If you have access to the wxPython book there is a chapter on the Py tools which is worth reading - try the local library as per a recent thread! Regards, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From jfabiani at yolo.com Sun Aug 5 01:23:20 2007 From: jfabiani at yolo.com (johnf) Date: Sat, 4 Aug 2007 16:23:20 -0700 Subject: [Tutor] Python Editors .. which do you reccomend for a amateur? In-Reply-To: References: Message-ID: <200708041623.21131.jfabiani@yolo.com> On Saturday 04 August 2007 08:34, Tony Noyeaux wrote: > I've been using Python IDLE,.. tried DrPython,.. had a try of ActiveState > Komodo IDE, Active Python,... > > What is a good python editor to use. I've seen good and bad with all of the > above from my newcomer perspective.. wondering what other feel is a good > editor to use... when you're new to python? > > > Tony Noyeaux I got to put my pitch in for wing. The latest is very good indeed. Yea it cost money but I feel well worth the money. -- John Fabiani From alan.gauld at btinternet.com Sun Aug 5 09:28:03 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 5 Aug 2007 08:28:03 +0100 Subject: [Tutor] Python Editors .. which do you reccomend for a amateur? References: <46B4CF5E.8040401@alum.rpi.edu><46B4D8D3.7060305@gazeta.pl><46B4E953.8060700@alum.rpi.edu> Message-ID: "Alan Gauld" wrote > > %PYTHON%\lib\site-packages\wx-2.6-msw-unicode\wx\py > > Just drag a shortcut to the file into the menu or onto the desktop. I forgot to mention that it helps to change the file extension to .pyw to avoid the console window popping up. Alan G From bhaaluu at gmail.com Sun Aug 5 18:23:33 2007 From: bhaaluu at gmail.com (bhaaluu) Date: Sun, 5 Aug 2007 12:23:33 -0400 Subject: [Tutor] Python Challenge Message-ID: Greetings: Here's a fun site, though probably geared more for intermediate Python programmers, than for beginners: http://www.pythonchallenge.com/ It's 33 levels of riddles that can be solved with Python in some way or another. =) So you have the site up in your browser, and your Python interpreter up, and you try to solve each riddle to get to the next level. There isn't much mouse work involved... you can't *click* your way through it. You have to think of Python solutions to solve each riddle. Each riddle is a combination of a picture and a clue, or hint. Read the hint, and study the picture carefully to figure out what to do. Happy Programming! -- bhaaluu at gmail dot com From ssg.hilton at comcast.net Sun Aug 5 18:59:16 2007 From: ssg.hilton at comcast.net (TheSarge) Date: Sun, 5 Aug 2007 09:59:16 -0700 (PDT) Subject: [Tutor] Newbie College Student Message-ID: <12006185.post@talk.nabble.com> Hi All, Been tasked with an assignment that is kicking my butt. We have been asked to write a py utilizing cgi to ask for simplistic web form guestbook information (name and email). I think I am lost on whether or not my actual py script needs to link to a cgi script or if I can do it all in a py script. It needs to log entries to a text file and everytime I think I have it working I go to my text file and it remains empty. I don't know if I can post my script code in here so if I can not then my apologies forthcoming. Any help or advice is most appreciated. py script: #!c:\python25\python.exe import cgi, cgitb, os temp = """
First Name:
Last Name:
Email:

""" path = 'c:\\file' # Create instance of FieldStorage form = cgi.FieldStorage() # Get data from field 'name' fname = form.getvalue('fname') # Get data from field 'address' lname = form.getvalue('lname') # Get data from field 'email' email = form.getvalue('email') if not os.path.isdir(path): os.mkdir(path) e=open(path + '\\' + 'logbook.txt','a') e.write("%s#%s#%s\n" % (fname,lname,email)) e.close() print 'Done' What am I doing wrong? Been working on this two weekends in a row and the assignment is already late. Thanks, TheSarge -- View this message in context: http://www.nabble.com/Newbie-College-Student-tf4220394.html#a12006185 Sent from the Python - tutor mailing list archive at Nabble.com. From jjcrump at myuw.net Sun Aug 5 20:28:55 2007 From: jjcrump at myuw.net (Jon Crump) Date: Sun, 5 Aug 2007 11:28:55 -0700 (PDT) Subject: [Tutor] more encoding confusion In-Reply-To: <46B37E3C.6060905@tds.net> References: <46B37E3C.6060905@tds.net> Message-ID: Kent, Many thanks again, and thanks too to Paul at http://tinyurl.com/yrl8cy. That's very effective, thanks very much for the detailed explanation; however, I'm a little surprised that it's necessary. I would have thought that there would be some standard module that included a unicode equivalent of the builtin method isupper(). On Fri, 3 Aug 2007, Kent Johnson wrote: > > What sort of re test can I do to catch lines whose defining > > characteristic is that they begin with two or more adjacent utf-8 > > encoded capital letters? > > First you have to decode the file to a Unicode string. > Then build the set of matching characters and build a regex. For example, > something like this: > > data = open('data.txt').read().decode('utf-8').splitlines() > > uppers = u''.join(unichr(i) for i in xrange(sys.maxunicode) > if unichr(i).isupper()) I modified uppers to include only the latin characters, and added the apostrophe to catch placenames like L'ISLE. > upperRe = u'^[%s]{2,}' % uppers > > for line in data: > if re.match(upperRe, line): > > > With a tip of the hat to > http://tinyurl.com/yrl8cy > > Kent From kent37 at tds.net Sun Aug 5 20:37:01 2007 From: kent37 at tds.net (Kent Johnson) Date: Sun, 05 Aug 2007 14:37:01 -0400 Subject: [Tutor] more encoding confusion In-Reply-To: References: <46B37E3C.6060905@tds.net> Message-ID: <46B618CD.4000502@tds.net> Jon Crump wrote: > > Kent, Many thanks again, and thanks too to Paul at > http://tinyurl.com/yrl8cy. > > That's very effective, thanks very much for the detailed explanation; > however, I'm a little surprised that it's necessary. I would have > thought that there would be some standard module that included a unicode > equivalent of the builtin method isupper(). Hmm...actually, isupper() works fine on unicode strings: In [18]: s='H\303\211RON'.decode('utf-8') In [21]: print 'H\303\211RON' H?RON In [22]: s.isupper() Out[22]: True :-) > I modified uppers to include only the latin characters, and added the > apostrophe to catch placenames like L'ISLE. Then you are back to needing a regular expression I think. Kent PS Please use Reply All to reply on-list. From bgailer at alum.rpi.edu Sun Aug 5 20:42:12 2007 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Sun, 05 Aug 2007 11:42:12 -0700 Subject: [Tutor] Newbie College Student In-Reply-To: <12006185.post@talk.nabble.com> References: <12006185.post@talk.nabble.com> Message-ID: <46B61A04.4050103@alum.rpi.edu> TheSarge wrote: > Hi All, > > Been tasked with an assignment that is kicking my butt. We have been asked > to write a py utilizing cgi to ask for simplistic web form guestbook > information (name and email). I think I am lost on whether or not my actual > py script needs to link to a cgi script or if I can do it all in a py > script. It needs to log entries to a text file and everytime I think I have > it working I go to my text file and it remains empty. I don't know if I can > post my script code in here so if I can not then my apologies forthcoming. > We welcome code. Without it we can't begin to help. Also if you get an exception please post the traceback also. > Any help or advice is most appreciated. > > py script: > > #!c:\python25\python.exe > import cgi, cgitb, os > > temp = """ > > >
> First Name:
> Last Name:
> Email:
>
> >
> > > > """ > path = 'c:\\file' > # Create instance of FieldStorage > form = cgi.FieldStorage() > > # Get data from field 'name' > fname = form.getvalue('fname') > > # Get data from field 'address' > lname = form.getvalue('lname') > > # Get data from field 'email' > email = form.getvalue('email') > > if not os.path.isdir(path): > os.mkdir(path) > e=open(path + '\\' + 'logbook.txt','a') > e.write("%s#%s#%s\n" % (fname,lname,email)) > e.close() > print 'Done' > > > What am I doing wrong? I assume you included the form html as a comment, and that the actual form is sent to the browser first, then the actual cgi program starts with path = The only problem I see is that the code to write the file is bypassed when the path already exists. You should be able to fix that with some changes to indentation. > Been working on this two weekends in a row and the > assignment is already late. > Next time ask sooner. We don't DO homework for students, but are glad to help when we see your effort and specific problems. It is good that you imported the cgitb module. Just add cgitb.enable() to activate it. -- Bob Gailer 510-978-4454 Oakland, CA 919-636-4239 Chapel Hill, NC From alan.gauld at btinternet.com Sun Aug 5 20:52:28 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 5 Aug 2007 19:52:28 +0100 Subject: [Tutor] Newbie College Student References: <12006185.post@talk.nabble.com> Message-ID: "TheSarge" wrote > information (name and email). I think I am lost on whether or not my > actual > py script needs to link to a cgi script or if I can do it all in a > py Your python script is a CGI script and it needs to run under a web server. There is a simple CGI server in the Python library that you can use for testing... > #!c:\python25\python.exe > import cgi, cgitb, os > > temp = """ > > >
> First Name:
> Last Name:
> Email:
>
> >
> > > > """ > path = 'c:\\file' > # Create instance of FieldStorage > form = cgi.FieldStorage() > > # Get data from field 'name' > fname = form.getvalue('fname') > > # Get data from field 'address' > lname = form.getvalue('lname') The comments seem to be wrong, assuming the html in temp ids the same as is in the html file that calls this? > # Get data from field 'email' > email = form.getvalue('email') > > if not os.path.isdir(path): > os.mkdir(path) > e=open(path + '\\' + 'logbook.txt','a') > e.write("%s#%s#%s\n" % (fname,lname,email)) > e.close() > print 'Done' Bob has already pointed out the bug here... HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From jjcrump at myuw.net Sun Aug 5 21:37:03 2007 From: jjcrump at myuw.net (Jon Crump) Date: Sun, 5 Aug 2007 12:37:03 -0700 (PDT) Subject: [Tutor] more encoding confusion In-Reply-To: <46B618CD.4000502@tds.net> References: <46B37E3C.6060905@tds.net> <46B618CD.4000502@tds.net> Message-ID: On Sun, 5 Aug 2007, Kent Johnson wrote: > Hmm...actually, isupper() works fine on unicode strings: > In [18]: s='H\303\211RON'.decode('utf-8') > In [21]: print 'H\303\211RON' > H?RON > In [22]: s.isupper() > Out[22]: True > > :-) > > >> I modified uppers to include only the latin characters, and added the >> apostrophe to catch placenames like L'ISLE. > > Then you are back to needing a regular expression I think. > Ah! I'm finally starting to get it. My problem wasn't with a regex to test the line, my problem was with reading the file in as utf-8 to begin with. When I take your advice and decode() right from the start using: open('textfile').read().decode('utf-8').splitlines() instead of input = open('textfile', 'r') text = input.readlines() Then the regex problem does not even arise. Now I can use this instead: for line in data: if line[0:2].isupper(): as you point out, isupper() works just fine on unicode strings; it also seems to consider the apostrophe uppercase as well because this catches not only H?RON, but L'ISLE as well. Now my only glitch is that line.title() screws up placenames like STOKE (BISHOP'S), turning it into Stoke (Bishop'S). From majidfouladpour at yahoo.co.uk Mon Aug 6 08:31:11 2007 From: majidfouladpour at yahoo.co.uk (Majid) Date: Mon, 06 Aug 2007 10:01:11 +0330 Subject: [Tutor] Batch file copy script Message-ID: <46B6C02F.6000909@yahoo.co.uk> Hi all, I am new to Python and this mailing list. I wondered if someone would be kind enough to give me a basic python skeleton to achieve the following. Many thanks in advance Majid --------------------------------- Here are the assumptions: 1. we have a list.txt file with entries like: /dists/dapper/Release.gpg /dists/dapper/main/binary-i386/Release /dists/dapper/restricted/binary-i386/Release /doc/install/manual/example-preseed.txt.gz /doc/install/manual/en/apa.html /doc/install/manual/en/apas01.html 2. The files referenced in the list file (and many other files) are in C:\source\ directory and subdirectories as defined in the list file - e.g. for the first entry above we have this file: C:\source\dists\dapper\Release.gpg 3. We want only the files listed in the list file to be copied to D:\target\ keeping the same directory structure. So for the first entry we want to have this file: D:\target\dists\dapper\Release.gpg 4. If a file listed in the list file is not found in the source, we want an entry to be added to C:\py\missing.txt (by the way the python script doing the job could be in this directory too - i.e. C:py\packagemaker.py - also the list file is here too: C:\py\list.txt) Here is a possible logic for the script: 1. Open the list (C:\py\list.txt). 2. Until the end of the file 3. Read a line from list.txt (e.g. '/dists/dapper/Release.gpg') 4. Change forward slashes to back slashes (e.g. '\dists\dapper\Release.gpg') 5. Add 'C:\source' to the string (e.g. 'C:\source\dists\dapper\Release.gpg') 6. If the file exists in the source folder 7. Copy the file from the source frolder to the target folder (e.g. copy C:\source\dists\dapper\Release.gpg to D:\target\dists\dapper\Release.gpg) 8. Else 9. Add the name of the missing file to missings.txt 10. End of loop Possible uses of the script? I have copied the contents of an ubuntu dvd to my hard drive (C:\source\). It contains many files and directories totaling 3.45 GB. I have also downloaded the .list files for the server and alternate instal iso images: ubuntu-6.06.1-server-i386.list and ubuntu-6.06.1-alternate-i386.list The ordinary 'desktop' install cd/dvd requires at least 512 MB or ram which I don't have. It is also impossible to download the 700 MB iso images for the server / alternate CDs as I only have a dial-up connection. To make the situation worse, these CDs could not be found in local stores in my city. So the only option left is making the server and alternate CDs myself. This is why I need the script. From dale.pearl at gmail.com Mon Aug 6 09:13:05 2007 From: dale.pearl at gmail.com (Dale Pearl) Date: Mon, 6 Aug 2007 00:13:05 -0700 Subject: [Tutor] need futher explaining Message-ID: <747edb7f0708060013u5499492fue9da8eeaadefbfbf@mail.gmail.com> I'm reading Beginning Python - From Novice to Professional by Magnus Lie Hetland (an Apress book) and there is a code example that I need further explaining on to fully grasp. There is a section with samle code of: names = ['anne', 'beth', 'george', 'damon'] ages = [12, 45, 32, 102] for i in range(len(names)): print names[i], 'is', ages[i], 'years old' now all of it makes sense to me except for the line for i in range(len(names)): the len statement calculates the number of characters I'm not quite understanding the magic here. forgive my stupidity this programming stuff is new to me but if someone could explain to me how this single line works it would be greatly appreciated. By the way this is a great book well worth the investment to anyone's library who is trying to learn Python. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070806/a50168a9/attachment-0001.htm From rabidpoobear at gmail.com Mon Aug 6 10:10:53 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Mon, 06 Aug 2007 03:10:53 -0500 Subject: [Tutor] Batch file copy script In-Reply-To: <46B6C02F.6000909@yahoo.co.uk> References: <46B6C02F.6000909@yahoo.co.uk> Message-ID: <46B6D78D.5000702@gmail.com> Majid wrote: > Hi all, > I am new to Python and this mailing list. I wondered if someone would be > kind enough to give me a basic python skeleton to achieve the following. > > Many thanks in advance > Majid > > --------------------------------- > > > Here are the assumptions: > > 1. we have a list.txt file with entries like: > > /dists/dapper/Release.gpg > /dists/dapper/main/binary-i386/Release > /dists/dapper/restricted/binary-i386/Release > /doc/install/manual/example-preseed.txt.gz > /doc/install/manual/en/apa.html > /doc/install/manual/en/apas01.html > > 2. The files referenced in the list file (and many other files) are > in C:\source\ directory and subdirectories as defined in the list > file - e.g. for the first entry above we have this file: > > C:\source\dists\dapper\Release.gpg > > 3. We want only the files listed in the list file to be copied to > D:\target\ keeping the same directory structure. So for the first > entry we want to have this file: > > D:\target\dists\dapper\Release.gpg > > 4. If a file listed in the list file is not found in the source, we > want an entry to be added to C:\py\missing.txt (by the way the > python script doing the job could be in this directory too - i.e. > C:py\packagemaker.py - also the list file is here too: C:\py\list.txt) > > > Here is a possible logic for the script: > > 1. Open the list (C:\py\list.txt). > 2. Until the end of the file > 3. Read a line from list.txt (e.g. '/dists/dapper/Release.gpg') > 4. Change forward slashes to back slashes (e.g. > '\dists\dapper\Release.gpg') > 5. Add 'C:\source' to the string (e.g. > 'C:\source\dists\dapper\Release.gpg') > 6. If the file exists in the source folder > 7. Copy the file from the source frolder to the target folder > (e.g. copy C:\source\dists\dapper\Release.gpg to > D:\target\dists\dapper\Release.gpg) > 8. Else > 9. Add the name of the missing file to missings.txt > 10. End of loop > import os, shutil target_dir = r'D:\target\' source_dir = r'C:\source\' missing_files = open("missings.txt","w") for line in open('list.txt'): source_file = os.path.normpath(source_dir + line) target_file = os.path.normpath(target_dir + line) if os.path.exists(target_file): shutil.copyfile(source_file, target_file) else: missing_files.write(line) missing_files.close() It's pretty straight-forward. Is anything in there confusing? Things that you might not have seen before: the r in front of the string makes it a 'raw string' meaning that a \t is a "\" and then a "t" instead of a tab character, and this goes for all other \s. In other words, the '\' isn't used to escape certain special ascii sequences, it's just a '\'. Secondly, the os.path.normpath() function will fix your path for your OS. SO if you have C:/some/path/to/file.ext it will switch it to C:\\some\\path\\to\\file.ext if you're on Windows. A good feature of this function is that it also fixes multiple slashes, so C:\\source\\/dapper will be correctly changed to C:\\source\\dapper Pretty cool function that I didn't know about 'til now. > > Possible uses of the script? > Not sure, you could probably generalize it quite a bit more than I did, if you found other use cases. > I have copied the contents of an ubuntu dvd to my hard drive > (C:\source\). It contains many files and directories totaling 3.45 GB. I > have also downloaded the .list files for the server and alternate instal > iso images: > > ubuntu-6.06.1-server-i386.list and ubuntu-6.06.1-alternate-i386.list > > The ordinary 'desktop' install cd/dvd requires at least 512 MB or ram > which I don't have. It is also impossible to download the 700 MB iso > images for the server / alternate CDs as I only have a dial-up > connection. To make the situation worse, these CDs could not be found in > local stores in my city. So the only option left is making the server > and alternate CDs myself. This is why I need the script. > That sucks. It was sounding kind of like a homework problem at first, but I believe you. I hope I helped, if you have any other questions please ask! -Luke From bhaaluu at gmail.com Mon Aug 6 10:08:09 2007 From: bhaaluu at gmail.com (bhaaluu) Date: Mon, 6 Aug 2007 04:08:09 -0400 Subject: [Tutor] Batch file copy script In-Reply-To: <46B6C02F.6000909@yahoo.co.uk> References: <46B6C02F.6000909@yahoo.co.uk> Message-ID: Greetings Majid, https://shipit.ubuntu.com/ The Ubunty people will ship a set of 5 CDs of the latest release to you, absolutely free. Go to the above site and fill out your shipping information. I have done this in the past, and they ship promptly. Why 5 CDs? It costs the same to ship 1 or 5, and they'd like for you to share them with other people. Another source of CDs: do you have a Linux Users Group (LUG) in your area? Also: look for Linux magazines with CD/DVD in a local newstand. BTW, I only have 256MB RAM, and have never had any problems installing Linux (Ubuntu or otherwise). Really, all you should need to run/install a LiveCD is 128MB RAM, and if you're not going to be running OpenOffice, you can get by with less than that. Hopefully helpful. -- bhaaluu at gmail dot com From bhaaluu at gmail.com Mon Aug 6 10:30:21 2007 From: bhaaluu at gmail.com (bhaaluu) Date: Mon, 6 Aug 2007 04:30:21 -0400 Subject: [Tutor] need futher explaining In-Reply-To: <747edb7f0708060013u5499492fue9da8eeaadefbfbf@mail.gmail.com> References: <747edb7f0708060013u5499492fue9da8eeaadefbfbf@mail.gmail.com> Message-ID: Greetings, I'm also a beginner to Python, but I think I can answer your question. One of the best ways to learn about how anything in Python works is to use the Python interactive interpreter, so, away we go (follow along, please): >>> names = ['anne', 'beth', 'george', 'damon'] >>> print names ['anne', 'beth', 'george', 'damon'] >>> print len(names) 4 >>> print names[0] anne >>> print names[3] damon 1. names is a 'list' which contains four elements 2. The elements in a list are indexed starting with zero (0) 3. So the 'for' loop is iterating the length of the names list len(names) which is the same as saying: for i in range(4): So len() isn't just for counting characters! It's count will depend on what 'type' it is counting. In the above case, it is counting elements in a 'list'. >>> print len(names[2]) 6 names[2] is: g e o r g e 6 characters. Why? >>> print type(names[2]) george is a string, so len() counts the characters in the string. I hope this is helpful. -- bhaaluu at gmail dot com On 8/6/07, Dale Pearl wrote: > I'm reading Beginning Python - From Novice to Professional by Magnus Lie > Hetland (an Apress book) and there is a code example that I need further > explaining on to fully grasp. > There is a section with samle code of: > names = ['anne', 'beth', 'george', 'damon'] > ages = [12, 45, 32, 102] > for i in range(len(names)): > print names[i], 'is', ages[i], 'years old' > > now all of it makes sense to me except for the line for i in > range(len(names)): > the len statement calculates the number of characters I'm not quite > understanding the magic here. > forgive my stupidity this programming stuff is new to me but if someone > could explain to me how this single line works it would be greatly > appreciated. > > By the way this is a great book well worth the investment to anyone's > library who is trying to learn Python. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From kent37 at tds.net Mon Aug 6 13:48:28 2007 From: kent37 at tds.net (Kent Johnson) Date: Mon, 06 Aug 2007 07:48:28 -0400 Subject: [Tutor] Batch file copy script In-Reply-To: <46B6C02F.6000909@yahoo.co.uk> References: <46B6C02F.6000909@yahoo.co.uk> Message-ID: <46B70A8C.5090809@tds.net> Majid wrote: > Here is a possible logic for the script: > > 1. Open the list (C:\py\list.txt). > 2. Until the end of the file > 3. Read a line from list.txt (e.g. '/dists/dapper/Release.gpg') > 4. Change forward slashes to back slashes (e.g. > '\dists\dapper\Release.gpg') > 5. Add 'C:\source' to the string (e.g. > 'C:\source\dists\dapper\Release.gpg') > 6. If the file exists in the source folder > 7. Copy the file from the source frolder to the target folder > (e.g. copy C:\source\dists\dapper\Release.gpg to > D:\target\dists\dapper\Release.gpg) > 8. Else > 9. Add the name of the missing file to missings.txt > 10. End of loop This would be a good first Python project. The actual script will be almost line-for-line the same as your outline. There are many good tutorials here: http://wiki.python.org/moin/BeginnersGuide/NonProgrammers You need to learn about lists and files, that's it. The shutil module has a copyfile() function that will do the actual copying. Kent From kent37 at tds.net Mon Aug 6 13:52:21 2007 From: kent37 at tds.net (Kent Johnson) Date: Mon, 06 Aug 2007 07:52:21 -0400 Subject: [Tutor] need futher explaining In-Reply-To: <747edb7f0708060013u5499492fue9da8eeaadefbfbf@mail.gmail.com> References: <747edb7f0708060013u5499492fue9da8eeaadefbfbf@mail.gmail.com> Message-ID: <46B70B75.4010403@tds.net> Dale Pearl wrote: > I'm reading Beginning Python - From Novice to Professional by Magnus Lie > Hetland (an Apress book) and there is a code example that I need further > explaining on to fully grasp. > There is a section with samle code of: > names = ['anne', 'beth', 'george', 'damon'] > ages = [12, 45, 32, 102] > for i in range(len(names)): > print names[i], 'is', ages[i], 'years old' bhaaluu answered your question, I just want to comment that IMO this is not idiomatic Python. A better way to write it would be to combine the two lists using zip(): for name, age in zip(names, ages): print name, 'is', age, 'years old' zip: http://docs.python.org/lib/built-in-funcs.html#l2h-81 Kent From rdm at rcblue.com Mon Aug 6 15:11:38 2007 From: rdm at rcblue.com (Dick Moores) Date: Mon, 06 Aug 2007 06:11:38 -0700 Subject: [Tutor] Ingenious script (IMO) Message-ID: <20070806131709.60E4F1E4006@bag.python.org> Google Answers folded, but Google has kept the archive accessible. I found this Python script at and modified it for U.S. money denominations: http://www.rcblue.com/Python/changeMaker_revised_for_US_denominations.py I'm still working at Python--been at it a while--and thought the script was ingenious. Do the Tutors agree? Or is it just run-of-the-mill programming? Could it have been more simply written? Thanks, Dick Moores From kent37 at tds.net Mon Aug 6 15:49:44 2007 From: kent37 at tds.net (Kent Johnson) Date: Mon, 06 Aug 2007 09:49:44 -0400 Subject: [Tutor] Ingenious script (IMO) In-Reply-To: <20070806131709.60E4F1E4006@bag.python.org> References: <20070806131709.60E4F1E4006@bag.python.org> Message-ID: <46B726F8.3000107@tds.net> Dick Moores wrote: > http://www.rcblue.com/Python/changeMaker_revised_for_US_denominations.py > > I'm still working at Python--been at it a while--and thought the > script was ingenious. Do the Tutors agree? Or is it just > run-of-the-mill programming? Could it have been more simply written? I don't find it either ingenious or well-written. The algorithm is the same one you would use to count out an amount by hand so it doesn't seem so unusual. IMO the code relies too much on indices. If you rewrite it using a dict (or, even better, defaultdict(int)) for coinCount, there is no need for indices at all. Even with coinCount as a list, it could be better written. coinCount = [] for d in denominations: coinCount.append(0) => coinCount = [0] * ndenominations The main loop could be for deno in range(ndenominations): if not remaining: break or for i, deno in enumerate(denominations): # i is now the index, deno is the actual denomination but I would write it this way and avoid the use of the index completely: from collections import defaultdict coinCount = defaultdict(int) remaining = change # Loop until either we have given all the change or we have # run out of coin denominations to check. for deno in denominations: if not remaining: break # For one denomination, count out coins of that denomination # as long as the remaining amount is greater than the denomination # amount. while remaining >= deno: coinCount[deno] += 1 print "remaining =", remaining remaining -= deno # Report the results. print "Your change is $%.02f"% (float(change) / CPD) for deno in denominations: if coinCount[deno] > 0: if deno >= 100: print "$%d bills:\t" % (deno / CPD), coinCount[deno] else: print "%d-cent coins:\t" % (deno), coinCount[deno] Kent From rdm at rcblue.com Mon Aug 6 16:31:57 2007 From: rdm at rcblue.com (Dick Moores) Date: Mon, 06 Aug 2007 07:31:57 -0700 Subject: [Tutor] Ingenious script (IMO) In-Reply-To: <46B726F8.3000107@tds.net> References: <20070806131709.60E4F1E4006@bag.python.org> <46B726F8.3000107@tds.net> Message-ID: <20070806143246.97BAA1E4010@bag.python.org> At 06:49 AM 8/6/2007, Kent Johnson wrote: >Dick Moores wrote: >>http://www.rcblue.com/Python/changeMaker_revised_for_US_denominations.py >>I'm still working at Python--been at it a while--and thought the >>script was ingenious. Do the Tutors agree? Or is it just >>run-of-the-mill programming? Could it have been more simply written? > >I don't find it either ingenious or well-written. The algorithm is >the same one you would use to count out an amount by hand so it >doesn't seem so unusual. IMO the code relies too much on indices. If >you rewrite it using a dict (or, even better, defaultdict(int)) for >coinCount, there is no need for indices at all. Even with coinCount >as a list, it could be better written. > >coinCount = [] >for d in denominations: > coinCount.append(0) > >=> > >coinCount = [0] * ndenominations > > >The main loop could be >for deno in range(ndenominations): > if not remaining: > break > >or >for i, deno in enumerate(denominations): ># i is now the index, deno is the actual denomination > > >but I would write it this way and avoid the use of the index completely: > >from collections import defaultdict >coinCount = defaultdict(int) >remaining = change > ># Loop until either we have given all the change or we have ># run out of coin denominations to check. >for deno in denominations: > if not remaining: > break > > # For one denomination, count out coins of that denomination > # as long as the remaining amount is greater than the denomination > # amount. > > while remaining >= deno: > coinCount[deno] += 1 > print "remaining =", remaining > remaining -= deno > ># Report the results. >print "Your change is $%.02f"% (float(change) / CPD) >for deno in denominations: > if coinCount[deno] > 0: > if deno >= 100: > print "$%d bills:\t" % (deno / CPD), coinCount[deno] > else: > print "%d-cent coins:\t" % (deno), coinCount[deno] > > >Kent Thanks Kent! Here's what I have after incorporating your suggestions: ================================= #!/usr/bin/env python #coding=utf-8 from collections import defaultdict CPD = 100 cost = int(CPD * float(raw_input("Enter the cost: "))) tend = int(CPD * float(raw_input("Enter the tendered amount: "))) # Calculate the change. change = tend - cost coinCount = defaultdict(int) print coinCount remaining = change denominations = (2000, 1000, 500, 100, 50, 25, 10, 5, 1) # Loop until either we have given all the change or we have # run out of coin denominations to check. for deno in denominations: if not remaining: break # For one denomination, count out coins of that denomination # as long as the remaining amount is greater than the denomination # amount. while remaining >= deno: coinCount[deno] += 1 remaining -= deno # Report the results. print "Your change is $%.02f"% (float(change) / CPD) for deno in denominations: if coinCount[deno] > 0: if deno >= 100: print "$%d bills:\t" % (deno / CPD), coinCount[deno] else: print "%d-cent coins:\t" % (deno), coinCount[deno] ======================================== Gotta say though, I still don't understand how the defaultdict works here. Dick From kent37 at tds.net Mon Aug 6 16:44:38 2007 From: kent37 at tds.net (Kent Johnson) Date: Mon, 06 Aug 2007 10:44:38 -0400 Subject: [Tutor] Ingenious script (IMO) In-Reply-To: <20070806143241.SIAI12548.inaamta11.mail.tds.net@alnrmhc15.comcast.net> References: <20070806131709.60E4F1E4006@bag.python.org> <46B726F8.3000107@tds.net> <20070806143241.SIAI12548.inaamta11.mail.tds.net@alnrmhc15.comcast.net> Message-ID: <46B733D6.2020001@tds.net> Dick Moores wrote: > Gotta say though, I still don't understand how the defaultdict works here. Did you try the docs? http://docs.python.org/lib/defaultdict-objects.html If coinCount were an ordinary dict, the line coinCount[deno] += 1 would have to be written as coinCount[deno] = coinCount.get(deno, 0) + 1 Using defaultdict(int) makes the use of 0 as the default value automatic. (Actually the default value is obtained by calling int(), whose value is 0.) Kent From carroll at tjc.com Mon Aug 6 17:03:07 2007 From: carroll at tjc.com (Terry Carroll) Date: Mon, 6 Aug 2007 08:03:07 -0700 (PDT) Subject: [Tutor] sqlite: does "?" work in PRAGMA commands? In-Reply-To: Message-ID: On Wed, 1 Aug 2007, Terry Carroll wrote: > Does the "?" approach not work with PRAGMA commands or something; or am I > doing this wrong? Just a quick follow-up on this, in case anyone else cares. My conclusion is that it's not supported. Googling around I found this pysqlite bug report: http://www.initd.org/tracker/pysqlite/ticket/160 It's not quite on target, since it's trying to use substitution for non-SQL variables in an SQL statement, but I think the principle is the same. The PRAGMA statement is not really an SQL statement, so the variables in it are not SQL variables. So this is not-working as designed, I think. From brunson at brunson.com Mon Aug 6 17:40:37 2007 From: brunson at brunson.com (Eric Brunson) Date: Mon, 06 Aug 2007 09:40:37 -0600 Subject: [Tutor] Ingenious script (IMO) In-Reply-To: <20070806143246.97BAA1E4010@bag.python.org> References: <20070806131709.60E4F1E4006@bag.python.org> <46B726F8.3000107@tds.net> <20070806143246.97BAA1E4010@bag.python.org> Message-ID: <46B740F5.5000309@brunson.com> Dick Moores wrote: > At 06:49 AM 8/6/2007, Kent Johnson wrote: > >> Dick Moores wrote: >> >>> http://www.rcblue.com/Python/changeMaker_revised_for_US_denominations.py >>> I'm still working at Python--been at it a while--and thought the >>> script was ingenious. Do the Tutors agree? Or is it just >>> run-of-the-mill programming? Could it have been more simply written? >>> >> I don't find it either ingenious or well-written. The algorithm is >> the same one you would use to count out an amount by hand so it >> doesn't seem so unusual. IMO the code relies too much on indices. If >> you rewrite it using a dict (or, even better, defaultdict(int)) for >> coinCount, there is no need for indices at all. Even with coinCount >> as a list, it could be better written. >> >> coinCount = [] >> for d in denominations: >> coinCount.append(0) >> >> => >> >> coinCount = [0] * ndenominations >> >> >> The main loop could be >> for deno in range(ndenominations): >> if not remaining: >> break >> >> or >> for i, deno in enumerate(denominations): >> # i is now the index, deno is the actual denomination >> >> >> but I would write it this way and avoid the use of the index completely: >> >> > >from collections import defaultdict > >> coinCount = defaultdict(int) >> remaining = change >> >> # Loop until either we have given all the change or we have >> # run out of coin denominations to check. >> for deno in denominations: >> if not remaining: >> break >> >> # For one denomination, count out coins of that denomination >> # as long as the remaining amount is greater than the denomination >> # amount. >> >> while remaining >= deno: >> coinCount[deno] += 1 >> print "remaining =", remaining >> remaining -= deno >> >> # Report the results. >> print "Your change is $%.02f"% (float(change) / CPD) >> for deno in denominations: >> if coinCount[deno] > 0: >> if deno >= 100: >> print "$%d bills:\t" % (deno / CPD), coinCount[deno] >> else: >> print "%d-cent coins:\t" % (deno), coinCount[deno] >> >> >> Kent >> > > Thanks Kent! > > Here's what I have after incorporating your suggestions: > > ================================= > #!/usr/bin/env python > #coding=utf-8 > from collections import defaultdict > > CPD = 100 > cost = int(CPD * float(raw_input("Enter the cost: "))) > tend = int(CPD * float(raw_input("Enter the tendered amount: "))) > > # Calculate the change. > change = tend - cost > > coinCount = defaultdict(int) > print coinCount > remaining = change > denominations = (2000, 1000, 500, 100, 50, 25, 10, 5, 1) > > # Loop until either we have given all the change or we have > # run out of coin denominations to check. > for deno in denominations: > if not remaining: > break > > > # For one denomination, count out coins of that denomination > # as long as the remaining amount is greater than the denomination > # amount. > > > while remaining >= deno: > coinCount[deno] += 1 > remaining -= deno > > Try something like: def makechange( amount, denominations ): coins = {} for d in denominations: coins[d] = int( amount/d ) amount = amount%d return coins > # Report the results. > print "Your change is $%.02f"% (float(change) / CPD) > for deno in denominations: > if coinCount[deno] > 0: > if deno >= 100: > print "$%d bills:\t" % (deno / CPD), coinCount[deno] > else: > print "%d-cent coins:\t" % (deno), coinCount[deno] > ======================================== > > Gotta say though, I still don't understand how the defaultdict works here. > > Dick > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From rdm at rcblue.com Mon Aug 6 17:43:50 2007 From: rdm at rcblue.com (Dick Moores) Date: Mon, 06 Aug 2007 08:43:50 -0700 Subject: [Tutor] Ingenious script (IMO) In-Reply-To: <46B733D6.2020001@tds.net> References: <20070806131709.60E4F1E4006@bag.python.org> <46B726F8.3000107@tds.net> <20070806143241.SIAI12548.inaamta11.mail.tds.net@alnrmhc15.comcast.net> <46B733D6.2020001@tds.net> Message-ID: <20070806154405.ABFC41E400D@bag.python.org> At 07:44 AM 8/6/2007, Kent Johnson wrote: >Dick Moores wrote: >>Gotta say though, I still don't understand how the defaultdict works here. > >Did you try the docs? >http://docs.python.org/lib/defaultdict-objects.html Yes, but it left me still in the dark. >If coinCount were an ordinary dict, the line > coinCount[deno] += 1 > >would have to be written as > coinCount[deno] = coinCount.get(deno, 0) + 1 > >Using defaultdict(int) makes the use of 0 as the default value >automatic. (Actually the default value is obtained by calling int(), >whose value is 0.) OK, thanks for spelling it out, Kent. Dick From rdmoores at gmail.com Mon Aug 6 18:51:46 2007 From: rdmoores at gmail.com (Dick Moores) Date: Mon, 6 Aug 2007 09:51:46 -0700 Subject: [Tutor] Ingenious script (IMO) In-Reply-To: <46B740F5.5000309@brunson.com> References: <20070806131709.60E4F1E4006@bag.python.org> <46B726F8.3000107@tds.net> <20070806143246.97BAA1E4010@bag.python.org> <46B740F5.5000309@brunson.com> Message-ID: On 8/6/07, Eric Brunson wrote: > > Try something like: > > def makechange( amount, denominations ): > > coins = {} > for d in denominations: > coins[d] = int( amount/d ) > amount = amount%d > > return coins > > Sorry, but could you spell out your point? Dick -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070806/6e75e795/attachment.htm From brunson at brunson.com Mon Aug 6 19:16:23 2007 From: brunson at brunson.com (Eric Brunson) Date: Mon, 06 Aug 2007 11:16:23 -0600 Subject: [Tutor] Ingenious script (IMO) In-Reply-To: References: <20070806131709.60E4F1E4006@bag.python.org> <46B726F8.3000107@tds.net> <20070806143246.97BAA1E4010@bag.python.org> <46B740F5.5000309@brunson.com> Message-ID: <46B75767.30509@brunson.com> Multiple subtractions is called division. It's a much more efficient loop. In this version you have exactly as many iterations as denominations. It the original, if you wanted to know how many 200 coins are in 1000000000, you would iterate ~5000000 times. Here's a timing test: denominations = ( 200, 100, 50, 25, 10, 5, 1 ) def makechange( amount, denominations ): coins = {} for d in denominations: coins[d] = int( amount/d ) amount = amount%d return coins def oldmakechange( amount, denominations ): coins = {} for d in denominations: coins[d] = 0 while amount >= d: coins[d] += 1 amount -= d return coins def comparetimings( trials=10000, amount=10000000 ): from timeit import Timer global denominations new = Timer( "makechange( %s, denominations )" % amount, "from __main__ import makechange, denominations" ).timeit( trials ) old = Timer( "oldmakechange( %s, denominations )" % amount, "from __main__ import oldmakechange, denominations" ).timeit( trials ) print old, new, old/new if __name__ == '__main__': comparetimings() Yields: 2.83604502678 0.000821828842163 3450.89498114 i.e. the division version runs about 3500 times faster for $100,000. It's a minor thing, but you asked how we'd improve the code. Math is a good thing to know. ;-) Dick Moores wrote: > On 8/6/07, *Eric Brunson* > wrote: > > Try something like: > > def makechange( amount, denominations ): > > coins = {} > for d in denominations: > coins[d] = int( amount/d ) > amount = amount%d > > return coins > > Sorry, but could you spell out your point? > > Dick From rdm at rcblue.com Mon Aug 6 21:02:59 2007 From: rdm at rcblue.com (Dick Moores) Date: Mon, 06 Aug 2007 12:02:59 -0700 Subject: [Tutor] Ingenious script (IMO) In-Reply-To: <46B75767.30509@brunson.com> References: <20070806131709.60E4F1E4006@bag.python.org> <46B726F8.3000107@tds.net> <20070806143246.97BAA1E4010@bag.python.org> <46B740F5.5000309@brunson.com> <46B75767.30509@brunson.com> Message-ID: <20070806190353.AD62F1E4007@bag.python.org> At 10:16 AM 8/6/2007, Eric Brunson wrote: Your point about efficiency is well-taken. >def makechange( amount, denominations ): > > coins = {} > for d in denominations: > coins[d] = int( amount/d ) > amount = amount%d > > return coins OK, I used this this way: ============================ def makechange( amount, denominations ): coins = {} for d in denominations: coins[d] = int( amount/d ) amount = amount%d return coins denominations = (2000, 1000, 500, 100, 50, 25, 10, 5, 1) amount = 2218 print makechange(2218, denominations) ================================== And get: {1: 3, 100: 2, 5: 1, 1000: 0, 10: 1, 2000: 1, 50: 0, 500: 0, 25: 0} That's the correct change: 3 pennies, 2 $1 bills, 1 nickel, no $10 bills, 1 dime, 1 $20 bill, no half-dollars, no $5 bills, no quarters. For amount = 3288: {1: 3, 100: 2, 5: 0, 1000: 1, 10: 1, 2000: 1, 50: 1, 500: 0, 25: 1} Why those weird orders? Dick ====================================== Bagdad Weather From kent37 at tds.net Mon Aug 6 21:46:45 2007 From: kent37 at tds.net (Kent Johnson) Date: Mon, 06 Aug 2007 15:46:45 -0400 Subject: [Tutor] Ingenious script (IMO) In-Reply-To: <20070806190353.AD62F1E4007@bag.python.org> References: <20070806131709.60E4F1E4006@bag.python.org> <46B726F8.3000107@tds.net> <20070806143246.97BAA1E4010@bag.python.org> <46B740F5.5000309@brunson.com> <46B75767.30509@brunson.com> <20070806190353.AD62F1E4007@bag.python.org> Message-ID: <46B77AA5.1050701@tds.net> Dick Moores wrote: > At 10:16 AM 8/6/2007, Eric Brunson wrote: > > Your point about efficiency is well-taken. > >> def makechange( amount, denominations ): >> >> coins = {} >> for d in denominations: >> coins[d] = int( amount/d ) >> amount = amount%d >> >> return coins > > OK, I used this this way: > > ============================ > def makechange( amount, denominations ): > > coins = {} > for d in denominations: > coins[d] = int( amount/d ) > amount = amount%d > > return coins > > denominations = (2000, 1000, 500, 100, 50, 25, 10, 5, 1) > amount = 2218 > print makechange(2218, denominations) > ================================== > > And get: > {1: 3, 100: 2, 5: 1, 1000: 0, 10: 1, 2000: 1, 50: 0, 500: 0, 25: 0} > > That's the correct change: 3 pennies, 2 $1 bills, 1 nickel, no $10 > bills, 1 dime, 1 $20 bill, no half-dollars, no $5 bills, no quarters. > > For amount = 3288: > {1: 3, 100: 2, 5: 0, 1000: 1, 10: 1, 2000: 1, 50: 1, 500: 0, 25: 1} > > Why those weird orders? Dictionaries are not ordered. If you want to see it in order you could sort the list of key, value pairs: print sorted(makechange(2218, denominations).items(), reverse=True) Kent From nebpro at gmail.com Mon Aug 6 21:51:18 2007 From: nebpro at gmail.com (Ben) Date: Mon, 6 Aug 2007 15:51:18 -0400 Subject: [Tutor] superscript with easydialogs Message-ID: Hi, I have been working with easydialogs module lately especially the progress bar (for Windows). I would like to put superscript text like (TM) to (?) when calling the label function. I have been looking around the net for some info, and can not find anything about it . It makes me wonder if python itself allow to the superscript. Any suggestions? Thanks in advance. -Ben -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070806/ffa0753a/attachment.html From keridee at jayco.net Mon Aug 6 23:17:31 2007 From: keridee at jayco.net (Tiger12506) Date: Mon, 6 Aug 2007 16:17:31 -0500 Subject: [Tutor] Ingenious script (IMO) References: <20070806131709.60E4F1E4006@bag.python.org> Message-ID: <00a301c7d86f$370459f0$91fce004@JSLAPTOP> Nice idea. Written style is average. Other tutors have discussed issues with performance, style, etc. I thought I would mention that whenever I am asked to give my opinion on a script, I compare it to something I have written/would write. In this case, I have already written. In my version, it not only tells how many of each denomination, but also how one would count back the change. It would be an interesting challenge to implement that, no? ;-) JS From brunson at brunson.com Mon Aug 6 22:27:40 2007 From: brunson at brunson.com (Eric Brunson) Date: Mon, 06 Aug 2007 14:27:40 -0600 Subject: [Tutor] Ingenious script (IMO) In-Reply-To: <20070806190906.3F50B11A0022@mail.comfortechassist.com> References: <20070806131709.60E4F1E4006@bag.python.org> <46B726F8.3000107@tds.net> <20070806143246.97BAA1E4010@bag.python.org> <46B740F5.5000309@brunson.com> <46B75767.30509@brunson.com> <20070806190906.3F50B11A0022@mail.comfortechassist.com> Message-ID: <46B7843C.1070609@brunson.com> Dick Moores wrote: > At 10:16 AM 8/6/2007, Eric Brunson wrote: > > Your point about efficiency is well-taken. > >> def makechange( amount, denominations ): >> >> coins = {} >> for d in denominations: >> coins[d] = int( amount/d ) >> amount = amount%d >> >> return coins > > OK, I used this this way: > > ============================ > def makechange( amount, denominations ): > > coins = {} > for d in denominations: > coins[d] = int( amount/d ) > amount = amount%d > > return coins > > denominations = (2000, 1000, 500, 100, 50, 25, 10, 5, 1) > amount = 2218 > print makechange(2218, denominations) > ================================== > > And get: > {1: 3, 100: 2, 5: 1, 1000: 0, 10: 1, 2000: 1, 50: 0, 500: 0, 25: 0} > > That's the correct change: 3 pennies, 2 $1 bills, 1 nickel, no $10 > bills, 1 dime, 1 $20 bill, no half-dollars, no $5 bills, no quarters. > > For amount = 3288: > {1: 3, 100: 2, 5: 0, 1000: 1, 10: 1, 2000: 1, 50: 1, 500: 0, 25: 1} > > Why those weird orders? Dictionary keys are not guaranteed to return in the order you add them. You can sort them manually if it's important: change = makechange( 2218, denominations ) print [ ( k, change[k] ) for k in sorted( change ) ] Or, since you have a sorted list of denominations already: change = makechange( 2218, denominations) print [ ( k, change[k] ) for k in denominations ) ] Or, if you know you're going to want them sorted use: coins = [] for d in denominations: coins.append( ( d, int( amount/d ) ) amount = amount%d to get an ordered list of tuples. Isn't programming fun? > > Dick > > > > ====================================== > Bagdad Weather > From rabidpoobear at gmail.com Mon Aug 6 22:32:00 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Mon, 06 Aug 2007 15:32:00 -0500 Subject: [Tutor] Ingenious script (IMO) In-Reply-To: <20070806190353.AD62F1E4007@bag.python.org> References: <20070806131709.60E4F1E4006@bag.python.org> <46B726F8.3000107@tds.net> <20070806143246.97BAA1E4010@bag.python.org> <46B740F5.5000309@brunson.com> <46B75767.30509@brunson.com> <20070806190353.AD62F1E4007@bag.python.org> Message-ID: <46B78540.801@gmail.com> Dick Moores wrote: > At 10:16 AM 8/6/2007, Eric Brunson wrote: > > Your point about efficiency is well-taken. > > >> def makechange( amount, denominations ): >> >> coins = {} >> for d in denominations: >> coins[d] = int( amount/d ) >> amount = amount%d >> >> return coins >> > > OK, I used this this way: > > ============================ > def makechange( amount, denominations ): > > coins = {} > for d in denominations: > coins[d] = int( amount/d ) > amount = amount%d > > return coins > > denominations = (2000, 1000, 500, 100, 50, 25, 10, 5, 1) > amount = 2218 > print makechange(2218, denominations) > ================================== > > And get: > {1: 3, 100: 2, 5: 1, 1000: 0, 10: 1, 2000: 1, 50: 0, 500: 0, 25: 0} > > That's the correct change: 3 pennies, 2 $1 bills, 1 nickel, no $10 > bills, 1 dime, 1 $20 bill, no half-dollars, no $5 bills, no quarters. > > For amount = 3288: > {1: 3, 100: 2, 5: 0, 1000: 1, 10: 1, 2000: 1, 50: 1, 500: 0, 25: 1} > > Why those weird orders? > Dictionaries are implemented as hash tables, not linked lists or some other data structure. see > http://en.wikipedia.org/wiki/Hash_table for more info. a dictionary's keys may coincidentally be ordered how you'd expect them to be, but it's not required so you should never depend on that. If you need them sorted, sort them :) -Luke > From ksterling at mindspring.com Mon Aug 6 22:51:35 2007 From: ksterling at mindspring.com (Ken Oliver) Date: Mon, 6 Aug 2007 16:51:35 -0400 (EDT) Subject: [Tutor] Ingenious script (IMO) Message-ID: <9340715.1186433495842.JavaMail.root@mswamui-cedar.atl.sa.earthlink.net> -----Original Message----- >From: Kent Johnson >Sent: Aug 6, 2007 3:46 PM >To: Dick Moores >Cc: Python Tutor List >Subject: Re: [Tutor] Ingenious script (IMO) > >Dick Moores wrote: >> At 10:16 AM 8/6/2007, Eric Brunson wrote: >> >> Your point about efficiency is well-taken. >> >>> def makechange( amount, denominations ): >>> >>> coins = {} >>> for d in denominations: >>> coins[d] = int( amount/d ) >>> amount = amount%d >>> >>> return coins >> >> OK, I used this this way: >> >> ============================ >> def makechange( amount, denominations ): >> >> coins = {} >> for d in denominations: >> coins[d] = int( amount/d ) >> amount = amount%d >> >> return coins >> >> denominations = (2000, 1000, 500, 100, 50, 25, 10, 5, 1) >> amount = 2218 >> print makechange(2218, denominations) >> ================================== >> >> And get: >> {1: 3, 100: 2, 5: 1, 1000: 0, 10: 1, 2000: 1, 50: 0, 500: 0, 25: 0} >> >> That's the correct change: 3 pennies, 2 $1 bills, 1 nickel, no $10 >> bills, 1 dime, 1 $20 bill, no half-dollars, no $5 bills, no quarters. >> >> For amount = 3288: >> {1: 3, 100: 2, 5: 0, 1000: 1, 10: 1, 2000: 1, 50: 1, 500: 0, 25: 1} >> >> Why those weird orders? > >Dictionaries are not ordered. If you want to see it in order you could >sort the list of key, value pairs: >print sorted(makechange(2218, denominations).items(), reverse=True) > >Kent Do you have a clever, pythonic way to suppress the denominations with "zero" counts? Ken From kent37 at tds.net Mon Aug 6 23:07:49 2007 From: kent37 at tds.net (Kent Johnson) Date: Mon, 06 Aug 2007 17:07:49 -0400 Subject: [Tutor] Ingenious script (IMO) In-Reply-To: <9340715.1186433495842.JavaMail.root@mswamui-cedar.atl.sa.earthlink.net> References: <9340715.1186433495842.JavaMail.root@mswamui-cedar.atl.sa.earthlink.net> Message-ID: <46B78DA5.5000401@tds.net> Ken Oliver wrote: > > -----Original Message----- >> From: Kent Johnson >> Sent: Aug 6, 2007 3:46 PM >> To: Dick Moores >> Cc: Python Tutor List >> Subject: Re: [Tutor] Ingenious script (IMO) >> >> Dick Moores wrote: >>> At 10:16 AM 8/6/2007, Eric Brunson wrote: >>> >>> Your point about efficiency is well-taken. >>> >>>> def makechange( amount, denominations ): >>>> >>>> coins = {} >>>> for d in denominations: >>>> coins[d] = int( amount/d ) >>>> amount = amount%d >>>> >>>> return coins >>> OK, I used this this way: >>> >>> ============================ >>> def makechange( amount, denominations ): >>> >>> coins = {} >>> for d in denominations: >>> coins[d] = int( amount/d ) >>> amount = amount%d >>> >>> return coins >>> >>> denominations = (2000, 1000, 500, 100, 50, 25, 10, 5, 1) >>> amount = 2218 >>> print makechange(2218, denominations) >>> ================================== >>> >>> And get: >>> {1: 3, 100: 2, 5: 1, 1000: 0, 10: 1, 2000: 1, 50: 0, 500: 0, 25: 0} >>> >>> That's the correct change: 3 pennies, 2 $1 bills, 1 nickel, no $10 >>> bills, 1 dime, 1 $20 bill, no half-dollars, no $5 bills, no quarters. >>> >>> For amount = 3288: >>> {1: 3, 100: 2, 5: 0, 1000: 1, 10: 1, 2000: 1, 50: 1, 500: 0, 25: 1} >>> >>> Why those weird orders? >> Dictionaries are not ordered. If you want to see it in order you could >> sort the list of key, value pairs: >> print sorted(makechange(2218, denominations).items(), reverse=True) >> >> Kent > > Do you have a clever, pythonic way to suppress the denominations with "zero" counts? Sure, just use a list comprehension to filter the list of items: non_zero_items = [(k, v) for k, v in makechange(2218, denominations).items() if v!=0] print sorted(non_zero_items, reverse=True) Kent From alan.gauld at btinternet.com Mon Aug 6 23:11:35 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 6 Aug 2007 22:11:35 +0100 Subject: [Tutor] superscript with easydialogs References: Message-ID: "Ben" wrote > I have been working with easydialogs module lately > especially the progress bar (for Windows). I would > like to put superscript text like (TM) to (?) when > calling the label function. To do that you will have to use rich text format for the label text and that's not normally available in Windows widgets. The super-scripting is controlled by the text style, font settings etc. You may be able to find a font that supports TM as a superscript specifically within its extended charater set. But I dont know if EasyDialogs even allows you to change the font... > It makes me wonder if python itself allow to the > superscript. Any suggestions? Thanks in advance. Its not a Python issue but a matter of what the standard windows widgets allow. To achieve what you want you might have to create a custom widget when supports display of rich text in its labels. But that would be true regardless of the programming langusage you used! HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From carroll at tjc.com Mon Aug 6 23:34:36 2007 From: carroll at tjc.com (Terry Carroll) Date: Mon, 6 Aug 2007 14:34:36 -0700 (PDT) Subject: [Tutor] superscript with easydialogs In-Reply-To: Message-ID: On Mon, 6 Aug 2007, Alan Gauld wrote: > "Ben" wrote > > > I have been working with easydialogs module lately > > especially the progress bar (for Windows). I would > > like to put superscript text like (TM) to (?) when > > calling the label function. > > The super-scripting is controlled by the text style, > font settings etc. You may be able to find a font that > supports TM as a superscript specifically within its > extended charater set. But I dont know if EasyDialogs > even allows you to change the font... I don't know easydialogs, but could you just use Unicode? label = u"SpamEateru\2122, now with EGG support" where 2122 is the Unicode codepoint for the TM symbol. From kent37 at tds.net Mon Aug 6 23:47:10 2007 From: kent37 at tds.net (Kent Johnson) Date: Mon, 06 Aug 2007 17:47:10 -0400 Subject: [Tutor] Ingenious script (IMO) In-Reply-To: <2593057.1186435695849.JavaMail.root@mswamui-cedar.atl.sa.earthlink.net> References: <2593057.1186435695849.JavaMail.root@mswamui-cedar.atl.sa.earthlink.net> Message-ID: <46B796DE.2020505@tds.net> Ken Oliver wrote: > I seem to stumble often with things like > > nz = [ (k,v) for k,v in lst if v!=0] > > I have not been able to wrap my brain around the parentheses. I see > it as reasonable to have the () around the k,v in the tuple in the first instance, but I feel like they should also be around k,v in the second instance (the for clause). You can write it as [ (k,v) for (k,v) in lst if v!=0] if you prefer. > Now can you do it all in one statement? Hehe. Just teasing. I hope it's obvious how to do that... Kent From rdm at rcblue.com Tue Aug 7 00:57:18 2007 From: rdm at rcblue.com (Dick Moores) Date: Mon, 06 Aug 2007 15:57:18 -0700 Subject: [Tutor] Ingenious script (IMO) In-Reply-To: <00a301c7d86f$370459f0$91fce004@JSLAPTOP> References: <20070806131709.60E4F1E4006@bag.python.org> <00a301c7d86f$370459f0$91fce004@JSLAPTOP> Message-ID: <20070806225738.1B8B81E400A@bag.python.org> At 02:17 PM 8/6/2007, you wrote: >Nice idea. Written style is average. Other tutors have discussed issues with >performance, style, etc. I thought I would mention that whenever I am asked >to give my opinion on a script, I compare it to something I have >written/would write. In this case, I have already written. In my version, it >not only tells how many of each denomination, but also how one would count >back the change. It would be an interesting challenge to implement that, no? >;-) First remind me how Americans do that. I lived in Japan a long time, and it's done quite differently there. For the U.S., say the output so far is: Enter the cost: 5.77 Enter the tendered amount: 10 Your change is $4.23 $1 bills: 4 10-cent coins: 2 1-cent coins: 3 What would be the U.S. way of counting back the change? I think we start with the $5.77, but then what? Dick ====================================== Bagdad Weather From alan.gauld at btinternet.com Tue Aug 7 01:12:34 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 7 Aug 2007 00:12:34 +0100 Subject: [Tutor] Ingenious script (IMO) References: <20070806131709.60E4F1E4006@bag.python.org><00a301c7d86f$370459f0$91fce004@JSLAPTOP> <20070806225738.1B8B81E400A@bag.python.org> Message-ID: "Dick Moores" wrote > For the U.S., say the output so far is: > > Enter the cost: 5.77 > Enter the tendered amount: 10 > Your change is $4.23 > What would be the U.S. way of counting back the change? I think we > start with the $5.77, but then what? Dunno about the US but in the UK we generally just hand over the total change as indicated on the till nowadays! :-) But in days of yore it was done thusly: 5.77 and 3(cents) is 5.80 and 20 (cents) is 6 and 4 (dollars) is 10. Except of course we use pounds and pence! Alan G. From kent37 at tds.net Tue Aug 7 01:15:47 2007 From: kent37 at tds.net (Kent Johnson) Date: Mon, 06 Aug 2007 19:15:47 -0400 Subject: [Tutor] Ingenious script (IMO) In-Reply-To: <20070806225738.1B8B81E400A@bag.python.org> References: <20070806131709.60E4F1E4006@bag.python.org> <00a301c7d86f$370459f0$91fce004@JSLAPTOP> <20070806225738.1B8B81E400A@bag.python.org> Message-ID: <46B7ABA3.9000601@tds.net> Dick Moores wrote: > At 02:17 PM 8/6/2007, you wrote: >> Nice idea. Written style is average. Other tutors have discussed issues with >> performance, style, etc. I thought I would mention that whenever I am asked >> to give my opinion on a script, I compare it to something I have >> written/would write. In this case, I have already written. In my version, it >> not only tells how many of each denomination, but also how one would count >> back the change. It would be an interesting challenge to implement that, no? >> ;-) > > First remind me how Americans do that. I lived in Japan a long time, > and it's done quite differently there. > > For the U.S., say the output so far is: > > Enter the cost: 5.77 > Enter the tendered amount: 10 > Your change is $4.23 > $1 bills: 4 > 10-cent coins: 2 > 1-cent coins: 3 > > What would be the U.S. way of counting back the change? I think we > start with the $5.77, but then what? The traditional way starts from the cost and counts up to the amount tendered. So to make change from $10 for $5.77 you would count three pennies -> $5.80 two dimes -> $6.00 four $1 -> $10 The modern way seems to be to look at the change amount given by the cash register and count that out starting with dollars... Kent From alan.gauld at btinternet.com Tue Aug 7 01:17:01 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 7 Aug 2007 00:17:01 +0100 Subject: [Tutor] superscript with easydialogs References: Message-ID: "Terry Carroll" wrote > > like to put superscript text like (TM) to (T) when > > calling the label function. > > font settings etc. You may be able to find a font that > supports TM as a superscript specifically within its > extended charater set. > > I don't know easydialogs, but could you just use Unicode? > > label = u"SpamEateru\2122, now with EGG support" That would be one instance of a font that supported the TM character. The problem is I don't know whether Windows supports unicode(I suspect it does nowadays) and if it does whether EasyDialogs supports changing the system font. If you don't mind messing about with the font used by the OS in all dialogs it might be possible that way... Alan G. From carroll at tjc.com Tue Aug 7 01:40:40 2007 From: carroll at tjc.com (Terry Carroll) Date: Mon, 6 Aug 2007 16:40:40 -0700 (PDT) Subject: [Tutor] superscript with easydialogs In-Reply-To: Message-ID: On Tue, 7 Aug 2007, Alan Gauld wrote: > The problem is I don't know whether Windows supports unicode(I suspect > it does nowadays) and if it does whether EasyDialogs supports changing > the system font. I think EasyDialogs is a Mac thing. From rabidpoobear at gmail.com Tue Aug 7 02:07:43 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Mon, 06 Aug 2007 19:07:43 -0500 Subject: [Tutor] superscript with easydialogs In-Reply-To: References: Message-ID: <46B7B7CF.3070102@gmail.com> Terry Carroll wrote: > On Tue, 7 Aug 2007, Alan Gauld wrote: > > >> The problem is I don't know whether Windows supports unicode(I suspect >> it does nowadays) and if it does whether EasyDialogs supports changing >> the system font. >> > > I think EasyDialogs is a Mac thing. > Ben mentioned Windows specifically in his original post. I think that's why Alan was talking about it. -Luke From carroll at tjc.com Tue Aug 7 02:22:49 2007 From: carroll at tjc.com (Terry Carroll) Date: Mon, 6 Aug 2007 17:22:49 -0700 (PDT) Subject: [Tutor] superscript with easydialogs In-Reply-To: <46B7B7CF.3070102@gmail.com> Message-ID: On Mon, 6 Aug 2007, Luke Paireepinart wrote: > Ben mentioned Windows specifically in his original post. > I think that's why Alan was talking about it. Ah. I missed that, thanks. Well, in that case, since I use Windows, I can give it a shot instead of guessing. It turns out, no, Unicode won't work, but using x\99 for the TM character does, at least on my system (no idea if this will be universal): import EasyDialogs lim = 100000 title = "FooBar\x99" bar = EasyDialogs.ProgressBar(title, maxval=lim) for i in range(lim): bar.inc() del bar From keridee at jayco.net Tue Aug 7 05:38:52 2007 From: keridee at jayco.net (Tiger12506) Date: Mon, 6 Aug 2007 22:38:52 -0500 Subject: [Tutor] Ingenious script (IMO) References: <20070806131709.60E4F1E4006@bag.python.org> <00a301c7d86f$370459f0$91fce004@JSLAPTOP><20070806225738.1B8B81E400A@bag.python.org> <46B7ABA3.9000601@tds.net> Message-ID: <001d01c7d8a4$7d851ba0$91fce004@JSLAPTOP> > The modern way seems to be to look at the change amount given by the > cash register and count that out starting with dollars... So true... tsk tsk. That's because the teenagers that give you the change do not know how to count it back. What a great idea to write a program that can show them how! Or perhaps the excuse is more the truth - it's faster to throw the change at you. I know that many old-timers would be very impressed to have their change counted back to them. (It's required sometimes-my father told stories of a blind man that knew how much money he had and where in his wallet it was by how the cashier counted it back). I imagine that however exactly it is phrased when you count back change is dialectual. Some people do it some way, some do it other ways. In my part of the US, the "proper" way is: $10.00 Say "5.77" "3 makes 80" "20 makes 6" "and four makes 10 dollars" "Have a nice day" While handing out the described amount at each line break. Sometimes, especially in important applications, like in a bank, they will count and hand the bills out to you individually - i.e. "and one, two, three, four makes 10 dollars" Of course, the "have a nice day" is optional, but it makes a nice touch ;-) Among the elders, it is considered very courteous to count back the change, but so often this is not the case that it is no longer considered rude to skip the counting... Anyway, the python part of this discussion is to point out that the method varies, so it would be even more of a challenge to provide options for how the change should be counted. JS From keridee at jayco.net Tue Aug 7 05:41:46 2007 From: keridee at jayco.net (Tiger12506) Date: Mon, 6 Aug 2007 22:41:46 -0500 Subject: [Tutor] superscript with easydialogs References: Message-ID: <002c01c7d8a4$e4fe3690$91fce004@JSLAPTOP> > It turns out, no, Unicode won't work, but using x\99 for the TM character > does, at least on my system (no idea if this will be universal): That's strange. Windows is Unicode based! All text operations done in Windows are first converted to unicode, calculated, and then back. That's even been mentioned on this list... From rdm at rcblue.com Tue Aug 7 05:32:35 2007 From: rdm at rcblue.com (Dick Moores) Date: Mon, 06 Aug 2007 20:32:35 -0700 Subject: [Tutor] Ingenious script (IMO) In-Reply-To: <001d01c7d8a4$7d851ba0$91fce004@JSLAPTOP> References: <20070806131709.60E4F1E4006@bag.python.org> <00a301c7d86f$370459f0$91fce004@JSLAPTOP> <20070806225738.1B8B81E400A@bag.python.org> <46B7ABA3.9000601@tds.net> <001d01c7d8a4$7d851ba0$91fce004@JSLAPTOP> Message-ID: <20070807033247.413261E4006@bag.python.org> At 08:38 PM 8/6/2007, Tiger12506 wrote: > > The modern way seems to be to look at the change amount given by the > > cash register and count that out starting with dollars... >So true... tsk tsk. > >That's because the teenagers that give you the change do not know how to >count it back. What a great idea to write a program that can show them how! >Or perhaps the excuse is more the truth - it's faster to throw the change at >you. I know that many old-timers would be very impressed to have their >change counted back to them. (It's required sometimes-my father told stories >of a blind man that knew how much money he had and where in his wallet it >was by how the cashier counted it back). > >I imagine that however exactly it is phrased when you count back change is >dialectual. Some people do it some way, some do it other ways. In my part of >the US, the "proper" way is: > >$10.00 >Say "5.77" >"3 makes 80" >"20 makes 6" >"and four makes 10 dollars" >"Have a nice day" > >While handing out the described amount at each line break. Sometimes, >especially in important applications, like in a bank, they will count and >hand the bills out to you individually - i.e. "and one, two, three, four >makes 10 dollars" >Of course, the "have a nice day" is optional, but it makes a nice touch ;-) >Among the elders, it is considered very courteous to count back the change, >but so often this is not the case that it is no longer considered rude to >skip the counting... > >Anyway, the python part of this discussion is to point out that the method >varies, so it would be even more of a challenge to provide options for how >the change should be counted. OK, I'll give it a try. Thanks for the challenges. Dick ====================================== Bagdad Weather From alan.gauld at btinternet.com Tue Aug 7 09:11:30 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 7 Aug 2007 08:11:30 +0100 Subject: [Tutor] superscript with easydialogs References: <002c01c7d8a4$e4fe3690$91fce004@JSLAPTOP> Message-ID: "Tiger12506" wrote >> It turns out, no, Unicode won't work, but using x\99 for the TM >> character >> does, at least on my system (no idea if this will be universal): > > That's strange. Windows is Unicode based! Unicode is effective at the font level. You need to have a font that supports the extended characters. The standard System font, which I think is what easyDialogs uses is a relic of the original Windows 3.0 and predates unicode. You can see which characters are supported by which font using the character map application found in Accessories. Arial for example does not appear to have the TM symbol as a character. HTH, Alan G. From zebra05 at gmail.com Tue Aug 7 11:12:41 2007 From: zebra05 at gmail.com (OkaMthembo) Date: Tue, 7 Aug 2007 11:12:41 +0200 Subject: [Tutor] Large Scale Python websites Message-ID: Hi all, Is anyone aware of any large scale web apps developed in Python? Please let me know of any that you know of... Kind Regards, -- Sithembewena Lloyd Dube "The Stupidry Foundry" -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070807/99b1cb86/attachment.htm From spmcinerney at hotmail.com Tue Aug 7 11:18:16 2007 From: spmcinerney at hotmail.com (Stephen McInerney) Date: Tue, 07 Aug 2007 02:18:16 -0700 Subject: [Tutor] Losing the expressiveness of C's for-statement? Message-ID: Hi all, As the Python doc says: "The for statement in Python differs a bit from what you may be used to in C or Pascal. Rather than giving the user the ability to define both the iteration step and halting condition (as C), Python's for statement iterates over the items of any sequence (a list or a string)." This is much poorer than C/C++, and does not allow for the step action to be multiple actions, fn calls etc. - not straightforwardly anyway. (don't take that as a challenge) - I know how to migrate to a while-loop, but I lament losing the very compact expressiveness of: for (node=start; valuenext) { ... } - I figure the straightforward answer will be "use a while-loop, put the iteration step at the end". - the fancy showoff answer will probably involve a funky iterator with side-effects, or returning tuples. - what if the loop iteration step involves variables from within the loop-body (e.g. as in quicksort stepsize); - what I'm trying to drive at here is the general solution of least idiomaticity, not of greatest language-specific cleverness Any comments or article links? Also, it would be useful to improve the Python tutorial on this. Since this is one area where Python is (syntactically) inferior to C/C++/Java. Thanks, Stephen _________________________________________________________________ More photos, more messages, more storage?get 2GB with Windows Live Hotmail. http://imagine-windowslive.com/hotmail/?locale=en-us&ocid=TXT_TAGHM_migration_HM_mini_2G_0507 From spmcinerney at hotmail.com Tue Aug 7 11:24:25 2007 From: spmcinerney at hotmail.com (Stephen McInerney) Date: Tue, 07 Aug 2007 02:24:25 -0700 Subject: [Tutor] Losing the expressiveness of C's for-statement?/ RESEND with example In-Reply-To: Message-ID: (Question as below) Sorry I meant to pick a tangible example to focus the discussion: This one cannot be (easily) translated to use Python's range() operator for (i=30000; i>0; i=i/2) { ... } So do you need to know a whole armory of other functions to use to generate iterators, or just translate to a while-loop already? Stephen >From: "Stephen McInerney" >To: tutor at python.org >Subject: Losing the expressiveness of C's for-statement? >Date: Tue, 07 Aug 2007 02:18:16 -0700 > >Hi all, > >As the Python doc says: "The for statement in Python differs a bit from >what you may be used to in C or Pascal. Rather than giving the user the >ability to define both the iteration step and halting condition (as C), >Python's for statement iterates over the items of any sequence (a list or a >string)." > >This is much poorer than C/C++, and does not allow for the step action to >be multiple actions, fn calls etc. - not straightforwardly anyway. (don't >take that as a challenge) >- I know how to migrate to a while-loop, but I lament losing the very >compact expressiveness of: >for (node=start; valuenext) { ... } >- I figure the straightforward answer will be "use a while-loop, put the >iteration step at the end". >- the fancy showoff answer will probably involve a funky iterator with >side-effects, or returning tuples. >- what if the loop iteration step involves variables from within the >loop-body (e.g. as in quicksort stepsize); >- what I'm trying to drive at here is the general solution of least >idiomaticity, not of greatest language-specific cleverness > >Any comments or article links? Also, it would be useful to improve the >Python tutorial on this. >Since this is one area where Python is (syntactically) inferior to >C/C++/Java. > >Thanks, >Stephen _________________________________________________________________ Find a local pizza place, movie theater, and more?.then map the best route! http://maps.live.com/default.aspx?v=2&ss=yp.bars~yp.pizza~yp.movie%20theater&cp=42.358996~-71.056691&style=r&lvl=13&tilt=-90&dir=0&alt=-1000&scene=950607&encType=1&FORM=MGAC01 From alan.gauld at btinternet.com Tue Aug 7 11:58:22 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 7 Aug 2007 10:58:22 +0100 Subject: [Tutor] Losing the expressiveness of C's for-statement?/ RESENDwith example References: Message-ID: "Stephen McInerney" wrote > Sorry I meant to pick a tangible example to focus the discussion: > > This one cannot be (easily) translated to use Python's range() > operator for (i=30000; i>0; i=i/2) { ... } You have to remember that C's for loop is mostly syntactic sugar over a while loop: expression1 while test action expression2 becomes for (expression1, test, expression2) action Pythons for loop is a much more powerful foreach construct intended to deal with collections. C's for loop is simply an extension of assembler syntax and deals with indices, memory addresses, numbers, whatever low level construct you want. The loop used for that kind of low level detail in Python is, as you say, the while loop. > So do you need to know a whole armory of other functions to use > to generate iterators, or just translate to a while-loop already? It's very rare that you need to do those kinds of tricks in Python, usually you avoid the issue entirely by using higher level data structures. You don't give us any reason why you want to generate a set of numbers from 30,000 down to zero decreasing by half each time: 30,000, 15,000, 7500, 3750, etc To understand the Pythonic solution to the problem we would need to know what those numbers were required for so that we could determine if another python data structure might be more appropriate. One of the challenges for C/C++ programmers in moving to higher order languages like Python (or Lisp, prolog, Smalltalk etc) is to stop thinking at the machine level and start thinking at the problem level. Of course sometimes you need to work at the lower levels and for those cases the while loop can be used, but it tends to be the exception rather than the rule. As to your particular case one non while option would be a generateor: def half(n): while int(n) > 0: n = n/2 yield n for x in half(300): print x, But without a context for x its impossible to know ewheher that is a sensible solution. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From spmcinerney at hotmail.com Tue Aug 7 12:24:18 2007 From: spmcinerney at hotmail.com (Stephen McInerney) Date: Tue, 07 Aug 2007 03:24:18 -0700 Subject: [Tutor] Losing the expressiveness of C's for-statement?/RESENDwith example In-Reply-To: Message-ID: Hi Alan, I don't deny the superiority of the underlying language design, I'm just pointing out the very real mindjolting effect of Python not supporting the universal syntax. Java is closer to C than Python is. I'm bringing this up as one hurdle to migration, not a fundamental flaw. Don't you agree that the Python tutorial should say something simple and accessible to beginners like: "For all for-loop constructs where the iteration can't be written as a simple range object, you probably want to transform it to a while-loop, (or the more advanced option being a generator)"? I think the tutorial is lacking on this (should I email Fred Drake?) Instead of leaving C and Java people cold scratching their heads about why they think the language is hopelessly quirky and not (syntactically) fully-featured? One of our aims should be to write code which is at least understandable to programmers of other languages. >Sorry I meant to pick a tangible example to focus the discussion: >This one cannot be (easily) translated to use Python's range() >operator for (i=30000; i>0; i=i/2) { ... } >You don't give us any reason why you want to generate a set >of numbers from 30,000 down to zero decreasing by half each >time: 30,000, 15,000, 7500, 3750, etc >To understand the Pythonic solution to the problem we would >need to know what those numbers were required for so that we >could determine if another python data structure might be more >appropriate. Yes I did: it occurs in a quicksort as we halve the stepsize each time, on an array of size 60000. Can you please give me your answer on this? We have to transform it to a while-loop? (or write a custom iterator?) It would nice to compare the most straightforward solution (while-loop?) the fastest solution, the last-memory solution and the most elegant solution. >You have to remember that C's for loop is mostly syntactic sugar >over a while loop: expression1 while test action expression2 Yes I know how to transform it. >Pythons for loop is a much more powerful foreach construct >intended to deal with collections. C's for loop is simply an extension >of assembler syntax and deals with indices, memory addresses, numbers, >whatever low level construct you want. The loop used for that kind >of low level detail in Python is, as you say, the while loop. >As to your particular case one non while option would be a generateor: > >def half(n): > while int(n) > 0: > n = n/2 > yield n > >for x in half(300): print x, It's ok but it's visually clunky. while-loop wins for clarity. lambda would also be too quirky. I know the generator is more runtime-efficient. It's regrettable we have to choose between the clear and the efficient, in this situation. Regards, Stephen _________________________________________________________________ Learn.Laugh.Share. Reallivemoms is right place! http://www.reallivemoms.com?ocid=TXT_TAGHM&loc=us From v.tini at tu-bs.de Tue Aug 7 12:20:29 2007 From: v.tini at tu-bs.de (Vivian Tini) Date: Tue, 7 Aug 2007 12:20:29 +0200 Subject: [Tutor] executing file properly Message-ID: <1186482029.46b8476d87460@webmail.tu-bs.de> Dear All, I am a newbie in Python and I would like to create command line interface for executing different softwares, either local or remotely. I begin with a very simple case in which I have an executable file called "TestCases" and this file requires Des.in as an the input. Both files are located in the same local folder. The TestCases executable works properly when I run it from the shell prompt. Then I try to run it from the Python command prompt by the following script: >>> import os >>> os.system("home/.../.../.../TestCases") I used "..." to type it short. Then it gives the following error output: cannot open Des.in Well in this case tbe os.system command is typed correctly already since this the error message given out is written in the code itself. So the executable run already only when running from Python prompt it cannot open this file. Could anyone suggest me what would be the cause of this problem? And how should I handle it ? Thank you in advance. Vivian From khamid.nurdiev at gmail.com Tue Aug 7 13:04:55 2007 From: khamid.nurdiev at gmail.com (Khamid Nurdiev) Date: Tue, 7 Aug 2007 15:04:55 +0400 Subject: [Tutor] Books with exercises and problems to solve Message-ID: Hello all, so long i have been learning python with two books 1) Official tutorial by Guido Van Rossum and 2) Pythong Programming: An Introduction to Computer Science by John M. Zelle and like them a lot as the first one gives a lot of explanations but without any exercises, but the second one has a lot of exercises to do which I like. I would like to know if anyone can recommend a book like the second one with a lot of exercises to do and problems to solve, not just the explanations for concurrent and also further study. Thanks a lot. P.S.= I am new both to Python and Programming too. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070807/93f5f030/attachment.html From kent37 at tds.net Tue Aug 7 13:15:36 2007 From: kent37 at tds.net (Kent Johnson) Date: Tue, 07 Aug 2007 07:15:36 -0400 Subject: [Tutor] Large Scale Python websites In-Reply-To: References: Message-ID: <46B85458.4070500@tds.net> OkaMthembo wrote: > Hi all, > > Is anyone aware of any large scale web apps developed in Python? Please > let me know of any that you know of... http://www.davidcramer.net/other/43/rapid-development-serving-500000-pageshour.html http://www.davidcramer.net/curse/44/what-powers-curse.html http://www.cogitooptimus.com/2007/03/21/deploying-trenchmice/ http://immike.net/blog/2007/07/06/interview-with-leah-culver-the-making-of-pownce/ Note that none of these are *just* Python, they all combine Python / Django with caching, load balancing and front-end servers. Don't know if any of these are large-scale... http://code.djangoproject.com/wiki/DjangoPoweredSites Kent From thorsten at thorstenkampe.de Tue Aug 7 13:18:09 2007 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Tue, 7 Aug 2007 12:18:09 +0100 Subject: [Tutor] executing file properly References: <1186482029.46b8476d87460@webmail.tu-bs.de> Message-ID: * Vivian Tini (Tue, 7 Aug 2007 12:20:29 +0200) > The TestCases executable works properly when I run it from the shell prompt. > > Then I try to run it from the Python command prompt by the following script: > >>> import os > >>> os.system("home/.../.../.../TestCases") > > I used "..." to type it short. > > Then it gives the following error output: > cannot open Des.in > > Well in this case tbe os.system command is typed correctly already since this > the error message given out is written in the code itself. So the executable > run already only when running from Python prompt it cannot open this file. > > Could anyone suggest me what would be the cause of this problem? You said it yourself: "I used "..." to type it short." > And how should I handle it ? Even simpler: don't use "..." From Andy.cheesman at bristol.ac.uk Tue Aug 7 13:19:36 2007 From: Andy.cheesman at bristol.ac.uk (Andy Cheesman) Date: Tue, 07 Aug 2007 12:19:36 +0100 Subject: [Tutor] comparing two numpy arrays Message-ID: <46B85548.7000805@bristol.ac.uk> Hi people, If I've two numpy arrays, is there a non-looping way of finding common values. (the example below has identical shapes for the arrays but this may not be the case in my scenario) e.g a = array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) b = array([ 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]) answer = array([ 5,6,7,8,9]) Thanks Andy From kent37 at tds.net Tue Aug 7 13:29:31 2007 From: kent37 at tds.net (Kent Johnson) Date: Tue, 07 Aug 2007 07:29:31 -0400 Subject: [Tutor] Losing the expressiveness of C's for-statement?/RESENDwith example In-Reply-To: References: Message-ID: <46B8579B.1080009@tds.net> Stephen McInerney wrote: > I think the tutorial is lacking on this (should I email Fred Drake?) > Instead of leaving C and Java people cold scratching their heads about > why they think the language is hopelessly quirky and not (syntactically) > fully-featured? The "About this document" link at the bottom of every page of the Python docs tells how to make suggestions. I have found that specific suggestions for changes to the docs (i.e., include the suggested text) filed in the bug tracker are often accepted and incorporated. Kent From kent37 at tds.net Tue Aug 7 13:34:53 2007 From: kent37 at tds.net (Kent Johnson) Date: Tue, 07 Aug 2007 07:34:53 -0400 Subject: [Tutor] executing file properly In-Reply-To: <1186482029.46b8476d87460@webmail.tu-bs.de> References: <1186482029.46b8476d87460@webmail.tu-bs.de> Message-ID: <46B858DD.8080700@tds.net> Vivian Tini wrote: > Dear All, > > I am a newbie in Python and I would like to create command line interface for > executing different softwares, either local or remotely. > > I begin with a very simple case in which I have an executable file called > "TestCases" and this file requires Des.in as an the input. Both files are > located in the same local folder. > > The TestCases executable works properly when I run it from the shell prompt. > > Then I try to run it from the Python command prompt by the following script: >>>> import os >>>> os.system("home/.../.../.../TestCases") > > I used "..." to type it short. > > Then it gives the following error output: > cannot open Des.in > > Well in this case tbe os.system command is typed correctly already since this > the error message given out is written in the code itself. So the executable > run already only when running from Python prompt it cannot open this file. > > Could anyone suggest me what would be the cause of this problem? And how > should I handle it ? I guess the working directory is not set to the dir containing TestCases so it doesn't find the file. I don't know if it will help to call os.chdir() before os.system(); you could use subprocess.Popen() instead of os.system(), it takes an explicit parameter of the cwd for the subprocess. Kent From kent37 at tds.net Tue Aug 7 13:37:39 2007 From: kent37 at tds.net (Kent Johnson) Date: Tue, 07 Aug 2007 07:37:39 -0400 Subject: [Tutor] Books with exercises and problems to solve In-Reply-To: References: Message-ID: <46B85983.50209@tds.net> Khamid Nurdiev wrote: > Hello all, > so long i have been learning python with two books 1) Official tutorial > by Guido Van Rossum and 2) Pythong Programming: An Introduction to > Computer Science by John M. Zelle and like them a lot as the first one > gives a lot of explanations but without any exercises, but the second > one has a lot of exercises to do which I like. I would like to know if > anyone can recommend a book like the second one with a lot of exercises > to do and problems to solve, not just the explanations for concurrent > and also further study. "Python Programming for the absolute beginner" is written for people with no prior programming experience and includes exercises. Wesley Chun's "Core Python Programming" includes exercises. Kent From khamid.nurdiev at gmail.com Tue Aug 7 13:53:23 2007 From: khamid.nurdiev at gmail.com (Khamid Nurdiev) Date: Tue, 7 Aug 2007 15:53:23 +0400 Subject: [Tutor] Books with exercises and problems to solve In-Reply-To: <46B85983.50209@tds.net> References: <46B85983.50209@tds.net> Message-ID: thanks a lot for your help On 8/7/07, Kent Johnson wrote: > > Khamid Nurdiev wrote: > > Hello all, > > so long i have been learning python with two books 1) Official tutorial > > by Guido Van Rossum and 2) Pythong Programming: An Introduction to > > Computer Science by John M. Zelle and like them a lot as the first one > > gives a lot of explanations but without any exercises, but the second > > one has a lot of exercises to do which I like. I would like to know if > > anyone can recommend a book like the second one with a lot of exercises > > to do and problems to solve, not just the explanations for concurrent > > and also further study. > > "Python Programming for the absolute beginner" is written for people > with no prior programming experience and includes exercises. > > Wesley Chun's "Core Python Programming" includes exercises. > > Kent > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070807/349208f2/attachment.htm From jsmith at medplus.com Tue Aug 7 15:00:33 2007 From: jsmith at medplus.com (Smith, Jeff) Date: Tue, 7 Aug 2007 09:00:33 -0400 Subject: [Tutor] Losing the expressiveness of C'sfor-statement?/RESENDwith example In-Reply-To: References: Message-ID: <288A3B43F7B2224D9C8441C9FC5D6A020214EE70@EXCHMAIL01.corp.medplus.com> From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Stephen McInerney From: alan.gauld at btinternet.com; tutor at python.org >>As to your particular case one non while option would be a generateor: >> >>def half(n): >> while int(n) > 0: >> n = n/2 >> yield n >> >>for x in half(300): print x, >It's ok but it's visually clunky. while-loop wins for clarity. lambda would also be too quirky. >I know the generator is more runtime-efficient. >It's regrettable we have to choose between the clear and the efficient, in this situation. I would have to disagree completely. Knowing both C and Python intimately now, I find this Pythonic expression far easier to read than the overly-verbose C statement. The nice thing about python is that it makes chunking much easier than C which increases readability. Remember that these lines would be visually separated. In the algorithmic part of the quicksort all you would have is fox x in decrement_by_halves(300): do stuff Note that I changed the name of the generator to be more explicit. The loop now tells exactly what is being generated. No more tearing apart an ugly C for construct which forces implementation of the generator at a place where you don't really need to know about it. Jeff From alan.gauld at btinternet.com Tue Aug 7 16:24:34 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 7 Aug 2007 15:24:34 +0100 Subject: [Tutor] Losing the expressiveness of C'sfor-statement?/RESENDwith example References: Message-ID: "Stephen McInerney" wrote > I don't deny the superiority of the underlying language design, > I'm just pointing out the very real mindjolting effect of Python not > supporting the universal syntax. An interesting term. The C syntax is extremely odd to most programmers who haven't been trained in it but in more traditional languages like Lisp, Cobol, Fortran, Pascal, ADA, etc. It is also highly error prone and a source of many bugs in C programs (I know I spent several years running a C maintenance project and for loop side-effects were right up there with uninitialised variables and memory leaks in the common error lists!). > Java is closer to C than Python is. True, Java deliberately set out to be a simple subset of C++ so it has a similar syntax. Python is closer to Lisp than C is but nobody would suggest that C should change its semantics to suit the tastes of Lisp programmers who are converting. Languages are different and learning the new idioms both positives and negatives) is part of the process. > Don't you agree that the Python tutorial should say something simple > and accessible to beginners like: "For all for-loop constructs where > the > iteration can't be written as a simple range object, In fact the range version of a for loop is only one style and probably not the most common. You should iterate over a collection not a range in most cases: ie someList = [1,2,3,4,5] for item in someList: print item and never for index in range(len(somelist)): print somelist[index] # bad bad bad! It is Pythons "foreach" effect that makes it so powerful. > I think the tutorial is lacking on this (should I email Fred Drake?) You could try it but that would imply that the tutorial should flag up where Python varies from the syntax of COBOL too - after all there are many more COBOL porogrammers than any other language! So explaining x = y + z we would need a note: Notice that Python uses a math symbol for addition instead of the more common COBOL usage ADD Y, Z TO X And explain to Smalltalk, ADA and Pascal programmers that = is assignment instead of := Where do you stop? > Instead of leaving C and Java people cold scratching their heads > about > why they think the language is hopelessly quirky and not > (syntactically) > fully-featured? A language is syntactically fully featured if it supports the 3 elements of structured programming (sequences, loops and branches) , or even more starkly if it is Turing complete. No language should try to encompass all styntax structures of all languages (that way lies PL/1!) > One of our aims should be to write code which is at least > understandable to > programmers of other languages. Yes, but that doesn't mean a similar syntax, it means an easy comprehension of the syntax as written. ie one that reads as much as possible like a natural language - a test that C fails miserably! >>You don't give us any reason why you want to generate a set >>of numbers from 30,000 down to zero decreasing by half each >>time: 30,000, 15,000, 7500, 3750, etc > Yes I did: it occurs in a quicksort as we halve the stepsize each > time, > on an array of size 60000. OK so use Pythons built in sort method. It uses quick sort I believe. But if it doesn't still use it and see if its fast enough. If it isn't consider refactoring your data structures to improve it. If that doesn't work then, as a last resort, consider writing your own sort function. When using high level languages leverage the language. > Can you please give me your answer on this? We have to transform it > to > a while-loop? (or write a custom iterator?) > It would nice to compare the most straightforward solution > (while-loop?) The most straightforward solution is to use the standard sort function. > the fastest solution, the last-memory solution and the most elegant > solution. Yes it's almost certainly all of those. >>def half(n): >> while int(n) > 0: >> n = n/2 >> yield n >> >>for x in half(300): print x, > > It's ok but it's visually clunky. while-loop wins for clarity. I disagree, the while lop is a distraction from what you are trying to achieve, which is use a specific list on numbers to performs some action, in your case a sort. The more you can hide the generation of the numbers the clearer your code becomes. (PS I agree the name "half" is not great but it was short in the interpreter! :-) > lambda would also be too quirky. lambda is no good here because Python's lambda only allows a single expression not loops - I originally thought a lambda might work. (The limitations of Python's lambda are another copmmon complaint for programmers moving from languages which better support functional programming, but that still doesn't mean Python should change its lambda to match) > I know the generator is more runtime-efficient. You know more than me in that case, I didn't even think about that, I simply tried to solve the problem. If run time efficiency is that critical Python is probably not the right language anyway - but only if you try it, and measure it, and know that run time efficiency is an issue. Python is not trying to get you close to the machine, quite the opposite, its trying to get you closer to the problem you are trying to solve. C is designed to get you close to the machnie, that's why its the right choice for writing device drivers etc. But C is a poor choice for more user centric problems. > It's regrettable we have to choose between the clear and the > efficient, in > this situation. The most clear and efficient is probably: myList.sort() HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From Mike.Hansen at atmel.com Tue Aug 7 16:35:29 2007 From: Mike.Hansen at atmel.com (Mike Hansen) Date: Tue, 7 Aug 2007 08:35:29 -0600 Subject: [Tutor] comparing two numpy arrays In-Reply-To: <46B85548.7000805@bristol.ac.uk> References: <46B85548.7000805@bristol.ac.uk> Message-ID: <57B026980605A64F9B23484C5659E32E9835B5@poccso.US.ad.atmel.com> > From: tutor-bounces at python.org > [mailto:tutor-bounces at python.org] On Behalf Of Andy Cheesman > > Hi people, > > If I've two numpy arrays, is there a non-looping way of finding common > values. (the example below has identical shapes for the > arrays but this > may not be the case in my scenario) > > e.g > a = array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) > b = array([ 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]) > > answer = array([ 5,6,7,8,9]) > > Thanks > > Andy You might try sets. http://docs.python.org/lib/types-set.html I'm guessing that you'd need to convert the arrays to sets. Maybe convert the arrays to lists or tuples then to sets? Maybe you might be able to directly convert the numpy arrays to sets? I haven't used numpy, so you'll need to experiment. Mike From alan.gauld at btinternet.com Tue Aug 7 16:38:25 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 7 Aug 2007 15:38:25 +0100 Subject: [Tutor] Large Scale Python websites References: Message-ID: "OkaMthembo" wrote > Is anyone aware of any large scale web apps developed in Python? > Please let > me know of any that you know of... The Zope web site has many examples. But it depends how you define large scale. Most of the really big ones (Google, Yahoo, IBM, BBC etc - anything with several million hits a day) use Java or C++ in my experience. But a lot of large and busy sites do exist using one or other of the Pyhon web frameworks, check the frameworks and you will find case histories. And even the biggest sites often use languages like Python etc for experimental features or occasional access areas or for administration or test duties. One of the good things abourt web developments is that its pretty easy to mix frameworks and have it appear seamless to the user. Alan G. From bgailer at alum.rpi.edu Tue Aug 7 16:44:47 2007 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Tue, 07 Aug 2007 07:44:47 -0700 Subject: [Tutor] comparing two numpy arrays In-Reply-To: <46B85548.7000805@bristol.ac.uk> References: <46B85548.7000805@bristol.ac.uk> Message-ID: <46B8855F.3070301@alum.rpi.edu> Andy Cheesman wrote: > Hi people, > > If I've two numpy arrays, is there a non-looping way of finding common > values. (the example below has identical shapes for the arrays but this > may not be the case in my scenario) > > e.g > a = array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) > b = array([ 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]) > > answer = array([ 5,6,7,8,9]) Set union? -- Bob Gailer 510-978-4454 Oakland, CA 919-636-4239 Chapel Hill, NC From wormwood_3 at yahoo.com Tue Aug 7 16:47:38 2007 From: wormwood_3 at yahoo.com (wormwood_3) Date: Tue, 7 Aug 2007 07:47:38 -0700 (PDT) Subject: [Tutor] Checking for custom error codes Message-ID: <889269.23128.qm@web32404.mail.mud.yahoo.com> Hi all, I am new to Python programming and this list, looks like a great place so far! Recently I was trying to do a "try: X except Y: Z" statement, checking for a custom error code that the rwhois.py module throws. Some details on the exercise and the full code can be found on this post ( http://assistedsilicon.blogspot.com/2007/08/fun-with-python-domainspotter.html ). So, here is what I tried: for potdomain in self.potdomains: try: who.whois(potdomain) self.availdomains.append(potdomain) except 'NoSuchDomain': pass self.totalchecked+=1 If you need more context, the whole program is here ( http://assistedsilicon.blogspot.com/2007/08/fun-with-python-domainspotter.html#code ). I first tried simply "except NoSuchDomain", since that was what I saw rwhois throw when I sent it a domain that was not registered. That did not work, so I quoted it. I got a warning that throwing a string exception is deprecated, but the check did not work anyway. Am I trying to check for this custom error wrongly? How should it be done? Thanks for any assistance! -Sam From wormwood_3 at yahoo.com Tue Aug 7 16:52:09 2007 From: wormwood_3 at yahoo.com (wormwood_3) Date: Tue, 7 Aug 2007 07:52:09 -0700 (PDT) Subject: [Tutor] Checking for custom error codes Message-ID: <760752.23855.qm@web32406.mail.mud.yahoo.com> Hi all, I am new to Python programming and this list, looks like a great place so far! Recently I was trying to do a "try: X except Y: Z" statement, checking for a custom error code that the rwhois.py module throws. Some details on the exercise and the full code can be found on this post ( http://assistedsilicon.blogspot.com/2007/08/fun-with-python-domainspotter.html ). So, here is what I tried: for potdomain in self.potdomains: try: who.whois(potdomain) self.availdomains.append(potdomain) except 'NoSuchDomain': pass self.totalchecked+=1 If you need more context, the whole program is here ( http://assistedsilicon.blogspot.com/2007/08/fun-with-python-domainspotter.html#code ). I first tried simply "except NoSuchDomain", since that was what I saw rwhois throw when I sent it a domain that was not registered. That did not work, so I quoted it. I got a warning that throwing a string exception is deprecated, but the check did not work anyway. Am I trying to check for this custom error wrongly? How should it be done? Thanks for any assistance! -Sam From bhaaluu at gmail.com Tue Aug 7 17:02:28 2007 From: bhaaluu at gmail.com (bhaaluu) Date: Tue, 7 Aug 2007 11:02:28 -0400 Subject: [Tutor] Large Scale Python websites In-Reply-To: References: Message-ID: http://www.python.org/Quotes.html Google "Python has been an important part of Google since the beginning, and remains so as the system grows and evolves. Today dozens of Google engineers use Python, and we're looking for more people with skills in this language." said Peter Norvig, director of search quality at Google, Inc. -- bhaaluu at gmail dot com On 8/7/07, Alan Gauld wrote: > > "OkaMthembo" wrote > > > Is anyone aware of any large scale web apps developed in Python? > > Please let > > me know of any that you know of... > > The Zope web site has many examples. > > But it depends how you define large scale. Most of the really big ones > (Google, > Yahoo, IBM, BBC etc - anything with several million hits a day) use > Java or C++ > in my experience. But a lot of large and busy sites do exist using one > or other > of the Pyhon web frameworks, check the frameworks and you will find > case > histories. > > And even the biggest sites often use languages like Python etc for > experimental features or occasional access areas or for administration > or test duties. One of the good things abourt web developments is that > its pretty easy to mix frameworks and have it appear seamless to the > user. > > Alan G. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Tue Aug 7 17:19:34 2007 From: kent37 at tds.net (Kent Johnson) Date: Tue, 07 Aug 2007 11:19:34 -0400 Subject: [Tutor] Losing the expressiveness of C'sfor-statement?/RESENDwith example In-Reply-To: References: Message-ID: <46B88D86.2090204@tds.net> Alan Gauld wrote: > OK so use Pythons built in sort method. It uses quick sort I believe. No, it uses 'timsort', an "adaptive, stable, natural mergesort [with] supernatural performance on many kinds of partially ordered arrays." Read about it here: http://svn.python.org/view/python/trunk/Objects/listsort.txt?rev=51013&view=auto > But if it doesn't still use it and see if its fast enough. If it isn't > consider > refactoring your data structures to improve it. If that doesn't work > then, > as a last resort, consider writing your own sort function. Hmmm...IMO there is vanishingly small chance that a sort written in Python will be faster than the built-in sort and slim chance that a sort written in C will be faster. timsort is at least the third sort algorithm to be used in Python - some smart people have been tweaking it for a long time. Kent From kent37 at tds.net Tue Aug 7 17:32:14 2007 From: kent37 at tds.net (Kent Johnson) Date: Tue, 07 Aug 2007 11:32:14 -0400 Subject: [Tutor] Checking for custom error codes In-Reply-To: <760752.23855.qm@web32406.mail.mud.yahoo.com> References: <760752.23855.qm@web32406.mail.mud.yahoo.com> Message-ID: <46B8907E.40606@tds.net> wormwood_3 wrote: > Hi all, > > I am new to Python programming and this list, looks like a great place so far! > > Recently I was trying to do a "try: X except Y: Z" statement, checking for a custom error code that the rwhois.py module throws. Some details on the exercise and the full code can be found on this post ( http://assistedsilicon.blogspot.com/2007/08/fun-with-python-domainspotter.html ). So, here is what I tried: > > for potdomain in self.potdomains: > try: > who.whois(potdomain) > self.availdomains.append(potdomain) > except 'NoSuchDomain': > pass > self.totalchecked+=1 > > If you need more context, the whole program is here ( http://assistedsilicon.blogspot.com/2007/08/fun-with-python-domainspotter.html#code ). I first tried simply "except NoSuchDomain", since that was what I saw rwhois throw when I sent it a domain that was not registered. That did not work, so I quoted it. I got a warning that throwing a string exception is deprecated, but the check did not work anyway. Am I trying to check for this custom error wrongly? How should it be done? Probably you need to import NoSuchDomain from rwhois: from rwhois import WhoisRecord, NoSuchDomain then use except NoSuchDomain: In general, when you ask a question here, "I tried X and it did not work" is not very informative and makes it difficult to give a good answer. It is very helpful to show the actual code you tried and the actual error message, including the full traceback. The error message and traceback include a lot of very helpful information; including them will greatly improve your chance of a correct answer. Kent From dkuhlman at rexx.com Tue Aug 7 17:39:16 2007 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Tue, 7 Aug 2007 08:39:16 -0700 Subject: [Tutor] Books with exercises and problems to solve In-Reply-To: References: Message-ID: <20070807153916.GA73465@cutter.rexx.com> On Tue, Aug 07, 2007 at 03:04:55PM +0400, Khamid Nurdiev wrote: > Hello all, > so long i have been learning python with two books 1) Official tutorial by > Guido Van Rossum and 2) Pythong Programming: An Introduction to Computer > Science by John M. Zelle and like them a lot as the first one gives a lot of > explanations but without any exercises, but the second one has a lot of > exercises to do which I like. I would like to know if anyone can recommend a > book like the second one with a lot of exercises to do and problems to > solve, not just the explanations for concurrent and also further study. > You might look at "Python Cookbook", by Alex Martelli. Each section (and there are many) gives a problem, a solution, and a discussion. So, you could read a problem section, write your own solution, then compare your solution with the solution in the book. And, as a bonus, the discussion section will help to understand how the solution works and why it's a good way to solve the problem. There is also an on-line version, which is definitely worth looking at, but does not have the problem-solution-discussion format: http://aspn.activestate.com/ASPN/Cookbook/Python/ Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman From bgailer at alum.rpi.edu Tue Aug 7 17:40:01 2007 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Tue, 07 Aug 2007 08:40:01 -0700 Subject: [Tutor] Checking for custom error codes In-Reply-To: <760752.23855.qm@web32406.mail.mud.yahoo.com> References: <760752.23855.qm@web32406.mail.mud.yahoo.com> Message-ID: <46B89251.6020707@alum.rpi.edu> wormwood_3 wrote: > Hi all, > > I am new to Python programming and this list, looks like a great place so far! > > Recently I was trying to do a "try: X except Y: Z" statement, checking for a custom error code that the rwhois.py module throws. Some details on the exercise and the full code can be found on this post ( http://assistedsilicon.blogspot.com/2007/08/fun-with-python-domainspotter.html ). So, here is what I tried: > > for potdomain in self.potdomains: > try: > who.whois(potdomain) > self.availdomains.append(potdomain) > except 'NoSuchDomain': > pass > self.totalchecked+=1 > > If you need more context, the whole program is here ( http://assistedsilicon.blogspot.com/2007/08/fun-with-python-domainspotter.html#code ). I first tried simply "except NoSuchDomain", since that was what I saw rwhois throw when I sent it a domain that was not registered. That did not work, so I quoted it. I got a warning that throwing a string exception is deprecated, but the check did not work anyway. Am I trying to check for this custom error wrongly? How should it be done? > Examining rwhois.py reveals raise 'NoSuchDomain' which is a string exception. Which should work even tho deprecated. When you say it did not work what is the evidence? > > -- Bob Gailer 510-978-4454 Oakland, CA 919-636-4239 Chapel Hill, NC From brunson at brunson.com Tue Aug 7 17:39:58 2007 From: brunson at brunson.com (Eric Brunson) Date: Tue, 07 Aug 2007 09:39:58 -0600 Subject: [Tutor] comparing two numpy arrays In-Reply-To: <46B8855F.3070301@alum.rpi.edu> References: <46B85548.7000805@bristol.ac.uk> <46B8855F.3070301@alum.rpi.edu> Message-ID: <46B8924E.80407@brunson.com> Bob Gailer wrote: > Andy Cheesman wrote: > >> Hi people, >> >> If I've two numpy arrays, is there a non-looping way of finding common >> values. (the example below has identical shapes for the arrays but this >> may not be the case in my scenario) >> >> e.g >> a = array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) >> b = array([ 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]) >> >> answer = array([ 5,6,7,8,9]) >> > Set union? > > Did you mean Set intersection? From wormwood_3 at yahoo.com Tue Aug 7 17:48:28 2007 From: wormwood_3 at yahoo.com (wormwood_3) Date: Tue, 7 Aug 2007 08:48:28 -0700 (PDT) Subject: [Tutor] Checking for custom error codes Message-ID: <758844.47474.qm@web32404.mail.mud.yahoo.com> >>Probably you need to import NoSuchDomain from rwhois: >>from rwhois import WhoisRecord, NoSuchDomain >> >>then use >> except NoSuchDomain: That sounds right, I will give it a shot soon. >>In general, when you ask a question here, "I tried X and it did not >>work" is not very informative and makes it difficult to give a good >>answer. It is very helpful to show the actual code you tried and the >>actual error message, including the full traceback. The error message >>and traceback include a lot of very helpful information; including them >>will greatly improve your chance of a correct answer. Sorry about that, I knew the code would be helpful, that's why I linked to my blog post that included the full code. I will post the traceback tonight when I can run it. From bgailer at alum.rpi.edu Tue Aug 7 19:05:02 2007 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Tue, 07 Aug 2007 10:05:02 -0700 Subject: [Tutor] comparing two numpy arrays In-Reply-To: <46B8924E.80407@brunson.com> References: <46B85548.7000805@bristol.ac.uk> <46B8855F.3070301@alum.rpi.edu> <46B8924E.80407@brunson.com> Message-ID: <46B8A63E.9010308@alum.rpi.edu> Eric Brunson wrote: > Bob Gailer wrote: >> Andy Cheesman wrote: >> >>> Hi people, >>> >>> If I've two numpy arrays, is there a non-looping way of finding common >>> values. (the example below has identical shapes for the arrays but this >>> may not be the case in my scenario) >>> >>> e.g >>> a = array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) >>> b = array([ 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]) >>> >>> answer = array([ 5,6,7,8,9]) >>> >> Set union? >> >> > Did you mean Set intersection? Yes. Sigh. > > -- Bob Gailer 510-978-4454 Oakland, CA 919-636-4239 Chapel Hill, NC From alan.gauld at btinternet.com Tue Aug 7 19:19:18 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 7 Aug 2007 18:19:18 +0100 Subject: [Tutor] Large Scale Python websites References: Message-ID: "bhaaluu" wrote > Google > "Python has been an important part of Google since the beginning, > and remains so as the system grows and evolves. Very true but they don't write the main Google web site/search engine in Python they use it to test and to administer the underlying data etc. ISTR from an interview, with Guido vanRossum of all people, that the core Google code is written in C++. Alan G. From alan.gauld at btinternet.com Tue Aug 7 19:25:51 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 7 Aug 2007 18:25:51 +0100 Subject: [Tutor] Checking for custom error codes References: <760752.23855.qm@web32406.mail.mud.yahoo.com> Message-ID: "wormwood_3" wrote > Recently I was trying to do a "try: X except Y: Z" statement, > checking for a custom error code > for potdomain in self.potdomains: > try: > who.whois(potdomain) > self.availdomains.append(potdomain) > except 'NoSuchDomain': > pass > self.totalchecked+=1 > > got a warning that throwing a string exception is deprecated, > but the check did not work anyway. So what did happen? Your code simply ignores the error so, for it not to work, I assume you are still getting an error report and traceback? If so what does it say? Python error messages may look arcane to start with but they usually contain enough information to identify a problem without any further debugging - but only if we can see them! :-) HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From brunson at brunson.com Tue Aug 7 19:38:41 2007 From: brunson at brunson.com (Eric Brunson) Date: Tue, 07 Aug 2007 11:38:41 -0600 Subject: [Tutor] Large Scale Python websites In-Reply-To: References: Message-ID: <46B8AE21.7080304@brunson.com> Alan Gauld wrote: > "OkaMthembo" wrote > > >> Is anyone aware of any large scale web apps developed in Python? >> Please let >> me know of any that you know of... >> > > The Zope web site has many examples. > > But it depends how you define large scale. Most of the really big ones > (Google, > Yahoo, IBM, BBC etc - anything with several million hits a day) use > Java or C++ > in my experience. But a lot of large and busy sites do exist using one > or other > of the Pyhon web frameworks, check the frameworks and you will find > case > histories. > > And even the biggest sites often use languages like Python etc for > experimental features or occasional access areas or for administration > or test duties. One of the good things abourt web developments is that > its pretty easy to mix frameworks and have it appear seamless to the > user. > YouTube runs primarily on Python with critical code sections compiled using psyco. http://highscalability.com/youtube-architecture Akamai is also a big python shop, from what I understand (no citation available). Those big enough for you? From Mike.Hansen at atmel.com Tue Aug 7 20:03:17 2007 From: Mike.Hansen at atmel.com (Mike Hansen) Date: Tue, 7 Aug 2007 12:03:17 -0600 Subject: [Tutor] Large Scale Python websites In-Reply-To: <46B8AE21.7080304@brunson.com> References: <46B8AE21.7080304@brunson.com> Message-ID: <57B026980605A64F9B23484C5659E32E9835FC@poccso.US.ad.atmel.com> > >> Is anyone aware of any large scale web apps developed in Python? > >> Please let > >> me know of any that you know of... I think that reddit.com switched from LISP to Python a while back. Mike From noufal at airtelbroadband.in Tue Aug 7 20:28:08 2007 From: noufal at airtelbroadband.in (Noufal Ibrahim) Date: Tue, 07 Aug 2007 23:58:08 +0530 Subject: [Tutor] subprocess and signals Message-ID: <46B8B9B8.60006@airtelbroadband.in> Hello everyone, I've come across a situation which is somewhat confusing to me. I googled for some details and came across another email thread on this very list but couldn't really glean a solution out of it. I have a program (a compiled binary) for which I need to write a wrapper (in python). The wrapper will construct some sane command line defaults for this binary and then execute it while storing some statistics like who launched it, where and when. Now this program will continuously print output (it's a parallel version of make). It it receives a SIGINT (via a Ctrl-C), it will print some statistics and go on with the build. If it receives a Ctrl-\ (SIGQUIT I think), it will terminate. I want my wrapper to be able to read the output of this program and print it while allowing these two signals to be passed to it. My wrapper (let's call it wrapper.py) has something like this ------------------------------------------------------------------ def createSignalDelegator(p): def sighandler(signal,frame,pmake = p): os.kill(pmake.pid,signal) return sighandler pmake = subprocess.Popen(pmake_cmd, bufsize = 1, stdout = subprocess.PIPE, stderr = subprocess.STDOUT) signal.signal(signal.SIGINT,createSignalDelegator(pmake)) signal.signal(signal.SIGQUIT,createSignalDelegator(pmake)) for op in pmake.stdout: print "-- %s"%str(op).strip() ------------------------------------------------------------------ I've substituted my actual binary with a simple python script that continuously prints a string and which traps sigint and sigquit to appear like the binary. It seems to be receiving the signals fine (since I log it's activity into a separate file) but the problems I get are like so 1. I don't see any output (from my 'build') on screen when I run my wrapper. 2. When I send a ^C to the wrapper, I don't see the output from the build script. 3. I sometimes get a pipe error and the whole wrapper dies leaving the other program running. I'd appreciate any insights into the problem. I'm not sure where to start looking. Thanks. -- ~noufal From brunson at brunson.com Tue Aug 7 20:42:06 2007 From: brunson at brunson.com (Eric Brunson) Date: Tue, 07 Aug 2007 12:42:06 -0600 Subject: [Tutor] subprocess and signals In-Reply-To: <46B8B9B8.60006@airtelbroadband.in> References: <46B8B9B8.60006@airtelbroadband.in> Message-ID: <46B8BCFE.6040803@brunson.com> Noufal Ibrahim wrote: > Hello everyone, > I've come across a situation which is somewhat confusing to me. > I googled for some details and came across another email thread on > this very list but couldn't really glean a solution out of it. > > I have a program (a compiled binary) for which I need to write a > wrapper (in python). The wrapper will construct some sane command line > defaults for this binary and then execute it while storing some > statistics like who launched it, where and when. > > Now this program will continuously print output (it's a parallel > version of make). It it receives a SIGINT (via a Ctrl-C), it will print > some statistics and go on with the build. If it receives a Ctrl-\ > (SIGQUIT I think), it will terminate. I want my wrapper to be able to > read the output of this program and print it while allowing these two > signals to be passed to it. > > My wrapper (let's call it wrapper.py) has something like this > > ------------------------------------------------------------------ > def createSignalDelegator(p): > def sighandler(signal,frame,pmake = p): > os.kill(pmake.pid,signal) > return sighandler > > pmake = subprocess.Popen(pmake_cmd, bufsize = 1, stdout = > subprocess.PIPE, stderr = subprocess.STDOUT) > > signal.signal(signal.SIGINT,createSignalDelegator(pmake)) > signal.signal(signal.SIGQUIT,createSignalDelegator(pmake)) > for op in pmake.stdout: > print "-- %s"%str(op).strip() > ------------------------------------------------------------------ > > I've substituted my actual binary with a simple python script that > continuously prints a string and which traps sigint and sigquit to > appear like the binary. It seems to be receiving the signals fine (since > I log it's activity into a separate file) but the problems I get are like so > I'm not an expert on the subprocess module, but I've used it a bit and I'm referring to the docs as I write this. > 1. I don't see any output (from my 'build') on screen when I run my > wrapper. > Why do you think you should? You've asked subprocess to pipe its output you your parent process, I believe you would need to use the communicate() method to get the output generated by the subprocess. > 2. When I send a ^C to the wrapper, I don't see the output from the > build script. > Fix #1 first and then this should fall into place. > 3. I sometimes get a pipe error and the whole wrapper dies leaving the > other program running. > Exact error messages help a lot. :-) > I'd appreciate any insights into the problem. I'm not sure where to > start looking. > > Thanks. > > > From tnoyeaux at msn.com Tue Aug 7 20:57:50 2007 From: tnoyeaux at msn.com (Tony Noyeaux) Date: Tue, 7 Aug 2007 14:57:50 -0400 Subject: [Tutor] Random module.. or? Message-ID: As always, thanks all for the ongoing help and suggestions... the learning continues. I've successfully made a number of programs, making use of various random code. Using random.choice etc #----------------------------------- import randomletters = ('a', 'b', 'c', 'd')a = random.choice(letters)print 'your random letter is %s' %(a) #------------------------------------or #------------------------------------ import randomletters = ('a', 'a', 'b', 'b', 'c', 'd')a = random.choice(letters)print 'your random letter is %s' %(a) #----------------------------------- In the first random... , each abcd, has a equal chance of coming out. In the 2nd random,... a b,.. have an extra chance vs c/d to come out, making them more likely. What i would like to experiment now with is,... How can you control randomness... lets say for fish. CatfishBreedA Can be say, 4inches, to 24inches long Most fish caught are say 7-14inches long Maybe 1 in 1000 catfish caught are say, 16-20 inches long Maybe 1 in 10000 catfish caught are say, 20inches + How.. can you program that kind of randomness? Or another way to look at it. BasketballerA Can score 4-45pts a game. Most games, he scores 15-25 pts Maybe 1 in 1000 games he scores 30 plus pts Maybe 1 in 10000 he scores 45 pts. The actual %'s, lengths, and pts are irrelevent,.. they are just used to as an example. Any guidance would be appreciated. Tony Noyeaux _________________________________________________________________ Learn. Laugh. Share. Reallivemoms is right place! http://www.reallivemoms.com?ocid=TXT_TAGHM&loc=us -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070807/be44f3da/attachment.html From noufal at airtelbroadband.in Tue Aug 7 21:23:09 2007 From: noufal at airtelbroadband.in (Noufal Ibrahim) Date: Wed, 08 Aug 2007 00:53:09 +0530 Subject: [Tutor] subprocess and signals In-Reply-To: <46B8BCFE.6040803@brunson.com> References: <46B8B9B8.60006@airtelbroadband.in> <46B8BCFE.6040803@brunson.com> Message-ID: <46B8C69D.4020501@airtelbroadband.in> Eric Brunson wrote: > Noufal Ibrahim wrote: [..] >> def createSignalDelegator(p): >> def sighandler(signal,frame,pmake = p): >> os.kill(pmake.pid,signal) >> return sighandler >> >> pmake = subprocess.Popen(pmake_cmd, bufsize = 1, stdout = >> subprocess.PIPE, stderr = subprocess.STDOUT) >> >> signal.signal(signal.SIGINT,createSignalDelegator(pmake)) >> signal.signal(signal.SIGQUIT,createSignalDelegator(pmake)) >> for op in pmake.stdout: >> print "-- %s"%str(op).strip() >> ------------------------------------------------------------------ >> [..] > I'm not an expert on the subprocess module, but I've used it a bit and > I'm referring to the docs as I write this. > >> 1. I don't see any output (from my 'build') on screen when I run my >> wrapper. >> > > Why do you think you should? You've asked subprocess to pipe its output > you your parent process, I believe you would need to use the > communicate() method to get the output generated by the subprocess. If I read from the stdout attribute of the Popen object, I should get the output of the pipe. Shouldn't I? That's what I'm trying to do. I think the code above is broken though so I've changed the last two lines of the snippet to look like this line = pmake.stdout.readline() while line: print "-- %s"%str(line).strip() line = pmake.stdout.readline() That sounds more sensible. The docs for communicate warn against using it when the data size is large and that's the case here. I did however try it like so (stdout,dummy) = pmake.communicate() line = stdout.readline() while line: print "-- %s"%str(line).strip() line = stdout.readline() and I get similar behaviour. >> 3. I sometimes get a pipe error and the whole wrapper dies leaving the >> other program running. >> > > Exact error messages help a lot. :-) Yeah I know. I didn't have access to the machine where I got the original error so I thought I'd slur around there a bit. :) But I got it now (this is with the original snippet). Traceback (most recent call last): File "./build_wrapper.py", line 246, in main() File "./build_wrapper.py", line 231, in main run_pmake(target,options,extra_flags,pmake_options) File "./build_wrapper.py", line 209, in run_pmake line = pmake.stdout.readline() IOError: [Errno 4] Interrupted system call This is with python2.4 (if that's useful). Also, the output of the actual program will be a bit slow (since it's doing compiles and stuff). Will some intermediate buffering create any trouble? Thanks. -- ~noufal From bgailer at alum.rpi.edu Tue Aug 7 21:37:32 2007 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Tue, 07 Aug 2007 12:37:32 -0700 Subject: [Tutor] Random module.. or? In-Reply-To: References: Message-ID: <46B8C9FC.4000303@alum.rpi.edu> Tony Noyeaux wrote: > As always, thanks all for the ongoing help and suggestions... the > learning continues. > > I've successfully made a number of programs, making use of various > random code. > > Using random.choice etc > #----------------------------------- > import random > letters = ('a', 'b', 'c', 'd') > a = random.choice(letters) > print 'your random letter is %s' %(a) > #------------------------------------ > or > #------------------------------------ > import random > letters = ('a', 'a', 'b', 'b', 'c', 'd') > a = random.choice(letters) > print 'your random letter is %s' %(a) > #----------------------------------- > > In the first random... , each abcd, has a equal chance of coming out. > In the 2nd random,... a b,.. have an extra chance vs c/d to come out, > making them more likely. > > What i would like to experiment now with is,... > > How can you control randomness... lets say for fish. > > CatfishBreedA > Can be say, 4inches, to 24inches long > Most fish caught are say 7-14inches long > Maybe 1 in 1000 catfish caught are say, 16-20 inches long > Maybe 1 in 10000 catfish caught are say, 20inches + > > How.. can you program that kind of randomness? > > Or another way to look at it. > > BasketballerA > Can score 4-45pts a game. > Most games, he scores 15-25 pts > Maybe 1 in 1000 games he scores 30 plus pts > Maybe 1 in 10000 he scores 45 pts. > > The actual %'s, lengths, and pts are irrelevent,.. they are just used > to as an example. > > > Any guidance would be appreciated. 10000 games would be distributed thus: 1 = 45 pts 10 = 30+ pts 99989 = 15-25 pts so generate a random integer between 1 and 10000. if it is <= 1 then 45 else if it is <= 11 then 30+ else 15-25 Enough to get you going? -- Bob Gailer 510-978-4454 Oakland, CA 919-636-4239 Chapel Hill, NC From bkjones at gmail.com Tue Aug 7 21:55:03 2007 From: bkjones at gmail.com (Brian Jones) Date: Tue, 7 Aug 2007 15:55:03 -0400 Subject: [Tutor] send os.system() output to tarfile? Message-ID: <6e5927ff0708071255i32ecc0b8h238c951682f40544@mail.gmail.com> Hi all, I've been lurking on this list for some time. It's great. Thanks for all the help. I'm a sysadmin by trade, and have slowly started using Python more and more in my work. However, this is my first experience with using the tarfile module. I'm currently writing a script to backup a mysql database. On the cli, I'd do something like this: 'mysqldump dbname | gzip -9 > dbname-date.gz' Note that "gzip -9" could just as easily be "tar cvzf" for example. Anyway, what I'm trying to do is figure out the right way to redirect the output generated by "os.system(mysqldump dbname)" to my tarfile object for compressing. What I tried were a few variations on this: ====================== #!/usr/bin/env python import os import time import tarfile import sys filename = time.strftime("%Y%m%d") + ".tgz" tarball = tarfile.open(filename, "w|gz", fileobj = sys.stdout) os.system( "ls -alrt" ) tarball.close() ====================== I also played around with redirecting stdout to the tarfile object, and some other things that are probably stuff you'd expect from a python n00b. What's the right way to do this? I was hoping to not be forced down the road of creating temp files, compressing *those*, and then blowing them away at the end. Any help greatly appreciated. brian. -- Brian K. Jones Python Magazine http://www.pythonmagazine.com My Blog http://m0j0.wordpress.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070807/1d0b99d7/attachment.html From dfkramer at ucdavis.edu Tue Aug 7 21:28:59 2007 From: dfkramer at ucdavis.edu (Dewight Kramer) Date: Tue, 7 Aug 2007 12:28:59 -0700 Subject: [Tutor] variable * raw_input Message-ID: <1869F460-E71B-4171-856B-84FF11708188@ucdavis.edu> Hello, So i am new to Python, and really to programming. I picked up book and so far I like it. right now I am trying to figure out a problem that I cant. It is a tipping program and I have assigned certain words to be a certain % and then I ask the user to type raw input of one of those names. After which I am trying to mutiply the Bill by the Service quality. But I dont understand something below is code. Thanks D # Tip Calulator - Ver # Challenges Ch2 - Question 3 # Developed by, Dewight # Developed on, 8/7/2007 # establish variables bill = float(0.0) bad = float (0.0) ok = float(0.10) good = float (0.15) great = float (0.20) service="nothing" tip = float () total = float () print "This is a tipping calculator." bill = raw_input ("\nWhat was the total bill amount? ") service = raw_input("Please input one of the following to"+ " discribe the service:"+"\nbad\nok\ngood\ngreat \n") tip = bill * service total = bill + tip print "Then you should leave a" + tip + "tip. This will bring the total to" + total +"." raw_input("\n\nPlease press enter to exit.") From bgailer at alum.rpi.edu Tue Aug 7 22:01:37 2007 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Tue, 07 Aug 2007 13:01:37 -0700 Subject: [Tutor] Random module.. or? CORRECTION In-Reply-To: <46B8C9FC.4000303@alum.rpi.edu> References: <46B8C9FC.4000303@alum.rpi.edu> Message-ID: <46B8CFA1.1050306@alum.rpi.edu> Bob Gailer wrote: > Tony Noyeaux wrote: > >> As always, thanks all for the ongoing help and suggestions... the >> learning continues. >> >> I've successfully made a number of programs, making use of various >> random code. >> >> Using random.choice etc >> #----------------------------------- >> import random >> letters = ('a', 'b', 'c', 'd') >> a = random.choice(letters) >> print 'your random letter is %s' %(a) >> #------------------------------------ >> or >> #------------------------------------ >> import random >> letters = ('a', 'a', 'b', 'b', 'c', 'd') >> a = random.choice(letters) >> print 'your random letter is %s' %(a) >> #----------------------------------- >> >> In the first random... , each abcd, has a equal chance of coming out. >> In the 2nd random,... a b,.. have an extra chance vs c/d to come out, >> making them more likely. >> >> What i would like to experiment now with is,... >> >> How can you control randomness... lets say for fish. >> >> CatfishBreedA >> Can be say, 4inches, to 24inches long >> Most fish caught are say 7-14inches long >> Maybe 1 in 1000 catfish caught are say, 16-20 inches long >> Maybe 1 in 10000 catfish caught are say, 20inches + >> >> How.. can you program that kind of randomness? >> >> Or another way to look at it. >> >> BasketballerA >> Can score 4-45pts a game. >> Most games, he scores 15-25 pts >> Maybe 1 in 1000 games he scores 30 plus pts >> Maybe 1 in 10000 he scores 45 pts. >> >> The actual %'s, lengths, and pts are irrelevent,.. they are just used >> to as an example. >> >> >> Any guidance would be appreciated. >> > 10000 games would be distributed thus: > 1 = 45 pts > 10 = 30+ pts > 9989 = 15-25 pts CORRECTED > so generate a random integer between 1 and 10000. > if it is <= 1 then 45 > else if it is <= 11 then 30+ > else 15-25 > > Enough to get you going? > > -- Bob Gailer 510-978-4454 Oakland, CA 919-636-4239 Chapel Hill, NC From alan.gauld at btinternet.com Tue Aug 7 22:38:25 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 7 Aug 2007 21:38:25 +0100 Subject: [Tutor] Random module.. or? References: <46B8C9FC.4000303@alum.rpi.edu> Message-ID: "Bob Gailer" wrote > 10000 games would be distributed thus: > 1 = 45 pts > 10 = 30+ pts > 99989 = 15-25 pts > so generate a random integer between 1 and 10000. > if it is <= 1 then 45 > else if it is <= 11 then 30+ > else 15-25 Bob's approach is typical for large data sets, for small data sets it can be easier to create a statistically representative sample population then pick on from the population. Thus if there are 3 possible outcomes and 1 is twice as likely as 2 which is 4 times as likely as 3 we can create a sample like: pop = [3,2,2,2,2,1,1,1,1,1,1,1,1] (List comprehensions, zip and other list building functions can help generate the population sample.) Now selecting a single entry from pop will give the right randomness. This technique has the advantage of a single random selection but it quickly runs out of steam for complex data. In that case Bob's approach is better but requires two random functions. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From bhaaluu at gmail.com Tue Aug 7 23:16:32 2007 From: bhaaluu at gmail.com (bhaaluu) Date: Tue, 7 Aug 2007 17:16:32 -0400 Subject: [Tutor] Random module.. or? CORRECTION In-Reply-To: <46B8CFA1.1050306@alum.rpi.edu> References: <46B8C9FC.4000303@alum.rpi.edu> <46B8CFA1.1050306@alum.rpi.edu> Message-ID: Greetings, I just had to play with Bob's probabilities... The standard disclaimer applies: This Python source code has been written by a Noob, so use it at your own risk. =) #!/usr/bin/env python # randy.py # 2007-08-07 # b h a a l u u at g m a i l dot c o m import random def randy(): a=[] for i in range(1,10001): a.append(i) #print a[0] #print a[9999] b = random.choice(a) print b if b <= 1: print "45 points scored!" elif b > 1 and b <= 11: print "30 points scored!" else: c=[] for i in range(26): c.append(i) d = random.choice(c) print d,"points scored!" randy() -- bhaaluu at gmail dot com On 8/7/07, Bob Gailer wrote: > Bob Gailer wrote: > > Tony Noyeaux wrote: > > > >> As always, thanks all for the ongoing help and suggestions... the > >> learning continues. > >> > >> I've successfully made a number of programs, making use of various > >> random code. > >> > >> Using random.choice etc > >> #----------------------------------- > >> import random > >> letters = ('a', 'b', 'c', 'd') > >> a = random.choice(letters) > >> print 'your random letter is %s' %(a) > >> #------------------------------------ > >> or > >> #------------------------------------ > >> import random > >> letters = ('a', 'a', 'b', 'b', 'c', 'd') > >> a = random.choice(letters) > >> print 'your random letter is %s' %(a) > >> #----------------------------------- > >> > >> In the first random... , each abcd, has a equal chance of coming out. > >> In the 2nd random,... a b,.. have an extra chance vs c/d to come out, > >> making them more likely. > >> > >> What i would like to experiment now with is,... > >> > >> How can you control randomness... lets say for fish. > >> > >> CatfishBreedA > >> Can be say, 4inches, to 24inches long > >> Most fish caught are say 7-14inches long > >> Maybe 1 in 1000 catfish caught are say, 16-20 inches long > >> Maybe 1 in 10000 catfish caught are say, 20inches + > >> > >> How.. can you program that kind of randomness? > >> > >> Or another way to look at it. > >> > >> BasketballerA > >> Can score 4-45pts a game. > >> Most games, he scores 15-25 pts > >> Maybe 1 in 1000 games he scores 30 plus pts > >> Maybe 1 in 10000 he scores 45 pts. > >> > >> The actual %'s, lengths, and pts are irrelevent,.. they are just used > >> to as an example. > >> > >> > >> Any guidance would be appreciated. > >> > > 10000 games would be distributed thus: > > 1 = 45 pts > > 10 = 30+ pts > > 9989 = 15-25 pts CORRECTED > > so generate a random integer between 1 and 10000. > > if it is <= 1 then 45 > > else if it is <= 11 then 30+ > > else 15-25 > > > > Enough to get you going? > > > > > > > -- > Bob Gailer > 510-978-4454 Oakland, CA > 919-636-4239 Chapel Hill, NC > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- bhaaluu at gmail dot com From alan.gauld at btinternet.com Tue Aug 7 23:33:20 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 7 Aug 2007 22:33:20 +0100 Subject: [Tutor] variable * raw_input References: <1869F460-E71B-4171-856B-84FF11708188@ucdavis.edu> Message-ID: "Dewight Kramer" wrote > quality. But I dont understand something below is code. Since you don't tell us what exactly you don't undertand I'll make some general comments on the code... > # establish variables > bill = float(0.0) > bad = float (0.0) > ok = float(0.10) > good = float (0.15) > great = float (0.20) You don;t need the float() call because the values are already floats by dint of having a decimal point in them. float is really for converting non float values(integer or string) to floats. > service="nothing" > tip = float () > total = float () these lsat two will be the same as tip = 0.0 total = 0.0 > print "This is a tipping calculator." > > bill = raw_input ("\nWhat was the total bill amount? ") raw_input returns a string, you probably want to convert that to a float, so here you do want to use float(), like so: > bill = float(raw_input ("\nWhat was the total bill amount? ")) > service = raw_input("Please input one of the following to"+ > " describe the service:"+"\nbad\nok\ngood\ngreat > \n") You could use a triple quoted string here for clearer layout: service = raw_input( """Please input one of the following to describe the service: bad ok good great """) > tip = bill * service But now you are trying to multiply a number(bill) by a string ('ok', 'bad' etc) Thsat won;t work, instead you need to convert the string into some kind of number. The common way to do that would be using a dictionary: serviceVal = {'bad': 0, 'ok': 0.1, 'good': 0.15, 'great':0.2} and now the tip line looks like: tip = bill * serviceVal[service] > total = bill + tip > print "Then you should leave a" + tip + "tip. This will bring the > total to" + total +"." You might find this easier using string formatting print "Then you should leave a $%.2f tip. This will bring the total to $%.2f." % (tip, total) Notice how that lets you control what the output looks like more precisely. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From steve.reighard at gmail.com Tue Aug 7 23:35:42 2007 From: steve.reighard at gmail.com (steve reighard) Date: Tue, 7 Aug 2007 16:35:42 -0500 Subject: [Tutor] Random module.. or? In-Reply-To: References: <46B8C9FC.4000303@alum.rpi.edu> Message-ID: <85661be80708071435u4b380cb8k41a49b723fc2b78d@mail.gmail.com> On 8/7/07, Alan Gauld wrote: > > > "Bob Gailer" wrote > > > 10000 games would be distributed thus: > > 1 = 45 pts > > 10 = 30+ pts > > 99989 = 15-25 pts > > so generate a random integer between 1 and 10000. > > if it is <= 1 then 45 > > else if it is <= 11 then 30+ > > else 15-25 > > Bob's approach is typical for large data sets, for small data sets > it can be easier to create a statistically representative sample > population then pick on from the population. > > Thus if there are 3 possible outcomes and 1 is twice as likely > as 2 which is 4 times as likely as 3 we can create a sample like: > > pop = [3,2,2,2,2,1,1,1,1,1,1,1,1] > > (List comprehensions, zip and other list building functions can > help generate the population sample.) > > Now selecting a single entry from pop will give the right > randomness. This technique has the advantage of a single > random selection but it quickly runs out of steam for complex > data. In that case Bob's approach is better but requires two > random functions. > > HTH, > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.freenetpages.co.uk/hp/alan.gauld > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > Python provides you with a pseudo random number generator whose output values are uniformly distributed between the input parameters. What you are dealing with in fish weights or test scores or other natural phenomena is most likely a normal distribution. Yes, it's the bell-shaped curve that your professors use to give you a letter grade from your numeric score on a test. There is an average score or weight called the mean and a measure of the pointedness of the curve called the standard deviation so that two thirds of all the scores are going to be within a standard deviation of that mean. In your catfish example suitable values might be mean = 10 inches with a standard deviation of 4 inches. There are several numerical algorithms that massage a uniformly distributed random value (or several uniformly distributed random values) into a normally distributed random value. Check out Wikipedia's normal distribution entry. The math is really juicy. You may end up with a recipe for the Python Cookbook. Have fun. Steve -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070807/977d1cc2/attachment.html From alan.gauld at btinternet.com Tue Aug 7 23:42:04 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 7 Aug 2007 22:42:04 +0100 Subject: [Tutor] Random module.. or? CORRECTION References: <46B8C9FC.4000303@alum.rpi.edu> <46B8CFA1.1050306@alum.rpi.edu> Message-ID: "bhaaluu" wrote > source code has been written by a Noob, so > use it at your own risk. =) Just a few comments... > def randy(): > a=[] > for i in range(1,10001): > a.append(i) a = range(1,10001) # range returns a list... > b = random.choice(a) > print b > if b <= 1: Can never be less than 1 so == would be more appropriate. In fact, more accurate too, since only one value out of 10000 can give 45. > print "45 points scored!" > elif b > 1 and b <= 11: > print "30 points scored!" But here you need to get a value between 30 and 45 so another call to choice would be appropriate. Otherwise players can only score a very limited set of scores! > else: > c=[] > for i in range(26): > c.append(i) c = range(26) > d = random.choice(c) d = random.choice(range(26)) replaces all of it! > print d,"points scored!" And for consistency I'd make the print statements above into assignments to d and then this final print statement can be dedented and covers all cases. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From dkuhlman at rexx.com Tue Aug 7 23:50:35 2007 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Tue, 7 Aug 2007 14:50:35 -0700 Subject: [Tutor] send os.system() output to tarfile? In-Reply-To: <6e5927ff0708071255i32ecc0b8h238c951682f40544@mail.gmail.com> References: <6e5927ff0708071255i32ecc0b8h238c951682f40544@mail.gmail.com> Message-ID: <20070807215035.GA97953@cutter.rexx.com> On Tue, Aug 07, 2007 at 03:55:03PM -0400, Brian Jones wrote: > > I'm currently writing a script to backup a mysql database. On the cli, I'd > do something like this: > 'mysqldump dbname | gzip -9 > dbname-date.gz' > > Note that "gzip -9" could just as easily be "tar cvzf" for example. > > Anyway, what I'm trying to do is figure out the right way to redirect the > output generated by "os.system(mysqldump dbname)" to my tarfile object for > compressing. What I tried were a few variations on this: > ====================== > #!/usr/bin/env python > > import os > import time > import tarfile > import sys > > filename = time.strftime("%Y%m%d") + ".tgz" > tarball = tarfile.open(filename, "w|gz", fileobj = sys.stdout) > os.system( "ls -alrt" ) > tarball.close() > > ====================== I'm not sure why you are are not doing something like this: cmd = 'mysqldump %s | gzip -9 > %s-%s.gz' % (dbname, dbname, date, ) os.system(cmd) But, if you want more control, then look at these functions/modules in the Pyhon standard library: - popen, popen2, etc -- http://docs.python.org/lib/os-process.html - tarfile -- http://docs.python.org/lib/module-tarfile.html popen will enable you to capture the output from your command. Use one of the other popenX functions if you need to capture both stdout and stderr. tarfile will enable you to stuff that captured output into a tar.gz file. Also, see the zipfile module if you want to save into a zip file. With tarfile, you may have to write data to a temp file and then archive that. With zipfile, you can write content directly into a zipfile. Is there a way around this? Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman From gofinner at hotmail.com Wed Aug 8 00:50:16 2007 From: gofinner at hotmail.com (Tim Finley) Date: Tue, 07 Aug 2007 16:50:16 -0600 Subject: [Tutor] How to parse and extract data from a log file? Message-ID: I'm a newbie to programming and am trying to learn Python. Maybe I'm wrong, but I thought a practical way of learning it would be to create a script. I want to automate the gathering of mailbox statistics for users in a post office. There are two lines containing this information for each user. I want to find the two lines for each user and place the information in a different file. I can't figure out how to find the information I'm after. Can you provide me an example or refer me to some place that has it? _________________________________________________________________ Messenger Caf? ? open for fun 24/7. Hot games, cool activities served daily. Visit now. http://cafemessenger.com?ocid=TXT_TAGHM_AugHMtagline From ricaraoz at gmail.com Wed Aug 8 01:05:28 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Tue, 07 Aug 2007 20:05:28 -0300 Subject: [Tutor] Losing the expressiveness of C's for-statement?/RESENDwith example In-Reply-To: References: Message-ID: <46B8FAB8.30402@bigfoot.com> Stephen McInerney wrote: > Hi Alan, > > I don't deny the superiority of the underlying language design, > I'm just pointing out the very real mindjolting effect of Python not > supporting the universal syntax. Java is closer to C than Python is. > I'm bringing this up as one hurdle to migration, not a fundamental flaw. > > Don't you agree that the Python tutorial should say something simple > and accessible to beginners like: "For all for-loop constructs where the > iteration can't be written as a simple range object, you probably want to > transform it to a while-loop, (or the more advanced option being a > generator)"? > I think the tutorial is lacking on this (should I email Fred Drake?) > Instead of leaving C and Java people cold scratching their heads about > why they think the language is hopelessly quirky and not (syntactically) > fully-featured? > One of our aims should be to write code which is at least understandable to > programmers of other languages. > > > >> Sorry I meant to pick a tangible example to focus the discussion: >> This one cannot be (easily) translated to use Python's range() >> operator for (i=30000; i>0; i=i/2) { ... } >> You don't give us any reason why you want to generate a set >> of numbers from 30,000 down to zero decreasing by half each >> time: 30,000, 15,000, 7500, 3750, etc >> To understand the Pythonic solution to the problem we would >> need to know what those numbers were required for so that we >> could determine if another python data structure might be more >> appropriate. > > Yes I did: it occurs in a quicksort as we halve the stepsize each time, > on an array of size 60000. > Can you please give me your answer on this? We have to transform it to > a while-loop? (or write a custom iterator?) Or just the usual? A recursive function? Elegant, succinct. From john at fouhy.net Wed Aug 8 01:07:48 2007 From: john at fouhy.net (John Fouhy) Date: Wed, 8 Aug 2007 11:07:48 +1200 Subject: [Tutor] How to parse and extract data from a log file? In-Reply-To: References: Message-ID: <5e58f2e40708071607l5f383279ue6a400ceac61b59c@mail.gmail.com> On 08/08/07, Tim Finley wrote: > I'm a newbie to programming and am trying to learn Python. Maybe I'm wrong, > but I thought a practical way of learning it would be to create a script. I > want to automate the gathering of mailbox statistics for users in a post > office. There are two lines containing this information for each user. I > want to find the two lines for each user and place the information in a > different file. I can't figure out how to find the information I'm after. > Can you provide me an example or refer me to some place that has it? Hi Tim, My first step in approaching a problem like this would probably be to parse the data. "parsing" means taking text data and adding structure to it. For example, suppose I had a data file "employees.csv" that looks like this: 1,joe,smith,ceo 2,fred,dagg,cio 3,karl,marx,cfo where the data format is: id, first name, surname, job I might proceed like this: #----- employees = {} # This is a dictionary. I will use this to store the parsed information. infile = open('employees.csv') # open the file for reading for line in infile: # go through the input file, one line at a time line = line.strip() # remove the newline character at the end of each line id, first, last, job = line.split(',') # split up line around comma characters employees[int(id)] = { 'first':first, 'last':last, 'job':job } # store data in dictionary #----- Once we get to here, we can do things like this: # What is employee 3's name? print employees[3]['first'], employees[3]['last'] # What is employee 1's job? print employees[1]['job'] This might not be the best data structure for you; it depends on what your data looks like and what you want to do with it. Python also has lists and tuples. I encourage you to go through the tutorial :-) -- John. From kent37 at tds.net Wed Aug 8 02:03:35 2007 From: kent37 at tds.net (Kent Johnson) Date: Tue, 07 Aug 2007 20:03:35 -0400 Subject: [Tutor] Random module.. or? CORRECTION In-Reply-To: References: <46B8C9FC.4000303@alum.rpi.edu> <46B8CFA1.1050306@alum.rpi.edu> Message-ID: <46B90857.4080305@tds.net> Alan Gauld wrote: > d = random.choice(range(26)) > > replaces all of it! or d = random.randrange(26) no need to creat the list at all. Kent From kent37 at tds.net Wed Aug 8 02:05:10 2007 From: kent37 at tds.net (Kent Johnson) Date: Tue, 07 Aug 2007 20:05:10 -0400 Subject: [Tutor] Random module.. or? In-Reply-To: <85661be80708071435u4b380cb8k41a49b723fc2b78d@mail.gmail.com> References: <46B8C9FC.4000303@alum.rpi.edu> <85661be80708071435u4b380cb8k41a49b723fc2b78d@mail.gmail.com> Message-ID: <46B908B6.7080403@tds.net> steve reighard wrote: > Python provides you with a pseudo random number generator whose output > values are uniformly distributed between the input parameters. What you > are dealing with in fish weights or test scores or other natural > phenomena is most likely a normal distribution. Check out Wikipedia's > normal distribution entry. The math is really juicy. You may end up > with a recipe for the Python Cookbook. No need for all that, use random.gauss() Kent From alan.gauld at btinternet.com Wed Aug 8 02:13:34 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 8 Aug 2007 01:13:34 +0100 Subject: [Tutor] send os.system() output to tarfile? References: <6e5927ff0708071255i32ecc0b8h238c951682f40544@mail.gmail.com> <20070807215035.GA97953@cutter.rexx.com> Message-ID: "Dave Kuhlman" wrote > But, if you want more control, then look at these functions/modules > in the Pyhon standard library: > > - popen, popen2, etc -- http://docs.python.org/lib/os-process.html Or the new(ish) subprocess module which supercedes system(), popenX(), commands, spawn(), execX() etc But yes, to read the output of your command you need more than system() which only returns the exit code of the command, usually zero. > - tarfile -- http://docs.python.org/lib/module-tarfile.html He is already using this one :-) Alan G. From kent37 at tds.net Tue Aug 7 21:57:36 2007 From: kent37 at tds.net (Kent Johnson) Date: Tue, 07 Aug 2007 15:57:36 -0400 Subject: [Tutor] Random module.. or? In-Reply-To: References: Message-ID: <46B8CEB0.3060208@tds.net> Tony Noyeaux wrote: > How can you control randomness... lets say for fish. > > CatfishBreedA > Can be say, 4inches, to 24inches long > Most fish caught are say 7-14inches long > Maybe 1 in 1000 catfish caught are say, 16-20 inches long > Maybe 1 in 10000 catfish caught are say, 20inches + > > How.. can you program that kind of randomness? > > Or another way to look at it. > > BasketballerA > Can score 4-45pts a game. > Most games, he scores 15-25 pts > Maybe 1 in 1000 games he scores 30 plus pts > Maybe 1 in 10000 he scores 45 pts. This sounds a lot like a normal distribution. http://en.wikipedia.org/wiki/Normal_distribution You can generate normally distributed random variables with random.gauss() Kent From alan.gauld at btinternet.com Wed Aug 8 02:18:42 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 8 Aug 2007 01:18:42 +0100 Subject: [Tutor] How to parse and extract data from a log file? References: Message-ID: "Tim Finley" wrote > but I thought a practical way of learning it would be to create a > script. Yep, its a good start once you've been through the language basics in a tutorial. > .... There are two lines containing this information for each user. > I > want to find the two lines for each user and place the information > in a > different file. I can't figure out how to find the information I'm > after. Look at the Handling Files and Handling Text topics in my tutorial. You may need to look at the Regular Expressions topic too if the patterns are complex. In particular look at the "Practical example" in the regex topic. Once you have a specific question or an error merssage come back here and we'll take it from there... HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From rabidpoobear at gmail.com Wed Aug 8 02:24:27 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Tue, 07 Aug 2007 19:24:27 -0500 Subject: [Tutor] executing file properly In-Reply-To: References: <1186482029.46b8476d87460@webmail.tu-bs.de> Message-ID: <46B90D3B.3040903@gmail.com> Thorsten Kampe wrote: > * Vivian Tini (Tue, 7 Aug 2007 12:20:29 +0200) > >> The TestCases executable works properly when I run it from the shell prompt. >> >> Then I try to run it from the Python command prompt by the following script: >> >>>>> import os >>>>> os.system("home/.../.../.../TestCases") >>>>> >> I used "..." to type it short. >> >> Then it gives the following error output: >> cannot open Des.in >> >> Well in this case tbe os.system command is typed correctly already since this >> the error message given out is written in the code itself. So the executable >> run already only when running from Python prompt it cannot open this file. >> >> Could anyone suggest me what would be the cause of this problem? >> > > You said it yourself: "I used "..." to type it short." > > >> And how should I handle it ? >> > > Even simpler: don't use "..." > I'm pretty sure he meant "I didn't type out the whole path in this e-mail so it wouldn't be > 80 characters and cause formatting issues" not that he didn't type the whole path in his original code. From brunson at brunson.com Wed Aug 8 02:31:08 2007 From: brunson at brunson.com (Eric Brunson) Date: Tue, 07 Aug 2007 18:31:08 -0600 Subject: [Tutor] Losing the expressiveness of C's for-statement?/RESENDwith example In-Reply-To: References: Message-ID: <46B90ECC.3050009@brunson.com> Stephen McInerney wrote: > Hi Alan, > > > [ snipage ] >> As to your particular case one non while option would be a generateor: >> >> def half(n): >> while int(n) > 0: >> n = n/2 >> yield n >> >> for x in half(300): print x, >> > > It's ok but it's visually clunky. while-loop wins for clarity. lambda would > also be too quirky. > I know the generator is more runtime-efficient. > It's regrettable we have to choose between the clear and the efficient, in > this situation. > That statement seems to be founded on the assumption that the C syntax is clear, which has not been established. It is clear to you because it is what you're used to seeing. Slap it down in front of a programmer that has never seen the idiom and see what they make of it. Any time you change languages you have to accustom yourself to it's nuances. C is probably one of the hardest languages I ever learned, I can't remember how many times I read and re-read the K&R chapter on pointer syntax. e. From wormwood_3 at yahoo.com Wed Aug 8 03:22:04 2007 From: wormwood_3 at yahoo.com (wormwood_3) Date: Tue, 7 Aug 2007 18:22:04 -0700 (PDT) Subject: [Tutor] Checking for custom error codes Message-ID: <496944.75541.qm@web32404.mail.mud.yahoo.com> >>Examining rwhois.py reveals >>raise 'NoSuchDomain' >>>which is a string exception. Which should work even tho deprecated. >>>When you say it did not work what is the evidence? -- Bob Gailer 510-978-4454 Oakland, CA 919-636-4239 Chapel Hill, NC _______________________________________ I did speak too soon on this. When I run the script using the code at the end, I get: rwhois.py:327: DeprecationWarning: raising a string exception is deprecated raise 'NoSuchDomain', self.domain =================== def lookup(self): """ Looks up each word in our list with whois """ """ Using rwhois, which is either broken or lacks most data: """ from rwhois import WhoisRecord who = WhoisRecord() self.totalchecked = 0 self.availdomains = [] for potdomain in self.potdomains: try: who.whois(potdomain) self.availdomains.append(potdomain) except 'NoSuchDomain': pass self.totalchecked+=1 def printresults(self): """ Prints the ones that do not seem to be taken, with some stats. """ print "Results are in! " print "%s total words checked, as .com and .net domains." % (self.totalchecked / 2) print "----------------------" print "Domains that seem to be available: \n" for availdomain in self.availdomains: print availdomain print "\n" print "----------------------" ==================== Then, I get back items in the list such as: Domains that seem to be available: AA.com AARP.com AARP.net I confirmed in spotchecking that some of these are taken, such as with whois -H AARP.com: Domain Name: AARP.COM Registrar: NETWORK SOLUTIONS, LLC. Whois Server: whois.networksolutions.com This may, however, be something else wrong with my code, or the rwhois module, not the try, except check. From wormwood_3 at yahoo.com Wed Aug 8 03:30:45 2007 From: wormwood_3 at yahoo.com (wormwood_3) Date: Tue, 7 Aug 2007 18:30:45 -0700 (PDT) Subject: [Tutor] Checking for custom error codes Message-ID: <722656.76194.qm@web32411.mail.mud.yahoo.com> >>Probably you need to import NoSuchDomain from rwhois: >>from rwhois import WhoisRecord, NoSuchDomain >> >>then use >> except NoSuchDomain: I tried adding: from rwhois import WhoisRecord, NoSuchDomain who = WhoisRecord() self.totalchecked = 0 self.availdomains = [] for potdomain in self.potdomains: try: who.whois(potdomain) self.availdomains.append(potdomain) except NoSuchDomain: pass self.totalchecked+=1 But I get back: Traceback (most recent call last): File "domainspotter.py", line 150, in runMainParser() File "domainspotter.py", line 147, in runMainParser td.run() File "domainspotter.py", line 71, in run checkdomains.lookup() File "domainspotter.py", line 108, in lookup from rwhois import WhoisRecord, NoSuchDomain ImportError: cannot import name NoSuchDomain Maybe I need to import something else to be able to throw it. I think if someone can explain a more general form of this I would be on better footing: To use a custom error code (from a module) in a loop or anywhere else, do I need to import the code itself? I had assumed that once I imported the module that defined the error code, I could catch it just like a core Python error code. >>In general, when you ask a question here, "I tried X and it did not >>work" is not very informative and makes it difficult to give a good >>answer. It is very helpful to show the actual code you tried and the >>actual error message, including the full traceback. The error message >>and traceback include a lot of very helpful information; including them >>will greatly improve your chance of a correct answer. Commented on this with the warning text in last response. Will endeavour to do better:-) _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From keridee at jayco.net Wed Aug 8 04:57:39 2007 From: keridee at jayco.net (Tiger12506) Date: Tue, 7 Aug 2007 21:57:39 -0500 Subject: [Tutor] Checking for custom error codes References: <722656.76194.qm@web32411.mail.mud.yahoo.com> Message-ID: <000801c7d967$e5cdff10$78fce004@JSLAPTOP> > Traceback (most recent call last): > File "domainspotter.py", line 150, in > runMainParser() > File "domainspotter.py", line 147, in runMainParser > td.run() > File "domainspotter.py", line 71, in run > checkdomains.lookup() > File "domainspotter.py", line 108, in lookup > from rwhois import WhoisRecord, NoSuchDomain > ImportError: cannot import name NoSuchDomain > > Maybe I need to import something else to be able to throw it. > > I think if someone can explain a more general form of this I would be on > better footing: To use a custom error code (from a module) in a loop or > anywhere else, do I need to import the code itself? I had assumed that > once I imported the module that defined the error code, I could catch it > just like a core Python error code. The problem is evident. The name NoSuchDomain is not defined. It is not a variable. It is just a string. When you call an error like this raise 'NoSuchDomain', it's called something - don't know what (string exception?) - but as you found out, that method of raising errors is now frowned upon (deprecated). The way you are supposed to raise errors is to create a new class, subclassing Exception. Then you would be able to catch it by variable name as you are trying to do with the import. But you certainly can't import a constant string! It's like trying to import the contents of a string variable, instead of the variable itself. Again, the problem is deprecation, the rwhois will eventually have to be re-written so that it uses exception classes, instead of just raising string errors. JS From wormwood_3 at yahoo.com Wed Aug 8 04:14:04 2007 From: wormwood_3 at yahoo.com (wormwood_3) Date: Tue, 7 Aug 2007 19:14:04 -0700 (PDT) Subject: [Tutor] Checking for custom error codes Message-ID: <594375.170.qm@web32412.mail.mud.yahoo.com> > Traceback (most recent call last): > File "domainspotter.py", line 150, in > runMainParser() > File "domainspotter.py", line 147, in runMainParser > td.run() > File "domainspotter.py", line 71, in run > checkdomains.lookup() > File "domainspotter.py", line 108, in lookup > from rwhois import WhoisRecord, NoSuchDomain > ImportError: cannot import name NoSuchDomain > > Maybe I need to import something else to be able to throw it. > > I think if someone can explain a more general form of this I would be on > better footing: To use a custom error code (from a module) in a loop or > anywhere else, do I need to import the code itself? I had assumed that > once I imported the module that defined the error code, I could catch it > just like a core Python error code. >>The problem is evident. The name NoSuchDomain is not defined. It is not a >>variable. It is just a string. When you call an error like this raise >>'NoSuchDomain', it's called something - don't know what (string >>exception?) - but as you found out, that method of raising errors is now >>frowned upon (deprecated). The way you are supposed to raise errors is to >>create a new class, subclassing Exception. Then you would be able to catch >>it by variable name as you are trying to do with the import. This is exactly what I needed, awesome! Looks like this is what you were saying to do?: http://docs.python.org/tut/node10.html#SECTION0010500000000000000000 >>But you certainly can't import a constant string! It's like trying to import the >>contents of a string variable, instead of the variable itself. Again, the >>problem is deprecation, the rwhois will eventually have to be re-written so >>that it uses exception classes, instead of just raising string errors. That would seem best. I will see if they have this in the works. Thanks again! From keridee at jayco.net Wed Aug 8 05:28:10 2007 From: keridee at jayco.net (Tiger12506) Date: Tue, 7 Aug 2007 22:28:10 -0500 Subject: [Tutor] Checking for custom error codes References: <594375.170.qm@web32412.mail.mud.yahoo.com> Message-ID: <000801c7d96c$289cab80$78fce004@JSLAPTOP> > This is exactly what I needed, awesome! Looks like this is what you were > saying to do?: > http://docs.python.org/tut/node10.html#SECTION0010500000000000000000 Why ~ exactly! A link tells a thousand words. (Or maybe more.) So does that mean that a link is inherently more valuable than a picture? ;-) JS From nephish at gmail.com Wed Aug 8 05:11:16 2007 From: nephish at gmail.com (shawn bright) Date: Tue, 7 Aug 2007 22:11:16 -0500 Subject: [Tutor] how to sort a dictionary by values Message-ID: <384c93600708072011l3a59d5f8o95dd0c9a4b997f92@mail.gmail.com> hello there all, i am wondering how to sort a dictionary that i have by values. And i also need to sort them from greatest to least like if i have a dictionary d = {'a':21.3, 'b':32.8, 'c': 12.92} how could i sort these from least to greatest so that the order would turn out b,a,c thanks shawn -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070807/e518a643/attachment.html From wormwood_3 at yahoo.com Wed Aug 8 05:44:37 2007 From: wormwood_3 at yahoo.com (wormwood_3) Date: Tue, 7 Aug 2007 20:44:37 -0700 (PDT) Subject: [Tutor] how to sort a dictionary by values Message-ID: <620793.50695.qm@web32403.mail.mud.yahoo.com> >>hello there all, >>i am wondering how to sort a dictionary that i have by values. >>And i also need to sort them from greatest to least >>like if i have a dictionary >> >>d = {'a':21.3, 'b':32.8, 'c': 12.92} >> >>how could i sort these from least to greatest >>so that the order would turn out >>b,a,c ---------------------------- Hi Shawn, I was not sure how to do this either, but some digging revealed a very handing cookbook recipe on just this! (http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/304440) So, here is an example of it working in the Python interpreter: ============== Python 2.5.1 (r251:54863, May 2 2007, 16:56:35) [GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> dict = {'a':21.3, 'b':32.8, 'c':12.92} >>> from operator import itemgetter >>> # This will print the dict, sorted by value: ... >>> print sorted(dict.items(), key=itemgetter(1)) [('c', 12.92), ('a', 21.300000000000001), ('b', 32.799999999999997)] ============== So just add that import, and use sorted() as I showed above, and you should be good to go. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070807/36e18500/attachment.html From kent37 at tds.net Wed Aug 8 05:47:26 2007 From: kent37 at tds.net (Kent Johnson) Date: Tue, 07 Aug 2007 23:47:26 -0400 Subject: [Tutor] how to sort a dictionary by values In-Reply-To: <384c93600708072011l3a59d5f8o95dd0c9a4b997f92@mail.gmail.com> References: <384c93600708072011l3a59d5f8o95dd0c9a4b997f92@mail.gmail.com> Message-ID: <46B93CCE.3070907@tds.net> shawn bright wrote: > hello there all, > i am wondering how to sort a dictionary that i have by values. > And i also need to sort them from greatest to least > like if i have a dictionary > > d = {'a':21.3, 'b':32.8, 'c': 12.92} > > how could i sort these from least to greatest > so that the order would turn out > b,a,c You can use d.__getitem__ as the key function for a sort of the keys. __getitem__() is the special method that is called for indexing a dictionary (or a list). In [24]: d = {'a':21.3, 'b':32.8, 'c': 12.92} In [26]: sorted(d.keys(), key=d.__getitem__, reverse=True) Out[26]: ['b', 'a', 'c'] More on sorting here: http://personalpages.tds.net/~kent37/kk/00007.html Kent From wormwood_3 at yahoo.com Wed Aug 8 05:58:39 2007 From: wormwood_3 at yahoo.com (wormwood_3) Date: Tue, 7 Aug 2007 20:58:39 -0700 (PDT) Subject: [Tutor] how to sort a dictionary by values Message-ID: <698454.37135.qm@web32404.mail.mud.yahoo.com> >>You can use d.__getitem__ as the key function for a sort of the keys. >>__getitem__() is the special method that is called for indexing a >>dictionary (or a list). Just curious: Is there a reason to use __getitem__() over itemgetter (used in the example in my reply)? >>In [24]: d = {'a':21.3, 'b':32.8, 'c': 12.92} >>In [26]: sorted(d.keys(), key=d.__getitem__, reverse=True) I think Shawn would want to leave off "reverse=True". The default is least to greatest, which is what he wanted, I think. From keridee at jayco.net Wed Aug 8 07:02:03 2007 From: keridee at jayco.net (Tiger12506) Date: Wed, 8 Aug 2007 00:02:03 -0500 Subject: [Tutor] how to sort a dictionary by values References: <698454.37135.qm@web32404.mail.mud.yahoo.com> Message-ID: <000601c7d979$46a2e7e0$32fce004@JSLAPTOP> > Just curious: Is there a reason to use __getitem__() over itemgetter (used > in the example in my reply)? __getitem__ is a method builtin to a dict object. itemgetter 1) has to be imported 2) is more generically used, therefore probably using a more generic/slower algorithm JS From rabidpoobear at gmail.com Wed Aug 8 08:21:07 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Wed, 08 Aug 2007 01:21:07 -0500 Subject: [Tutor] how to sort a dictionary by values In-Reply-To: <698454.37135.qm@web32404.mail.mud.yahoo.com> References: <698454.37135.qm@web32404.mail.mud.yahoo.com> Message-ID: <46B960D3.2040500@gmail.com> wormwood_3 wrote: >>> You can use d.__getitem__ as the key function for a sort of the keys. >>> __getitem__() is the special method that is called for indexing a >>> dictionary (or a list). >>> > > Just curious: Is there a reason to use __getitem__() over itemgetter (used in the example in my reply)? > > >>> In [24]: d = {'a':21.3, 'b':32.8, 'c': 12.92} >>> In [26]: sorted(d.keys(), key=d.__getitem__, reverse=True) >>> > > I think Shawn would want to leave off "reverse=True". The default is least to greatest, which is what he wanted, I think. > It wouldn't have taken you very long to check to see what he wanted :) To save you time ;) he did want them in decreasing order. -Luke From alan.gauld at btinternet.com Wed Aug 8 09:48:22 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 8 Aug 2007 08:48:22 +0100 Subject: [Tutor] Checking for custom error codes References: <496944.75541.qm@web32404.mail.mud.yahoo.com> Message-ID: "wormwood_3" wrote > def lookup(self): > ... > for potdomain in self.potdomains: > try: > who.whois(potdomain) > self.availdomains.append(potdomain) > except 'NoSuchDomain': > pass > This may, however, be something else wrong with my code, or the > rwhois module, not the try, except check. You couldcheck that the except is working by replacing the pass statement with a print statement. If the print statement shows up you know the except worked so you can put the pass back in. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From zebra05 at gmail.com Wed Aug 8 09:54:02 2007 From: zebra05 at gmail.com (OkaMthembo) Date: Wed, 8 Aug 2007 09:54:02 +0200 Subject: [Tutor] Large Scale Python websites In-Reply-To: <57B026980605A64F9B23484C5659E32E9835FC@poccso.US.ad.atmel.com> References: <46B8AE21.7080304@brunson.com> <57B026980605A64F9B23484C5659E32E9835FC@poccso.US.ad.atmel.com> Message-ID: On 8/7/07, Mike Hansen wrote: > > > >> Is anyone aware of any large scale web apps developed in Python? > > >> Please let > > >> me know of any that you know of... > > I think that reddit.com switched from LISP to Python a while back. > > Mike > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > Interesting to hear these examples, especially YouTube. Apparently, Yelp.comand Slide.com also use the beautiful language. Thanks to everyone, -- Sithembewena Lloyd Dube "The Stupidry Foundry" -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070808/9c8d718a/attachment.html From Andy.cheesman at bristol.ac.uk Wed Aug 8 10:55:54 2007 From: Andy.cheesman at bristol.ac.uk (Andy Cheesman) Date: Wed, 08 Aug 2007 09:55:54 +0100 Subject: [Tutor] comparing two numpy arrays In-Reply-To: <46B8A63E.9010308@alum.rpi.edu> References: <46B85548.7000805@bristol.ac.uk> <46B8855F.3070301@alum.rpi.edu> <46B8924E.80407@brunson.com> <46B8A63E.9010308@alum.rpi.edu> Message-ID: <46B9851A.90409@bristol.ac.uk> Thats a great solution, thanks! I've googled a bit for manipulation of sets into other data structure(lists, arrays) and not seen much. Is the only way of interconversion a brute force method? i.e a = set([1, 2, 3]) b = [] for thing in a: b.append(thing) Andy Bob Gailer wrote: > Eric Brunson wrote: >> Bob Gailer wrote: >>> Andy Cheesman wrote: >>> >>>> Hi people, >>>> >>>> If I've two numpy arrays, is there a non-looping way of finding common >>>> values. (the example below has identical shapes for the arrays but this >>>> may not be the case in my scenario) >>>> >>>> e.g >>>> a = array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) >>>> b = array([ 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]) >>>> >>>> answer = array([ 5,6,7,8,9]) >>>> >>> Set union? >>> >>> >> Did you mean Set intersection? > Yes. Sigh. >> > > From kent37 at tds.net Wed Aug 8 12:57:32 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 08 Aug 2007 06:57:32 -0400 Subject: [Tutor] how to sort a dictionary by values In-Reply-To: <698454.37135.qm@web32404.mail.mud.yahoo.com> References: <698454.37135.qm@web32404.mail.mud.yahoo.com> Message-ID: <46B9A19C.7070606@tds.net> wormwood_3 wrote: >>> You can use d.__getitem__ as the key function for a sort of the keys. >>> __getitem__() is the special method that is called for indexing a >>> dictionary (or a list). > > Just curious: Is there a reason to use __getitem__() over itemgetter > (used in the example in my reply)? The results are different. My code gives a list of keys, sorted by value, which was how I interpreted the request. Your code gives a list of key, value pairs, sorted by value. It's easy enough to change your list to just keys with a list comprehension. Then you are essentially doing a sort using decorate-sort-undecorate (except the decorate step builds the tuples in the wrong order). You could think of the sort using key=d.__getitem__ as the modern equivalent of your DSU sort. OTOH if the OP really *wants* a sorted list of key, value pairs, your version is fine. >>> In [24]: d = {'a':21.3, 'b':32.8, 'c': 12.92} >>> In [26]: sorted(d.keys(), key=d.__getitem__, reverse=True) > > I think Shawn would want to leave off "reverse=True". The default is > least to greatest, which is what he wanted, I think. Possibly. He did say "least to greatest" but his example output is greatest to least. Kent From kent37 at tds.net Wed Aug 8 13:09:46 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 08 Aug 2007 07:09:46 -0400 Subject: [Tutor] how to sort a dictionary by values In-Reply-To: <000601c7d979$46a2e7e0$32fce004@JSLAPTOP> References: <698454.37135.qm@web32404.mail.mud.yahoo.com> <000601c7d979$46a2e7e0$32fce004@JSLAPTOP> Message-ID: <46B9A47A.9030302@tds.net> Tiger12506 wrote: >> Just curious: Is there a reason to use __getitem__() over itemgetter (used >> in the example in my reply)? > > __getitem__ is a method builtin to a dict object. itemgetter 1) has to be > imported 2) is more generically used, therefore probably using a more > generic/slower algorithm itemgetter() written in C and should be pretty fast. The actual sort algorithm is the same in either case, in fact the list of keys to be sorted is the same in either case. On my computer my version seems to be a little faster on random data but as I noted in a separate email, the results are different so the algorithm should be chosen based on the desired results. In [27]: import random In [28]: d = dict( (i, random.random()) for i in range(1000) ) In [29]: import timeit In [34]: timeit.Timer('sorted(d.keys(), key=d.__getitem__, reverse=True)', 'from __main__ import d').timeit(10000) Out[34]: 7.3717570304870605 In [38]: timeit.Timer('sorted(d.items(), key=operator.itemgetter(1), reverse=True)', 'from __main__ import d; import operator').timeit(10000) Out[38]: 8.2723259925842285 Kent From kent37 at tds.net Wed Aug 8 13:11:16 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 08 Aug 2007 07:11:16 -0400 Subject: [Tutor] comparing two numpy arrays In-Reply-To: <46B9851A.90409@bristol.ac.uk> References: <46B85548.7000805@bristol.ac.uk> <46B8855F.3070301@alum.rpi.edu> <46B8924E.80407@brunson.com> <46B8A63E.9010308@alum.rpi.edu> <46B9851A.90409@bristol.ac.uk> Message-ID: <46B9A4D4.7010806@tds.net> Andy Cheesman wrote: > I've googled a bit for manipulation of > sets into other data structure(lists, arrays) and not seen much. Is the > only way of interconversion a brute force method? > > i.e a = set([1, 2, 3]) > b = [] > for thing in a: > b.append(thing) No, a set is a sequence, you can convert it to a list directly: b = list(a) Kent From nephish at gmail.com Wed Aug 8 14:02:33 2007 From: nephish at gmail.com (shawn bright) Date: Wed, 8 Aug 2007 07:02:33 -0500 Subject: [Tutor] how to sort a dictionary by values In-Reply-To: <46B9A47A.9030302@tds.net> References: <698454.37135.qm@web32404.mail.mud.yahoo.com> <000601c7d979$46a2e7e0$32fce004@JSLAPTOP> <46B9A47A.9030302@tds.net> Message-ID: <384c93600708080502o52d5a571l2b519b077e33058@mail.gmail.com> sorry all, i did mean greatest to least, thanks for all the help here shawn On 8/8/07, Kent Johnson wrote: > > Tiger12506 wrote: > >> Just curious: Is there a reason to use __getitem__() over itemgetter > (used > >> in the example in my reply)? > > > > __getitem__ is a method builtin to a dict object. itemgetter 1) has to > be > > imported 2) is more generically used, therefore probably using a more > > generic/slower algorithm > > itemgetter() written in C and should be pretty fast. The actual sort > algorithm is the same in either case, in fact the list of keys to be > sorted is the same in either case. > > On my computer my version seems to be a little faster on random data but > as I noted in a separate email, the results are different so the > algorithm should be chosen based on the desired results. > > In [27]: import random > In [28]: d = dict( (i, random.random()) for i in range(1000) ) > In [29]: import timeit > In [34]: timeit.Timer('sorted(d.keys(), key=d.__getitem__, > reverse=True)', 'from __main__ import d').timeit(10000) > Out[34]: 7.3717570304870605 > In [38]: timeit.Timer('sorted(d.items(), key=operator.itemgetter(1), > reverse=True)', 'from __main__ import d; import operator').timeit(10000) > Out[38]: 8.2723259925842285 > > Kent > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070808/5f0ea49c/attachment.html From janos.juhasz at VELUX.com Wed Aug 8 14:18:07 2007 From: janos.juhasz at VELUX.com (=?ISO-8859-1?Q?J=E1nos_Juh=E1sz?=) Date: Wed, 8 Aug 2007 14:18:07 +0200 Subject: [Tutor] from netcat to socket In-Reply-To: Message-ID: Dear All, I made a small script to emulate a jetdirect device and capture the data sent from SAP to three separate barcode printers. I need it to make backup for the SAP printing, as I can place the captured files onto a local server and place a small batch file beside them, that can be used to print the files without SAP. My first version worked with nc.exe (netcat) like so : from threading import Thread import os import time printers = (('10.36.24.40', 'front'), ('10.36.24.41', 'gable'), ('10.36.24.42', 'top')) class CaptureThread(Thread): def __init__(self, address, type): Thread.__init__(self) self.setDaemon(True) self.address = address self.type = type self.port = 9100 def run(self): command = 'nc -l -s %s -p %d > %s.prn' %(self.address, self.port, self.type) print command os.system(command) print '%s is printed' % self.type time.sleep(2) # wait for two seconds def capture(): print_threads = [] for ip, name in printers: print_thread = CaptureThread(ip, name) print_thread.start() print_threads.append(print_thread) # now wait for them to finish for print_thread in print_threads: print_thread.join() if __name__ == '__main__': while 1: print '-'*30 capture() #do stuff with the saved files I tried to change it to be socket based like so: from threading import Thread import os import time import socket ## Settings threads = {'front':{'capt':('127.0.0.1', 9100), 'dest':('127.0.0.1', 9100), 'thread':None}, 'gable':{'capt':('127.0.0.1', 9101), 'dest':('127.0.0.1', 9101), 'thread':None}, 'top': {'capt':('127.0.0.1', 9102), 'dest':('127.0.0.1', 9102), 'thread':None}, } class PrinterThread(Thread): def __init__(self, address, port): Thread.__init__(self) self.setDaemon(True) self.address = address self.port = port self.content = '' self.soc = socket.socket( socket.AF_INET, socket.SOCK_STREAM ) self.soc.bind((address, port)) self.soc.listen(1) def run(self): try: conn, addr = self.soc.accept() while 1: data = conn.recv(1024) self.content += data if not data: conn.close() break except: print 'exception (connection closed)' So the question is, how translate command = 'nc -l -s %s -p %d > %s.prn' %(self.address, self.port, self.type) os.system(command) to be socket based. I also would ask your opinions about the structure of 'threads'. Regards, Janos From sebastien at solutions-linux.org Wed Aug 8 19:22:54 2007 From: sebastien at solutions-linux.org (Sebastien) Date: Wed, 8 Aug 2007 12:22:54 -0500 Subject: [Tutor] Removing tags with BeautifulSoup Message-ID: <6aa58ba2cf960630deda758f970c1cef@localhost> Hi, I'm in the process of cleaning some html files with BeautifulSoup and I want to remove all traces of the tables. Here is the bit of the code that deals with tables: def remove(soup, tagname): for tag in soup.findAll(tagname): contents = tag.contents parent = tag.parent tag.extract() for tag in contents: parent.append(tag) remove(soup, "table") remove(soup, "tr") remove(soup, "td") It works fine but leaves an empty table structure at the end of the soup. Like: ... And the extract method of BeautifulSoup seems the extract only what is in the tags. So I'm just looking for a quick and dirty way to remove this table structure at the end of the documents. I'm thinking with re but there must be a way to do it with BeautifulSoup, maybe I'm missing something. An other thing that makes me wonder, this code: for script in soup("script"): soup.script.extract() Works fine and remove script tags, but: for table in soup("table"): soup.table.extract() Raises AttributeError: 'NoneType' object has no attribute 'extract' Oh, and BTW, when I extract script tags this way, all the tag is gone, like I want it, it doesn't only removes the content of the tag. Thanks in advance From alan.gauld at btinternet.com Wed Aug 8 20:12:44 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 8 Aug 2007 19:12:44 +0100 Subject: [Tutor] comparing two numpy arrays References: <46B85548.7000805@bristol.ac.uk><46B8855F.3070301@alum.rpi.edu> <46B8924E.80407@brunson.com><46B8A63E.9010308@alum.rpi.edu> <46B9851A.90409@bristol.ac.uk> Message-ID: "Andy Cheesman" wrote > only way of interconversion a brute force method? > > i.e a = set([1, 2, 3]) > b = [] > for thing in a: > b.append(thing) Which looks a lot like a list comprehension: b = [member for member in Set([1,2,3])] HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Wed Aug 8 20:45:51 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 8 Aug 2007 19:45:51 +0100 Subject: [Tutor] comparing two numpy arrays References: <46B85548.7000805@bristol.ac.uk> <46B8855F.3070301@alum.rpi.edu> <46B8924E.80407@brunson.com> <46B8A63E.9010308@alum.rpi.edu><46B9851A.90409@bristol.ac.uk> <46B9A4D4.7010806@tds.net> Message-ID: "Kent Johnson" wrote > No, a set is a sequence, you can convert it to a list directly: > b = list(a) But this is better than an LC obviously! :-) Alan G From bylindoso at gmail.com Wed Aug 8 20:48:36 2007 From: bylindoso at gmail.com (Diego Lindoso) Date: Wed, 8 Aug 2007 15:48:36 -0300 Subject: [Tutor] dial-up from Python Message-ID: <2f92aab20708081148t74235218m5bbe019c1b39804@mail.gmail.com> -- Diego Lindoso. Fone: 3466-2387 Cel : 9634-5993 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070808/9250bbe4/attachment-0001.html From rabidpoobear at gmail.com Wed Aug 8 21:56:55 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Wed, 08 Aug 2007 14:56:55 -0500 Subject: [Tutor] dial-up from Python In-Reply-To: <2f92aab20708081148t74235218m5bbe019c1b39804@mail.gmail.com> References: <2f92aab20708081148t74235218m5bbe019c1b39804@mail.gmail.com> Message-ID: <46BA2007.8040008@gmail.com> Diego Lindoso wrote: > > > -- > Diego Lindoso. > Fone: 3466-2387 > Cel : 9634-5993 Beeep! Beep beep boop boop beep!!!! cshhhh shhk shhhhhhk cshhhhh.... [connection timeout] -Luke From bob at pbsit.com Wed Aug 8 22:16:07 2007 From: bob at pbsit.com (Bob Larsen) Date: Wed, 08 Aug 2007 16:16:07 -0400 Subject: [Tutor] httplib exceptions Message-ID: <46BA2487.5030202@pbsit.com> I have written a script which checks all of my servers at predetermined intervals. code: try: page = urllib2.urlopen(url) soup= page.read() reex = re.compile(regex) test = re.findall(reex,soup) except ValueError,e: return 0 if test: return 1 else: return 0 Without the try clause the following exception is thrown: Traceback (most recent call last): File "~/webcheck2.py", line 116, in ? if sitetest(url,search): File "~/webcheck2.py", line 71, in sitetest soup= page.read() File "/usr/lib/python2.4/socket.py", line 285, in read data = self._sock.recv(recv_size) File "/usr/lib/python2.4/httplib.py", line 460, in read return self._read_chunked(amt) File "/usr/lib/python2.4/httplib.py", line 499, in _read_chunked chunk_left = int(line, 16) ValueError: invalid literal for int(): This script has been running well for months. Within the past week it has started misbehaving. There is a python Bug: http://sourceforge.net/tracker/index.php?func=detail&aid=1486335&group_id=5470&atid=105470 that states this is caused by a missing EOF, and is "not a big deal" At this point I am confused. What exactly is causing this problem that didn't exist until a week ago? How can I work Around this? Any Insight is greatly appreciated Bob Larsen -- This message has been scanned for viruses and dangerous content by MailScanner, and is believed to be clean. From kent37 at tds.net Wed Aug 8 23:07:51 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 08 Aug 2007 17:07:51 -0400 Subject: [Tutor] httplib exceptions In-Reply-To: <46BA2487.5030202@pbsit.com> References: <46BA2487.5030202@pbsit.com> Message-ID: <46BA30A7.7040409@tds.net> Bob Larsen wrote: > I have written a script which checks all of my servers at predetermined > intervals. > > code: > > try: > page = urllib2.urlopen(url) > soup= page.read() > reex = re.compile(regex) > test = re.findall(reex,soup) > except ValueError,e: > return 0 > if test: > return 1 > else: > return 0 > > Without the try clause the following exception is thrown: > > Traceback (most recent call last): > File "~/webcheck2.py", line 116, in ? > if sitetest(url,search): > File "~/webcheck2.py", line 71, in sitetest > soup= page.read() > File "/usr/lib/python2.4/socket.py", line 285, in read > data = self._sock.recv(recv_size) > File "/usr/lib/python2.4/httplib.py", line 460, in read > return self._read_chunked(amt) > File "/usr/lib/python2.4/httplib.py", line 499, in _read_chunked > chunk_left = int(line, 16) > ValueError: invalid literal for int(): > > This script has been running well for months. Within the past week it > has started misbehaving. > > There is a python Bug: > http://sourceforge.net/tracker/index.php?func=detail&aid=1486335&group_id=5470&atid=105470 > > that states this is caused by a missing EOF, and is "not a big deal" > > At this point I am confused. > > What exactly is causing this problem that didn't exist until a week ago? > > How can I work Around this? > > Any Insight is greatly appreciated Not much to add but sympathy...I occasionally see this error also when reading web pages from public servers. My read on the bug report is - they think it is an error in the data coming from the server - they don't know the right way to fix it So, has anything changed on the servers you are pinging? an upgrade to a new version or change to a different server? I guess you could try the patch, I haven't been that adventurous. Kent From alan.gauld at btinternet.com Wed Aug 8 23:34:00 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 8 Aug 2007 22:34:00 +0100 Subject: [Tutor] httplib exceptions References: <46BA2487.5030202@pbsit.com> Message-ID: "Bob Larsen" wrote It won't help with your problem but... > try: > page = urllib2.urlopen(url) > soup= page.read() > reex = re.compile(regex) > test = re.findall(reex,soup) You could change this to test = reex.findall(soup) Its normal when compiling a regex to use the methods of the compiled expression rather than to pass the compiled regex to a module function. > except ValueError,e: > return 0 > if test: > return 1 > else: > return 0 And the if/else could be replaced with return bool(test) And on the real problem: > There is a python Bug: > http://sourceforge.net/tracker/index.php?func=detail&aid=1486335&group_id=5470&atid=105470 > > that states this is caused by a missing EOF, and is "not a big deal" Any chance that you are running into OS differences? eg Checking a Unix file on a Windows box or vice versa? Windows expects an EOF at the end of a file, Unix doesn't. Not sure what happens when you add in the complexity of sucking the file across the net though... Alan G. From kent37 at tds.net Wed Aug 8 23:41:16 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 08 Aug 2007 17:41:16 -0400 Subject: [Tutor] httplib exceptions In-Reply-To: References: <46BA2487.5030202@pbsit.com> Message-ID: <46BA387C.6040801@tds.net> Alan Gauld wrote: >> There is a python Bug: >> http://sourceforge.net/tracker/index.php?func=detail&aid=1486335&group_id=5470&atid=105470 >> >> that states this is caused by a missing EOF, and is "not a big deal" > > Any chance that you are running into OS differences? eg Checking a > Unix file on > a Windows box or vice versa? Windows expects an EOF at the end of a > file, > Unix doesn't. Not sure what happens when you add in the complexity of > sucking the file across the net though... The problem is in httplib in the portion of the code that handles HTTP 1.1 chunked transfers, so I don't think differences in file handling come in to play. Kent From ssg.hilton at comcast.net Thu Aug 9 02:16:33 2007 From: ssg.hilton at comcast.net (TheSarge) Date: Wed, 8 Aug 2007 17:16:33 -0700 (PDT) Subject: [Tutor] Shelve problem Message-ID: <12064251.post@talk.nabble.com> I have five data files, that are used to build a database. 1.txt 2.txt 3.txt 4.text 5.txt I want to build a database using a persistent dictionary (shelve). The specifications are that the key for each dictionary keyword pair, is the lefthand side value of the # sign, and the corresponding value for the data is the phrase on the righthand side. Can someone help me manipulate this please? I can't not get a grasp on shelves and on what I need to do. Thanks, TheSarge -- View this message in context: http://www.nabble.com/Shelve-problem-tf4239852.html#a12064251 Sent from the Python - tutor mailing list archive at Nabble.com. From carroll at tjc.com Thu Aug 9 04:44:57 2007 From: carroll at tjc.com (Terry Carroll) Date: Wed, 8 Aug 2007 19:44:57 -0700 (PDT) Subject: [Tutor] Shelve problem In-Reply-To: <12064251.post@talk.nabble.com> Message-ID: On Wed, 8 Aug 2007, TheSarge wrote: > I have five data files, that are used to build a database. > > 1.txt > 2.txt > 3.txt > 4.text > 5.txt > > I want to build a database using a persistent dictionary (shelve). > > The specifications are that the key for each dictionary keyword pair, is the > lefthand side > value of the # sign, and the corresponding value for the data is the phrase > on the > righthand side. > > Can someone help me manipulate this please? I can't not get a grasp on > shelves and on what I need to do. Basically, once you create a shelf object (which you do by calling shelve.open on a new or existing filename), you treat it like a dictionary. When you close it, the values in the dictionary are saved. For example, in one program, you would have: shelf = shelve.open("testfile.shelf") And later, lines like: shelf["a"] = "Alligators all around" # just like a dictionary. shelf["b"] = "Bursting balloons" . . . shelf["z"] = "Zippety Zound" and eventually: shelf.close() Then, in another program (or later in the same program) you could re-open the shelf-file and use it as a dictionary shlf = shelv.open("testfile.shelf") for key in shlf: print key, shlf[key] and you should see, in arbitrary order, things like: b Bursting balloons r Riding reindeer e Entertaining Elephants a Aligators all around Is this a homework problem, or a real-life application? From kent37 at tds.net Thu Aug 9 00:31:46 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 08 Aug 2007 18:31:46 -0400 Subject: [Tutor] Bookpool sale on Addison Wesley Message-ID: <46BA4452.5000303@tds.net> Bookpool is having a sale on all books from Addison-Wesley and Prentice Hall. In my opinion these are two of the best publishers for top-notch computer titles. A few Python books on sale: Core Python Programming $27.25 http://www.bookpool.com/sm/0132269937 Rapid Web Applications with TurboGears $24.50 http://www.bookpool.com/sm/0132433885 Some recommended non-Python books: Design Patterns: Elements of Reusable Object-Oriented Software $32.95 http://www.bookpool.com/sm/0201633612 Refactoring: Improving the Design of Existing Code http://www.bookpool.com/sm/0201485672 Agile Software Development Principles, Patterns, and Practices http://www.bookpool.com/sm/0135974445 Extreme Programming Explained: Embrace Change, 2nd Edition http://www.bookpool.com/sm/0321278658 and all the other books in this series These are just a few personal favorites, there are many more excellent books on sale. Kent From rdm at rcblue.com Thu Aug 9 15:55:12 2007 From: rdm at rcblue.com (Dick Moores) Date: Thu, 09 Aug 2007 06:55:12 -0700 Subject: [Tutor] Python Editors .. which do you reccomend for a amateur? In-Reply-To: <200708041623.21131.jfabiani@yolo.com> References: <200708041623.21131.jfabiani@yolo.com> Message-ID: <20070809135548.7374C1E400D@bag.python.org> At 04:23 PM 8/4/2007, johnf wrote: >I got to put my pitch in for wing. The latest is very good indeed. Yea it >cost money but I feel well worth the money. John, Could you tell us what it is about Wing that you like so much? I assume you mean Wing IDE Professional? Have you tried the new version 3 beta? Thanks, Dick Moores ====================================== Bagdad Weather From titleistfour at gmail.com Thu Aug 9 16:40:05 2007 From: titleistfour at gmail.com (jay) Date: Thu, 9 Aug 2007 09:40:05 -0500 Subject: [Tutor] Extending logging module Message-ID: <7c25bb490708090740t10b0e0d9rd00d6bd3f47d88cd@mail.gmail.com> Hello, I've been using the python logging module a lot lately, and I've come across an instance where I need some new levels. Specifically, python does not include ALERT and NOTICE in the default set of logging levels. I am wondering how trivial it would be to extend the logging module to include these 2 levels that are standard with syslog? My first test was just to use the addLevelName method to add the two new levels, but syslog ignores them and logs at the next highest priority, no matter what I use. Looking further into the code and as a test, I changed the following to see if this would even work lib/python2.5/logging/__init__.py -> class Logger -> add new notice and alert root level functions -> new _levelNames for notice and alert -> new default level names for notice and alert lib/python2.5/logging/handlers.py -> class SysLogHandler priority_map was changed to include notice and alert It actually worked, but this is not the way I would like to handle the problem. I would prefer to extend the classes instead. However, I'm not too familiar with that, and I had to change things in so many places, I'm wondering if its even possible? I don't like changing the standard libraries, what happens if I have to upgrade python? My changes get overwritten. Can anyone offer some help or suggestions? Thanks Jay -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070809/9fbee351/attachment.html From kent37 at tds.net Thu Aug 9 17:15:20 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 09 Aug 2007 11:15:20 -0400 Subject: [Tutor] Extending logging module In-Reply-To: <7c25bb490708090740t10b0e0d9rd00d6bd3f47d88cd@mail.gmail.com> References: <7c25bb490708090740t10b0e0d9rd00d6bd3f47d88cd@mail.gmail.com> Message-ID: <46BB2F88.3040008@tds.net> jay wrote: > Hello, > > I've been using the python logging module a lot lately, and I've come > across an instance where I need some new levels. Specifically, python > does not include ALERT and NOTICE in the default set of logging levels. > I am wondering how trivial it would be to extend the logging module to > include these 2 levels that are standard with syslog? > > My first test was just to use the addLevelName method to add the two new > levels, but syslog ignores them and logs at the next highest priority, > no matter what I use. > > Looking further into the code and as a test, I changed the following to > see if this would even work > > lib/python2.5/logging/__init__.py > -> class Logger > -> add new notice and alert root level functions > -> new _levelNames for notice and alert > -> new default level names for notice and alert You could do all this by patching the logging module at runtime: import logging logging.ALERT = 60 logging.addLevelName(logging.ALERT, 'ALERT') def Logger_alert(self, msg, *args, **kwargs): ... logging.Logger.alert = Logger_alert def alert(msg, *args, **kwargs): ... logging.alert = alert It's a little ugly but since you are just extending the module with new constants and functions it seems pretty safe and clean to me. It would be cool if addLevelName() did all this patching for you, it wouldn't be hard to do...maybe you want to propose a patch... > lib/python2.5/logging/handlers.py > -> class SysLogHandler priority_map was changed to include notice and > alert You can do this by subclassing SysLogHandler: class FixedSysLogHandler(SysLogHandler): priority_map = { ... } then configure logging to use FixedSysLogHandler instead of SysLogHandler. You might want to post about this on comp.lang.python, I think the author of the logging module will see it there. Kent From brunson at brunson.com Thu Aug 9 17:48:53 2007 From: brunson at brunson.com (Eric Brunson) Date: Thu, 09 Aug 2007 09:48:53 -0600 Subject: [Tutor] variable * raw_input In-Reply-To: <1869F460-E71B-4171-856B-84FF11708188@ucdavis.edu> References: <1869F460-E71B-4171-856B-84FF11708188@ucdavis.edu> Message-ID: <46BB3765.9010503@brunson.com> Dewight Kramer wrote: > Hello, > > So i am new to Python, and really to programming. I picked up book > and so far I like it. right now I am trying to figure out a problem > that I cant. > > It is a tipping program and I have assigned certain words to be a > certain % and then I ask the user to type raw input of one of those > names. After which I am trying to mutiply the Bill by the Service > quality. But I dont understand something below is code. > > Thanks > D > > # Tip Calulator - Ver > # Challenges Ch2 - Question 3 > # Developed by, Dewight > # Developed on, 8/7/2007 > > > # establish variables > bill = float(0.0) > bad = float (0.0) > ok = float(0.10) > good = float (0.15) > great = float (0.20) > Speaking as a former waiter, this should probably read: great = float (0.25) good = float (0.20) ok = float(0.15) bad = float (0.10) eatathomeyoucheapskatebagofcrap = float(0.0) ;-) I now return you to your regularly scheduled Python discussion. > service="nothing" > tip = float () > total = float () > > print "This is a tipping calculator." > > bill = raw_input ("\nWhat was the total bill amount? ") > service = raw_input("Please input one of the following to"+ > " discribe the service:"+"\nbad\nok\ngood\ngreat > \n") > > tip = bill * service > total = bill + tip > print "Then you should leave a" + tip + "tip. This will bring the > total to" + total +"." > > > raw_input("\n\nPlease press enter to exit.") > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From titleistfour at gmail.com Thu Aug 9 18:06:26 2007 From: titleistfour at gmail.com (jay) Date: Thu, 9 Aug 2007 11:06:26 -0500 Subject: [Tutor] Extending logging module In-Reply-To: <46BB2F88.3040008@tds.net> References: <7c25bb490708090740t10b0e0d9rd00d6bd3f47d88cd@mail.gmail.com> <46BB2F88.3040008@tds.net> Message-ID: <7c25bb490708090906v703d1b9crb29a97cb3f862452@mail.gmail.com> Kent, Thanks for the suggestion. If will look more into your suggestions, and also shoot a post over to comp.lang.python. Jay On 8/9/07, Kent Johnson wrote: > > jay wrote: > > Hello, > > > > I've been using the python logging module a lot lately, and I've come > > across an instance where I need some new levels. Specifically, python > > does not include ALERT and NOTICE in the default set of logging levels. > > I am wondering how trivial it would be to extend the logging module to > > include these 2 levels that are standard with syslog? > > > > My first test was just to use the addLevelName method to add the two new > > levels, but syslog ignores them and logs at the next highest priority, > > no matter what I use. > > > > Looking further into the code and as a test, I changed the following to > > see if this would even work > > > > lib/python2.5/logging/__init__.py > > -> class Logger > > -> add new notice and alert root level functions > > -> new _levelNames for notice and alert > > -> new default level names for notice and alert > > You could do all this by patching the logging module at runtime: > import logging > logging.ALERT = 60 > logging.addLevelName(logging.ALERT, 'ALERT') > > def Logger_alert(self, msg, *args, **kwargs): > ... > > logging.Logger.alert = Logger_alert > > def alert(msg, *args, **kwargs): > ... > > logging.alert = alert > > It's a little ugly but since you are just extending the module with new > constants and functions it seems pretty safe and clean to me. It would > be cool if addLevelName() did all this patching for you, it wouldn't be > hard to do...maybe you want to propose a patch... > > > lib/python2.5/logging/handlers.py > > -> class SysLogHandler priority_map was changed to include notice and > > alert > > You can do this by subclassing SysLogHandler: > > class FixedSysLogHandler(SysLogHandler): > priority_map = { ... } > > then configure logging to use FixedSysLogHandler instead of SysLogHandler. > > > You might want to post about this on comp.lang.python , I think the > author of the logging module will see it there. > > Kent > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070809/8d061e77/attachment.htm From bill at celestial.net Thu Aug 9 18:54:15 2007 From: bill at celestial.net (Bill Campbell) Date: Thu, 9 Aug 2007 09:54:15 -0700 Subject: [Tutor] Bookpool sale on Addison Wesley In-Reply-To: <46BA4452.5000303@tds.net> References: <46BA4452.5000303@tds.net> Message-ID: <20070809165415.GA26447@ayn.mi.celestial.com> On Wed, Aug 08, 2007, Kent Johnson wrote: >Bookpool is having a sale on all books from Addison-Wesley and Prentice >Hall. In my opinion these are two of the best publishers for top-notch >computer titles. I've found bookpool.com to generally have better prices on technical books than Amazon or Powells. They're generally the first place I look. (my only assocation with any of them is as a customer). ... Bill -- INTERNET: bill at celestial.com Bill Campbell; Celestial Software LLC URL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way FAX: (206) 232-9186 Mercer Island, WA 98040-0820; (206) 236-1676 Government is actually the worst failure of civilized man. There has never been a really good one, and even those that are most tolerable are arbitrary, cruel, grasping and unintelligent. -- H. L. Mencken From sazelton at nd.edu Thu Aug 9 15:16:24 2007 From: sazelton at nd.edu (Sean Azelton) Date: Thu, 09 Aug 2007 09:16:24 -0400 Subject: [Tutor] Bookpool sale on Addison Wesley In-Reply-To: <46BA4452.5000303@tds.net> References: <46BA4452.5000303@tds.net> Message-ID: <46BB13A8.5050608@nd.edu> Thanks Kent. Can anyone tell me why the below book is listed as SOOOO expensive? With the sale Kent mentioned, it looks like a great deal - but unfortunately I don't really know anything about the authors. Object-Oriented Programming in Python Michael H Goldwasser, David Letscher Prentice Hall List Price: $102.00 Our Price: $55.95 You Save: $46.05 (45% Off) Estimated Publication Date November 2007, 700 pages, ISBN 0136150314 Is this a good buy? Thanks, Sean Azelton University of Notre Dame Kent Johnson wrote: > Bookpool is having a sale on all books from Addison-Wesley and Prentice > Hall. In my opinion these are two of the best publishers for top-notch > computer titles. > > A few Python books on sale: > Core Python Programming $27.25 > http://www.bookpool.com/sm/0132269937 > > Rapid Web Applications with TurboGears $24.50 > http://www.bookpool.com/sm/0132433885 > > Some recommended non-Python books: > Design Patterns: Elements of Reusable Object-Oriented Software $32.95 > http://www.bookpool.com/sm/0201633612 > > Refactoring: Improving the Design of Existing Code > http://www.bookpool.com/sm/0201485672 > > Agile Software Development Principles, Patterns, and Practices > http://www.bookpool.com/sm/0135974445 > > Extreme Programming Explained: Embrace Change, 2nd Edition > http://www.bookpool.com/sm/0321278658 > and all the other books in this series > > These are just a few personal favorites, there are many more excellent > books on sale. > > Kent > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3229 bytes Desc: S/MIME Cryptographic Signature Url : http://mail.python.org/pipermail/tutor/attachments/20070809/08ac049a/attachment-0001.bin From Mike.Hansen at atmel.com Thu Aug 9 19:08:12 2007 From: Mike.Hansen at atmel.com (Mike Hansen) Date: Thu, 9 Aug 2007 11:08:12 -0600 Subject: [Tutor] Bookpool sale on Addison Wesley In-Reply-To: <20070809165415.GA26447@ayn.mi.celestial.com> References: <46BA4452.5000303@tds.net> <20070809165415.GA26447@ayn.mi.celestial.com> Message-ID: <57B026980605A64F9B23484C5659E32E983794@poccso.US.ad.atmel.com> > -----Original Message----- > From: Bill Campbell > Sent: Thursday, August 09, 2007 10:54 AM > To: tutor at python.org > Subject: Re: [Tutor] Bookpool sale on Addison Wesley > > I've found bookpool.com to generally have better prices on > technical books than Amazon or Powells. They're generally the > first place I look. > > (my only assocation with any of them is as a customer). > > ... > Bill Bookpool is pretty good. Half.com and nerdbooks.com are other places I look for cheaper tech books. Mike From wormwood_3 at yahoo.com Thu Aug 9 19:35:36 2007 From: wormwood_3 at yahoo.com (wormwood_3) Date: Thu, 9 Aug 2007 10:35:36 -0700 (PDT) Subject: [Tutor] Bookpool sale on Addison Wesley Message-ID: <590897.12982.qm@web32404.mail.mud.yahoo.com> Thanks for the heads up! I have been looking to get Core Python Programming for a while now. _______________________________ ----- Original Message ---- From: Kent Johnson To: Tutor at python.org Sent: Wednesday, August 8, 2007 6:31:46 PM Subject: [Tutor] Bookpool sale on Addison Wesley Bookpool is having a sale on all books from Addison-Wesley and Prentice Hall. In my opinion these are two of the best publishers for top-notch computer titles. A few Python books on sale: Core Python Programming $27.25 http://www.bookpool.com/sm/0132269937 Rapid Web Applications with TurboGears $24.50 http://www.bookpool.com/sm/0132433885 Some recommended non-Python books: Design Patterns: Elements of Reusable Object-Oriented Software $32.95 http://www.bookpool.com/sm/0201633612 Refactoring: Improving the Design of Existing Code http://www.bookpool.com/sm/0201485672 Agile Software Development Principles, Patterns, and Practices http://www.bookpool.com/sm/0135974445 Extreme Programming Explained: Embrace Change, 2nd Edition http://www.bookpool.com/sm/0321278658 and all the other books in this series These are just a few personal favorites, there are many more excellent books on sale. Kent _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From rdm at rcblue.com Thu Aug 9 19:57:24 2007 From: rdm at rcblue.com (Dick Moores) Date: Thu, 09 Aug 2007 10:57:24 -0700 Subject: [Tutor] Bookpool sale on Addison Wesley In-Reply-To: <57B026980605A64F9B23484C5659E32E983794@poccso.US.ad.atmel. com> References: <46BA4452.5000303@tds.net> <20070809165415.GA26447@ayn.mi.celestial.com> <57B026980605A64F9B23484C5659E32E983794@poccso.US.ad.atmel.com> Message-ID: <20070809175737.5B4E01E400E@bag.python.org> I always first check BestBookDeal.com. Dick Moores From sazelton at nd.edu Thu Aug 9 20:41:23 2007 From: sazelton at nd.edu (Sean Azelton) Date: Thu, 9 Aug 2007 14:41:23 -0400 Subject: [Tutor] Bookpool sale on Addison Wesley In-Reply-To: <46BB13A8.5050608@nd.edu> References: <46BA4452.5000303@tds.net> <46BB13A8.5050608@nd.edu> Message-ID: Oh - I didn't mean Bookpool was too expensive - they are almost half the price of Amazon on this book. for clarification - I was wondering why the "Object-Oriented Programming in Python" book lists for $102.00 US when most books list for half that price. Sean On 8/9/07, Sean Azelton wrote: > Thanks Kent. > > Can anyone tell me why the below book is listed as SOOOO expensive? > With the sale Kent mentioned, it looks like a great deal - but > unfortunately I don't really know anything about the authors. > > Object-Oriented Programming in Python > Michael H Goldwasser, David Letscher > Prentice Hall > List Price: $102.00 > Our Price: $55.95 > You Save: $46.05 (45% Off) > > Estimated Publication Date November 2007, 700 pages, ISBN 0136150314 > > Is this a good buy? > > Thanks, > > Sean Azelton > University of Notre Dame > > Kent Johnson wrote: > > Bookpool is having a sale on all books from Addison-Wesley and Prentice > > Hall. In my opinion these are two of the best publishers for top-notch > > computer titles. > > > > A few Python books on sale: > > Core Python Programming $27.25 > > http://www.bookpool.com/sm/0132269937 > > > > Rapid Web Applications with TurboGears $24.50 > > http://www.bookpool.com/sm/0132433885 > > > > Some recommended non-Python books: > > Design Patterns: Elements of Reusable Object-Oriented Software $32.95 > > http://www.bookpool.com/sm/0201633612 > > > > Refactoring: Improving the Design of Existing Code > > http://www.bookpool.com/sm/0201485672 > > > > Agile Software Development Principles, Patterns, and Practices > > http://www.bookpool.com/sm/0135974445 > > > > Extreme Programming Explained: Embrace Change, 2nd Edition > > http://www.bookpool.com/sm/0321278658 > > and all the other books in this series > > > > These are just a few personal favorites, there are many more excellent > > books on sale. > > > > Kent > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > From taserian at gmail.com Thu Aug 9 20:58:34 2007 From: taserian at gmail.com (taserian) Date: Thu, 9 Aug 2007 14:58:34 -0400 Subject: [Tutor] Bookpool sale on Addison Wesley In-Reply-To: References: <46BA4452.5000303@tds.net> <46BB13A8.5050608@nd.edu> Message-ID: <70dbc4d40708091158n52392c8fy3a3209a6ea48d25e@mail.gmail.com> I think it's intended to be a collegiate-level textbook, and not a find-a-copy-at-your-local-bookstore type of book. Textbooks are considerably more expensive. Tony R. On 8/9/07, Sean Azelton wrote: > > Oh - I didn't mean Bookpool was too expensive - they are almost half > the price of Amazon on this book. for clarification - I was wondering > why the "Object-Oriented Programming in Python" book lists for $102.00 > US when most books list for half that price. > > Sean > > On 8/9/07, Sean Azelton wrote: > > Thanks Kent. > > > > Can anyone tell me why the below book is listed as SOOOO expensive? > > With the sale Kent mentioned, it looks like a great deal - but > > unfortunately I don't really know anything about the authors. > > > > Object-Oriented Programming in Python > > Michael H Goldwasser, David Letscher > > Prentice Hall > > List Price: $102.00 > > Our Price: $55.95 > > You Save: $46.05 (45% Off) > > > > Estimated Publication Date November 2007, 700 pages, ISBN 0136150314 > > > > Is this a good buy? > > > > Thanks, > > > > Sean Azelton > > University of Notre Dame > > > > Kent Johnson wrote: > > > Bookpool is having a sale on all books from Addison-Wesley and > Prentice > > > Hall. In my opinion these are two of the best publishers for top-notch > > > computer titles. > > > > > > A few Python books on sale: > > > Core Python Programming $27.25 > > > http://www.bookpool.com/sm/0132269937 > > > > > > Rapid Web Applications with TurboGears $24.50 > > > http://www.bookpool.com/sm/0132433885 > > > > > > Some recommended non-Python books: > > > Design Patterns: Elements of Reusable Object-Oriented Software $32.95 > > > http://www.bookpool.com/sm/0201633612 > > > > > > Refactoring: Improving the Design of Existing Code > > > http://www.bookpool.com/sm/0201485672 > > > > > > Agile Software Development Principles, Patterns, and Practices > > > http://www.bookpool.com/sm/0135974445 > > > > > > Extreme Programming Explained: Embrace Change, 2nd Edition > > > http://www.bookpool.com/sm/0321278658 > > > and all the other books in this series > > > > > > These are just a few personal favorites, there are many more excellent > > > books on sale. > > > > > > Kent > > > _______________________________________________ > > > Tutor maillist - Tutor at python.org > > > http://mail.python.org/mailman/listinfo/tutor > > > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070809/5c572267/attachment.html From titleistfour at gmail.com Thu Aug 9 21:05:09 2007 From: titleistfour at gmail.com (jay) Date: Thu, 9 Aug 2007 14:05:09 -0500 Subject: [Tutor] Extending logging module In-Reply-To: <7c25bb490708090906v703d1b9crb29a97cb3f862452@mail.gmail.com> References: <7c25bb490708090740t10b0e0d9rd00d6bd3f47d88cd@mail.gmail.com> <46BB2F88.3040008@tds.net> <7c25bb490708090906v703d1b9crb29a97cb3f862452@mail.gmail.com> Message-ID: <7c25bb490708091205p21a39f0fqf337bd3f9b7f7b97@mail.gmail.com> I have a working solution for this, based largely on what Kent posted. Thought I would post it for others in case your either curious, or need to do this in the future. There are probably other ways to do this. To add a new level NOTICE for logging to syslog # Change the default levels to include NOTICE in # the proper order of priority logging.FATAL = logging.CRITICAL = 60 logging.ERROR = 50 logging.WARN = logging.WARNING = 40 logging.NOTICE = 30 # insert the levels with all the redefined values # anything below NOTICE we don't have to add back in, its # not getting redefined above with a new value logging.addLevelName(logging.NOTICE, 'NOTICE') logging.addLevelName(logging.WARNING, 'WARNING') logging.addLevelName(logging.WARN, 'WARN') logging.addLevelName(logging.ERROR, 'ERROR') logging.addLevelName(logging.FATAL, 'FATAL') logging.addLevelName(logging.CRITICAL, 'CRITICAL') # define a new logger function for notice # this is exactly like existing info, critical, debug...etc def Logger_notice(self, msg, *args, **kwargs): """ Log 'msg % args' with severity 'NOTICE'. To pass exception information, use the keyword argument exc_info with a true value, e.g. logger.notice("Houston, we have a %s", "major disaster", exc_info=1) """ if self.manager.disable >= logging.NOTICE: return if logging.NOTICE >= self.getEffectiveLevel(): apply(self._log, (logging.NOTICE, msg, args), kwargs) # make the notice function known in the system Logger class logging.Logger.notice = Logger_notice # define a new root level notice function # this is exactly like existing info, critical, debug...etc def root_notice(msg, *args, **kwargs): """ Log a message with severity 'NOTICE' on the root logger. """ if len(root.handlers) == 0: basicConfig() apply(root.notice, (msg,)+args, kwargs) # make the notice root level function known logging.notice = root_notice # add NOTICE to the priority map of all the levels logging.handlers.SysLogHandler.priority_map['NOTICE'] = 'notice' >From there you can create your new logger and do a myLog.notice('test notice message'). It works quite nicely, though its a lot of repeated code if you have to define several new levels. Thanks for your suggestion Kent. Will wait and see if I get a different response from comp.lang.python. Jay On 8/9/07, jay wrote: > > Kent, > > Thanks for the suggestion. If will look more into your suggestions, and > also shoot a post over to comp.lang.python. > > Jay > > On 8/9/07, Kent Johnson wrote: > > > > jay wrote: > > > Hello, > > > > > > I've been using the python logging module a lot lately, and I've come > > > across an instance where I need some new levels. Specifically, python > > > does not include ALERT and NOTICE in the default set of logging > > levels. > > > I am wondering how trivial it would be to extend the logging module to > > > > > include these 2 levels that are standard with syslog? > > > > > > My first test was just to use the addLevelName method to add the two > > new > > > levels, but syslog ignores them and logs at the next highest priority, > > > > > no matter what I use. > > > > > > Looking further into the code and as a test, I changed the following > > to > > > see if this would even work > > > > > > lib/python2.5/logging/__init__.py > > > -> class Logger > > > -> add new notice and alert root level functions > > > -> new _levelNames for notice and alert > > > -> new default level names for notice and alert > > > > You could do all this by patching the logging module at runtime: > > import logging > > logging.ALERT = 60 > > logging.addLevelName(logging.ALERT, 'ALERT') > > > > def Logger_alert(self, msg, *args, **kwargs): > > ... > > > > logging.Logger.alert = Logger_alert > > > > def alert(msg, *args, **kwargs): > > ... > > > > logging.alert = alert > > > > It's a little ugly but since you are just extending the module with new > > constants and functions it seems pretty safe and clean to me. It would > > be cool if addLevelName() did all this patching for you, it wouldn't be > > hard to do...maybe you want to propose a patch... > > > > > lib/python2.5/logging/handlers.py > > > -> class SysLogHandler priority_map was changed to include notice > > and > > > alert > > > > You can do this by subclassing SysLogHandler: > > > > class FixedSysLogHandler(SysLogHandler): > > priority_map = { ... } > > > > then configure logging to use FixedSysLogHandler instead of > > SysLogHandler. > > > > > > You might want to post about this on comp.lang.python , I think the > > author of the logging module will see it there. > > > > Kent > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070809/35e2244d/attachment.html From wescpy at gmail.com Thu Aug 9 21:22:40 2007 From: wescpy at gmail.com (wesley chun) Date: Thu, 9 Aug 2007 12:22:40 -0700 Subject: [Tutor] Bookpool sale on Addison Wesley In-Reply-To: <70dbc4d40708091158n52392c8fy3a3209a6ea48d25e@mail.gmail.com> References: <46BA4452.5000303@tds.net> <46BB13A8.5050608@nd.edu> <70dbc4d40708091158n52392c8fy3a3209a6ea48d25e@mail.gmail.com> Message-ID: <78b3a9580708091222k394f2812le2bbfee0050981b8@mail.gmail.com> On 8/9/07, taserian wrote: > I think it's intended to be a collegiate-level textbook, and not a > find-a-copy-at-your-local-bookstore type of book. Textbooks > are considerably more expensive. > > On 8/9/07, Sean Azelton wrote: > > Oh - I didn't mean Bookpool was too expensive - they are almost half > > the price of Amazon on this book. for clarification - I was wondering > > why the "Object-Oriented Programming in Python" book lists for $102.00 > > US when most books list for half that price. > > > On 8/9/07, Sean Azelton wrote: > > > Can anyone tell me why the below book is listed as SOOOO expensive? > > > > > > Object-Oriented Programming in Python > > > Michael H Goldwasser, David Letscher > > > List Price: $102.00 > > > Our Price: $55.95 > > > You Save: $46.05 (45% Off) welcome to the wonderful world of book publishing! :-) as tony has alluded to, yes, the reason why it's so much is because it's being sold as a college textbook -- remember how much your's were? the author royalties are generally higher, but your book can only be found in college and/or technical bookstores, and generally at very steep prices and low discounts, so a 45% discount is *fantabulous*!! it's probably because this book won't make it out on time for the current school year, so to get some adoption, you need to make it affordable enough for people to buy on their own, even if they *aren't* in college. hope this helps! -wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From kent37 at tds.net Thu Aug 9 21:26:26 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 09 Aug 2007 15:26:26 -0400 Subject: [Tutor] Extending logging module In-Reply-To: <7c25bb490708091205p21a39f0fqf337bd3f9b7f7b97@mail.gmail.com> References: <7c25bb490708090740t10b0e0d9rd00d6bd3f47d88cd@mail.gmail.com> <46BB2F88.3040008@tds.net> <7c25bb490708090906v703d1b9crb29a97cb3f862452@mail.gmail.com> <7c25bb490708091205p21a39f0fqf337bd3f9b7f7b97@mail.gmail.com> Message-ID: <46BB6A62.9080804@tds.net> jay wrote: > I have a working solution for this, based largely on what Kent posted. > Thought I would post it for others in case your either curious, or need > to do this in the future. There are probably other ways to do this. > > To add a new level NOTICE for logging to syslog > > # Change the default levels to include NOTICE in > # the proper order of priority > logging.FATAL = logging.CRITICAL = 60 > logging.ERROR = 50 > logging.WARN = logging.WARNING = 40 > logging.NOTICE = 30 > > # insert the levels with all the redefined values > # anything below NOTICE we don't have to add back in, its > # not getting redefined above with a new value > logging.addLevelName(logging.NOTICE , 'NOTICE') > logging.addLevelName(logging.WARNING, 'WARNING') > logging.addLevelName(logging.WARN, 'WARN') > logging.addLevelName(logging.ERROR, 'ERROR') > logging.addLevelName (logging.FATAL, 'FATAL') > logging.addLevelName(logging.CRITICAL, 'CRITICAL') Are you sure you have to move FATAL, ERROR and WARN? Did you try NOTICE = 25? Kent From bhaaluu at gmail.com Thu Aug 9 21:29:41 2007 From: bhaaluu at gmail.com (bhaaluu) Date: Thu, 9 Aug 2007 15:29:41 -0400 Subject: [Tutor] Bookpool sale on Addison Wesley In-Reply-To: <46BB13A8.5050608@nd.edu> References: <46BA4452.5000303@tds.net> <46BB13A8.5050608@nd.edu> Message-ID: Greetings, On 8/9/07, Sean Azelton wrote: > > Can anyone tell me why the below book is listed as SOOOO expensive? It might be a textbook? Textbooks are always expensive. > With the sale Kent mentioned, it looks like a great deal - but > unfortunately I don't really know anything about the authors. > > Object-Oriented Programming in Python > Michael H Goldwasser, David Letscher > Prentice Hall > List Price: $102.00 > Our Price: $55.95 > You Save: $46.05 (45% Off) > > Estimated Publication Date November 2007, 700 pages, ISBN 0136150314 It hasn't been published yet. Often, people review books before they are published, so look for a review of the book. > Is this a good buy? That's really hard to say until people have read it and reviewed it. The review by the book's publisher is usually prejudiced in favor of the book, as are the reviews by the author, his family, and friends. =) Unless you can get a complimentary 'review copy', and check it out for yourself (and write review for the rest of us), you won't know until people have had a chance to check it out. This may very well be a 2nd or subsequent edition, in which case, you may be able to find a review of a previous edition, and judge the book by those reviews. If it is a new edition, and you think $50 is too much to spend, check this site out: http://used.addall.com They list books from most of the used-book dealers (Alibris, Amazon, Abebooks, Biblio, Powells, etc.). I usually check Price Ascending to get the low prices. Caveat: when buying from used-book dealers, the lowest-price dealer isn't always the best deal! Check out their over-all track-record. Is this the 1st book they're selling, or the 12,000th? What kind of positive feedback rating do they have? Other than that (common-sense?) warning, *I* have had great success buying used-books from used-book dealers. > > Thanks, > > Sean Azelton > University of Notre Dame Often, a previous edition of a textbook can be found for less than half the cover price of the newest edition. If the new edition hasn't been completely reformated or otherwise changed, the previous edition will serve nicely. Often errata can be found for older editions. Happy Programming! -- bhaaluu at gmail dot com From kent37 at tds.net Thu Aug 9 21:40:21 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 09 Aug 2007 15:40:21 -0400 Subject: [Tutor] Extending logging module In-Reply-To: <7c25bb490708091205p21a39f0fqf337bd3f9b7f7b97@mail.gmail.com> References: <7c25bb490708090740t10b0e0d9rd00d6bd3f47d88cd@mail.gmail.com> <46BB2F88.3040008@tds.net> <7c25bb490708090906v703d1b9crb29a97cb3f862452@mail.gmail.com> <7c25bb490708091205p21a39f0fqf337bd3f9b7f7b97@mail.gmail.com> Message-ID: <46BB6DA5.6080308@tds.net> jay wrote: > I have a working solution for this, based largely on what Kent posted. > Thought I would post it for others in case your either curious, or need > to do this in the future. There are probably other ways to do this. > > It works quite nicely, though its a lot of repeated > code if you have to define several new levels. Here is a *completely untested off-the-top-of-my-head* rewrite for logging.addLevelName() that does this for you and saves having to repeat the function definitions. Maybe this could be used to create the standard logging functions too! def addLevelName(level, levelName): """ Associate 'levelName' with 'level'. This is used when converting levels to text during message formatting. """ import logging _acquireLock() try: #unlikely to cause an exception, but you never know... _levelNames[level] = levelName _levelNames[levelName] = level lowerName = levelName.lower() # define a new Logger function for the new level # this is like existing info, critical, debug...etc def Logger_func(self, msg, *args, **kwargs): if self.manager.disable >= level: return if level >= self.getEffectiveLevel(): self._log(level, msg, args, **kwargs) # Add the new function to the Logger class setattr(logging.Logger, lowerName, Logger_func) # define a new root level logging function # this is like existing info, critical, debug...etc def root_func(msg, *args, **kwargs): if len(root.handlers) == 0: basicConfig() Logger_func(root, (msg,)+args, kwargs) # make the root level function known setattr(logging, lowerName, root_func) finally: _releaseLock() Kent From sazelton at nd.edu Thu Aug 9 21:49:10 2007 From: sazelton at nd.edu (Sean Azelton) Date: Thu, 9 Aug 2007 15:49:10 -0400 Subject: [Tutor] Bookpool sale on Addison Wesley In-Reply-To: <78b3a9580708091222k394f2812le2bbfee0050981b8@mail.gmail.com> References: <46BA4452.5000303@tds.net> <46BB13A8.5050608@nd.edu> <70dbc4d40708091158n52392c8fy3a3209a6ea48d25e@mail.gmail.com> <78b3a9580708091222k394f2812le2bbfee0050981b8@mail.gmail.com> Message-ID: Yes - collegiate text book does make sense. I certainly do remember how expensive mine were! For my part I think I'll stick with your book Wesley, and Mark Lutz's book (since I already have that one). Thanks! Sean On 8/9/07, wesley chun wrote: > On 8/9/07, taserian wrote: > > I think it's intended to be a collegiate-level textbook, and not a > > find-a-copy-at-your-local-bookstore type of book. Textbooks > > are considerably more expensive. > > > > On 8/9/07, Sean Azelton wrote: > > > Oh - I didn't mean Bookpool was too expensive - they are almost half > > > the price of Amazon on this book. for clarification - I was wondering > > > why the "Object-Oriented Programming in Python" book lists for $102.00 > > > US when most books list for half that price. > > > > > On 8/9/07, Sean Azelton wrote: > > > > Can anyone tell me why the below book is listed as SOOOO expensive? > > > > > > > > Object-Oriented Programming in Python > > > > Michael H Goldwasser, David Letscher > > > > List Price: $102.00 > > > > Our Price: $55.95 > > > > You Save: $46.05 (45% Off) > > > welcome to the wonderful world of book publishing! :-) as tony has > alluded to, yes, the reason why it's so much is because it's being > sold as a college textbook -- remember how much your's were? the > author royalties are generally higher, but your book can only be found > in college and/or technical bookstores, and generally at very steep > prices and low discounts, so a 45% discount is *fantabulous*!! it's > probably because this book won't make it out on time for the current > school year, so to get some adoption, you need to make it affordable > enough for people to buy on their own, even if they *aren't* in > college. > > hope this helps! > -wesley > - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - > "Core Python Programming", Prentice Hall, (c)2007,2001 > http://corepython.com > > wesley.j.chun :: wescpy-at-gmail.com > python training and technical consulting > cyberweb.consulting : silicon valley, ca > http://cyberwebconsulting.com > From titleistfour at gmail.com Thu Aug 9 21:49:54 2007 From: titleistfour at gmail.com (jay) Date: Thu, 9 Aug 2007 14:49:54 -0500 Subject: [Tutor] Extending logging module In-Reply-To: <46BB6DA5.6080308@tds.net> References: <7c25bb490708090740t10b0e0d9rd00d6bd3f47d88cd@mail.gmail.com> <46BB2F88.3040008@tds.net> <7c25bb490708090906v703d1b9crb29a97cb3f862452@mail.gmail.com> <7c25bb490708091205p21a39f0fqf337bd3f9b7f7b97@mail.gmail.com> <46BB6DA5.6080308@tds.net> Message-ID: <7c25bb490708091249m14b57fbchb8b2ad77471ef3f8@mail.gmail.com> Nice! I will have to test this On 8/9/07, Kent Johnson wrote: > > jay wrote: > > I have a working solution for this, based largely on what Kent posted. > > Thought I would post it for others in case your either curious, or need > > to do this in the future. There are probably other ways to do this. > > > > It works quite nicely, though its a lot of repeated > > code if you have to define several new levels. > > Here is a *completely untested off-the-top-of-my-head* rewrite for > logging.addLevelName() that does this for you and saves having to repeat > the function definitions. Maybe this could be used to create the > standard logging functions too! > > def addLevelName(level, levelName): > """ > Associate 'levelName' with 'level'. > > This is used when converting levels to text during message > formatting. > """ > import logging > _acquireLock() > try: #unlikely to cause an exception, but you never know... > _levelNames[level] = levelName > _levelNames[levelName] = level > > lowerName = levelName.lower() > > # define a new Logger function for the new level > # this is like existing info, critical, debug...etc > def Logger_func(self, msg, *args, **kwargs): > if self.manager.disable >= level: > return > if level >= self.getEffectiveLevel(): > self._log(level, msg, args, **kwargs) > > # Add the new function to the Logger class > setattr(logging.Logger, lowerName, Logger_func) > > # define a new root level logging function > # this is like existing info, critical, debug...etc > def root_func(msg, *args, **kwargs): > if len(root.handlers) == 0: > basicConfig() > Logger_func(root, (msg,)+args, kwargs) > > # make the root level function known > setattr(logging, lowerName, root_func) > > finally: > _releaseLock() > > > Kent > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070809/aec0826b/attachment.htm From rdm at rcblue.com Thu Aug 9 21:51:33 2007 From: rdm at rcblue.com (Dick Moores) Date: Thu, 09 Aug 2007 12:51:33 -0700 Subject: [Tutor] WinPdb? Message-ID: <20070809195144.A046B1E400A@bag.python.org> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070809/ed761552/attachment.html From wescpy at gmail.com Thu Aug 9 22:11:44 2007 From: wescpy at gmail.com (wesley chun) Date: Thu, 9 Aug 2007 13:11:44 -0700 Subject: [Tutor] Bookpool sale on Addison Wesley In-Reply-To: References: <46BA4452.5000303@tds.net> <46BB13A8.5050608@nd.edu> <70dbc4d40708091158n52392c8fy3a3209a6ea48d25e@mail.gmail.com> <78b3a9580708091222k394f2812le2bbfee0050981b8@mail.gmail.com> Message-ID: <78b3a9580708091311y2c0f9887s24f0ab948af29850@mail.gmail.com> On 8/9/07, Sean Azelton wrote: > Yes - collegiate text book does make sense. I certainly do remember > how expensive mine were! > > For my part I think I'll stick with your book Wesley, and Mark Lutz's > book (since I already have that one). that's great! :-) of course, i should note that although the OOP chapter in Core Python is (as the lead tech reviewer put it) "huge" (120pp.), it's not a substitute for a book whose *entire focus* is OOP. anyway, i'm going to pick up a copy of it myself at some point and check it out to see if it's worth a hundred bucks. :-) cheers, -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From rabidpoobear at gmail.com Thu Aug 9 22:43:06 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Thu, 09 Aug 2007 15:43:06 -0500 Subject: [Tutor] WinPdb? In-Reply-To: <20070809195144.A046B1E400A@bag.python.org> References: <20070809195144.A046B1E400A@bag.python.org> Message-ID: <46BB7C5A.30103@gmail.com> Dick Moores wrote: > (I posted this to the python-list 24 hours ago, and didn't get a > single response. How about you guys?) You mean this list? Cause if you mean this list, then you didn't post it correctly. > > The only debugging I've done so far is to put in print statements > where I want to see what's happening. But it's often "through a glass > darkly". > > However, I just discovered that my excellent (IMO) Python editor, > Ulipad, comes with WinPdb, and I'm thinking it's about time I learned > how to use a debugger. > > But first, could I get some reviews here of WinPdb before I invest a > lot of time in learning it? I've found a couple links to tutorials on > the WinPdb website (< http://www.digitalpeers.com/pythondebugger/>, > where you'll also notice that version 1.2.0 came out August 6 (the > latest svn revision of Ulipad already has it: > (Ulipad's developer Limodou (who's > in Beijing), is /very /responsive). > > Thanks, > > Dick Moores > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From keridee at jayco.net Fri Aug 10 00:00:44 2007 From: keridee at jayco.net (Tiger12506) Date: Thu, 9 Aug 2007 17:00:44 -0500 Subject: [Tutor] WinPdb? References: <20070809195144.A046B1E400A@bag.python.org> <46BB7C5A.30103@gmail.com> Message-ID: <000601c7dad0$bfe7ca00$4bfce004@JSLAPTOP> > Dick Moores wrote: >> (I posted this to the python-list 24 hours ago, and didn't get a >> single response. How about you guys?) > You mean this list? Cause if you mean this list, then you didn't post > it correctly. I don't believe he did. There are seperate python-lists, comp.lang.python, one actually called python-list I believe, and besides, since he specifically said "How about you guys?" as in let's try someone else - I think he didn't mean this list. From kent37 at tds.net Thu Aug 9 23:05:00 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 09 Aug 2007 17:05:00 -0400 Subject: [Tutor] WinPdb? In-Reply-To: <20070809195144.A046B1E400A@bag.python.org> References: <20070809195144.A046B1E400A@bag.python.org> Message-ID: <46BB817C.5090002@tds.net> Dick Moores wrote: > However, I just discovered that my excellent (IMO) Python editor, > Ulipad, comes with WinPdb, and I'm thinking it's about time I learned > how to use a debugger. > > But first, could I get some reviews here of WinPdb before I invest a lot > of time in learning it? I've used WinPdb, it works as advertised, definitely handy for the times when print isn't enough. Kent From alan.gauld at btinternet.com Thu Aug 9 23:09:58 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 9 Aug 2007 22:09:58 +0100 Subject: [Tutor] Bookpool sale on Addison Wesley References: <46BA4452.5000303@tds.net> <46BB13A8.5050608@nd.edu> Message-ID: "Sean Azelton" wrote > Object-Oriented Programming in Python > Michael H Goldwasser, David Letscher > Prentice Hall > List Price: $102.00 cough! How much?!!!! > Our Price: $55.95 Still expensive but within the realms of reality. > Estimated Publication Date November 2007, 700 pages, ISBN 0136150314 > Is this a good buy? Doesn't look like it, but then I haven't read it. It just might be the greatest OOP/Python book ever written. But I doubt it. The Deitel books are similarly expensive($75) at list price but less than $50 at discount. The latter price is realistic, the list price silly. I think some publishers deliberately go for high list price and rely on people being suckered in by the huge discounts. Ignore the saving, ask: is the price I'm paying what I feel is right for what I'm getting? Alan G. From bob at pbsit.com Thu Aug 9 23:22:44 2007 From: bob at pbsit.com (Bob Larsen) Date: Thu, 9 Aug 2007 17:22:44 -0400 (EDT) Subject: [Tutor] httplib exceptions In-Reply-To: Message-ID: <18005115.1186694564132.JavaMail.tomcat@pbs11> Both Systems are Linux, In fact both are REd Hat Based, The Web Server is Fedora (I'm Not sure which version that particular server is running) and my workstation is running CentOS 5. I am sure that both are running an ext3 file system. Of Course there isn't a "file" there is just the web page stored in memory (possibly in swap, but I doubt it) The whole situation is most frustrating. Thanks for the Advice on the Regex code. Bob -- This message has been scanned for viruses and dangerous content by MailScanner, and is believed to be clean. From J.Randy.Pearson at comcast.net Thu Aug 9 23:03:37 2007 From: J.Randy.Pearson at comcast.net (Randy Pearson) Date: Thu, 9 Aug 2007 17:03:37 -0400 Subject: [Tutor] Bookpool sale on Addison Wesley In-Reply-To: <78b3a9580708091311y2c0f9887s24f0ab948af29850@mail.gmail.com> References: <46BA4452.5000303@tds.net> <46BB13A8.5050608@nd.edu><70dbc4d40708091158n52392c8fy3a3209a6ea48d25e@mail.gmail.com><78b3a9580708091222k394f2812le2bbfee0050981b8@mail.gmail.com> <78b3a9580708091311y2c0f9887s24f0ab948af29850@mail.gmail.com> Message-ID: <002301c7dac8$c29caa70$8495ced0@FJ1> Does this book fully integrate 2.4/2.5 language and module additions? The first Python book I read presented core elements from a list-tuple-dictionary perspective. Now that there are Sets, and an array module, I'm interested in a presentation that incorporates those. The help topics are fine, but not a substitute for learning when you would use the new tyles/modules. Thanks, -rp -----Original Message----- that's great! :-) of course, i should note that although the OOP chapter in Core Python is (as the lead tech reviewer put it) "huge" (120pp.), it's not a substitute for a book whose *entire focus* is OOP. anyway, i'm going to pick up a copy of it myself at some point and check it out to see if it's worth a hundred bucks. :-) cheers, -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From alan.gauld at btinternet.com Thu Aug 9 23:14:52 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 9 Aug 2007 22:14:52 +0100 Subject: [Tutor] Bookpool sale on Addison Wesley References: <46BA4452.5000303@tds.net> <46BB13A8.5050608@nd.edu> Message-ID: "bhaaluu" wrote > It might be a textbook? Textbooks are always expensive. You can tell I went to a Scottish university: most of my textbooks were under $20, some under $10... And anything over that was bought at the student's union thrift-stall, second hand! :-) Alan G. Scottish landlady to new lodger: "Jist tell me whit ye need laddie and I'll show ye how to dae withoot it...." From rdm at rcblue.com Fri Aug 10 00:10:21 2007 From: rdm at rcblue.com (Dick Moores) Date: Thu, 09 Aug 2007 15:10:21 -0700 Subject: [Tutor] WinPdb? In-Reply-To: <000601c7dad0$bfe7ca00$4bfce004@JSLAPTOP> References: <20070809195144.A046B1E400A@bag.python.org> <46BB7C5A.30103@gmail.com> <000601c7dad0$bfe7ca00$4bfce004@JSLAPTOP> Message-ID: <20070809221036.6DB641E409A@bag.python.org> At 03:00 PM 8/9/2007, you wrote: > > Dick Moores wrote: > >> (I posted this to the python-list 24 hours ago, and didn't get a > >> single response. How about you guys?) > > You mean this list? Cause if you mean this list, then you didn't post > > it correctly. > >I don't believe he did. There are seperate python-lists, comp.lang.python, >one actually called python-list I believe, and besides, since he >specifically said "How about you guys?" as in let's try someone else - I >think he didn't mean this list. Right. I meant the python list named "python-list" with the address python-list at python.org. ;) However, it should also have gone, as a matter of course, to the comp.lang.python newsgroup. I just checked and it's not there, even though more recent posts of mine in other threads ARE there. Dick From wescpy at gmail.com Fri Aug 10 00:53:41 2007 From: wescpy at gmail.com (wesley chun) Date: Thu, 9 Aug 2007 15:53:41 -0700 Subject: [Tutor] Bookpool sale on Addison Wesley In-Reply-To: <002301c7dac8$c29caa70$8495ced0@FJ1> References: <46BA4452.5000303@tds.net> <46BB13A8.5050608@nd.edu> <70dbc4d40708091158n52392c8fy3a3209a6ea48d25e@mail.gmail.com> <78b3a9580708091222k394f2812le2bbfee0050981b8@mail.gmail.com> <78b3a9580708091311y2c0f9887s24f0ab948af29850@mail.gmail.com> <002301c7dac8$c29caa70$8495ced0@FJ1> Message-ID: <78b3a9580708091553r1a0f435alafc34fc710f76ac6@mail.gmail.com> > Does this book fully integrate 2.4/2.5 language and module additions? yes, and even some minor stuff that's "guaranteed" to be in 2.6, i.e., as and with become keywords, the continued extinction of string exceptions, the continuing migration towards absolute and relative importing, etc. here is the PEP for the 2.6 release: http://www.python.org/dev/peps/pep-0361/ > The first Python book I read presented core elements from a > list-tuple-dictionary perspective. my approach is more from an object perspective. once you fully understand Python's treatment of objects, memory management, references, etc., then i compare/contrast all of the standard types and how they relate to one another, again, from that perspective, NOT: "Python has numbers, strings, lists, tuples, and dictionaries, and here is how to use them." the book's "manifesto" or philosophy is available at its website: http://corepython.com or my note on its page at Amazon: http://amazon.com/o/asin/0132269937 > Now that there are Sets, and an array > module, I'm interested in a presentation that incorporates those. The help > topics are fine, but not a substitute for learning when you would use the > new tyles/modules. sets are similar to dicts in that they are hashed types, so they are incorporated into the same chapter. likewise, strings, lists, and tuples are all sequences, so they get their own chapter. this applies to numbers too. and true to my word, all 3 of those come *after* the objects and memory management chapter(s). for further reading, here is the PEP for sets: http://www.python.org/dev/peps/pep-0218/ the array module contains specialized object types for numerical calculations. since most of the time, you will be using lists instead, i do reference that module but do not go in-depth as it is not a core part of the language. (folks coming from other languages may find this "demotion" of arrays more difficult to swallow, but that really isn't the case. both arrays and lists are sequence types, with the main difference that lists are heterogeneous. other than that, they work just like arrays from other languages, so that's what people tend to use, esp. since it is a standard type that you do not have import to use.) for more on the array module: http://www.python.org/doc/2.5/lib/module-array.html you can get a table of contents at any online book retailer, or even the publisher's website. you can even download a sample chapter and the index there too. links to retailers and the publisher, as well as reviews and other goodies are also available at the book's website. Note: bookpool is currently sold out. it happens quite regularly... i don't know how to tell them to order more to keep in stock! ;-) anyway, from what i've seen, it takes them about a week or two to get them in. it is also likely that this publisher's sale will last the entire month, but if you want the guarantee the price, you can just order it now and wait for them to ship it to you. i only know all this cuz i generally buy my books from bookpool too! hope this helps! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From alan.gauld at btinternet.com Fri Aug 10 01:31:28 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 10 Aug 2007 00:31:28 +0100 Subject: [Tutor] WinPdb? References: <20070809195144.A046B1E400A@bag.python.org> Message-ID: "Dick Moores" wrote > The only debugging I've done so far is to put in print statements > where I want to see what's happening. Thats OK for basic stuff but for complex things you can wind up with an awful lot of printing going on! > However, I just discovered that my excellent (IMO) Python editor, > Ulipad, comes with WinPdb, and I'm thinking it's about time > I learned how to use a debugger. Everyone should, they are wonderful tools provided you stay in control. > But first, could I get some reviews here of WinPdb Its very good, I think the one in eclipse/PyDev is slightly better but its close. Its certainly better than either IDLE or Pythonwin. The main thing in using debuggers is to avoid the temptation to just start the program and step all the way through. Learn to use a combination of break points - to target a suspect function or control structure and watches - the equivalent of your print statements. If the debugger supports conditional watches so much the better, then you only get output when the value goes to a particular condition. Once you've broken the flow at a suspect function and shown a known error via a watch set another break point at the next level up then rerun to there (conditional break points are great too but I don't think pdb does those...) only then do you need to start stepping line by line until you see the bug occur. At that point give up on the debugger and engage your brain! BTW If you can get a copy of my book (the paper one - a library mebbe?) there is a chapter in there about debugging which includes the use of raw pdb... HTH, Alan G From ricaraoz at gmail.com Thu Aug 9 18:52:02 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Thu, 09 Aug 2007 13:52:02 -0300 Subject: [Tutor] need futher explaining In-Reply-To: References: <747edb7f0708060013u5499492fue9da8eeaadefbfbf@mail.gmail.com> Message-ID: <46BB4632.3060208@bigfoot.com> bhaaluu wrote: > Greetings, > > I'm also a beginner to Python, but I think I can answer > your question. One of the best ways to learn about how > anything in Python works is to use the Python interactive > interpreter, so, away we go (follow along, please): > >>>> names = ['anne', 'beth', 'george', 'damon'] >>>> print names > ['anne', 'beth', 'george', 'damon'] >>>> print len(names) > 4 >>>> print names[0] > anne >>>> print names[3] > damon > > 1. names is a 'list' which contains four elements > 2. The elements in a list are indexed starting with zero (0) > 3. So the 'for' loop is iterating the length of the names list len(names) > which is the same as saying: for i in range(4): > > So len() isn't just for counting characters! It's count will depend > on what 'type' it is counting. In the above case, it is counting elements > in a 'list'. > >>>> print len(names[2]) > 6 > > names[2] is: g e o r g e > 6 characters. > Why? > >>>> print type(names[2]) > > > george is a string, so len() counts the characters in the string. > > I hope this is helpful. That aside. It would have been better style to write : for person, age in zip(names, ages): print person, 'is', age, 'years old' zip takes two lists and combines them in a list of tuples which you assign one by one to person and age in the for. I guess he does it the way it is because he hasn't come to explain zip() yet. HTH From J.Randy.Pearson at comcast.net Fri Aug 10 01:18:39 2007 From: J.Randy.Pearson at comcast.net (Randy Pearson) Date: Thu, 9 Aug 2007 19:18:39 -0400 Subject: [Tutor] Bookpool sale on Addison Wesley In-Reply-To: <78b3a9580708091553r1a0f435alafc34fc710f76ac6@mail.gmail.com> References: <46BA4452.5000303@tds.net> <46BB13A8.5050608@nd.edu> <70dbc4d40708091158n52392c8fy3a3209a6ea48d25e@mail.gmail.com> <78b3a9580708091222k394f2812le2bbfee0050981b8@mail.gmail.com> <78b3a9580708091311y2c0f9887s24f0ab948af29850@mail.gmail.com> <002301c7dac8$c29caa70$8495ced0@FJ1> <78b3a9580708091553r1a0f435alafc34fc710f76ac6@mail.gmail.com> Message-ID: <002401c7dadb$a5ad00a0$8495ced0@FJ1> Yes, helps very much in conveying your philosophy and approach. I have a decent OO background from a few other languages, and this your approach sounds very appealing. Consider the book ordered ! -- Randy -----Original Message----- >> hope this helps! >> -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From wescpy at gmail.com Fri Aug 10 09:44:45 2007 From: wescpy at gmail.com (wesley chun) Date: Fri, 10 Aug 2007 00:44:45 -0700 Subject: [Tutor] need futher explaining In-Reply-To: <747edb7f0708060013u5499492fue9da8eeaadefbfbf@mail.gmail.com> References: <747edb7f0708060013u5499492fue9da8eeaadefbfbf@mail.gmail.com> Message-ID: <78b3a9580708100044u4d38df51xf1a7d585adefb07b@mail.gmail.com> > names = ['anne', 'beth', 'george', 'damon'] > ages = [12, 45, 32, 102] > for i in range(len(names)): > print names[i], 'is', ages[i], 'years old' > > now all of it makes sense to me except for the line for i in range(len(names)): > the len statement calculates the number of characters hi, and welcome to python! first of all len() is built-in function and not a statement. the way you can tell is that if it has parentheses after it, i.e., "len()", then it is usually a function. a statement will not have that, i.e., print, if, for, etc. those are statements. minor semantics... anyway, len() can be used to find out how many things there are in an object. as you've pointed out, len() can be used to determine how many characters are in a string. but len() can also be used to find out how many objects are in a list, tuple, or dictionary (dict): >>> names = ['anne', 'beth', 'george', 'damon'] >>> len(names) 4 the example above is less clear to beginners because there is also the complication added due to the the call to the range() built-in function. range() works like this: >>> range(4) [0, 1, 2, 3] >>> range(2, 6) [2, 3, 4, 5] >>> range(2, 10, 2) [2, 4, 6, 8] with a single argument, range() will create a list of numbers from 0 up to but not including the number, as in range(4) above. with a pair of parameters, range() will create a list of numbers from the first number up to but not including the 2nd number, as in range(2, 6). finally, with 3 arguments, range() will create a list of numbers from the first number up to but not including the 2nd number, but skipping each time by the 3rd number, as in range(2, 10, 2). in the original example, len(names) is called first, which we saw results in 4. then that gets fed to range(), or effectively, range(4). so it's the same thing as having this for-loop: >>> for i in range(4): ... print names[i], 'is', ages[i], 'years old' ... does this code make more sense to you? hope so! kent also had a good idea in that there is a better way to pulling out the elements of two lists via the same index. there is *clearly* a relationship between the 1st name and the 1st age, as well as the 2nd name and 2nd age, etc. his idea is to create another list, but pairing the elements of each list that have a relationship to each other. that's what the zip() built-in function does... it takes 2 lists and "zips" them up like a zipper into a list of tuples: >>> zip(names, ages) [('anne', 12), ('beth', 45), ('george', 32), ('damon', 102)] now you can iterate over the name-age pairs together using his example. let's go back to the original example. why did the author use a strange syntax that would possibly confuse readers and new Python programmers? well, Python's for-loop is really built to iterate over sequences of items and is less of a counting one like it is in other languages such as C/C++, Java, and Perl. range() was created to make it act more like a counting loop. a long time ago, using range(len()) was the only way to loop through a sequence via its index instead of by element like "for name in names" (which is the typical way of iterating through a sequence). in this particular case, because the author wanted to get elements of 2 different lists at the same time, he had no choice but to go with the more confusing index route and range(len()). a 3rd way of doing the same thing became possible starting in Python 2.3, when the enumerate() function was added to the language. what i've shown you above are the two different ways to iterate through a sequence... either by element or by index. but there are times that you want *both*, and that's where enumerate() comes in. it is a special iterator that emits both an index and an element as it traverses the sequence/iterable: >>> for i, name in enumerate(names): ... print "person #%d's name is %s and they are %d years old." % (i, name, ages[i]) ... person #0's name is anne and they are 12 years old. person #1's name is beth and they are 45 years old. person #2's name is george and they are 32 years old. person #3's name is damon and they are 102 years old. for those of you who have Core Python, enumerate() is discussed in section 8.6 along with for-loops and range(). hope this helps! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From spmcinerney at hotmail.com Fri Aug 10 11:37:12 2007 From: spmcinerney at hotmail.com (Stephen McInerney) Date: Fri, 10 Aug 2007 02:37:12 -0700 Subject: [Tutor] Losing the expressiveness ofC'sfor-statement?/RESENDwith example In-Reply-To: Message-ID: Guys, I'm annoyed at how far offtopic and frankly rude the responses to my email were, and I'm just going to submit my doc change request to Fred Drake exactly as I was intending to before I sent the first mail. I didn't get much decent opinion on my central question: "isn't this idiom more restrictive than C/C++/Java (aka the rest of the universe), don't you agree it's badly explained in the doc (there is no basic advice to transform to while loop or else write generator), and the doc should have a simple change (add one or two lines with links is all that's needed)." I made it clear that my motivation was that this is badly explained and is a real hurdle to migration. Show any of the code we discussed to non-Python programmers and they'll be lost. Nobody attempted to address the valid follow-on question about generators returning a tuple (e.g. walking a pointer, and incrementing a count, let alone anything more complex) - quibbling the motivation for the quicksort example I gave was clearly offtopic; I'm very well aware there are better Python implementions, that's irrelevant; the motivation was to give a legitimate example which clearly arises commonly. - nowhere did I ask for "the language to be changed". I made it clear this was a question about how the *documentation* *describes* the Python approach (very badly describes). In any case, when we talk about people migrating from other languages, C/C++/Java is ~60-95% of the audience, COBOL is irrelevant and PL/I is ancient history. - This is offtopic, but the C for-loop syntax is very syntactically powerful, so when people perceive Python lacks it, they may baulk at that. We have to do a better job selling why Python is better. The C for-loop syntax itself is not error-prone at all. Unless you mean off-by-one errors etc., missing initializations, and those are mostly semantic not syntax-related. Anyway most of those can be caught by trivial linting and code reviews, and the rest by automated checkers. >The C syntax is extremely odd to most programmers who haven't been >trained in it but in more traditional languages like Lisp, Cobol, Fortran, >Pascal, ADA, etc. I couldn't disagree more strongly. Those were already dated in 1980 - almost everyone these days learns C/C++/Java(/C#) as their main programming language, unless they're mechanical engineers or accounting programmers. Look at TIOBE Index to confirm that. I am an EE who started out in the 80s with garbage like BASIC, Fortran, Pascal and assembly, but when I discovered C in 1992 I almost wept that the for-loop syntax was so simple yet infinitely powerful. >But C is a poor choice for more user centric problems. I never said otherwise, but the reality we're operating in is that the common languages in use will always lag the leading edge by ~15-30 years. So we should at least make very basic accomodations for that migration reality. Specifically, give the people a hint to use while-loops and generators. > > It's regrettable we have to choose between the clear and the > > efficient, in this situation. > >The most clear and efficient is probably: > >myList.sort() Alan - this was totally unnecessary and trashes the entire (legitimate) context of my question. Regards, Stephen >From: "Alan Gauld" >To: tutor at python.org >Subject: Re: [Tutor] Losing the expressiveness >ofC'sfor-statement?/RESENDwith example >Date: Tue, 7 Aug 2007 15:24:34 +0100 > >"Stephen McInerney" wrote > > > I don't deny the superiority of the underlying language design, > > I'm just pointing out the very real mindjolting effect of Python not > > supporting the universal syntax. > >An interesting term. The C syntax is extremely odd to most programmers >who haven't been trained in it but in more traditional languages like >Lisp, >Cobol, Fortran, Pascal, ADA, etc. It is also highly error prone and a >source of many bugs in C programs (I know I spent several years >running >a C maintenance project and for loop side-effects were right up there >with >uninitialised variables and memory leaks in the common error lists!). > > > Java is closer to C than Python is. > >True, Java deliberately set out to be a simple subset of C++ so it >has a similar syntax. Python is closer to Lisp than C is but nobody >would suggest that C should change its semantics to suit the tastes >of Lisp programmers who are converting. Languages are different and >learning the new idioms both positives and negatives) is part of the >process. > > > Don't you agree that the Python tutorial should say something simple > > and accessible to beginners like: "For all for-loop constructs where > > the > > iteration can't be written as a simple range object, > >In fact the range version of a for loop is only one style and probably >not the most common. You should iterate over a collection not a range >in most cases: > >ie > >someList = [1,2,3,4,5] > >for item in someList: > print item > >and never > >for index in range(len(somelist)): > print somelist[index] # bad bad bad! > >It is Pythons "foreach" effect that makes it so powerful. > > > I think the tutorial is lacking on this (should I email Fred Drake?) > >You could try it but that would imply that the tutorial should flag >up where Python varies from the syntax of COBOL too - after all there >are many more COBOL porogrammers than any other language! > >So explaining > >x = y + z > >we would need a note: > >Notice that Python uses a math symbol for addition instead >of the more common COBOL usage > >ADD Y, Z TO X > >And explain to Smalltalk, ADA and Pascal programmers that = is >assignment instead of := > >Where do you stop? > > > Instead of leaving C and Java people cold scratching their heads > > about > > why they think the language is hopelessly quirky and not > > (syntactically) > > fully-featured? > >A language is syntactically fully featured if it supports the 3 >elements >of structured programming (sequences, loops and branches) , or even >more starkly if it is Turing complete. No language should try to >encompass >all styntax structures of all languages (that way lies PL/1!) > > > One of our aims should be to write code which is at least > > understandable to > > programmers of other languages. > >Yes, but that doesn't mean a similar syntax, it means an easy >comprehension of the syntax as written. ie one that reads as much >as possible like a natural language - a test that C fails miserably! > > >>You don't give us any reason why you want to generate a set > >>of numbers from 30,000 down to zero decreasing by half each > >>time: 30,000, 15,000, 7500, 3750, etc > > > Yes I did: it occurs in a quicksort as we halve the stepsize each > > time, > > on an array of size 60000. > >OK so use Pythons built in sort method. It uses quick sort I believe. >But if it doesn't still use it and see if its fast enough. If it isn't >consider >refactoring your data structures to improve it. If that doesn't work >then, >as a last resort, consider writing your own sort function. When using >high level languages leverage the language. > > > Can you please give me your answer on this? We have to transform it > > to > > a while-loop? (or write a custom iterator?) > > It would nice to compare the most straightforward solution > > (while-loop?) > >The most straightforward solution is to use the standard sort >function. > > > the fastest solution, the last-memory solution and the most elegant > > solution. > >Yes it's almost certainly all of those. > > >>def half(n): > >> while int(n) > 0: > >> n = n/2 > >> yield n > >> > >>for x in half(300): print x, > > > > It's ok but it's visually clunky. while-loop wins for clarity. > >I disagree, the while lop is a distraction from what you are trying to >achieve, >which is use a specific list on numbers to performs some action, in >your >case a sort. The more you can hide the generation of the numbers the >clearer your code becomes. (PS I agree the name "half" is not great >but it was short in the interpreter! :-) > > > lambda would also be too quirky. > >lambda is no good here because Python's lambda only allows a >single expression not loops - I originally thought a lambda might >work. >(The limitations of Python's lambda are another copmmon complaint for >programmers moving from languages which better support functional >programming, but that still doesn't mean Python should change its >lambda to match) > > > I know the generator is more runtime-efficient. > >You know more than me in that case, I didn't even think about that, I >simply >tried to solve the problem. If run time efficiency is that critical >Python is probably >not the right language anyway - but only if you try it, and measure >it, and >know that run time efficiency is an issue. Python is not trying to get >you close to the machine, quite the opposite, its trying to get you >closer >to the problem you are trying to solve. C is designed to get you close >to >the machnie, that's why its the right choice for writing device >drivers etc. >But C is a poor choice for more user centric problems. > > > It's regrettable we have to choose between the clear and the > > efficient, in > > this situation. > >The most clear and efficient is probably: > >myList.sort() > >HTH, > >-- >Alan Gauld >Author of the Learn to Program web site >http://www.freenetpages.co.uk/hp/alan.gauld > > >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor _________________________________________________________________ More photos, more messages, more storage?get 2GB with Windows Live Hotmail. http://imagine-windowslive.com/hotmail/?locale=en-us&ocid=TXT_TAGHM_migration_HM_mini_2G_0507 From jaggojaggo at yahoo.com Fri Aug 10 11:54:44 2007 From: jaggojaggo at yahoo.com (Jaggo) Date: Fri, 10 Aug 2007 02:54:44 -0700 (PDT) Subject: [Tutor] Simple way to compare Two lists Message-ID: <771577.67258.qm@web52502.mail.re2.yahoo.com> Hello! I desperately need a simple way to compare whether any item of SmallList is in BigList. My current way, def IsAPartOfList(SmallList,BigList) for item in SmallList: if item in BigList: return True return False Takes up waay too much time to process. Can anyone think of any better way? Usually, SmallList is generated using range(Long, Long+ ~300) BigList is usually of a few hundreds of long numbers. The long numbers themselves represent date in seconds-since-the-epoch time. (E.G: time.time() is now in seconds-since-the-epoch, 1186739653.4679999 at the time of writing.) Thank you for your help, Omer Tabach. ---------------- Now playing: Haggard - Requiem in D-Minor posted with FoxyTunes --------------------------------- Looking for a deal? Find great prices on flights and hotels with Yahoo! FareChase. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070810/2a2f7453/attachment.html From rabidpoobear at gmail.com Fri Aug 10 12:35:27 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Fri, 10 Aug 2007 05:35:27 -0500 Subject: [Tutor] Losing the expressiveness ofC'sfor-statement?/RESENDwith example In-Reply-To: References: Message-ID: <46BC3F6F.1050900@gmail.com> Stephen McInerney wrote: > Guys, > > I'm annoyed at how far offtopic and frankly rude the responses to my > email were, > and I'm just going to submit my doc change request to Fred Drake > exactly as > I was intending to before I sent the first mail. I have found your e-mails to be far more rude than those of the other list members. > I didn't get much decent opinion on my central question: > "isn't this idiom more restrictive than C/C++/Java (aka the rest of > the universe), I'm pretty sure a lot of people use .NET, Ruby, PHP, Perl, and other languages, so I wouldn't say C/C++/Java is the 'universe.' A large part, though. Yes, it's more restrictive. Python's 'for' loop has a specific purpose of iterating over collections. This feels similar to saying "Isn't the fact that you don't have direct access to the pointers that variables are storing more restrictive than C++?" It restricts you from accessing the pointers, this is true. However, it doesn't restrict you from anything you actually need to do. Python's aiming for the most common use-case of a for loop to be the clearest syntactically. > don't you agree it's badly explained in the doc (there is no basic > advice to transform > to while loop or else write generator), and the doc should have a > simple change > (add one or two lines with links is all that's needed)." Which doc is this? I don't think this addition would be a line or two. It's not simply "translate all your C++ for loops to while loops." There are particular situations where for loops are desired, and some where while are, and this requires a fairly in-depth discussion. > I made it clear that my motivation was that this is badly explained > and is a real > hurdle to migration. Then perhaps you should have avoided statements like "This is much poorer than C/C++" and "this is one area where Python is (syntactically) inferior to C/C++/Java. " Them's fighting words. It was completely unnecessary to use such strong language. You're not writing a college essay. We're not going to slap you on the wrists if you say things like "in my opinion." Just because you didn't put "in my opinion" doesn't change the fact that it is your opinion, and the list members disagreed with you. So they discussed why your statements were faulty. If I said Your mother was a hamster and your father smelt of elderberries! How do I program hello, world! in Python? I'm pretty sure most of the focus of the ensuing discussion would fall upon whether your mother were, in fact, a rodent. > Show any of the code we discussed to non-Python > programmers and they'll be lost. Nobody attempted to address the valid > follow-on question about generators returning a tuple (e.g. walking a > pointer, > and incrementing a count, let alone anything more complex) > > - quibbling the motivation for the quicksort example I gave was > clearly offtopic; > I'm very well aware there are better Python implementions, that's > irrelevant; > the motivation was to give a legitimate example which clearly arises > commonly. I quite enjoyed the discussion. It was educational and it involved Python. It was in the spirit of the list, whether it followed your topic or not. Telling everyone off for discussing Python on a python tutor mailing list is not a good way to get the discussion back on track. You'll just get lots of e-mails like this one that, again, have no bearing on the original subject. > - nowhere did I ask for "the language to be changed". I made it clear > this > was a question about how the *documentation* *describes* the > Python approach (very badly describes). Again, these parenthetical criticisms are not doing you any good. They just piss people off. > In any case, when we talk about people migrating from other languages, > C/C++/Java is ~60-95% of the audience, COBOL is irrelevant and PL/I is > ancient history. > > - This is offtopic, but the C for-loop syntax is very syntactically > powerful, > so when people perceive Python lacks it, they may baulk at that. We > have to > do a better job selling why Python is better. The first time I used Python's for loop it was instantly clear that it was better to me. The same for all of my friends who I've introduced to Python. I think its ease of use speaks for itself and it's unnecessary to be preachy about it moreso than a simple explanation of the differences and the motivations behind the changes would be. > The C for-loop syntax itself is not error-prone at all. > Unless you mean off-by-one errors etc., missing initializations, and > those are mostly semantic not syntax-related. > Anyway most of those can be caught by trivial linting and code reviews, > and the rest by automated checkers. > > >> The C syntax is extremely odd to most programmers who haven't been >> trained in it but in more traditional languages like Lisp, Cobol, >> Fortran, Pascal, ADA, etc. > > I couldn't disagree more strongly. > Those were already dated in 1980 - almost everyone these days learns > C/C++/Java(/C#) > as their main programming language, unless they're mechanical > engineers or > accounting programmers. Look at TIOBE Index to confirm that. > > I am an EE who started out in the 80s with garbage like BASIC, > Fortran, Pascal and assembly, > but when I discovered C in 1992 I almost wept that the for-loop syntax > was so simple yet infinitely powerful. > >> But C is a poor choice for more user centric problems. > I never said otherwise, but the reality we're operating in is that the > common languages in use will always lag the leading edge by ~15-30 > years. So we should at least make very basic accomodations for that > migration reality. Specifically, give the people a hint to use > while-loops and generators. It seems like you have a pretty clear idea of what you want to be in the docs. So why don't you write it up and we'll critique it or something? Or did you want someone else to write it? >> > It's regrettable we have to choose between the clear and the >> > efficient, in this situation. >> >> The most clear and efficient is probably: >> >> myList.sort() > > Alan - this was totally unnecessary and trashes the entire > (legitimate) context of my question. Perhaps his reply was too succinct, but I felt it had a good point - for the common case when one just wants to sort a list, it's much easier to use the sort() method than to reimplement a sort. I understand your original example was just a case where a situation under discussion arose, and the sorting itself was irrelevant, but Alan's comment wasn't totally unnecessary. He's right, myList.sort() is much more clear and efficient. -Luke From tomfitzyuk at gmail.com Fri Aug 10 11:50:43 2007 From: tomfitzyuk at gmail.com (Tom Fitzhenry) Date: Fri, 10 Aug 2007 10:50:43 +0100 Subject: [Tutor] Simple way to compare Two lists In-Reply-To: <771577.67258.qm@web52502.mail.re2.yahoo.com> References: <771577.67258.qm@web52502.mail.re2.yahoo.com> Message-ID: <20070810095043.GA3582@desktop> On Fri, Aug 10, 2007 at 02:54:44AM -0700, Jaggo wrote: > Can anyone think of any better way? If SmallList and BigList are sorted (in order), there is a faster method: def IsAPartOfList(SmallList,BigList): for i in BigList: for j in SmallList: if i==j: return true if i>j: break return false (I'm not sure how encouraged using break statements are, so wait for a tutor to answer) If one list is already sorted but the other isn't, it may still be faster to sort the unsorted list then use the method above. If neither SmallList or BigList are sorted, it's probably best to use your original method, which I cannot improve. -- Tom Fitzhenry From alika at spray.se Fri Aug 10 13:23:35 2007 From: alika at spray.se (Ali Alhakim) Date: Fri, 10 Aug 2007 11:23:35 +0000 Subject: [Tutor] Extension problem Message-ID: <114389462915737@lycos-europe.com> Hello! I'm quiet new to Python and definitely a beginner in implementing Python extensions in C/C++. I've followed the structure given in the formal Python documentation to write the following code block: =========== //cmatmod.c #include static unsigned int eigenvect_calc(double *min_eps) { return 5; } static PyObject *cmat_eigv(PyObject *self, PyObject *args) { double *min_eps; unsigned int m; if(!PyArg_ParseTuple(args, "d", &min_eps)) return NULL; m=eigenvect_calc(min_eps); return Py_BuildValue("I", m); } static PyMethodDef cmat_methods[]= { { "eigenvect", cmat_eigv, METH_VARARGS, "Comment"},{NULL, NULL, 0, NULL} }; void initcmat(void) { (void) Py_InitModule("cmat", cmat_methods); } =========== I have succeeded to build and install this extension using disutils package in the setup.py file below: =========== from distutils.core import setup from distutils.extension import Extension setup(name='eigenvect', version='1.0', ext_modules=[Extension('cmat', ['cmatmod.c'])], ) ========== But when I try to call eigenvect(3.0) from Python I would receive a core dump: ========== 6 [main] python 2336 _cygtls::handle_exceptions: Error while dumping state (probably corrupted stack) Segmentation fault (core dumped) ========== My question is what is wrong with the extension code above? Is it something with reference counting? I don't know which method is suitable for debugging extension codes. I've tried gdb but I didn't understand the debug information: ========== (gdb) >>> eigenvect(4.0) Program received signal SIGSEGV, Segmentation fault. ---Type to continue, or q to quit--- 0x6abb248e in libpython2!PyEval_EvalFrameEx () from /usr/bin/libpython2.5dll (gdb) ========== /best regards Spray Webbhotell. Ingen startkostnad, 3 m?nader gratis och fri support. Perfekt f?r dig som ska starta en egen webbplats. http://www.spray.se/kampanj From Andy.cheesman at bristol.ac.uk Fri Aug 10 14:02:28 2007 From: Andy.cheesman at bristol.ac.uk (Andy Cheesman) Date: Fri, 10 Aug 2007 13:02:28 +0100 Subject: [Tutor] Simple way to compare Two lists In-Reply-To: <20070810095043.GA3582@desktop> References: <771577.67258.qm@web52502.mail.re2.yahoo.com> <20070810095043.GA3582@desktop> Message-ID: <46BC53D4.7040801@bristol.ac.uk> I think you could use sets, (I asked a similar question a few days ago re numpy arrays). ie Convert both list to sets use Set intersection convert answer to lists HTH Andy Tom Fitzhenry wrote: > On Fri, Aug 10, 2007 at 02:54:44AM -0700, Jaggo wrote: >> Can anyone think of any better way? > > If SmallList and BigList are sorted (in order), there is a faster method: > > def IsAPartOfList(SmallList,BigList): > for i in BigList: > for j in SmallList: > if i==j: > return true > if i>j: > break > return false > > (I'm not sure how encouraged using break statements are, so wait for a tutor to > answer) > > If one list is already sorted but the other isn't, it may still be faster to > sort the unsorted list then use the method above. > > If neither SmallList or BigList are sorted, it's probably best to use your > original method, which I cannot improve. > From kent37 at tds.net Fri Aug 10 14:07:39 2007 From: kent37 at tds.net (Kent Johnson) Date: Fri, 10 Aug 2007 08:07:39 -0400 Subject: [Tutor] Simple way to compare Two lists In-Reply-To: <771577.67258.qm@web52502.mail.re2.yahoo.com> References: <771577.67258.qm@web52502.mail.re2.yahoo.com> Message-ID: <46BC550B.6040306@tds.net> Jaggo wrote: > Hello! > > I desperately need a simple way to compare whether any item of SmallList > is in BigList. > > My current way, > > def IsAPartOfList(SmallList,BigList) > for item in SmallList: > if item in BigList: > return True > return False > > Takes up waay too much time to process. > Can anyone think of any better way? > > Usually, SmallList is generated using range(Long, Long+ ~300) > BigList is usually of a few hundreds of long numbers. Why not just check if if any item in BigList is in the range Long, Long+300? for item in BigList: if Long < item <= Long+300: return True return False which (in Python 2.5) can be shortened to return any(item in BigList if if Long < item <= Long+300) If you really have to make the list, you will do better with a set, especially if the set can be reused over multiple calls. bigSet = set(BigList) return any(item for item in SmallList if item in BigList) If speed is critical, you might see if it matters which list becomes the set and which is iterated. Kent From ms at cerenity.org Fri Aug 10 14:17:50 2007 From: ms at cerenity.org (Michael Sparks) Date: Fri, 10 Aug 2007 13:17:50 +0100 Subject: [Tutor] Simple way to compare Two lists In-Reply-To: <771577.67258.qm@web52502.mail.re2.yahoo.com> References: <771577.67258.qm@web52502.mail.re2.yahoo.com> Message-ID: <200708101317.50951.ms@cerenity.org> Hi, You're really asking about optimisation incidentally. On Friday 10 August 2007 10:54, Jaggo wrote: > Hello! > > I desperately need a simple way to compare whether any item of SmallList is > in BigList. A simple way: True in [x in BigList for x in SmallList] Not efficient necessarily, but it is a simple way. Sounds like you want a faster way. > My current way, > > def IsAPartOfList(SmallList,BigList) > for item in SmallList: > if item in BigList: > return True > return False This is directly equivalent to my approach above BUT I *expect* your approach will run faster. *Since you short circuit the result by returning true. > Takes up waay too much time to process. > Can anyone think of any better way? So what you're really after is a quicker way, yes? The problem you have here is worst case IsAPartOfList will run through all the elements of BigList a number of times (specifically len(SmallList). Sorting the two lists and then working through may be quicker, but I'm struck that the cost of sorting BigList itself may be more costly than you want given you say the above function you wrote (which is pretty efficient) is too slow. Two immediate thoughts - use psyco on the function. It's a simple enough function and psyco may be able to give you a dramatic speedup. Alternatively you could reverse your loop. Rather than do SmallList * BigList number of comparisons, if there are duplicates in BigList (rather than being a set), then you could iterate through BigList more efficiently. If I read your spec correctly, then the following holds true even though its the inverse of what you stated as the probem: def IsAPartOfList_2(SmallList,BigList) for item in BigList: if item in SmallList: return True return False Incidentally this simple reversal may in itself be quicker depending on your data. If the numbers are generated from (say) a list of events and you're correlating events, then you may find this quicker: def IsAPartOfList_3(SmallList,BigList) for item in reversed(BigList): if item in SmallList: return True return False Since that exploits domain knowledge about the two lists. This becomes especially likely if the lists are likely to be already sorted because they've come from some ordered source (eg a server log). Furthermore if BigList is a list of times all in ascending order, and SmallList is a list of times in ascending order, and the latter represents a list of "recent" events and BigList represents a list of all events, then you can make another optimsation to take advantage of that knowledge: def IsAPartOfList_4(SmallList,BigList) for item in reversed(BigList): if item in reversed(SmallList): return True return False Why? Consider the following two lists: BigList: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39] SmallList: [33, 34, 35, 36] Then IsAPartOfList_4 will make 13 comparisons before returning True. Whereas IsAPartOfList_2 will make 133 comparisons, and your original will make 34 comparisons. However, if you have duplicates in BigList, we can skip the "if item in SmallList" every time we have a duplicate: def IsAPartOfList(SmallList,BigList) seen = {} for item in BigList: if not seen.get(item, False): if item in SmallList: return True return False This will only give you a potential speedup IF two things hold: * BigList contains duplicates * seen.get(item, False) is quicker IF these things don't hold then you won't see any improvement. Personally I'd try using psyco on the function since then you leave the function looking clean and simple. Which is things is quickest will depend heavily on the likely structure of the data, likelihood of duplicate, ordering and likely similarities between data. Overall though you have two choices: * Exploit your knowledge of the distribution and ordering of values * Use psyco These aren't mutually exclusive options :-) Michael. From kent37 at tds.net Fri Aug 10 14:11:47 2007 From: kent37 at tds.net (Kent Johnson) Date: Fri, 10 Aug 2007 08:11:47 -0400 Subject: [Tutor] Simple way to compare Two lists In-Reply-To: <20070810095043.GA3582@desktop> References: <771577.67258.qm@web52502.mail.re2.yahoo.com> <20070810095043.GA3582@desktop> Message-ID: <46BC5603.9060703@tds.net> Tom Fitzhenry wrote: > On Fri, Aug 10, 2007 at 02:54:44AM -0700, Jaggo wrote: >> Can anyone think of any better way? > > If SmallList and BigList are sorted (in order), there is a faster method: > > def IsAPartOfList(SmallList,BigList): > for i in BigList: > for j in SmallList: > if i==j: > return true > if i>j: > break > return false > > (I'm not sure how encouraged using break statements are, so wait for a tutor to > answer) break is fine! If the list you are searching is sorted you can use the bisect module to do a binary search instead of the linear search above. > If one list is already sorted but the other isn't, it may still be faster to > sort the unsorted list then use the method above. I don't think BigList has to be sorted in the above algorithm. If both lists are sorted I suppose you could write it like a merge sort, walking along both lists looking for a match. Kent From kent37 at tds.net Fri Aug 10 14:34:11 2007 From: kent37 at tds.net (Kent Johnson) Date: Fri, 10 Aug 2007 08:34:11 -0400 Subject: [Tutor] Losing the expressiveness ofC'sfor-statement?/RESENDwith example In-Reply-To: References: Message-ID: <46BC5B43.5080109@tds.net> Stephen McInerney wrote: > Guys, > > I'm annoyed at how far offtopic If you get annoyed at threads drifting off-topic you'd better stay away from all public mailing lists! > and frankly rude the responses to my > email were, Re-reading the entire thread I don't see anything I would construe as rude. I think you need to lighten up a bit. > I didn't get much decent opinion on my central question: > "isn't this idiom more restrictive than C/C++/Java (aka the rest of the > universe), You got considerable disagreement, it seems to me. Most of the posts are either explicitly disagreeing or trying to point you to the Python way of doing things. > Nobody attempted to address the valid > follow-on question about generators returning a tuple (e.g. walking a > pointer, > and incrementing a count, let alone anything more complex) I don't see any question about generators and tuples. Maybe you should start a new thread about that, it's pretty off-topic for this one ;) > - quibbling the motivation for the quicksort example I gave was clearly > offtopic; > I'm very well aware there are better Python implementions, that's > irrelevant; > the motivation was to give a legitimate example which clearly arises > commonly. Wait. You say it is a "legitimate example that occurs commonly" but we are not allowed to talk about other ways to do it? You actually seem to have two items on your agenda - convincing us that for loops in C are more powerful than in Python, and that Python is lacking - changing the docs to reflect this We don't buy the first item so the second one doesn't get much traction. > - This is offtopic, Uh oh! > but the C for-loop syntax is very syntactically > powerful, > so when people perceive Python lacks it, they may baulk at that. We have to > do a better job selling why Python is better. > The C for-loop syntax itself is not error-prone at all. > Unless you mean off-by-one errors etc., missing initializations, and > those are mostly semantic not syntax-related. Yeah other than that it isn't error-prone at all. >> > It's regrettable we have to choose between the clear and the >> > efficient, in this situation. >> >> The most clear and efficient is probably: >> >> myList.sort() > > Alan - this was totally unnecessary and trashes the entire (legitimate) > context of my question. The point is that Python has efficient ways to do many common operations that may be different from the way you expect. Kent From jsmith at medplus.com Fri Aug 10 16:07:31 2007 From: jsmith at medplus.com (Smith, Jeff) Date: Fri, 10 Aug 2007 10:07:31 -0400 Subject: [Tutor] Losing the expressiveness ofC'sfor-statement?/RESENDwith example In-Reply-To: <46BC5B43.5080109@tds.net> References: <46BC5B43.5080109@tds.net> Message-ID: <288A3B43F7B2224D9C8441C9FC5D6A02021C2315@EXCHMAIL01.corp.medplus.com> From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Kent Johnson Stephen McInerney wrote: >> The C for-loop syntax itself is not error-prone at all. >> Unless you mean off-by-one errors etc., missing initializations, and >> those are mostly semantic not syntax-related. > Yeah other than that it isn't error-prone at all. This distinction is, unfortunately, lost on most programmers. When there is a bug in the code that needs to be tracked down and resolved, it doesn't really matter much whether it is the fault of the compiler, or the language sytnax which drives a programmer to make mistakes. Quibbling about this doesn't make these errors magically disappear. IMHO, a language being syntactically error prone is far worse since there's no way for the vendor to "fix" that one! Jeff P.S. This should in no way be construed as undercutting my belief that Python should have a case statement, a ternary operator, and full-fledged lambdas...sometimes the risk of syntactic errors is overcome by a construct's logically expressive usefulness...but that's grist for another mill :-) From kent37 at tds.net Fri Aug 10 16:23:02 2007 From: kent37 at tds.net (Kent Johnson) Date: Fri, 10 Aug 2007 10:23:02 -0400 Subject: [Tutor] Losing the expressiveness ofC'sfor-statement?/RESENDwith example In-Reply-To: <288A3B43F7B2224D9C8441C9FC5D6A02021C2315@EXCHMAIL01.corp.medplus.com> References: <46BC5B43.5080109@tds.net> <288A3B43F7B2224D9C8441C9FC5D6A02021C2315@EXCHMAIL01.corp.medplus.com> Message-ID: <46BC74C6.3000906@tds.net> Smith, Jeff wrote: > P.S. This should in no way be construed as undercutting my belief that > Python should have a case statement, a ternary operator, and > full-fledged lambdas Python 2.5 does have conditional expressions that do the work of a ternary operator: x = y if z else w http://docs.python.org/whatsnew/pep-308.html Kent From jsmith at medplus.com Fri Aug 10 16:26:22 2007 From: jsmith at medplus.com (Smith, Jeff) Date: Fri, 10 Aug 2007 10:26:22 -0400 Subject: [Tutor] Losing the expressiveness ofC'sfor-statement?/RESENDwith example In-Reply-To: <46BC74C6.3000906@tds.net> References: <46BC5B43.5080109@tds.net> <288A3B43F7B2224D9C8441C9FC5D6A02021C2315@EXCHMAIL01.corp.medplus.com> <46BC74C6.3000906@tds.net> Message-ID: <288A3B43F7B2224D9C8441C9FC5D6A02021C235B@EXCHMAIL01.corp.medplus.com> Thank you for reminding me of that! I've just started with 2.5 but that one had slipped my memory and I've still been using X = (z and [y] or [w])[0] Thank! Jeff -----Original Message----- From: Kent Johnson [mailto:kent37 at tds.net] Sent: Friday, August 10, 2007 10:23 AM To: Smith, Jeff Cc: tutor at python.org Subject: Re: [Tutor] Losing the expressiveness ofC'sfor-statement?/RESENDwith example Smith, Jeff wrote: > P.S. This should in no way be construed as undercutting my belief that > Python should have a case statement, a ternary operator, and > full-fledged lambdas Python 2.5 does have conditional expressions that do the work of a ternary operator: x = y if z else w http://docs.python.org/whatsnew/pep-308.html Kent From jsmith at medplus.com Fri Aug 10 16:31:21 2007 From: jsmith at medplus.com (Smith, Jeff) Date: Fri, 10 Aug 2007 10:31:21 -0400 Subject: [Tutor] Losing the expressivenessofC'sfor-statement?/RESENDwith example In-Reply-To: References: Message-ID: <288A3B43F7B2224D9C8441C9FC5D6A02021C236A@EXCHMAIL01.corp.medplus.com> From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Stephen McInerney > I didn't get much decent opinion on my central question: > "isn't this idiom more restrictive than C/C++/Java (aka the rest of the universe)," I thought you got plenty of decent opinion and most of was disagreement. And, frankly, this underlies your lack of knowledge about the universe. And I'm not saying that to be rude. While those three languages may be near the top for something like the TIOBE TCP index, even they admit that it is "based on the world-wide availability of skilled engineers, courses, and third party vendors. This availability is determined by using the Google and Yahoo! search engines to calculate the ratings." This is not a very good way to determine real world use although it is probably instructive if you are starting a new project and are looking for some direction as to choice of language. It says nothing, however about the number of programmers actually using a language. This list would almost certainly include COBOL and Visual Basic (which is actually #3 on the TCP as well). > quibbling the motivation for the quicksort example I gave was clearly offtopic; I'm very well aware there are > better Python implementions, that's irrelevant; the motivation was to give a legitimate example which clearly > arises commonly. Maybe that's because many of us don't feel that it was an example that arises commonly. Once you become experienced OO language programming and start to think in OO constructs, which Python is very good at facilitating, that type of usage virtually disappears. > In any case, when we talk about people migrating from other languages, C/C++/Java is ~60-95% of the audience, > COBOL is irrelevant and PL/I is ancient history. Actually, since COBOL and PL/I are both ancient history with tons of legacy code in service, they are the classic target for migration. I'll admit I was amused by the figure of 60-95%...what's the error bar on that :-) >>The C syntax is extremely odd to most programmers who haven't been >>trained in it but in more traditional languages like Lisp, Cobol, >>Fortran, Pascal, ADA, etc. > I couldn't disagree more strongly. > Those were already dated in 1980 - almost everyone these days learns C/C++/Java(/C#) > as their main programming language, unless they're mechanical engineers or accounting programmers. Look at TIOBE > Index to confirm that. They may have been dated but they were still in heavy use. At many engineering schools and research labs FORTRAN was still be widely taught well into the 90's and is still in fair use today. And the TCP doesn't give a breakdown by job category. And since it's based on Google and Yahoo searches, I'm not sure of its general usefulness anyway. >>myList.sort() >Alan - this was totally unnecessary and trashes the entire (legitimate) context of my question. Why? It most certainly isn't...it speaks directly to your contention that implementing a quicksort is a common task nowadays... Jeff From ms at cerenity.org Fri Aug 10 19:55:08 2007 From: ms at cerenity.org (Michael Sparks) Date: Fri, 10 Aug 2007 18:55:08 +0100 Subject: [Tutor] =?iso-8859-1?q?Losing_the_expressiveness=09ofC=27sfor-sta?= =?iso-8859-1?q?tement=3F/RESENDwith_example?= In-Reply-To: <288A3B43F7B2224D9C8441C9FC5D6A02021C2315@EXCHMAIL01.corp.medplus.com> References: <46BC5B43.5080109@tds.net> <288A3B43F7B2224D9C8441C9FC5D6A02021C2315@EXCHMAIL01.corp.medplus.com> Message-ID: <200708101855.09079.ms@cerenity.org> Stephen, I've come into this thread late, but it looks like you're lamenting the fact you can stipulate complex iterations on a single line, which can be nice. I'd not really missed this in several years of programming with python. However, Your post is interesting because it raises a point I've personally not considered before. Your example loops are: for (node=start; valuenext) { ... } for (i=30000; i>0; i=i/2) { ... } The argument you got back is that this is just syntactic sugar for logic along the lines of: node=start; while valuenext Which of course is true. However simply saying that does miss the fact that it is syntactic sugar with a purpose. Syntactic sugar is generally added for one of two reasons - speed of coding, or clarity of coding. In this case it can be argued it does both, since it spells out the iterator algorithm clearly on a single line. Specifically you can look at one line and see the loop logic. This is nowhere near as clear with this form: node=start; while valuenext And its certainly not on one line. If you still want to spell out the iteration in one location, then you're right you do have to use a generator. However the fact that you can put a def anyway means you can do this: start = getNodesFromSomewhere() def traverseNodes(start): node = start yield node while node.next: node = node.next yield node for node in traverseNodes(start): ... Similarly you can do this: def bisectdown(i=30000): while i >0: yield i i = i/2 for node in bisectdown(30000): ... That said, I agree that its not as nice perhaps as C's compact one liner for each of these. HOWEVER, you can rebuild C's version: (or something close) import compiler def cfor(iter_name, args,locals): Y=[x.strip().rstrip() for x in args.split(";")] Y[0] = compiler.compile(Y[0], "__main__.py", "exec") Y[1] = compiler.compile(Y[1], "__main__.py", "eval") Y[2] = compiler.compile(Y[2], "__main__.py", "exec") Y.append( compiler.compile(iter_name, "__main__.py", "eval")) exec(Y[0],locals,locals) while eval(Y[1],locals,locals): yield eval(Y[3],locals,locals) exec(Y[2],locals,locals) You can then use this as follows: max = 10 for i in cfor("i", "i=30000; i>max; i=i/2",locals()): print i And also: start = getNodesFromSomewhere() for node in cfor("n", "n=start; n.next is not None; n = node.next", locals()): ... That's potentially quite useful. Yes there's a little cruft there (locals()), but its not hideously inefficient either because I've made sure we compile the code fragments and run those. Personally I think its not a huge loss, but if you do, then you can always reuse this cfor iterator if you like. I disagree though regarding the idea that C's for syntax is a universal syntax. It isn't. It's a commonly understood syntax due to C derived languages (C/C++/Java), but far from universal. I've had to learn many different "for" syntaxes over many years for different languages. Even then where a C-type loop is availabe, it isn't always idiomatic to use it. For example perl (which does have a C-type for loop) idiomatically uses foreach extensively. And you also get *very* different iterative behaviour in ruby. Different languages have different concepts. Just because you can write one language like another doesn't mean you should. That said, given that maxim, it sounds like your beef with more with docs rather than the lack of the construct, asking "is this a problem normally", to which the answer is most definitely not, "what do people normally do", to which you have numerous replies - people either create an iterator (as you often would in C++ and Java) or use a while loop. As for rudeness, bear in mind that text is a naturally harsh medium, and also cultural norms are very different for different posters. One man's polite behaviour is another man's gravest insult. No one means to be rude, so it's worth remembering that. (And yes, I know, merely saying that can be considered rude in itself in some cultures :-) You found people rude, they found you rude. None of you intended to be, and probably weren't from your own perspectives, that's what really matters. Michael. From alan.gauld at btinternet.com Fri Aug 10 20:51:22 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 10 Aug 2007 19:51:22 +0100 Subject: [Tutor] Losing theexpressiveness ofC'sfor-statement?/RESENDwith example References: <46BC5B43.5080109@tds.net> <288A3B43F7B2224D9C8441C9FC5D6A02021C2315@EXCHMAIL01.corp.medplus.com> Message-ID: "Smith, Jeff" wrote > Python should have a case statement, I don;t care about that one, but we do ave the even less useful(IMHO) with statement so don't give up hope! > a ternary operator, Well you have that now in 2.5 I believe. > full-fledged lambdas... I'm with you there but I've been waiting long enough to have given up. In fact I think we are more likely to lose lambdas altogether than see an improved version! Alan G From adam.jtm30 at gmail.com Fri Aug 10 21:21:58 2007 From: adam.jtm30 at gmail.com (Adam Bark) Date: Fri, 10 Aug 2007 20:21:58 +0100 Subject: [Tutor] Losing theexpressiveness ofC'sfor-statement?/RESENDwith example In-Reply-To: References: <46BC5B43.5080109@tds.net> <288A3B43F7B2224D9C8441C9FC5D6A02021C2315@EXCHMAIL01.corp.medplus.com> Message-ID: On 10/08/07, Alan Gauld wrote: > > full-fledged lambdas... > > I'm with you there but I've been waiting long enough to have > given up. In fact I think we are more likely to lose lambdas > altogether than see an improved version! Guido said he's keeping lambdas in Python 3000, I think pretty much as is http://www.artima.com/weblogs/viewpost.jsp?thread=208549 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070810/aba7b3e5/attachment.html From handel.d at gmail.com Fri Aug 10 21:25:49 2007 From: handel.d at gmail.com (David Handel) Date: Fri, 10 Aug 2007 15:25:49 -0400 Subject: [Tutor] Installation of Django on Mac Tiger Message-ID: <724354bd0708101225g4d6f146bh795db20e0375bffb@mail.gmail.com> Hi. I'm not a real programmer/low level Unix guy yet. I realize that this is not a Django forum per se. But, I don't know where else to turn before giving up. Can anyone help me install Django on my Mac? I have tried all sorts of approaches outlnied on various blogs and have Django on my MacBook Pro but I think that I have simply failed to get Python to see the Django module. Thanks, David Handel -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070810/839ff9a5/attachment.htm From kent37 at tds.net Fri Aug 10 21:44:21 2007 From: kent37 at tds.net (Kent Johnson) Date: Fri, 10 Aug 2007 15:44:21 -0400 Subject: [Tutor] Installation of Django on Mac Tiger In-Reply-To: <724354bd0708101225g4d6f146bh795db20e0375bffb@mail.gmail.com> References: <724354bd0708101225g4d6f146bh795db20e0375bffb@mail.gmail.com> Message-ID: <46BCC015.3010306@tds.net> David Handel wrote: > Hi. I'm not a real programmer/low level Unix guy yet. I realize that > this is not a Django forum per se. But, I don't know where else to turn > before giving up. > > Can anyone help me install Django on my Mac? I have tried all sorts of > approaches outlnied on various blogs and have Django on my MacBook Pro > but I think that I have simply failed to get Python to see the Django > module. It sounds like you don't have Django in the Python search path. Here is one way: Download the 0.96 release and unpack it. Open a command line to the Django-0.96 directory and run > python setup.py install Kent From keridee at jayco.net Fri Aug 10 23:02:15 2007 From: keridee at jayco.net (Tiger12506) Date: Fri, 10 Aug 2007 16:02:15 -0500 Subject: [Tutor] Losing the expressivenessofC'sfor-statement?/RESENDwith example References: Message-ID: <00ae01c7db91$c0b114c0$dffce004@JSLAPTOP> It seems this is a delightful exchange of rude threats and insults. ;-) My question is: If you love C syntax so much, why don't you program in C and leave us python people alone? And also: It is not the responsibility of the docs to ease the way for C programmers. That is what a specific tutorial is for. The docs are there for the sole purpose of teaching you how to program in python. That is - how you *think* in python. The reason for loops are not the same in python as they are in C is because they are not the same language. You are supposed to write things differently in python than in C (because they are different languages), and the fact that you don't seem capable of doing that tells me that *you* sir are inferior, not python's for. I certainly would not expect to go to Spain, tell them their language is inferior, and then ask them to make concessions for English speakers. JS From jsmith at medplus.com Fri Aug 10 22:13:20 2007 From: jsmith at medplus.com (Smith, Jeff) Date: Fri, 10 Aug 2007 16:13:20 -0400 Subject: [Tutor] Losing the expressivenessofC'sfor-statement?/RESENDwithexample In-Reply-To: <00ae01c7db91$c0b114c0$dffce004@JSLAPTOP> References: <00ae01c7db91$c0b114c0$dffce004@JSLAPTOP> Message-ID: <288A3B43F7B2224D9C8441C9FC5D6A020221B191@EXCHMAIL01.corp.medplus.com> That's a good point. He keeps indicating that the tutorial should make reference to C/C++/Java syntax specifically because that's what the rest of the known universe uses. To carry your example one step farther, it's like expecting a grade school Spanish text to have pointers for English speakers because that's what the rest of the known universe speaks. Not only is the claim itself specious, but if the target audience for the book is children learning Spanish, it would make things worse, not better, by only managing to confuse them with something they don't understand. If that's the case, we should have pointers in our English books in Mandarin, which, I believe, really is the most spoken language. I'm sure his local school board would by his argument :-) Jeff -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Tiger12506 Sent: Friday, August 10, 2007 5:02 PM To: tutor at python.org Subject: Re: [Tutor] Losing the expressivenessofC'sfor-statement?/RESENDwithexample It seems this is a delightful exchange of rude threats and insults. ;-) My question is: If you love C syntax so much, why don't you program in C and leave us python people alone? And also: It is not the responsibility of the docs to ease the way for C programmers. That is what a specific tutorial is for. The docs are there for the sole purpose of teaching you how to program in python. That is - how you *think* in python. The reason for loops are not the same in python as they are in C is because they are not the same language. You are supposed to write things differently in python than in C (because they are different languages), and the fact that you don't seem capable of doing that tells me that *you* sir are inferior, not python's for. I certainly would not expect to go to Spain, tell them their language is inferior, and then ask them to make concessions for English speakers. JS _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From alan.gauld at btinternet.com Sat Aug 11 03:12:18 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 11 Aug 2007 02:12:18 +0100 Subject: [Tutor] Losing the expressivenessofC'sfor-statement?/RESENDwith example References: Message-ID: "Stephen McInerney" wrote > I'm annoyed at how far offtopic and frankly rude the responses Don;t get annoyed at off topic posts, that's all part of the fun in a group like this which is aimed at teaching novices how to program and specifically how to program in Python. The wider issues are all part of the training. As to rudeness, this is a very polite group by most internet standards, but if anything I wrote upset you I apologise, it wasn't my intention. > I'm just going to submit my doc change request to Fred Drake > exactly as I was intending to before I sent the first mail. That's fine and Fred may well incorporate it. Personally I believe that would be a mistake as it sets a bad precedent. It may even encourage C programmers to try to convert their C coding style into Python, and that would be a big mistake - both for the individuals concerned and for the Python community. > I didn't get much decent opinion on my central question: You got a lot of very good opinion, namely that you are comparing apples and oranges. C's for loop is syntactic sugar for a while loop. Python's for loop is a foreach construct for iterating over a collection. Very different things, and impossible to compare sensibly. > "isn't this idiom more restrictive than C/C++/Java (aka the > rest of the universe), But your central premis that C/C++/Java form the "rest of the universe" is just plain wrong. There are many, many other languages in day to day use. Infoweek and Computing magazines regularly run surveys of their readers which show COBOL to be the most widely practiced language today (as indeed it has been for the last 30 years!) - looking at job ads doesn't take account of the fact that most COBOL jobs are with big corporations and are often jobs for life! I know several of our (5000 or so) in-house COBOL jockeys who have over 30 years service...) > don't you agree it's badly explained in the doc (there is no basic > advice to transform to while loop or else write generator), and the > doc > should have a simple change The docs explain how the python for loop works pretty well I think. They do not explain the differences between Python's for loop and C's for loop any more than they explain the differences between Pythons lambda and Lisp's version. Whether the docs should do that is a moot point that the maintainer (Fred) can decide. > Show any of the code we discussed to non-Python programmers > and they'll be lost. That I doubt, most of it was generic apart from the generator 'yield' construct. And anyone used to generators - Lisp, Ruby, Smalltalk programmers would all guess at its function pretty well intuitively. > follow-on question about generators returning a tuple > (e.g. walking a pointer, and incrementing a count, let alone > anything more complex) Sorry, I missed it. Can you ask again in a separate thread and we can take a look at it. > - quibbling the motivation for the quicksort example I gave was > clearly offtopic; No, it was an example of how, by considering the actual purpose of the code we can usually find a completely different solution to any such problem. There are very few scenarios that actually require that kind of low level algorithmic access in Python - algorithm design being one valid example! > the motivation was to give a legitimate example which clearly arises > commonly. And my point was that in Python it doesn't arise very commonly at all. There is nearly always an alternative style of solution, often avoiding for loops entirely. > In any case, when we talk about people migrating from other > languages, > C/C++/Java is ~60-95% of the audience, COBOL is irrelevant Going by the posts we see on this list the majority of the folks coming to python come from other scripting languages: PHP, Perl, Visual Basic or from shell scripting (DOS Batch, VMS DCL or Unix shell) or from other high level languages like Rebol, Mathematica or Lisp. There are also many first timers since python is fast becoming the teaching language of choice in colleges and schools. We very rarely get questions from C/C++ programmers and only a few from Java. We have had at least one COBOL programmer but I agree they aren't that common - mostly they are still hacking away in COBOL! Where they might come from is using Python as a replacement for their JCL scripts, and we have had a couple of those at least... > and PL/I is ancient history. But we can learn from history and the lesson of PL/1 was - don't try to create a language with all the features of every other language, it will be a monster! I know you weren't trying to change the for loop merely translate its style in the docs, but my point was that anyone looking for all their best loved featires from language X in language Y is doomed to failure. > - This is offtopic, but the C for-loop syntax is very syntactically > powerful, so when people perceive Python lacks it, they may baulk > at that. No arguments about its power, but anyone who gives up on a language because one favourite control structure is missing is foolish in the extreme. > We have to do a better job selling why Python is better. Its not better, just different. There are jobs that I would never try to do in Python and for some I would pick C every time. For others SQL or Prolog or even COBOL might be more appropriate. > The C for-loop syntax itself is not error-prone at all. > Unless you mean off-by-one errors etc., missing initializations, and > those > are mostly semantic not syntax-related. All I can say is that having seen several thousand C bugs pass through my maintenance team I can tell you that for loop errors are up there in the top 5 problem areas. Your list gives many but there are also problems with side-effects introduced because of C's assignment as an expression "feature". And if everyone rigorously lint'ed their C then I agree many would be caught but I can attest that many C programmers do not use lint - and indeed its not (readily) available on some platforms (eg embedded controllers etc). > >The C syntax is extremely odd to most programmers who haven't been > >trained in it but in more traditional languages like Lisp, Cobol, > >Fortran, > >Pascal, ADA, etc. > Those were already dated in 1980 Well ADA didn't even exist in 1980. And new versions of COBOL and Fortran have been standardised in the last 10 years. Admittedly Borland Delphi is probably the last bastion of Pascal and Lisp has had a long but loyal following since the early 60's with CLOS standardised during the early 90's(?). > - almost everyone these days learns C/C++/Java(/C#) Those who go through University probably do, but many colleges and high schools teach VB or interpreted languages (like python). And scientists still get taught Fortran in many schools. And IS programmers are still universally taught COBOL because it is still the king of large scale data crunching. > I am an EE who started out in the 80s with garbage like BASIC, > Fortran, Pascal and assembly, Me too, (except we didn't do Fortran) but I didn't find them garbage (but I didn't like early BASICs its true), rather I found the different approaches interesting. I also learnt Smalltalk at Uni - an advantage for which I am immensly thankful since it opened my eyes to OOP long before it became generally popular. I came to C during a vacation job in 1985 and loved its conciseness and low level access, but I grew to hate things like casting, and the arcane pointer syntax etc. > we should at least make very basic accomodations for that > migration reality. Specifically, give the people a hint to use > while-loops and generators. The docs describe while loops and generators. What we don't want to encourage is C programmers coming to python and trying to mentally translate their C code into Python by translating for loops into while loops. That will nearly always be the wrong approach. (K&R makes a similar point about discouraging Pascal programmers from doing things like #define BEGIN { #define END } in C.) > >myList.sort() > > Alan - this was totally unnecessary and trashes the entire > (legitimate) > context of my question. Not so, it illustrates that the fundamental solution to your specific example was in looking for a native solution to the problem - sorting a collection. Using the built in functionality will nearly always be faster and more efficient than building your own. And there are very few cases where you need to build your own algorithms in python. And as I said above we can't compare the general case because C and python for loops are fundamentally different things. I guess what I'm trying to say is that it is pointless trying to get the documentation to provide pointers for any one language when there are so many others out there(*). The purpose of the languages is different, the syntax is different and so are the semantics of the constructs. (*) Interestingly my web tutor actually does take a comparative approach teaching 3 languages in parallel. (One of which, JavaScript, uses the C style for loop) But this apparent contradiction in stance is in fact because I believe that the syntactic differences in languages are vastly overplayed. Learning programming happens at a much more fundamental level than at the language syntax. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Sat Aug 11 04:35:01 2007 From: kent37 at tds.net (Kent Johnson) Date: Fri, 10 Aug 2007 22:35:01 -0400 Subject: [Tutor] Installation of Django on Mac Tiger In-Reply-To: <724354bd0708101630l3a2fdb7r25a426c4092f21ee@mail.gmail.com> References: <724354bd0708101225g4d6f146bh795db20e0375bffb@mail.gmail.com> <46BCC015.3010306@tds.net> <724354bd0708101630l3a2fdb7r25a426c4092f21ee@mail.gmail.com> Message-ID: <46BD2055.9050107@tds.net> David Handel wrote: > Hi Kent, > I'm not having much luck. I placed the Django 0.96 folder in /Library Better to put it in a Download folder or some such, it doesn't need to be in Library. Not a big deal though. > and then ran the following session: > Last login: Fri Aug 10 16:58:58 on ttyp1 > Welcome to Darwin! > david-handels-computer:~ davidHandel$ cd Library > david-handels-computer:~/Library davidHandel$ python setup.py install This is the right command, but you have to be in the dir that contains setup.py when you give it. I.e. from Library, $ cd Django-0.96 $ python setup.py install > /Library/Frameworks/Python.framework/Versions/2.5/Resources/Python.app/Contents/MacOS/Python: > can't open file 'setup.py': [Errno 2] No such file or directory > david-handels-computer:~/Library davidHandel$ python > Python 2.5.1 (r251:54869, Apr 18 2007, 22:08:04) > [GCC 4.0.1 (Apple Computer, Inc. build 5367)] on darwin > Type "help", "copyright", "credits" or "license" for more information. > >>> setup.py install This is not the right way to do it. Kent PS Please use Reply All to reply to the list. From spmcinerney at hotmail.com Sat Aug 11 10:13:54 2007 From: spmcinerney at hotmail.com (Stephen McInerney) Date: Sat, 11 Aug 2007 01:13:54 -0700 Subject: [Tutor] Losing the expressivenessofC'sfor-statement?/RESENDwithexample In-Reply-To: Message-ID: Hi Alan, I appreciate your very thoughtful answer. I had previously thought you were not taking the intent of my question seriously, it did seem to have strayed hopelessly offtopic (e.g. I knew all about Python's quicksort() already, but the generic question about for-loops very much stands). We certainly don't want the Python equivalent of Pascal-migration abominations like: >#define BEGIN { #define END } but idiomatic translation of for-loops into Python is hard: (e.g. list comprehensions vs basic iterator vs while loop vs generator vs special-purpose fn) How can we address that reasonably and succinctly without polluting the doc with language-migration-specific details, that is a worthy question... I believe we can do a better job simply by grouping and highlighting related alternative concepts like I listed above. As to a generator returning tuples/sequences, I will look into how far that goes. Also, I believe my generic comment about being forced to choose the efficient approach vs the most clear, legible or simple approach stands, and I will think up some examples. I will collect my response and further thoughts and repost in a few days when I have more time... Best, Stephen >From: "Alan Gauld" >To: tutor at python.org >Subject: Re: [Tutor] Losing the >expressivenessofC'sfor-statement?/RESENDwithexample >Date: Sat, 11 Aug 2007 02:12:18 +0100 > >"Stephen McInerney" wrote > > > I'm annoyed at how far offtopic and frankly rude the responses > >Don;t get annoyed at off topic posts, that's all part of the fun in >a group like this which is aimed at teaching novices how to >program and specifically how to program in Python. The wider >issues are all part of the training. > >As to rudeness, this is a very polite group by most internet >standards, >but if anything I wrote upset you I apologise, it wasn't my intention. > > > I'm just going to submit my doc change request to Fred Drake > > exactly as I was intending to before I sent the first mail. > >That's fine and Fred may well incorporate it. Personally I believe >that >would be a mistake as it sets a bad precedent. It may even encourage >C programmers to try to convert their C coding style into Python, >and that would be a big mistake - both for the individuals concerned >and for the Python community. > > > I didn't get much decent opinion on my central question: > >You got a lot of very good opinion, namely that you are comparing >apples and oranges. C's for loop is syntactic sugar for a while loop. >Python's for loop is a foreach construct for iterating over a >collection. >Very different things, and impossible to compare sensibly. > > > "isn't this idiom more restrictive than C/C++/Java (aka the > > rest of the universe), > >But your central premis that C/C++/Java form the "rest of the >universe" >is just plain wrong. There are many, many other languages in day to >day use. >Infoweek and Computing magazines regularly run surveys of their >readers >which show COBOL to be the most widely practiced language today (as >indeed it has been for the last 30 years!) - looking at job ads >doesn't take >account of the fact that most COBOL jobs are with big corporations and >are often jobs for life! I know several of our (5000 or so) in-house >COBOL >jockeys who have over 30 years service...) > > > don't you agree it's badly explained in the doc (there is no basic > > advice to transform to while loop or else write generator), and the > > doc > > should have a simple change > >The docs explain how the python for loop works pretty well I think. >They do not explain the differences between Python's for loop and C's >for loop any more than they explain the differences between Pythons >lambda and Lisp's version. Whether the docs should do that is a >moot point that the maintainer (Fred) can decide. > > > Show any of the code we discussed to non-Python programmers > > and they'll be lost. > >That I doubt, most of it was generic apart from the generator 'yield' >construct. And anyone used to generators - Lisp, Ruby, Smalltalk >programmers would all guess at its function pretty well intuitively. > > > follow-on question about generators returning a tuple > > (e.g. walking a pointer, and incrementing a count, let alone > > anything more complex) > >Sorry, I missed it. Can you ask again in a separate thread and we >can take a look at it. > > > - quibbling the motivation for the quicksort example I gave was > > clearly offtopic; > >No, it was an example of how, by considering the actual purpose >of the code we can usually find a completely different solution to >any such problem. There are very few scenarios that actually require >that kind of low level algorithmic access in Python - algorithm >design being one valid example! > > > the motivation was to give a legitimate example which clearly arises > > commonly. > >And my point was that in Python it doesn't arise very commonly at all. >There is nearly always an alternative style of solution, often >avoiding for >loops entirely. > > > In any case, when we talk about people migrating from other > > languages, > > C/C++/Java is ~60-95% of the audience, COBOL is irrelevant > >Going by the posts we see on this list the majority of the folks >coming >to python come from other scripting languages: PHP, Perl, Visual Basic >or from shell scripting (DOS Batch, VMS DCL or Unix shell) or from >other high level languages like Rebol, Mathematica or Lisp. There are >also many first timers since python is fast becoming the teaching >language >of choice in colleges and schools. We very rarely get questions from >C/C++ >programmers and only a few from Java. We have had at least one COBOL >programmer but I agree they aren't that common - mostly they are still >hacking away in COBOL! Where they might come from is using Python >as a replacement for their JCL scripts, and we have had a couple of >those >at least... > > > and PL/I is ancient history. > >But we can learn from history and the lesson of PL/1 was - don't try >to >create a language with all the features of every other language, it >will >be a monster! I know you weren't trying to change the for loop merely >translate its style in the docs, but my point was that anyone looking >for all their best loved featires from language X in language Y is >doomed >to failure. > > > - This is offtopic, but the C for-loop syntax is very syntactically > > powerful, so when people perceive Python lacks it, they may baulk > > at that. > >No arguments about its power, but anyone who gives up on a language >because one favourite control structure is missing is foolish in the >extreme. > > > We have to do a better job selling why Python is better. > >Its not better, just different. There are jobs that I would never try >to do in Python and for some I would pick C every time. For others >SQL or Prolog or even COBOL might be more appropriate. > > > The C for-loop syntax itself is not error-prone at all. > > Unless you mean off-by-one errors etc., missing initializations, and > > those > > are mostly semantic not syntax-related. > >All I can say is that having seen several thousand C bugs pass >through my maintenance team I can tell you that for loop errors >are up there in the top 5 problem areas. Your list gives many but >there are also problems with side-effects introduced because of C's >assignment as an expression "feature". And if everyone rigorously >lint'ed their C then I agree many would be caught but I can attest >that >many C programmers do not use lint - and indeed its not (readily) >available on some platforms (eg embedded controllers etc). > > > >The C syntax is extremely odd to most programmers who haven't been > > >trained in it but in more traditional languages like Lisp, Cobol, > > >Fortran, > > >Pascal, ADA, etc. > > Those were already dated in 1980 > >Well ADA didn't even exist in 1980. And new versions of COBOL and >Fortran have been standardised in the last 10 years. Admittedly >Borland Delphi is probably the last bastion of Pascal and Lisp >has had a long but loyal following since the early 60's with CLOS >standardised during the early 90's(?). > > > - almost everyone these days learns C/C++/Java(/C#) > >Those who go through University probably do, but many colleges >and high schools teach VB or interpreted languages (like python). >And scientists still get taught Fortran in many schools. And IS >programmers are still universally taught COBOL because it is still >the king of large scale data crunching. > > > I am an EE who started out in the 80s with garbage like BASIC, > > Fortran, Pascal and assembly, > >Me too, (except we didn't do Fortran) but I didn't find them garbage >(but I didn't like early BASICs its true), rather I found the >different >approaches interesting. I also learnt Smalltalk at Uni - an advantage >for which I am immensly thankful since it opened my eyes to OOP >long before it became generally popular. I came to C during a vacation >job in 1985 and loved its conciseness and low level access, but I grew >to hate things like casting, and the arcane pointer syntax etc. > > > we should at least make very basic accomodations for that > > migration reality. Specifically, give the people a hint to use > > while-loops and generators. > >The docs describe while loops and generators. What we don't >want to encourage is C programmers coming to python and trying >to mentally translate their C code into Python by translating for >loops into while loops. That will nearly always be the wrong >approach. (K&R makes a similar point about discouraging Pascal >programmers from doing things like >#define BEGIN { >#define END } >in C.) > > > >myList.sort() > > > > Alan - this was totally unnecessary and trashes the entire > > (legitimate) > > context of my question. > >Not so, it illustrates that the fundamental solution to your specific >example was in looking for a native solution to the problem - sorting >a collection. Using the built in functionality will nearly always be >faster >and more efficient than building your own. And there are very few >cases where you need to build your own algorithms in python. > >And as I said above we can't compare the general case because >C and python for loops are fundamentally different things. > >I guess what I'm trying to say is that it is pointless trying to get >the >documentation to provide pointers for any one language when there >are so many others out there(*). The purpose of the languages is >different, the syntax is different and so are the semantics of the >constructs. > >(*) Interestingly my web tutor actually does take a comparative >approach >teaching 3 languages in parallel. (One of which, JavaScript, uses the >C style for loop) But this apparent contradiction in stance is in >fact >because I believe that the syntactic differences in languages are >vastly overplayed. Learning programming happens at a much more >fundamental level than at the language syntax. > >HTH, > >-- >Alan Gauld >Author of the Learn to Program web site >http://www.freenetpages.co.uk/hp/alan.gauld > > >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor _________________________________________________________________ A new home for Mom, no cleanup required. All starts here. http://www.reallivemoms.com?ocid=TXT_TAGHM&loc=us From rdm at rcblue.com Sat Aug 11 10:22:19 2007 From: rdm at rcblue.com (Dick Moores) Date: Sat, 11 Aug 2007 01:22:19 -0700 Subject: [Tutor] Opinions about this new Python book? Message-ID: <20070811082318.518111E4005@bag.python.org> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070811/5f250cc2/attachment.html From rdm at rcblue.com Sat Aug 11 10:49:23 2007 From: rdm at rcblue.com (Dick Moores) Date: Sat, 11 Aug 2007 01:49:23 -0700 Subject: [Tutor] WinPdb? In-Reply-To: References: <20070809195144.A046B1E400A@bag.python.org> Message-ID: <20070811084934.738001E4005@bag.python.org> At 04:31 PM 8/9/2007, Alan Gauld wrote: >"Dick Moores" wrote > > > The only debugging I've done so far is to put in print statements > > where I want to see what's happening. > >Thats OK for basic stuff but for complex things you can wind up >with an awful lot of printing going on! > > > However, I just discovered that my excellent (IMO) Python editor, > > Ulipad, comes with WinPdb, and I'm thinking it's about time > > I learned how to use a debugger. > >Everyone should, they are wonderful tools provided you stay >in control. > > > But first, could I get some reviews here of WinPdb > >Its very good, I think the one in eclipse/PyDev is slightly better >but its close. Its certainly better than either IDLE or Pythonwin. > >The main thing in using debuggers is to avoid the temptation to >just start the program and step all the way through. Learn to use >a combination of break points - to target a suspect function or >control structure and watches - the equivalent of your print >statements. If the debugger supports conditional watches so >much the better, then you only get output when the value >goes to a particular condition. > >Once you've broken the flow at a suspect function and shown >a known error via a watch set another break point at the next >level up then rerun to there (conditional break points are great >too but I don't think pdb does those...) only then do you need >to start stepping line by line until you see the bug occur. > >At that point give up on the debugger and engage your brain! > >BTW If you can get a copy of my book (the paper one - a >library mebbe?) there is a chapter in there about debugging >which includes the use of raw pdb... Thanks for all the advice and tips, Alan. Unfortunately, I can't find your book around here. Are there any other books/webpages on debugging you or others can recommend? Dick From noufal at airtelbroadband.in Sat Aug 11 11:06:49 2007 From: noufal at airtelbroadband.in (Noufal Ibrahim) Date: Sat, 11 Aug 2007 14:36:49 +0530 Subject: [Tutor] Losing theexpressivenessofC'sfor-statement?/RESENDwithexample In-Reply-To: References: Message-ID: <46BD7C29.8090004@airtelbroadband.in> Stephen McInerney wrote: > Hi Alan, [..] > How can we address that reasonably and succinctly without polluting the doc > with language-migration-specific details, that is a worthy question... I > believe we can do a better job simply by grouping and highlighting related > alternative concepts like I listed above. I think such treatment of the various python constructs should be reserved for documents like say, "Python for C programmers"(which should also warn people IMHO about the inefficiency of translating C directly to Python). The official Python tutorial whose intent is to teach proper Python shouldn't encourage you to write C programs in Python. I don't think it should make any references to other languages since it has it's own idioms. As far as I know, K&R doesn't make any references to other languages which might have been popular at the time C was being introduced (eg. "this statement is equivalent to the COBOL statement foo"). I think that was a good thing. -- ~noufal From rdm at rcblue.com Sat Aug 11 13:11:04 2007 From: rdm at rcblue.com (Dick Moores) Date: Sat, 11 Aug 2007 04:11:04 -0700 Subject: [Tutor] Ingenious script (IMO) In-Reply-To: <20070806143246.97BAA1E4010@bag.python.org> References: <20070806131709.60E4F1E4006@bag.python.org> <46B726F8.3000107@tds.net> <20070806143246.97BAA1E4010@bag.python.org> Message-ID: <20070811111226.7A0101E401C@bag.python.org> At 07:31 AM 8/6/2007, Dick Moores wrote: >At 06:49 AM 8/6/2007, Kent Johnson wrote: > >Dick Moores wrote: > >>http://www.rcblue.com/Python/changeMaker_revised_for_US_denominations.py > >>I'm still working at Python--been at it a while--and thought the > >>script was ingenious. Do the Tutors agree? Or is it just > >>run-of-the-mill programming? Could it have been more simply written? > > > >I don't find it either ingenious or well-written. The algorithm is > >the same one you would use to count out an amount by hand so it > >doesn't seem so unusual. IMO the code relies too much on indices. If > >you rewrite it using a dict (or, even better, defaultdict(int)) for > >coinCount, there is no need for indices at all. Even with coinCount > >as a list, it could be better written. > > > >coinCount = [] > >for d in denominations: > > coinCount.append(0) > > > >=> > > > >coinCount = [0] * ndenominations > > > > > >The main loop could be > >for deno in range(ndenominations): > > if not remaining: > > break > > > >or > >for i, deno in enumerate(denominations): > ># i is now the index, deno is the actual denomination > > > > > >but I would write it this way and avoid the use of the index completely: > > > >from collections import defaultdict > >coinCount = defaultdict(int) > >remaining = change > > > ># Loop until either we have given all the change or we have > ># run out of coin denominations to check. > >for deno in denominations: > > if not remaining: > > break > > > > # For one denomination, count out coins of that denomination > > # as long as the remaining amount is greater than the denomination > > # amount. > > > > while remaining >= deno: > > coinCount[deno] += 1 > > print "remaining =", remaining > > remaining -= deno > > > ># Report the results. > >print "Your change is $%.02f"% (float(change) / CPD) > >for deno in denominations: > > if coinCount[deno] > 0: > > if deno >= 100: > > print "$%d bills:\t" % (deno / CPD), coinCount[deno] > > else: > > print "%d-cent coins:\t" % (deno), coinCount[deno] > > > > > >Kent > >Thanks Kent! > >Here's what I have after incorporating your suggestions: > >================================= >#!/usr/bin/env python >#coding=utf-8 >from collections import defaultdict > >CPD = 100 >cost = int(CPD * float(raw_input("Enter the cost: "))) >tend = int(CPD * float(raw_input("Enter the tendered amount: "))) > ># Calculate the change. >change = tend - cost > >coinCount = defaultdict(int) >print coinCount >remaining = change >denominations = (2000, 1000, 500, 100, 50, 25, 10, 5, 1) > ># Loop until either we have given all the change or we have ># run out of coin denominations to check. >for deno in denominations: > if not remaining: > break > > > # For one denomination, count out coins of that denomination > # as long as the remaining amount is greater than the denomination > # amount. > > > while remaining >= deno: > coinCount[deno] += 1 > remaining -= deno > > ># Report the results. >print "Your change is $%.02f"% (float(change) / CPD) >for deno in denominations: > if coinCount[deno] > 0: > if deno >= 100: > print "$%d bills:\t" % (deno / CPD), coinCount[deno] > else: > print "%d-cent coins:\t" % (deno), coinCount[deno] >======================================== > >Gotta say though, I still don't understand how the defaultdict works here. > >Dick I was just about finished with a script that would tell the clerk how to give the change to the customer, when I discovered that the above script computes the wrong amount of change in certain situations. It works fine if the customer tenders only bills and no change, but that's not realistic. For example, if the cost is $1.78 the customer may well tender $2.03 so he can get a quarter back rather than 2 dimes and 2 pennies. But the script in that case will compute change of 24 cents! Try it out. I've put the same script on the web, but deleted the line that I'd left in by mistake, "print coinCount". So, does this mean I should use the decimal module? Or is there another way to fix the problem? Thanks, Dick From rdm at rcblue.com Sat Aug 11 13:24:06 2007 From: rdm at rcblue.com (Dick Moores) Date: Sat, 11 Aug 2007 04:24:06 -0700 Subject: [Tutor] Ingenious script (IMO) In-Reply-To: <7.1.0.9.2.20070811034842.038b5158@rcblue.com> References: <20070806131709.60E4F1E4006@bag.python.org> <46B726F8.3000107@tds.net> <20070806143246.97BAA1E4010@bag.python.org> <7.1.0.9.2.20070811034842.038b5158@rcblue.com> Message-ID: <20070811112419.357CC1E400B@bag.python.org> At 04:11 AM 8/11/2007, Dick Moores wrote: >I was just about finished with a script that would tell the clerk >how to give the change to the customer, when I discovered that the >above script computes the wrong amount of change in certain >situations. It works fine if the customer tenders only bills and no >change, but that's not realistic. For example, if the cost is $1.78 >the customer may well tender $2.03 so he can get a quarter back >rather than 2 dimes and 2 pennies. But the script in that case will >compute change of 24 cents! Try it out. I've put the same script on >the web, but deleted the line that I'd left in by mistake, "print coinCount". Sorry. Forgot to include the link. >So, does this mean I should use the decimal module? Or is there >another way to fix the problem? > >Thanks, > >Dick From alan.gauld at btinternet.com Sat Aug 11 14:01:36 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 11 Aug 2007 13:01:36 +0100 Subject: [Tutor] LosingtheexpressivenessofC'sfor-statement?/RESENDwithexample References: <46BD7C29.8090004@airtelbroadband.in> Message-ID: "Noufal Ibrahim" wrote > I think such treatment of the various python constructs should be > reserved for documents like say, "Python for C programmers"( Actually that's not a bad idea, except I'm not sure such convertion courses exist? But it would be useful to have a set of concise crib sheets for the most common conversion languages, say: Java, Perl, C/C++, Visual Basic and Unix shell (and maybe Mathematica and Lisp). Now those would be sensible places to document how to 'translate' common language idioms into Python and point out the Pythonic alternative idioms. Does anyone know of any good starting points? If there were a standard format it might be quite a nice "cottage industry" section of the python web site that could grow as people added new guides... In fact it could be a Topic Guide section to itself... What do y'all think? Alan G. From kent37 at tds.net Sat Aug 11 14:52:28 2007 From: kent37 at tds.net (Kent Johnson) Date: Sat, 11 Aug 2007 08:52:28 -0400 Subject: [Tutor] LosingtheexpressivenessofC'sfor-statement?/RESENDwithexample In-Reply-To: References: <46BD7C29.8090004@airtelbroadband.in> Message-ID: <46BDB10C.70002@tds.net> Alan Gauld wrote: > "Noufal Ibrahim" wrote > >> I think such treatment of the various python constructs should be >> reserved for documents like say, "Python for C programmers"( > > Actually that's not a bad idea, except I'm not sure such convertion > courses exist? > > But it would be useful to have a set of concise crib sheets for > the most common conversion languages, say: > > Java, Perl, C/C++, Visual Basic and Unix shell > (and maybe Mathematica and Lisp). I agree, this would be a good place for the document Stephen suggests. The wiki has a page "MovingToPythonFromOtherLanguages" http://wiki.python.org/moin/MovingToPythonFromOtherLanguages I just added a link to that page from the BeginnersGuide/Programmers page. This page has some tips that are C/C++ specific. It could link to a MovingToPythonFromC page. (There is already MovingToPythonFromPerl) Kent From kent37 at tds.net Sat Aug 11 15:05:44 2007 From: kent37 at tds.net (Kent Johnson) Date: Sat, 11 Aug 2007 09:05:44 -0400 Subject: [Tutor] Ingenious script (IMO) In-Reply-To: <20070811111226.7A0101E401C@bag.python.org> References: <20070806131709.60E4F1E4006@bag.python.org> <46B726F8.3000107@tds.net> <20070806143246.97BAA1E4010@bag.python.org> <20070811111226.7A0101E401C@bag.python.org> Message-ID: <46BDB428.3000308@tds.net> Dick Moores wrote: > I was just about finished with a script that would tell the clerk how > to give the change to the customer, when I discovered that the above > script computes the wrong amount of change in certain situations. It > works fine if the customer tenders only bills and no change, but > that's not realistic. For example, if the cost is $1.78 the customer > may well tender $2.03 so he can get a quarter back rather than 2 > dimes and 2 pennies. But the script in that case will compute change > of 24 cents! Try it out. I've put the same script on the web, but > deleted the line that I'd left in by mistake, "print coinCount". The problem is that int(100 * float("2.03")) is 202, not 203, because the float representation of 2.03 is actually 2.0299999999999998. The same problem occurs if you enter 2.03 as the cost and 3.00 as the amount tendered; it computes change of $0.98. Use int(round(100 * float("2.03"))) to get the correct amount. Kent From amonroe at columbus.rr.com Sat Aug 11 15:24:10 2007 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Sat, 11 Aug 2007 09:24:10 -0400 Subject: [Tutor] LosingtheexpressivenessofC'sfor-statement?/RESENDwithexample In-Reply-To: References: <46BD7C29.8090004@airtelbroadband.in> Message-ID: <16355250596.20070811092410@columbus.rr.com> > "Noufal Ibrahim" wrote >> I think such treatment of the various python constructs should be >> reserved for documents like say, "Python for C programmers"( > Actually that's not a bad idea, except I'm not sure such convertion > courses exist? > But it would be useful to have a set of concise crib sheets for > the most common conversion languages, say: > Java, Perl, C/C++, Visual Basic and Unix shell > (and maybe Mathematica and Lisp). > Now those would be sensible places to document how to 'translate' > common language idioms into Python and point out the Pythonic > alternative idioms. > Does anyone know of any good starting points? If there were a standard > format it might be quite a nice "cottage industry" section of the > python > web site that could grow as people added new guides... In fact it > could > be a Topic Guide section to itself... http://99-bottles-of-beer.net/ :) Alan From jerry.vb at gmail.com Sat Aug 11 15:59:31 2007 From: jerry.vb at gmail.com (Jerry VanBrimmer) Date: Sat, 11 Aug 2007 06:59:31 -0700 Subject: [Tutor] IDLE 1.2 Question Message-ID: <901b226d0708110659q6e17aae3o714e18bd71322820@mail.gmail.com> I'm using IDLE 1.2 with Python 2.5. My question is, when I'm coding something in an IDLE window, save the code as a file.py, then click on Run>Run Module; and then I change something in the code, resave the file, click on Run>Run Module again; does this remap the namespace in the Python shell? (While using the same shell.) It seems to me that sometimes it does and sometimes it doesn't. Can anybody clarify this, just how does IDLE handle the namespace mapping? Thanks! From rdm at rcblue.com Sat Aug 11 16:02:00 2007 From: rdm at rcblue.com (Dick Moores) Date: Sat, 11 Aug 2007 07:02:00 -0700 Subject: [Tutor] Ingenious script (IMO) In-Reply-To: <46BDB428.3000308@tds.net> References: <20070806131709.60E4F1E4006@bag.python.org> <46B726F8.3000107@tds.net> <20070806143246.97BAA1E4010@bag.python.org> <20070811111226.7A0101E401C@bag.python.org> <46BDB428.3000308@tds.net> Message-ID: <20070811140209.067121E4005@bag.python.org> At 06:05 AM 8/11/2007, Kent Johnson wrote: >Dick Moores wrote: > > I was just about finished with a script that would tell the clerk how > > to give the change to the customer, when I discovered that the above > > script computes the wrong amount of change in certain situations. It > > works fine if the customer tenders only bills and no change, but > > that's not realistic. For example, if the cost is $1.78 the customer > > may well tender $2.03 so he can get a quarter back rather than 2 > > dimes and 2 pennies. But the script in that case will compute change > > of 24 cents! Try it out. I've put the same script on the web, but > > deleted the line that I'd left in by mistake, "print coinCount". > >The problem is that >int(100 * float("2.03")) >is 202, not 203, because the float representation of 2.03 is actually >2.0299999999999998. > >The same problem occurs if you enter 2.03 as the cost and 3.00 as the >amount tendered; it computes change of $0.98. > >Use int(round(100 * float("2.03"))) to get the correct amount. That did it. Thanks, Kent. Here's the script that hands over change in the traditional way. Is there a better way to handle the singulars and plurals? Dick From rdm at rcblue.com Sat Aug 11 16:19:26 2007 From: rdm at rcblue.com (Dick Moores) Date: Sat, 11 Aug 2007 07:19:26 -0700 Subject: [Tutor] Ingenious script (IMO) In-Reply-To: <46BDC3F2.1090406@alum.rpi.edu> References: <20070806131709.60E4F1E4006@bag.python.org> <46B726F8.3000107@tds.net> <20070806143246.97BAA1E4010@bag.python.org> <20070811111226.7A0101E401C@bag.python.org> <46BDB428.3000308@tds.net> <20070811140209.067121E4005@bag.python.org> <46BDC3F2.1090406@alum.rpi.edu> Message-ID: <20070811141931.94E151E400E@bag.python.org> At 07:13 AM 8/11/2007, bob gailer wrote: >Dick Moores wrote: >>Here's the script that hands over change in the traditional way. >> >> >>Is there a better way to handle the singulars and plurals? >> >What do you mean by "better"? >More efficient? >More readable/maintainable? >Less code? Phythonic. Dick From rdm at rcblue.com Sat Aug 11 16:25:03 2007 From: rdm at rcblue.com (Dick Moores) Date: Sat, 11 Aug 2007 07:25:03 -0700 Subject: [Tutor] Ingenious script (IMO) In-Reply-To: <46BDC5E3.6050504@alum.rpi.edu> References: <20070806131709.60E4F1E4006@bag.python.org> <46B726F8.3000107@tds.net> <20070806143246.97BAA1E4010@bag.python.org> <20070811111226.7A0101E401C@bag.python.org> <46BDB428.3000308@tds.net> <20070811140209.067121E4005@bag.python.org> <46BDC3F2.1090406@alum.rpi.edu> <20070811141925.99407397314@c9mailgw22.amadis.com> <46BDC5E3.6050504@alum.rpi.edu> Message-ID: <20070811142514.680CE1E401A@bag.python.org> At 07:21 AM 8/11/2007, bob gailer wrote: >Dick Moores wrote: >>At 07:13 AM 8/11/2007, bob gailer wrote: >>>Dick Moores wrote: >>>>Here's the script that hands over change in the traditional way. >>>> >>>> >>>>Is there a better way to handle the singulars and plurals? >>>What do you mean by "better"? >>>More efficient? >>>More readable/maintainable? >>>Less code? >> >>Phythonic. >What about the current code is not "Pythonic"? Hey, that's MY question. :-) I'd just appreciate some constructive criticism. Dick From handel.d at gmail.com Sat Aug 11 16:35:29 2007 From: handel.d at gmail.com (David Handel) Date: Sat, 11 Aug 2007 10:35:29 -0400 Subject: [Tutor] Installation of Django on Mac Tiger In-Reply-To: <46BD2055.9050107@tds.net> References: <724354bd0708101225g4d6f146bh795db20e0375bffb@mail.gmail.com> <46BCC015.3010306@tds.net> <724354bd0708101630l3a2fdb7r25a426c4092f21ee@mail.gmail.com> <46BD2055.9050107@tds.net> Message-ID: <724354bd0708110735x39dc5da7x16340c1bba20c2d2@mail.gmail.com> Thanks Kent. It worked. What a simple fix when you know what you are doing. There are so many people out there complaining that they spent days setting up Django on Mac Tiger. Hopefully newbies will find this post when they're feeling "terminal". Cheers, David On 8/10/07, Kent Johnson wrote: > > David Handel wrote: > > Hi Kent, > > I'm not having much luck. I placed the Django 0.96 folder in /Library > > Better to put it in a Download folder or some such, it doesn't need to > be in Library. Not a big deal though. > > > and then ran the following session: > > Last login: Fri Aug 10 16:58:58 on ttyp1 > > Welcome to Darwin! > > david-handels-computer:~ davidHandel$ cd Library > > david-handels-computer:~/Library davidHandel$ python setup.py install > > This is the right command, but you have to be in the dir that contains > setup.py when you give it. I.e. from Library, > $ cd Django-0.96 > $ python setup.py install > > > > /Library/Frameworks/Python.framework/Versions/2.5/Resources/Python.app/Contents/MacOS/Python: > > can't open file 'setup.py': [Errno 2] No such file or directory > > david-handels-computer:~/Library davidHandel$ python > > Python 2.5.1 (r251:54869, Apr 18 2007, 22:08:04) > > [GCC 4.0.1 (Apple Computer, Inc. build 5367)] on darwin > > Type "help", "copyright", "credits" or "license" for more information. > > >>> setup.py install > > This is not the right way to do it. > > Kent > > PS Please use Reply All to reply to the list. > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070811/d73704c1/attachment.html From bgailer at alum.rpi.edu Sat Aug 11 16:13:06 2007 From: bgailer at alum.rpi.edu (bob gailer) Date: Sat, 11 Aug 2007 07:13:06 -0700 Subject: [Tutor] Ingenious script (IMO) In-Reply-To: <20070811140209.067121E4005@bag.python.org> References: <20070806131709.60E4F1E4006@bag.python.org> <46B726F8.3000107@tds.net> <20070806143246.97BAA1E4010@bag.python.org> <20070811111226.7A0101E401C@bag.python.org> <46BDB428.3000308@tds.net> <20070811140209.067121E4005@bag.python.org> Message-ID: <46BDC3F2.1090406@alum.rpi.edu> Dick Moores wrote: > Here's the script that hands over change in the traditional way. > > > Is there a better way to handle the singulars and plurals? > What do you mean by "better"? More efficient? More readable/maintainable? Less code? From bgailer at alum.rpi.edu Sat Aug 11 16:21:23 2007 From: bgailer at alum.rpi.edu (bob gailer) Date: Sat, 11 Aug 2007 07:21:23 -0700 Subject: [Tutor] Ingenious script (IMO) In-Reply-To: <20070811141925.99407397314@c9mailgw22.amadis.com> References: <20070806131709.60E4F1E4006@bag.python.org> <46B726F8.3000107@tds.net> <20070806143246.97BAA1E4010@bag.python.org> <20070811111226.7A0101E401C@bag.python.org> <46BDB428.3000308@tds.net> <20070811140209.067121E4005@bag.python.org> <46BDC3F2.1090406@alum.rpi.edu> <20070811141925.99407397314@c9mailgw22.amadis.com> Message-ID: <46BDC5E3.6050504@alum.rpi.edu> Dick Moores wrote: > At 07:13 AM 8/11/2007, bob gailer wrote: >> Dick Moores wrote: >>> Here's the script that hands over change in the traditional way. >>> >>> >>> Is there a better way to handle the singulars and plurals? >>> >> What do you mean by "better"? >> More efficient? >> More readable/maintainable? >> Less code? > > Phythonic. What about the current code is not "Pythonic"? > > > From D3IBZ at hotmail.com Sat Aug 11 17:19:03 2007 From: D3IBZ at hotmail.com (Darren Williams) Date: Sat, 11 Aug 2007 11:19:03 -0400 Subject: [Tutor] LosingtheexpressivenessofC'sfor-statement?/RESENDwithexample References: <46BD7C29.8090004@airtelbroadband.in> <16355250596.20070811092410@columbus.rr.com> Message-ID: If that doesn't inpire you to take up programming... nothing will. >http://99-bottles-of-beer.net/ > > :) > > Alan > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From bgailer at alum.rpi.edu Sat Aug 11 17:28:01 2007 From: bgailer at alum.rpi.edu (bob gailer) Date: Sat, 11 Aug 2007 08:28:01 -0700 Subject: [Tutor] Ingenious script (IMO) In-Reply-To: <20070811141931.94E151E400E@bag.python.org> References: <20070806131709.60E4F1E4006@bag.python.org> <46B726F8.3000107@tds.net> <20070806143246.97BAA1E4010@bag.python.org> <20070811111226.7A0101E401C@bag.python.org> <46BDB428.3000308@tds.net> <20070811140209.067121E4005@bag.python.org> <46BDC3F2.1090406@alum.rpi.edu> <20070811141931.94E151E400E@bag.python.org> Message-ID: <46BDD581.7070504@alum.rpi.edu> Dick Moores wrote: > At 07:13 AM 8/11/2007, bob gailer wrote: > >> Dick Moores wrote: >> >>> Here's the script that hands over change in the traditional way. >>> >>> >>> Is there a better way to handle the singulars and plurals? >>> >>> >> What do you mean by "better"? >> More efficient? >> More readable/maintainable? >> Less code? >> > > Phythonic. > OK, I'll take a stab. coins = ('penny', 'pennies', 'nickel', 'nickels', 'dime', 'dimes', 'quarter','quarters', 'half-dollar') First I'd move that outside the loop, since it needs be assigned only once. Then I'd change it to: coins = (('penny', 'pennies'), ('nickel', 'nickels'), ('dime', 'dimes'), ('quarter','quarters'), ('half-dollar',)) Next I'd replace this if coinCount[deno] == 1: astr = coins[idx * 2] else: astr = coins[idx * 2 + 1] with (using a more meaningful name than astr) coin = coins[idx][coinCount[deno] == 1] I must stop here due to time constraints. When I read the entire program there's a lot I'd change to make it "better". From bgailer at alum.rpi.edu Sat Aug 11 19:07:11 2007 From: bgailer at alum.rpi.edu (bob gailer) Date: Sat, 11 Aug 2007 10:07:11 -0700 Subject: [Tutor] Ingenious script (IMO) CORRECTION In-Reply-To: <46BDD581.7070504@alum.rpi.edu> References: <20070806131709.60E4F1E4006@bag.python.org> <46B726F8.3000107@tds.net> <20070806143246.97BAA1E4010@bag.python.org> <20070811111226.7A0101E401C@bag.python.org> <46BDB428.3000308@tds.net> <20070811140209.067121E4005@bag.python.org> <46BDC3F2.1090406@alum.rpi.edu> <20070811141931.94E151E400E@bag.python.org> <46BDD581.7070504@alum.rpi.edu> Message-ID: <46BDECBF.6080801@alum.rpi.edu> bob gailer wrote: > coin = coins[idx][coinCount[deno] > 1] # CORRECTION > From ghashsnaga at gmail.com Sat Aug 11 23:40:18 2007 From: ghashsnaga at gmail.com (Ara Kooser) Date: Sat, 11 Aug 2007 15:40:18 -0600 Subject: [Tutor] global question Message-ID: <2107481c0708111440v181edaa0q528f018e319f4040@mail.gmail.com> Hello, I am back working on a text adventure game using functions. I broke down the game into areas (modules) but I am having trouble getting the other modules to recognize the globals I have set in the main program. My main program looks like this: #################################################################################### #A sample text adventure game using functions #Version 1.0 #By Ara Kooser # #################################################################################### import random import sys import string import outside1 import town1 import items ################################################################################ # #Contains the character's information # ################################################################################ stre = 9 con = 8 inte = 11 agl = 14 app = 10 mag = 6 sz = 9 hp = 17 reputation = 0 stealth = False # Grass quest quest1 = False # Mushroom quest quest2 = False # Orc quest quest3 = False cursed = False poison = False diseased = False equipment = {'Sword': 1, 'Dagger': 1, 'Walking staff': 1, 'Leather Armor':1} backpack = {'Flint and steel': 1, 'Rations': 7, 'dressing kit': 6, 'waterskin': 2} belt_pouch = {} money = {'ducats': 50} Forage = 45 Haggle = 33 Stealth = 28 Fishing = 58 Herbalism = 48 Climb = 52 Sword = 34 Staff = 47 Dagger = 42 Field_Dressing = 62 ##################################################################################### # help function that will give you a list of commands def help(): print "look, examine (object), n, w, e, s, take (item)" print "climb, stealth, fishing, herbalism, forage, haggle" print "aid (applies first aid)" print "wield (object), attack, flee, close, withdraw, maintain" print "inv (returns inventory list), cs" print "Example: examine book, take ducats, attack orc" def character_sheet(): print """\ ============================================================================ Name: Profession: Apprentice Social Class: Low Race: Human ============================================================================ Strength 9 Constitution 8 Intelligence 11 Agility 14 Appearance 10 Magic 6 Size 9 ============================================================================ Skills: Forage, Haggle, Stealth, Fishing, Herbalism, Climb, Sword, Staff, Dagger, Field Dressing ============================================================================ """ The other modules are outside1, etc.. outside1 looks like this def outside1(): print " Current Hit Points = ",hp print " Current Reputation = ",reputation print equipment print backpack ...... When I run this I get: Traceback (most recent call last): File "/Users/ara/Desktop/text_advent/outside1.py", line 452, in outside1() File "/Users/ara/Desktop/text_advent/outside1.py", line 26, in outside1 print " Current Hit Points = ",hp NameError: global name 'hp' is not defined I kind of suspect the global name I set on main wouldn't work for the outside1 module. Is there a way to do this. I don't want to copy the globals into each area file because they need to be updated during this course of the game. Thanks for any help or suggestions. Ara -- Quis hic locus, quae regio, quae mundi plaga. Ubi sum. Sub ortu solis an sub cardine glacialis ursae. From dkuhlman at rexx.com Sun Aug 12 00:36:07 2007 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Sat, 11 Aug 2007 15:36:07 -0700 Subject: [Tutor] global question In-Reply-To: <2107481c0708111440v181edaa0q528f018e319f4040@mail.gmail.com> References: <2107481c0708111440v181edaa0q528f018e319f4040@mail.gmail.com> Message-ID: <20070811223607.GA1268@cutter.rexx.com> On Sat, Aug 11, 2007 at 03:40:18PM -0600, Ara Kooser wrote: > Hello, > > I am back working on a text adventure game using functions. I broke > down the game into areas (modules) but I am having trouble getting the > other modules to recognize the globals I have set in the main program. > If you want your globals available to multiple modules, then put your "globals" in a separate module, and import that module in each module that needs access to the globals. ################################## # globals.py stre = 9 con = 8 inte = 11 agl = 14 # etc ################################## # outside1.py import globals def whatever(): x = globals.stre # etc ################################## Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman From alan.gauld at btinternet.com Sun Aug 12 01:35:25 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 12 Aug 2007 00:35:25 +0100 Subject: [Tutor] global question References: <2107481c0708111440v181edaa0q528f018e319f4040@mail.gmail.com> Message-ID: "Ara Kooser" wrote > I am back working on a text adventure game using functions. I > broke > down the game into areas (modules) but I am having trouble getting > the > other modules to recognize the globals I have set in the main > program. Yes you can't see from a module into the client that is importing. The solution is either: don't use golobals (usually by creating classes that hold the "global" data internally. - this is the "best" solution from a programming/ computer science point of view. Or, put all the globals into a module which can be imported by all other modules. Like this: # globals.py foo = 42 bar = 27 # mymod.py import globals def f(): print globals.foo + globals.bar # main.py import globals, mymod globals.foo = 125 mymod.f() Its obviously more verbose and poses some restrictions in that you are sharing data and any attempt at multi-threading will surely end in tears, but otherwise it should work... HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From rabidpoobear at gmail.com Sun Aug 12 03:02:52 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sat, 11 Aug 2007 20:02:52 -0500 Subject: [Tutor] IDLE 1.2 Question In-Reply-To: <901b226d0708110659q6e17aae3o714e18bd71322820@mail.gmail.com> References: <901b226d0708110659q6e17aae3o714e18bd71322820@mail.gmail.com> Message-ID: <46BE5C3C.4090706@gmail.com> Jerry VanBrimmer wrote: > I'm using IDLE 1.2 with Python 2.5. > > My question is, when I'm coding something in an IDLE window, save the > code as a file.py, then click on Run>Run Module; and then I change > something in the code, resave the file, click on Run>Run Module again; > does this remap the namespace in the Python shell? (While using the > same shell.) It seems to me that sometimes it does and sometimes it > doesn't. Can anybody clarify this, just how does IDLE handle the > namespace mapping? > It depends whether IDLE is opened with a subprocess or not. If it's a subprocess, your program will have a separate interpreter entirely from that used by IDLE, so the namespace will be the default namespace. If IDLE doesn't have a subprocess, your program will be run in the same interpreter as IDLE itself is running in, and since IDLE doesn't end between runs of your program, all the variables you declare will hang around. You could test this if you want. Do import random print random.randint(1,5) then take out the import and run it again. If the print statement still works, IDLE's not using a subprocess. There have been many threads about this, it's usually a Windows issue. -Luke From jeff at san-dc.com Sun Aug 12 03:39:58 2007 From: jeff at san-dc.com (Jeff Johnson) Date: Sat, 11 Aug 2007 18:39:58 -0700 Subject: [Tutor] Ingenious script (IMO) In-Reply-To: <20070806131709.60E4F1E4006@bag.python.org> Message-ID: <002901c7dc81$b1baf4e0$5f01a8c0@dcsoftware.local> I wish I had a better way to represent "pennies" vs. "penny" but it works. This was a nice challenge to help me learn python. Thanks and keep them coming! My contribution: cents = 100 cost = int(round(cents * float(raw_input("Enter the cost: ")))) tendered = int(round(cents * float(raw_input("Enter the amount tendered: ")))) change = tendered - cost denominations = [2000, 1000, 500, 100, 50, 25, 10, 5, 1] money = ['$20.00', '$10.00', '$5.00', '$1.00', 'Fifty Cent Piece', 'Quarter', 'Dime', 'Nickel', 'Penny'] moneys = ['$20.00', '$10.00', '$5.00', '$1.00', 'Fifty Cent Pieces', 'Quarters', 'Dimes', 'Nickels', 'Pennies'] givetocustomer = [0, 0, 0, 0, 0, 0, 0, 0, 0] lnlen = len(denominations) lni = 0 while lni <= lnlen - 1: # floor division yields no decimals and no rounding givetocustomer[lni] = change // denominations[lni] # modulus returns remainder change = change % denominations[lni] if givetocustomer[lni] > 0: if givetocustomer[lni] > 1: print str(givetocustomer[lni]) + ' ' + moneys[lni] else: print str(givetocustomer[lni]) + ' ' + money[lni] lni += 1 Jeff Jeff Johnson jeff at san-dc.com 623-582-0323 Fax 623-869-0675 > -----Original Message----- > From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf > Of Dick Moores > Sent: Monday, August 06, 2007 6:12 AM > To: Python Tutor List > Subject: [Tutor] Ingenious script (IMO) > > Google Answers folded, but Google has kept the archive accessible. I > found this Python script at > > > and modified it for U.S. money denominations: > > http://www.rcblue.com/Python/changeMaker_revised_for_US_denominations.py > > I'm still working at Python--been at it a while--and thought the > script was ingenious. Do the Tutors agree? Or is it just > run-of-the-mill programming? Could it have been more simply written? > > Thanks, > > Dick Moores > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > No virus found in this incoming message. > Checked by AVG Free Edition. > Version: 7.5.476 / Virus Database: 269.11.6/938 - Release Date: 8/5/2007 > 4:16 PM > -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 4232 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20070811/f0295dbb/attachment.bin From jerry.vb at gmail.com Sun Aug 12 20:45:38 2007 From: jerry.vb at gmail.com (Jerry VanBrimmer) Date: Sun, 12 Aug 2007 11:45:38 -0700 Subject: [Tutor] IDLE 1.2 Question In-Reply-To: <46BE5C3C.4090706@gmail.com> References: <901b226d0708110659q6e17aae3o714e18bd71322820@mail.gmail.com> <46BE5C3C.4090706@gmail.com> Message-ID: <901b226d0708121145o39718e55t799c707511e74ae8@mail.gmail.com> Thank you, sorry for the repeat question. On 8/11/07, Luke Paireepinart wrote: > It depends whether IDLE is opened with a subprocess or not. If it's a > subprocess, your program will have a separate interpreter entirely from > that used by IDLE, so the namespace will be the default namespace. > If IDLE doesn't have a subprocess, your program will be run in the same > interpreter as IDLE itself is running in, and since IDLE doesn't end > between runs of your program, all the variables you declare will hang > around. > You could test this if you want. Do > import random > print random.randint(1,5) > > then take out the import and run it again. If the print statement still > works, IDLE's not using a subprocess. > There have been many threads about this, it's usually a Windows issue. > -Luke > -- Jesus is coming!................................................Rev. 1:7 The Bottom Line................................................John 3:3-7 From khamid.nurdiev at gmail.com Sun Aug 12 22:15:37 2007 From: khamid.nurdiev at gmail.com (Khamid Nurdiev) Date: Mon, 13 Aug 2007 01:15:37 +0500 Subject: [Tutor] Decoding Message-ID: Hello All, I am currently learning python with the book "Python programming: An introduction to CS" by John M. Zelle and have come the section where he speaks of encoding messages. Currently the basic snippet looks like this: def dec(): > > import string > > message=raw_input("Enter the message to decode: ") > > result='' > > for x in string.split(message): > > result=result+chr(eval(x)) > > return result > > > > print dec() > > it works fine as expected but I want to enter the message as a variable like: a='12 34 84 39 122' and when the function dec() invoked, i would just enter "a" as an input and thus have changed the code a little bit but it is not working. def dec(): > > import string > > message=raw_input("Enter the message to decode: ") > > a=message[1:-1] > > result='' > > for x in string.split(a): > > result=result+chr(eval(x)) > > return result > > > > print dec() > > > Have tried many ways, i don't want to write them all here as they will take too much space. None of them work. maybe you guys know some way out? or where is it going wrong? Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070813/dd9d9a08/attachment.html From bhaaluu at gmail.com Sun Aug 12 23:01:25 2007 From: bhaaluu at gmail.com (bhaaluu) Date: Sun, 12 Aug 2007 17:01:25 -0400 Subject: [Tutor] Decoding In-Reply-To: References: Message-ID: Greetings, Disclaimer: I'm a Python Noob, so use the code snippets in this post, at your own risk! Is this what you're looking for? def dec(a): import string result='' for x in string.split(a): result=result+chr(eval(x)) return result print dec(raw_input("Enter the message to decode: ")) I took raw_input() out of the dec() function and pass the string to the function as an argument. Or, to assign it to a variable, then pass it: a=raw_input("Enter the message to decode: ") print dec(a) Or, if you want to read the code from a file on disk called code.txt which has the following code in it: 65 66 67 68 fin=open('code.txt','r) a = fin.read() fin.close() print dec(a) ABCD -- bhaaluu at gmail dot com On 8/12/07, Khamid Nurdiev wrote: > Hello All, > I am currently learning python with the book "Python programming: An introduction to CS" by John M. Zelle and have come the section where he speaks of encoding messages. Currently the basic snippet looks like this: > > > > > > > def dec(): > > > import string > > > message=raw_input("Enter the message to decode: ") > > > result='' > > > for x in string.split(message): > > > result=result+chr(eval(x)) > > > return result > > > > > > print dec() > > > > > it works fine as expected but I want to enter the message as a variable like: > a='12 34 84 39 122' > and when the function dec() invoked, i would just enter "a" as an input and thus have changed the code a little bit but it is not working. > > > > > > > def dec(): > > > import string > > > message=raw_input("Enter the message to decode: ") > > > a=message[1:-1] > > > result='' > > > for x in string.split(a): > > > result=result+chr(eval(x)) > > > return result > > > > > > print dec() > > > > > > > Have tried many ways, i don't want to write them all here as they will take too much space. None of them work. maybe you guys know some way out? or where is it going wrong? > > Thanks > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From rdm at rcblue.com Sun Aug 12 23:12:10 2007 From: rdm at rcblue.com (Dick Moores) Date: Sun, 12 Aug 2007 14:12:10 -0700 Subject: [Tutor] Decoding In-Reply-To: References: Message-ID: <20070812211229.2D5DD1E4013@bag.python.org> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070812/2a74e690/attachment.htm From rdm at rcblue.com Sun Aug 12 23:34:27 2007 From: rdm at rcblue.com (Dick Moores) Date: Sun, 12 Aug 2007 14:34:27 -0700 Subject: [Tutor] Decoding In-Reply-To: <20070812211229.2D5DD1E4013@bag.python.org> References: <20070812211229.2D5DD1E4013@bag.python.org> Message-ID: <20070812213437.5B5BF1E400B@bag.python.org> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070812/11be09d4/attachment.html From khamid.nurdiev at gmail.com Mon Aug 13 00:37:48 2007 From: khamid.nurdiev at gmail.com (Khamid Nurdiev) Date: Mon, 13 Aug 2007 03:37:48 +0500 Subject: [Tutor] Decoding In-Reply-To: References: Message-ID: Thanks, it really works. On 8/13/07, bhaaluu wrote: > > Greetings, > > Disclaimer: I'm a Python Noob, > so use the code snippets > in this post, at your own risk! > > Is this what you're looking for? > > def dec(a): > import string > result='' > for x in string.split(a): > result=result+chr(eval(x)) > return result > > print dec(raw_input("Enter the message to decode: ")) > > I took raw_input() out of the dec() function and pass the string to the > function > as an argument. Or, to assign it to a variable, then pass it: > > a=raw_input("Enter the message to decode: ") > print dec(a) > > Or, if you want to read the code from a file on disk called code.txt > which has the following code in it: > 65 66 67 68 > > fin=open('code.txt','r) > a = fin.read() > fin.close() > print dec(a) > > ABCD > -- > bhaaluu at gmail dot com > > On 8/12/07, Khamid Nurdiev wrote: > > Hello All, > > I am currently learning python with the book "Python programming: An > introduction to CS" by John M. Zelle and have come the section where he > speaks of encoding messages. Currently the basic snippet looks like this: > > > > > > > > > > > def dec(): > > > > import string > > > > message=raw_input("Enter the message to decode: ") > > > > result='' > > > > for x in string.split(message): > > > > result=result+chr(eval(x)) > > > > return result > > > > > > > > print dec() > > > > > > > > > it works fine as expected but I want to enter the message as a variable > like: > > a='12 34 84 39 122' > > and when the function dec() invoked, i would just enter "a" as an input > and thus have changed the code a little bit but it is not working. > > > > > > > > > > > def dec(): > > > > import string > > > > message=raw_input("Enter the message to decode: ") > > > > a=message[1:-1] > > > > result='' > > > > for x in string.split(a): > > > > result=result+chr(eval(x)) > > > > return result > > > > > > > > print dec() > > > > > > > > > > > Have tried many ways, i don't want to write them all here as they will > take too much space. None of them work. maybe you guys know some way out? or > where is it going wrong? > > > > Thanks > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070813/277ab6c0/attachment.htm From sli1que at yahoo.com Mon Aug 13 01:37:50 2007 From: sli1que at yahoo.com (Eric Walker) Date: Sun, 12 Aug 2007 16:37:50 -0700 (PDT) Subject: [Tutor] Decoding In-Reply-To: Message-ID: <936560.24320.qm@web60114.mail.yahoo.com> newbie here, I just tried playing around with the dec function and I get errors. Correct me if I am wrong. After getting the input, the string.split will parse the string across whitespace chars so in other words you get a list of each word entered. Then when it does the eval(x) part it dies. I tries to evaluate the word to be an existing variable or something. Am I missing something here. Thanks Eric --- Khamid Nurdiev wrote: > Thanks, it really works. > > > On 8/13/07, bhaaluu wrote: > > > > Greetings, > > > > Disclaimer: I'm a Python Noob, > > so use the code snippets > > in this post, at your own risk! > > > > Is this what you're looking for? > > > > def dec(a): > > import string > > result='' > > for x in string.split(a): > > result=result+chr(eval(x)) > > return result > > > > print dec(raw_input("Enter the message to decode: > ")) > > > > I took raw_input() out of the dec() function and > pass the string to the > > function > > as an argument. Or, to assign it to a variable, > then pass it: > > > > a=raw_input("Enter the message to decode: ") > > print dec(a) > > > > Or, if you want to read the code from a file on > disk called code.txt > > which has the following code in it: > > 65 66 67 68 > > > > fin=open('code.txt','r) > > a = fin.read() > > fin.close() > > print dec(a) > > > > ABCD > > -- > > bhaaluu at gmail dot com > > > > On 8/12/07, Khamid Nurdiev > wrote: > > > Hello All, > > > I am currently learning python with the book > "Python programming: An > > introduction to CS" by John M. Zelle and have come > the section where he > > speaks of encoding messages. Currently the basic > snippet looks like this: > > > > > > > > > > > > > > > def dec(): > > > > > import string > > > > > message=raw_input("Enter the message to > decode: ") > > > > > result='' > > > > > for x in string.split(message): > > > > > result=result+chr(eval(x)) > > > > > return result > > > > > > > > > > print dec() > > > > > > > > > > > > > it works fine as expected but I want to enter > the message as a variable > > like: > > > a='12 34 84 39 122' > > > and when the function dec() invoked, i would > just enter "a" as an input > > and thus have changed the code a little bit but it > is not working. > > > > > > > > > > > > > > > def dec(): > > > > > import string > > > > > message=raw_input("Enter the message to > decode: ") > > > > > a=message[1:-1] > > > > > result='' > > > > > for x in string.split(a): > > > > > result=result+chr(eval(x)) > > > > > return result > > > > > > > > > > print dec() > > > > > > > > > > > > > > > Have tried many ways, i don't want to write them > all here as they will > > take too much space. None of them work. maybe you > guys know some way out? or > > where is it going wrong? > > > > > > Thanks > > > > > > _______________________________________________ > > > Tutor maillist - Tutor at python.org > > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > ____________________________________________________________________________________ Fussy? Opinionated? Impossible to please? Perfect. Join Yahoo!'s user panel and lay it on us. http://surveylink.yahoo.com/gmrs/yahoo_panel_invite.asp?a=7 From bhaaluu at gmail.com Mon Aug 13 03:12:00 2007 From: bhaaluu at gmail.com (bhaaluu) Date: Sun, 12 Aug 2007 21:12:00 -0400 Subject: [Tutor] Decoding In-Reply-To: <936560.24320.qm@web60114.mail.yahoo.com> References: <936560.24320.qm@web60114.mail.yahoo.com> Message-ID: Greetings, >From what I can tell of this "decoding" function, it uses the chr() function to return the ascii character: >>> print chr(eval('65')) A >>> print ord('A') 65 In this textbook example, the "code" is simple a string of the ASCII characters' numeric values. Nothing fancy. What does this 'coded' message decode to, using the dec function? a = "72 101 108 108 111 32 69 114 105 99 33" Happy Programming! -- bhaaluu at gmail dot com On 8/12/07, Eric Walker wrote: > newbie here, > I just tried playing around with the dec function and > I get errors. Correct me if I am wrong. After getting > the input, the string.split will parse the string > across whitespace chars so in other words you get a > list of each word entered. Then when it does the > eval(x) part it dies. I tries to evaluate the word to > be an existing variable or something. Am I missing > something here. > > Thanks > > Eric > > > --- Khamid Nurdiev wrote: > > > Thanks, it really works. > > > > > > On 8/13/07, bhaaluu wrote: > > > > > > Greetings, > > > > > > Disclaimer: I'm a Python Noob, > > > so use the code snippets > > > in this post, at your own risk! > > > > > > Is this what you're looking for? > > > > > > def dec(a): > > > import string > > > result='' > > > for x in string.split(a): > > > result=result+chr(eval(x)) > > > return result > > > > > > print dec(raw_input("Enter the message to decode: > > ")) > > > > > > I took raw_input() out of the dec() function and > > pass the string to the > > > function > > > as an argument. Or, to assign it to a variable, > > then pass it: > > > > > > a=raw_input("Enter the message to decode: ") > > > print dec(a) > > > > > > Or, if you want to read the code from a file on > > disk called code.txt > > > which has the following code in it: > > > 65 66 67 68 > > > > > > fin=open('code.txt','r) > > > a = fin.read() > > > fin.close() > > > print dec(a) > > > > > > ABCD > > > -- > > > bhaaluu at gmail dot com > > > > > > On 8/12/07, Khamid Nurdiev > > wrote: > > > > Hello All, > > > > I am currently learning python with the book > > "Python programming: An > > > introduction to CS" by John M. Zelle and have come > > the section where he > > > speaks of encoding messages. Currently the basic > > snippet looks like this: > > > > > > > > > > > > > > > > > > > def dec(): > > > > > > import string > > > > > > message=raw_input("Enter the message to > > decode: ") > > > > > > result='' > > > > > > for x in string.split(message): > > > > > > result=result+chr(eval(x)) > > > > > > return result > > > > > > > > > > > > print dec() > > > > > > > > > > > > > > > > > it works fine as expected but I want to enter > > the message as a variable > > > like: > > > > a='12 34 84 39 122' > > > > and when the function dec() invoked, i would > > just enter "a" as an input > > > and thus have changed the code a little bit but it > > is not working. > > > > > > > > > > > > > > > > > > > def dec(): > > > > > > import string > > > > > > message=raw_input("Enter the message to > > decode: ") > > > > > > a=message[1:-1] > > > > > > result='' > > > > > > for x in string.split(a): > > > > > > result=result+chr(eval(x)) > > > > > > return result > > > > > > > > > > > > print dec() > > > > > > > > > > > > > > > > > > > Have tried many ways, i don't want to write them > > all here as they will > > > take too much space. None of them work. maybe you > > guys know some way out? or > > > where is it going wrong? > > > > > > > > Thanks > > > > > > > > _______________________________________________ > > > > Tutor maillist - Tutor at python.org > > > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > > > > > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > ____________________________________________________________________________________ > Fussy? Opinionated? Impossible to please? Perfect. Join Yahoo!'s user panel and lay it on us. http://surveylink.yahoo.com/gmrs/yahoo_panel_invite.asp?a=7 > > From bgailer at alum.rpi.edu Mon Aug 13 03:24:39 2007 From: bgailer at alum.rpi.edu (bob gailer) Date: Sun, 12 Aug 2007 18:24:39 -0700 Subject: [Tutor] Decoding In-Reply-To: <936560.24320.qm@web60114.mail.yahoo.com> References: <936560.24320.qm@web60114.mail.yahoo.com> Message-ID: <46BFB2D7.3040105@alum.rpi.edu> Eric Walker wrote: > newbie here, > Welcome > I just tried playing around with the dec function and > I get errors. Please always post the traceback (error message), and the code you are using. > Correct me if I am wrong. After getting > the input, What input is dec() expecting? As I read it the input is intended to be a string of numbers separated by whitespace. Something like 33 34 35 (which should decode to "abc"). > the string.split will parse the string > across whitespace chars so in other words you get a > list of each word entered. True > Then when it does the > eval(x) part it dies. I tries to evaluate the word to > be an existing variable or something. Am I missing > something here. > The reference says: "eval(expression, ...)* *The expression argument is parsed and evaluated as a Python expression. ** From sli1que at yahoo.com Mon Aug 13 03:47:17 2007 From: sli1que at yahoo.com (Eric Walker) Date: Sun, 12 Aug 2007 18:47:17 -0700 (PDT) Subject: [Tutor] Decoding In-Reply-To: Message-ID: <251377.88617.qm@web60112.mail.yahoo.com> --- bhaaluu wrote: > Greetings, > > From what I can tell of this "decoding" function, it > uses > the chr() function to return the ascii character: > > >>> print chr(eval('65')) > A > > >>> print ord('A') > 65 > > In this textbook example, the "code" is simple a > string of the > ASCII characters' numeric values. Nothing fancy. > > What does this 'coded' message decode to, using the > dec function? > > a = "72 101 108 108 111 32 69 114 105 99 33" > > Happy Programming! > -- > bhaaluu at gmail dot com > > On 8/12/07, Eric Walker wrote: > > newbie here, > > I just tried playing around with the dec function > and > > I get errors. Correct me if I am wrong. After > getting > > the input, the string.split will parse the string > > across whitespace chars so in other words you get > a > > list of each word entered. Then when it does the > > eval(x) part it dies. I tries to evaluate the word > to > > be an existing variable or something. Am I missing > > something here. > > > > Thanks > > > > Eric > > > > > > --- Khamid Nurdiev > wrote: > > > > > Thanks, it really works. > > > > > > > > > On 8/13/07, bhaaluu wrote: > > > > > > > > Greetings, > > > > > > > > Disclaimer: I'm a Python Noob, > > > > so use the code snippets > > > > in this post, at your own risk! > > > > > > > > Is this what you're looking for? > > > > > > > > def dec(a): > > > > import string > > > > result='' > > > > for x in string.split(a): > > > > result=result+chr(eval(x)) > > > > return result > > > > > > > > print dec(raw_input("Enter the message to > decode: > > > ")) > > > > > > > > I took raw_input() out of the dec() function > and > > > pass the string to the > > > > function > > > > as an argument. Or, to assign it to a > variable, > > > then pass it: > > > > > > > > a=raw_input("Enter the message to decode: ") > > > > print dec(a) > > > > > > > > Or, if you want to read the code from a file > on > > > disk called code.txt > > > > which has the following code in it: > > > > 65 66 67 68 > > > > > > > > fin=open('code.txt','r) > > > > a = fin.read() > > > > fin.close() > > > > print dec(a) > > > > > > > > ABCD > > > > -- > > > > bhaaluu at gmail dot com > > > > > > > > On 8/12/07, Khamid Nurdiev > > > wrote: > > > > > Hello All, > > > > > I am currently learning python with the > book > > > "Python programming: An > > > > introduction to CS" by John M. Zelle and have > come > > > the section where he > > > > speaks of encoding messages. Currently the > basic > > > snippet looks like this: > > > > > > > > > > > > > > > > > > > > > > > def dec(): > > > > > > > import string > > > > > > > message=raw_input("Enter the message > to > > > decode: ") > > > > > > > result='' > > > > > > > for x in string.split(message): > > > > > > > result=result+chr(eval(x)) > > > > > > > return result > > > > > > > > > > > > > > print dec() > > > > > > > > > > > > > > > > > > > > > it works fine as expected but I want to > enter > > > the message as a variable > > > > like: > > > > > a='12 34 84 39 122' > > > > > and when the function dec() invoked, i would > > > just enter "a" as an input > > > > and thus have changed the code a little bit > but it > > > is not working. > > > > > > > > > > > > > > > > > > > > > > > def dec(): > > > > > > > import string > > > > > > > message=raw_input("Enter the > message to > > > decode: ") > > > > > > > a=message[1:-1] > > > > > > > result='' > > > > > > > for x in string.split(a): > > > > > > > result=result+chr(eval(x)) > > > > > > > return result > > > > > > > > > > > > > > print dec() > > > > > > > > > > > > > > > > > > > > > > > Have tried many ways, i don't want to write > them > > > all here as they will > > > > take too much space. None of them work. maybe > you > > > guys know some way out? or > > > > where is it going wrong? > > > > > > > > > > Thanks > > > > > > > > > > > _______________________________________________ > > > > > Tutor maillist - Tutor at python.org > > > > > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > > > > > > > > > > > > > _______________________________________________ > > > Tutor maillist - Tutor at python.org > > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > > > > > > ____________________________________________________________________________________ > > Fussy? Opinionated? Impossible to please? Perfect. > Join Yahoo!'s user panel and lay it on us. > http://surveylink.yahoo.com/gmrs/yahoo_panel_invite.asp?a=7 > > > > > Thanks, I didn't know the input was only numbers. If that is the case then it works great. Thanks ____________________________________________________________________________________ Need a vacation? Get great deals to amazing places on Yahoo! Travel. http://travel.yahoo.com/ From sli1que at yahoo.com Mon Aug 13 03:51:35 2007 From: sli1que at yahoo.com (Eric Walker) Date: Sun, 12 Aug 2007 18:51:35 -0700 (PDT) Subject: [Tutor] Decoding In-Reply-To: Message-ID: <269620.35541.qm@web60116.mail.yahoo.com> --- bhaaluu wrote: > Greetings, > > From what I can tell of this "decoding" function, it > uses > the chr() function to return the ascii character: > > >>> print chr(eval('65')) > A > > >>> print ord('A') > 65 > > In this textbook example, the "code" is simple a > string of the > ASCII characters' numeric values. Nothing fancy. > > What does this 'coded' message decode to, using the > dec function? > > a = "72 101 108 108 111 32 69 114 105 99 33" > > Happy Programming! > -- > bhaaluu at gmail dot com > > On 8/12/07, Eric Walker wrote: > > newbie here, > > I just tried playing around with the dec function > and > > I get errors. Correct me if I am wrong. After > getting > > the input, the string.split will parse the string > > across whitespace chars so in other words you get > a > > list of each word entered. Then when it does the > > eval(x) part it dies. I tries to evaluate the word > to > > be an existing variable or something. Am I missing > > something here. > > > > Thanks > > > > Eric > > > > > > --- Khamid Nurdiev > wrote: > > > > > Thanks, it really works. > > > > > > > > > On 8/13/07, bhaaluu wrote: > > > > > > > > Greetings, > > > > > > > > Disclaimer: I'm a Python Noob, > > > > so use the code snippets > > > > in this post, at your own risk! > > > > > > > > Is this what you're looking for? > > > > > > > > def dec(a): > > > > import string > > > > result='' > > > > for x in string.split(a): > > > > result=result+chr(eval(x)) > > > > return result > > > > > > > > print dec(raw_input("Enter the message to > decode: > > > ")) > > > > > > > > I took raw_input() out of the dec() function > and > > > pass the string to the > > > > function > > > > as an argument. Or, to assign it to a > variable, > > > then pass it: > > > > > > > > a=raw_input("Enter the message to decode: ") > > > > print dec(a) > > > > > > > > Or, if you want to read the code from a file > on > > > disk called code.txt > > > > which has the following code in it: > > > > 65 66 67 68 > > > > > > > > fin=open('code.txt','r) > > > > a = fin.read() > > > > fin.close() > > > > print dec(a) > > > > > > > > ABCD > > > > -- > > > > bhaaluu at gmail dot com > > > > > > > > On 8/12/07, Khamid Nurdiev > > > wrote: > > > > > Hello All, > > > > > I am currently learning python with the > book > > > "Python programming: An > > > > introduction to CS" by John M. Zelle and have > come > > > the section where he > > > > speaks of encoding messages. Currently the > basic > > > snippet looks like this: > > > > > > > > > > > > > > > > > > > > > > > def dec(): > > > > > > > import string > > > > > > > message=raw_input("Enter the message > to > > > decode: ") > > > > > > > result='' > > > > > > > for x in string.split(message): > > > > > > > result=result+chr(eval(x)) > > > > > > > return result > > > > > > > > > > > > > > print dec() > > > > > > > > > > > > > > > > > > > > > it works fine as expected but I want to > enter > > > the message as a variable > > > > like: > > > > > a='12 34 84 39 122' > > > > > and when the function dec() invoked, i would > > > just enter "a" as an input > > > > and thus have changed the code a little bit > but it > > > is not working. > > > > > > > > > > > > > > > > > > > > > > > def dec(): > > > > > > > import string > > > > > > > message=raw_input("Enter the > message to > > > decode: ") > > > > > > > a=message[1:-1] > > > > > > > result='' > > > > > > > for x in string.split(a): > > > > > > > result=result+chr(eval(x)) > > > > > > > return result > > > > > > > > > > > > > > print dec() > > > > > > > > > > > > > > > > > > > > > > > Have tried many ways, i don't want to write > them > > > all here as they will > > > > take too much space. None of them work. maybe > you > > > guys know some way out? or > > > > where is it going wrong? > > > > > > > > > > Thanks > > > > > > > > > > > _______________________________________________ > > > > > Tutor maillist - Tutor at python.org > > > > > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > > > > > > > > > > > > > _______________________________________________ > > > Tutor maillist - Tutor at python.org > > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > > > > > > ____________________________________________________________________________________ > > Fussy? Opinionated? Impossible to please? Perfect. > Join Yahoo!'s user panel and lay it on us. > http://surveylink.yahoo.com/gmrs/yahoo_panel_invite.asp?a=7 > > > > > Hello Eric! Nice thanks.... I had the wrong input type.. ____________________________________________________________________________________ Choose the right car based on your needs. Check out Yahoo! Autos new Car Finder tool. http://autos.yahoo.com/carfinder/ From kent37 at tds.net Mon Aug 13 04:08:36 2007 From: kent37 at tds.net (Kent Johnson) Date: Sun, 12 Aug 2007 22:08:36 -0400 Subject: [Tutor] Decoding In-Reply-To: References: <936560.24320.qm@web60114.mail.yahoo.com> Message-ID: <46BFBD24.3010902@tds.net> bhaaluu wrote: > Greetings, > >>From what I can tell of this "decoding" function, it uses > the chr() function to return the ascii character: > >>>> print chr(eval('65')) > A There is no need to use eval() here. Since the expected values are integers, just use int(): In [6]: chr(int('65')) Out[6]: 'A' This gives a clearer error message when the input is not as expected: In [7]: chr(int('How')) ------------------------------------------------------------ Traceback (most recent call last): File "", line 1, in : invalid literal for int() with base 10: 'How' In general it's a good idea to avoid using eval() especially with user input, it is a gaping security hole. Kent From lawrence at pantherexpress.net Mon Aug 13 04:40:01 2007 From: lawrence at pantherexpress.net (Lawrence Wang) Date: Sun, 12 Aug 2007 22:40:01 -0400 Subject: [Tutor] weird socket errors on linux with asyncore Message-ID: <22e13a220708121940s3fd4ff56q7c4c63eb2e88e076@mail.gmail.com> apologies if this doesn't belong on tutor. i have a long-running script that manages a bunch of sockets with asyncore, opening 600 connections every 30 seconds for short transactions, and every now and then (like anywhere from twice an hour to once every few hours) i get this weird error: "filedescriptor out of range in select()". i found a bug report that stated that this was an issue with python 2.4.3, so i upgraded to 2.5.1 -- but it's still happening. anyone seen this before? thanks in advance for any help you can provide. --lawrence -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070812/90140273/attachment.html From spmcinerney at hotmail.com Mon Aug 13 12:31:36 2007 From: spmcinerney at hotmail.com (Stephen McInerney) Date: Mon, 13 Aug 2007 03:31:36 -0700 Subject: [Tutor] LosingtheexpressivenessofC'sfor-statement?/RESENDwithexample In-Reply-To: <46BDB10C.70002@tds.net> Message-ID: I didn't suggest embedding C-specific stuff in the documentation; I merely said the current tutorial is deficient on this topic; this is more so important since the language is currently a moving target (as the comments about the increasing power of list comprehensions prove my point. Many Python people are still not aware that basic loops can be done away with via list comprehensiosn with an if conditional qualifier) I gave an idea of what I'm proposing: very simple one-liners like: "Idiomatic translation of for-loops in Python may involve the following: list comprehensions / iterators / while-loop / generators (or special-purpose functions e.g. builtin quicksort() )) That's the sort of thing: a very compact signpost to other related topics. Not embedding pages of stuff - that rightly goes in the migration guide suggested. In response to Noufal's comment, K&R does a very good job of illustrating the philosophy of the (C) language design. Thanks for the links but the moin wiki one seems dead. I do not have time now to write up my suggested doc changes, but I will do that in the next few weeks and post here. Regards, Stephen _________________________________________________________________ Messenger Caf? ? open for fun 24/7. Hot games, cool activities served daily. Visit now. http://cafemessenger.com?ocid=TXT_TAGHM_AugHMtagline From Andy.cheesman at bristol.ac.uk Mon Aug 13 13:36:23 2007 From: Andy.cheesman at bristol.ac.uk (Andy Cheesman) Date: Mon, 13 Aug 2007 12:36:23 +0100 Subject: [Tutor] Finding a row match within a numpy array Message-ID: <46C04237.2010002@bristol.ac.uk> Dear nice people I'm trying to match a row (b) within a large numpy array (a). My most successful attempt is below hit = equal(b, a) total_hits = add.reduce(hit, 1) max_hit = argmax(total_hits, 0) answer = a[max_hit] where ... a = array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11], [12, 13, 14, 15]]) b = array([8, 9, 10, 11]) I was wondering if people could suggest a possible more efficient route as there seems to be numerous steps. Thanks Andy From bhaaluu at gmail.com Mon Aug 13 13:57:38 2007 From: bhaaluu at gmail.com (bhaaluu) Date: Mon, 13 Aug 2007 07:57:38 -0400 Subject: [Tutor] Security [Was: Re: Decoding] Message-ID: Greetings, On 8/12/07, Kent Johnson wrote: > bhaaluu wrote: > > > >>>> print chr(eval('65')) > > A > > There is no need to use eval() here. Since the expected values are > integers, just use int(): > In [6]: chr(int('65')) > Out[6]: 'A' > > This gives a clearer error message when the input is not as expected: > In [7]: chr(int('How')) > ------------------------------------------------------------ > Traceback (most recent call last): > File "", line 1, in > : invalid literal for int() with base 10: > 'How' > > In general it's a good idea to avoid using eval() especially with user > input, it is a gaping security hole. > > Kent The original poster posted a post with the following function: def dec(): import string message=raw_input("Enter the message to decode: ") result='' for x in string.split(message): result=result+chr(eval(x)) return result print dec() which is from the book: "Python programming: An introduction to CS" by John M. Zelle. As a Python Noob, I'm obviously ignorant of most of the Python language, but I wonder why the author of a book would include a function that is a "gaping security hole," when the int() function would do the job just as nicely, and without the security concerns? Of course, I don't know what context the snippet is in because I don't have a copy of the book in question. But as a Python Noob, I really do appreciate your heads-up about eval(), and I have it red-flagged as a 'gaping security' concern, and will use it with extreme caution in the future. =) Now for MY question: Besides eval(), are there other functions that should be 'red-flagged' as well? I just haven't been around Python long enough yet to become familiar with all of the Standard Library. Correct me if I'm wrong, but with 29 keywords, and over 176 library functions, Python weighs-in at over 200 Standard "objects"? Cheers! =) -- bhaaluu at gmail dot com From bhaaluu at gmail.com Mon Aug 13 14:12:18 2007 From: bhaaluu at gmail.com (bhaaluu) Date: Mon, 13 Aug 2007 08:12:18 -0400 Subject: [Tutor] Security [Was: Re: Decoding] In-Reply-To: References: Message-ID: Greetings, Although it is considered bad form to answer one's own post, I'm going to do so anyway, anyhow, http://docs.python.org/lib/built-in-funcs.html It turns out that both eval() and int() are Python interpreter built-ins. Now I really wonder why the author of the book used eval() rather than int() in the book's example? > The original poster posted a post with the following function: > def dec(): > import string > message=raw_input("Enter the message to decode: ") > result='' > for x in string.split(message): > result=result+chr(eval(x)) > return result > > print dec() > which is from the book: > "Python programming: An introduction to CS" by John M. Zelle. -- bhaaluu at gmail dot com On 8/13/07, bhaaluu wrote: > Greetings, > > On 8/12/07, Kent Johnson wrote: > > bhaaluu wrote: > > > > > >>>> print chr(eval('65')) > > > A > > > > There is no need to use eval() here. Since the expected values are > > integers, just use int(): > > In [6]: chr(int('65')) > > Out[6]: 'A' > > > > This gives a clearer error message when the input is not as expected: > > In [7]: chr(int('How')) > > ------------------------------------------------------------ > > Traceback (most recent call last): > > File "", line 1, in > > : invalid literal for int() with base 10: > > 'How' > > > > In general it's a good idea to avoid using eval() especially with user > > input, it is a gaping security hole. > > > > Kent > > The original poster posted a post with the following function: > def dec(): > import string > message=raw_input("Enter the message to decode: ") > result='' > for x in string.split(message): > result=result+chr(eval(x)) > return result > > print dec() > which is from the book: > "Python programming: An introduction to CS" by John M. Zelle. > > As a Python Noob, I'm obviously ignorant of most of the Python > language, but I wonder why the author of a book would include > a function that is a "gaping security hole," when the int() function > would do the job just as nicely, and without the security concerns? > > Of course, I don't know what context the snippet is in because I > don't have a copy of the book in question. But as a Python Noob, > I really do appreciate your heads-up about eval(), and I have it > red-flagged as a 'gaping security' concern, and will use it with > extreme caution in the future. =) > > Now for MY question: Besides eval(), are there other functions that > should be 'red-flagged' as well? I just haven't been around Python > long enough yet to become familiar with all of the Standard Library. > Correct me if I'm wrong, but with 29 keywords, and over 176 library > functions, Python weighs-in at over 200 Standard "objects"? > > Cheers! =) > -- > bhaaluu at gmail dot com > From kent37 at tds.net Mon Aug 13 14:30:27 2007 From: kent37 at tds.net (Kent Johnson) Date: Mon, 13 Aug 2007 08:30:27 -0400 Subject: [Tutor] weird socket errors on linux with asyncore In-Reply-To: <22e13a220708121940s3fd4ff56q7c4c63eb2e88e076@mail.gmail.com> References: <22e13a220708121940s3fd4ff56q7c4c63eb2e88e076@mail.gmail.com> Message-ID: <46C04EE3.3000809@tds.net> Lawrence Wang wrote: > apologies if this doesn't belong on tutor. > > i have a long-running script that manages a bunch of sockets with > asyncore, opening 600 connections every 30 seconds for short > transactions, and every now and then (like anywhere from twice an hour > to once every few hours) i get this weird error: "filedescriptor out of > range in select()". i found a bug report that stated that this was an > issue with python 2.4.3, so i upgraded to 2.5.1 -- but it's still > happening. anyone seen this before? I'm guessing here...Googling finds these threads: http://mail.python.org/pipermail/python-list/2003-June/211842.html http://groups.google.co.kr/group/comp.lang.python/msg/12b55d8a2fe61a20 both of which suggest that the problem is too many open files and the solution is to use poll() instead of select(). What platform are you running on? Can you figure out the max number of sockets configured in your implementation of Python (the value of FD_SETSIZE in socketmodule.c)? Perhaps you are occasionally trying to open too many sockets. Either 600 is too many and usually you close some sockets before all 600 have been opened, or maybe sometimes enough of the 600 have not completed in 30 seconds that the next poll overflows? HTH Kent From kent37 at tds.net Mon Aug 13 16:28:07 2007 From: kent37 at tds.net (Kent Johnson) Date: Mon, 13 Aug 2007 10:28:07 -0400 Subject: [Tutor] Security [Was: Re: Decoding] In-Reply-To: References: Message-ID: <46C06A77.7040803@tds.net> bhaaluu wrote: > The original poster posted a post with the following function: > def dec(): > import string > message=raw_input("Enter the message to decode: ") > result='' > for x in string.split(message): > result=result+chr(eval(x)) > return result > > print dec() > which is from the book: > "Python programming: An introduction to CS" by John M. Zelle. > > As a Python Noob, I'm obviously ignorant of most of the Python > language, but I wonder why the author of a book would include > a function that is a "gaping security hole," when the int() function > would do the job just as nicely, and without the security concerns? I can't answer for Mr Zelle. Looking at the book, he introduces int(), float() and long() shortly after the section containing the above example. > > Of course, I don't know what context the snippet is in because I > don't have a copy of the book in question. But as a Python Noob, > I really do appreciate your heads-up about eval(), and I have it > red-flagged as a 'gaping security' concern, and will use it with > extreme caution in the future. =) Good. There is almost always a better way to accomplish a task than to use eval(). > Now for MY question: Besides eval(), are there other functions that > should be 'red-flagged' as well? I just haven't been around Python > long enough yet to become familiar with all of the Standard Library. > Correct me if I'm wrong, but with 29 keywords, and over 176 library > functions, Python weighs-in at over 200 Standard "objects"? Anything where user input is executed as code is a security hole and should never be opened to untrusted users. eval() exec execfile() come to mind. Kent From bgailer at alum.rpi.edu Mon Aug 13 17:58:19 2007 From: bgailer at alum.rpi.edu (bob gailer) Date: Mon, 13 Aug 2007 08:58:19 -0700 Subject: [Tutor] Finding a row match within a numpy array In-Reply-To: <46C04237.2010002@bristol.ac.uk> References: <46C04237.2010002@bristol.ac.uk> Message-ID: <46C07F9B.4090907@alum.rpi.edu> Andy Cheesman wrote: > Dear nice people > > I'm trying to match a row (b) within a large numpy array (a). My most > successful attempt is below > > hit = equal(b, a) > total_hits = add.reduce(hit, 1) > max_hit = argmax(total_hits, 0) > answer = a[max_hit] > > where ... > a = array([[ 0, 1, 2, 3], > [ 4, 5, 6, 7], > [ 8, 9, 10, 11], > [12, 13, 14, 15]]) > > b = array([8, 9, 10, 11]) > > > > I was wondering if people could suggest a possible more efficient route > as there seems to be numerous steps. As an APL programmer I appreciate your approach. I'm not a numpy expert. I'm assuming one can apply *for* to an array to iterate thru the rows. Try this: for ix, row in enumerate(a): if row == b: break else: ix = 0 Cheers, nice person From ms at cerenity.org Mon Aug 13 18:46:57 2007 From: ms at cerenity.org (Michael Sparks) Date: Mon, 13 Aug 2007 17:46:57 +0100 Subject: [Tutor] Security [Was: Re: Decoding] In-Reply-To: <46C06A77.7040803@tds.net> References: <46C06A77.7040803@tds.net> Message-ID: <200708131746.57338.ms@cerenity.org> On Monday 13 August 2007 15:28, Kent Johnson wrote: > > The original poster posted a post with the following function: ... > > message=raw_input("Enter the message to decode: ") > > result='' > > for x in string.split(message): > > result=result+chr(eval(x)) > Anything where user input is executed as code is a security hole and > should never be opened to untrusted users. foo = raw_input(...) x = eval(foo) Is an exception, in almost[*] every scenario I can think of. (and is the context eval was being used as far as I can see without reading the whole thread) [*] One scenario that seems unlikely but possible is a scenario where a machine has been put into a form of kiosk mode where the *only* thing they can do is type responses to the raw_input prompt. Given where raw_input runs, this strikes me as highly unrealistic/unlikely. Why? Because if they can type on the keyboard of a machine that's running raw_input they have the ability to do far more damage that way than any other. (ability to use a real sledgehammer on the machine springs to mind :-) Michael. From alan.gauld at btinternet.com Mon Aug 13 20:17:56 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 13 Aug 2007 19:17:56 +0100 Subject: [Tutor] Finding a row match within a numpy array References: <46C04237.2010002@bristol.ac.uk> Message-ID: "Andy Cheesman" wrote > I'm trying to match a row (b) within a large numpy array (a). My > most > successful attempt is below I'm nonumpy expert but... > hit = equal(b, a) > total_hits = add.reduce(hit, 1) > max_hit = argmax(total_hits, 0) > answer = a[max_hit] Where are all of these functions coming from? Are they numpy? (I couldn't find them on the reference at: http://www.hjcb.nl/python/Arrays.html) Their function is not intuitively obvious to me. For example, why does "equal" take a row and an array - would an array ever be equal to a row or vice versa? (Unless the array only had one row, I suppose?) And what is add.reduce? Is it related to the standard reduce? - the prototype is different... Even argmax is not totally clear, how does it differ from normal max()? In other words I'm not sure what the steps are doing so can't suggest much improvement. Maybe other > where ... > a = array([[ 0, 1, 2, 3], > [ 4, 5, 6, 7], > [ 8, 9, 10, 11], > [12, 13, 14, 15]]) > > b = array([8, 9, 10, 11]) > > > > I was wondering if people could suggest a possible more efficient > route > as there seems to be numerous steps. > > Thanks > Andy > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at btinternet.com Mon Aug 13 20:26:27 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 13 Aug 2007 19:26:27 +0100 Subject: [Tutor] Security [Was: Re: Decoding] References: Message-ID: "bhaaluu" wrote > Now for MY question: Besides eval(), are there other functions that > should be 'red-flagged' as well? Pretty much anything that can execute user entered code is a potential security problem. The most common are probably: eval() exec() execfile() input() All of these execute code one way or another and unless you are absolutely sure that the code couldn't be malicious you should avoid using them. In most cases thee are safer alternatives. BTW All are fine for prototyping ideas, experimenting at the >>> prompt etc and can save you some typing. But if you then want to turn your idea into a script think about changing these functions to something safer. Also in databases using string substitution instead of the DBAPI substitution can allow SQL injection attacks. See my database topic in my tutor for more on that one. Search for the heading: A Word about Security I'm sure others will bring up other examples but these are the ones we see most often on this list. HTH, Alan G. From khamid.nurdiev at gmail.com Mon Aug 13 20:50:35 2007 From: khamid.nurdiev at gmail.com (Khamid Nurdiev) Date: Mon, 13 Aug 2007 23:50:35 +0500 Subject: [Tutor] Security [Was: Re: Decoding] In-Reply-To: <46C06A77.7040803@tds.net> References: <46C06A77.7040803@tds.net> Message-ID: It is Good that you have the book because i have a few questions concerning the books again. This book by M. Zelle is getting really difficult shortly after that section (also as i see the examples are getting fewer) but it was easy till that part, so the question is: is it to me or is the rest of the book indeed explained not well(not like the beginning parts)?. Having heard the recommendations on books for beginners i have ordered the book "Core Python Programming" by Wesley Chun, so comparing those two books which one is more suitable (recommended) for a beginner to both python and programming? Here in our local library, the first edition of "Core python programming" is available so i guess i will use it till I receive the second edition, but i think it might take like a month, if not more till it gets to where i live. Is there much difference between the first and second editions? And also one more book, i haven't ordered it yet, is the "Python from novice to professional" by Magnus Lie Hetland, is it worth ordering and studying for a complete noob? thanks for your answers. On 8/13/07, Kent Johnson wrote: > > bhaaluu wrote: > > > The original poster posted a post with the following function: > > def dec(): > > import string > > message=raw_input("Enter the message to decode: ") > > result='' > > for x in string.split(message): > > result=result+chr(eval(x)) > > return result > > > > print dec() > > which is from the book: > > "Python programming: An introduction to CS" by John M. Zelle. > > > > As a Python Noob, I'm obviously ignorant of most of the Python > > language, but I wonder why the author of a book would include > > a function that is a "gaping security hole," when the int() function > > would do the job just as nicely, and without the security concerns? > > I can't answer for Mr Zelle. Looking at the book, he introduces int(), > float() and long() shortly after the section containing the above example. > > > > Of course, I don't know what context the snippet is in because I > > don't have a copy of the book in question. But as a Python Noob, > > I really do appreciate your heads-up about eval(), and I have it > > red-flagged as a 'gaping security' concern, and will use it with > > extreme caution in the future. =) > > Good. There is almost always a better way to accomplish a task than to > use eval(). > > > Now for MY question: Besides eval(), are there other functions that > > should be 'red-flagged' as well? I just haven't been around Python > > long enough yet to become familiar with all of the Standard Library. > > Correct me if I'm wrong, but with 29 keywords, and over 176 library > > functions, Python weighs-in at over 200 Standard "objects"? > > Anything where user input is executed as code is a security hole and > should never be opened to untrusted users. > eval() > exec > execfile() > > come to mind. > > Kent > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070813/04c4ef8e/attachment.html From bgailer at alum.rpi.edu Mon Aug 13 21:50:37 2007 From: bgailer at alum.rpi.edu (bob gailer) Date: Mon, 13 Aug 2007 12:50:37 -0700 Subject: [Tutor] Finding a row match within a numpy array In-Reply-To: <46C07F9B.4090907@alum.rpi.edu> References: <46C04237.2010002@bristol.ac.uk> <46C07F9B.4090907@alum.rpi.edu> Message-ID: <46C0B60D.3090707@alum.rpi.edu> bob gailer wrote: > Andy Cheesman wrote: > >> Dear nice people >> >> I'm trying to match a row (b) within a large numpy array (a). My most >> successful attempt is below >> >> hit = equal(b, a) >> total_hits = add.reduce(hit, 1) >> max_hit = argmax(total_hits, 0) >> answer = a[max_hit] >> >> where ... >> a = array([[ 0, 1, 2, 3], >> [ 4, 5, 6, 7], >> [ 8, 9, 10, 11], >> [12, 13, 14, 15]]) >> >> b = array([8, 9, 10, 11]) >> >> >> >> I was wondering if people could suggest a possible more efficient route >> as there seems to be numerous steps. >> > As an APL programmer I appreciate your approach. > I'm not a numpy expert. I'm assuming one can apply *for* to an array to > iterate thru the rows. Try this: > > Let's fix that a bit (assumes 0 origin indexing): > for answer, row in enumerate(a): > if row == b: > break > else: > # do something to handle no match > > Cheers, > nice person > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From bhaaluu at gmail.com Mon Aug 13 22:17:23 2007 From: bhaaluu at gmail.com (bhaaluu) Date: Mon, 13 Aug 2007 16:17:23 -0400 Subject: [Tutor] Python Book Recommendations [Was:[Re: Security]] Message-ID: Greetings, The only Python Books I have are the ones that are freely available for download from the Internet. Here is the list: Learning to Program (by Alan Gauld - a Tutor on this list.) http://www.freenetpages.co.uk/hp/alan.gauld/index.htm This book is also available for purchase in dead-tree form. How To Think Like a Computer Scientist: Learning with Python http://ibiblio.org/obp/thinkCS/python/english2e/html/index.html Dive Into Python http://www.diveintopython.org/ A Byte of Python http://swaroopch.info/text/Byte_of_Python:Main_Page Python Documentation http://docs.python.org/index.html Thinking in Python http://mindview.net/Books/TIPython Text Processing in Python http://gnosis.cx/TPiP/ Your best bet may be the "Learning to Program" book by Alan Gauld. Also there are a ton of tutorials on the Internet, many of which will get you up to speed with the basic stuff in a hurry. On 8/13/07, Khamid Nurdiev wrote: > It is Good that you have the book because i have a few questions concerning > the books again. This book by M. Zelle is getting really difficult shortly > after that section (also as i see the examples are getting fewer) but it was > easy till that part, so the question is: is it to me or is the rest of the > book indeed explained not well(not like the beginning parts)?. I call that the "Chapter 3 Syndrome." They start out the book holding your hand, and explaining everything nicely... then around Chapter 3 the author gets tired of going so slowly, and the pace picks up and leaves me behind. =) > Having heard > the recommendations on books for beginners i have ordered the book "Core > Python Programming" by Wesley Chun, so comparing those two books which one > is more suitable (recommended) for a beginner to both python and > programming? Programming isn't for everyone! Until you find out whether or not it's for you, don't spend hundreds and thousands of dollars on computer programming books! =) > Here in our local library, the first edition of "Core python programming" > is available so i guess i will use it till I receive the second edition, but > i think it might take like a month, if not more till it gets to where i > live. Is there much difference between the first and second editions? And > also one more book, i haven't ordered it yet, is the "Python from novice to > professional" by Magnus Lie Hetland, is it worth ordering and studying for a > complete noob? I think your local library is a great idea for checking out programming books! Also, look into the Inter-library loan system for books that might not be in your library branch. Most libraries can borrow books for you from another branch within the system, or even from out-of-state. Another resource is the local used-book stores. $40-$50 programming books for $4-$5. They may have some highlighting or underlining, but that doesn't usually make the content suffer. Often they'll have the CD or floppy disk in the back cover. Finally, if you do find a computer programming book that you think is the Philosopher's Stone, and you can't live without it, check all the used-book stores that sell online at: http://used.addall.com > > thanks for your answers. > You're welcome. =) -- bhaaluu at gmail dot com From keridee at jayco.net Mon Aug 13 23:39:54 2007 From: keridee at jayco.net (Tiger12506) Date: Mon, 13 Aug 2007 16:39:54 -0500 Subject: [Tutor] Security [Was: Re: Decoding] References: <46C06A77.7040803@tds.net> <200708131746.57338.ms@cerenity.org> Message-ID: <002101c7ddf2$808b5eb0$bffce004@JSLAPTOP> > foo = raw_input(...) > x = eval(foo) > > Is an exception, in almost[*] every scenario I can think of. (and is the > context eval was being used as far as I can see without reading the whole > thread) > > [*] One scenario that seems unlikely but possible is a scenario where a > machine has been put into a form of kiosk mode where the *only* > thing > they can do is type responses to the raw_input prompt. Given where > raw_input runs, this strikes me as highly unrealistic/unlikely. > > Why? Because if they can type on the keyboard of a machine that's running > raw_input they have the ability to do far more damage that way than any > other. (ability to use a real sledgehammer on the machine springs to mind > :-) Let your program run on your machine and I'll walk by, type in this string, and hit enter. We'll see how much of an exception it is when you can't boot your XP machine anymore. ;-) "file('boot.ini','w').close()" Of course, x would be set to None (the return value of the file method close()), but the damage is already done. btw - that *one scenario* happens a lot more often than you think. For example, you write a library. It doesn't have to be raw_input. You could get that string from anywhere. A text box, a username. A registry value!! If your program uses eval on a registry string, someone could set that key before hand to something similar to above. JS From kent37 at tds.net Mon Aug 13 22:53:16 2007 From: kent37 at tds.net (Kent Johnson) Date: Mon, 13 Aug 2007 16:53:16 -0400 Subject: [Tutor] Security [Was: Re: Decoding] In-Reply-To: <200708131746.57338.ms@cerenity.org> References: <46C06A77.7040803@tds.net> <200708131746.57338.ms@cerenity.org> Message-ID: <46C0C4BC.1000402@tds.net> Michael Sparks wrote: >> Anything where user input is executed as code is a security hole and >> should never be opened to untrusted users. > > foo = raw_input(...) > x = eval(foo) > > Is an exception, in almost[*] every scenario I can think of. (and is the > context eval was being used as far as I can see without reading the whole > thread) > > Why? Because if they can type on the keyboard of a machine that's running > raw_input they have the ability to do far more damage that way than any > other. (ability to use a real sledgehammer on the machine springs to mind > :-) Hmm...could be a remote connection such as ssh, which precludes the sledgehammer though probably not the sort of mischief you can get into with eval()...perhaps there are untrusted remote connections where eval() would still be a significant risk, I don't know... Kent From rabidpoobear at gmail.com Mon Aug 13 23:31:58 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Mon, 13 Aug 2007 16:31:58 -0500 Subject: [Tutor] Security [Was: Re: Decoding] In-Reply-To: References: <46C06A77.7040803@tds.net> Message-ID: <46C0CDCE.3090605@gmail.com> Khamid Nurdiev wrote: > It is Good that you have the book because i have a few questions > concerning the books again. This book by M. Zelle is getting really > difficult shortly after that section (also as i see the examples are > getting fewer) but it was easy till that part, so the question is: is > it to me or is the rest of the book indeed explained not well(not like > the beginning parts)?. Having heard the recommendations on books for > beginners i have ordered the book "Core Python Programming" by Wesley > Chun, so comparing those two books which one is more suitable > (recommended) for a beginner to both python and programming? I haven't read either book, but if nothing else, it helps that Wes is a regular here at [tutor]. > Here in our local library, the first edition of "Core python > programming" is available so i guess i will use it till I receive the > second edition, but i think it might take like a month, if not more > till it gets to where i live. Is there much difference between the > first and second editions? And also one more book, i haven't ordered > it yet, is the "Python from novice to professional" by Magnus Lie > Hetland, is it worth ordering and studying for a complete noob? > > thanks for your answers. From carroll at tjc.com Mon Aug 13 23:32:46 2007 From: carroll at tjc.com (Terry Carroll) Date: Mon, 13 Aug 2007 14:32:46 -0700 (PDT) Subject: [Tutor] Security [Was: Re: Decoding] In-Reply-To: Message-ID: On Mon, 13 Aug 2007, Alan Gauld wrote: > eval() > exec() > execfile() > input() Two of my favorite things about Python 3000 will be having input() go away and fixing integer division. From ms at cerenity.org Mon Aug 13 23:55:41 2007 From: ms at cerenity.org (Michael Sparks) Date: Mon, 13 Aug 2007 22:55:41 +0100 Subject: [Tutor] Security [Was: Re: Decoding] In-Reply-To: <46C0C4BC.1000402@tds.net> References: <200708131746.57338.ms@cerenity.org> <46C0C4BC.1000402@tds.net> Message-ID: <200708132255.46883.ms@cerenity.org> On Monday 13 August 2007 21:53, Kent Johnson wrote: > Hmm...could be a remote connection such as ssh, which precludes the > sledgehammer though probably not the sort of mischief you can get into > with eval()...perhaps there are untrusted remote connections where > eval() would still be a significant risk, I don't know... If they can ssh into a box, the likelihood of that ssh connection *only* allowing them access to run that single python program strikes me as vanishingly small :-) Generally speaking I agree that eval is a good opportunity for problems, but if its in response to raw_input, I think the likelihood of it being the biggest potential security problem is low :) (After all, if they're ssh'ing in, they're more likely to ssh in, *then* run the code. They could happily delete and trash all sorts of things either inside or outside python. They could even write their own scripts to assist them in their devilish plans too, far exceeding the minor demon of eval ;-) Eval can however be an amazingly useful function, especially when combined with exec. Michael. From alan.gauld at btinternet.com Tue Aug 14 01:09:46 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 14 Aug 2007 00:09:46 +0100 Subject: [Tutor] Security [Was: Re: Decoding] References: <46C06A77.7040803@tds.net> Message-ID: "Khamid Nurdiev" wrote > This book by M. Zelle is getting really difficult shortly > after that section I can't comment on the specific book but unfortunately its a common phenomenon that "beginner" books start of easy then suddenly get much harder. This is partly because it is very hard for an experienced programmer to think like a true beginner, there is just so much we take for granted as obvious. > the recommendations on books for beginners i have ordered the book > "Core > Python Programming" by Wesley Chun, so comparing those two books > which one > is more suitable (recommended) for a beginner to both python and > programming? Wes' book is a very good book on Python, personally I think it might be quite fast paced and detailed for a beginner to programming but there are plenty tutorials on the web for that, including mine! :-) > Here in our local library, the first edition of "Core python > programming" > is available so i guess i will use it till I receive the second > edition, ... > . Is there much difference between the first and second editions? In the detauil yes but not in the fundamental principles. Especially the early chapters seem pretty similar. Mind you I've only looked at the second edition in depth, I've only seen the first edition in book stores... > also one more book, i haven't ordered it yet, is the "Python from > novice to > professional" by Magnus Lie Hetland, is it worth ordering and > studying for a > complete noob? No idea but you really don't want too many introductory texts, you will rarely look at them once you learn how to program. (Wes' book is a good exception since he has a lot of "under the covers" stuff about how python works which even experienced pythonistas can use) HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From ms at cerenity.org Tue Aug 14 01:24:14 2007 From: ms at cerenity.org (Michael Sparks) Date: Tue, 14 Aug 2007 00:24:14 +0100 Subject: [Tutor] Security [Was: Re: Decoding] In-Reply-To: <002101c7ddf2$808b5eb0$bffce004@JSLAPTOP> References: <200708131746.57338.ms@cerenity.org> <002101c7ddf2$808b5eb0$bffce004@JSLAPTOP> Message-ID: <200708140024.15719.ms@cerenity.org> On Monday 13 August 2007 22:39, Tiger12506 wrote: > > foo = raw_input(...) > > x = eval(foo) > > ... > Let your program run on your machine and I'll walk by, type in this string, > and hit enter. We'll see how much of an exception it is when you can't boot > your XP machine anymore. > ;-) Who cares? I don't run XP :-D Also, a broken XP machine is an opportunity anyway, not a problem. Seriously though, if typing: > "file('boot.ini','w').close()" Into an "eval prompt" worked then equally leaving a python interpreter open would be dumb, let alone a console. Oddly my desktop machine often has a shell open, and often has a python interpreter running as well. Indeed at present it has 11 shells open. The non graphical console is a root shell (accessible by alt-f1). My work machines likewise have around a dozen shells open each. However, when I leave my machine alone the display locks itself, and its normally behind a locked door (unless I'm with it). Quite frankly anyone getting worried about this: > > foo = raw_input(...) > > x = eval(foo) Is pretty over anxious IMO. "Gosh, the person at the console might be able to get python do something which they can do anyway". (This is rather distinct from taking random crap from someone not on the local console and just doing it (eg from a network connection/external resource)) If the user wishes to trash their own machine, using an eval prompt is a rather bizarre way to go about it. Michael. From keridee at jayco.net Tue Aug 14 03:28:09 2007 From: keridee at jayco.net (Tiger12506) Date: Mon, 13 Aug 2007 20:28:09 -0500 Subject: [Tutor] Security [Was: Re: Decoding] References: <200708131746.57338.ms@cerenity.org> <002101c7ddf2$808b5eb0$bffce004@JSLAPTOP> <200708140024.15719.ms@cerenity.org> Message-ID: <003101c7de12$63454490$bffce004@JSLAPTOP> > On Monday 13 August 2007 22:39, Tiger12506 wrote: >> > foo = raw_input(...) >> > x = eval(foo) >> > > ... >> Let your program run on your machine and I'll walk by, type in this >> string, >> and hit enter. We'll see how much of an exception it is when you can't >> boot >> your XP machine anymore. >> ;-) > > Who cares? I don't run XP :-D I'm sure the equivalent can be done on different operating systems. > Also, a broken XP machine is an opportunity anyway, not a problem. Agreed. > Seriously though, if typing: > >> "file('boot.ini','w').close()" > > Into an "eval prompt" worked then equally leaving a python interpreter > open > would be dumb, let alone a console. It does work. Try it with a simple file "temp.txt" for example. You can run any function call if the string is parsed with eval. Notice I did not say "type into an eval prompt type loop" I mean entirely if the string is parsed with eval. > Oddly my desktop machine often has a shell open, and often has a python > interpreter running as well. Indeed at present it has 11 shells open. The > non > graphical console is a root shell (accessible by alt-f1). My work machines > likewise have around a dozen shells open each. > > However, when I leave my machine alone the display locks itself, and its > normally behind a locked door (unless I'm with it). > > Quite frankly anyone getting worried about this: > >> > foo = raw_input(...) >> > x = eval(foo) > > Is pretty over anxious IMO. "Gosh, the person at the console might be able > to > get python do something which they can do anyway". Again. Anytime the function is parsed with eval, you can run *any* python function that is in the scope that the eval function is being executed from. Security risks are never simple. Of course they can do it with a python console window open. But if you are worried about security you don't allow them access to the python console. You ecapsulate it. But what if you use eval in a library function you write, which is used to parse some input? Peer to peer networks, http servers, even text files that you try to parse could be corrupted to cause your computer damage. The point is that eval is a security risk "greater than other implementations" that is-using int() is much more secure than eval(). > (This is rather distinct from taking random crap from someone not on the > local > console and just doing it (eg from a network connection/external > resource)) > > If the user wishes to trash their own machine, using an eval prompt is a > rather bizarre way to go about it. Sometimes it's not what they want to do. Kiosks centers are a good example. But if you parse a text file that you haven't reviewed... that's possible. Not likely. But possible. It's along the same lines as buffer overruns. It's possible. Not as likely. But possible. JS From wescpy at gmail.com Tue Aug 14 03:30:31 2007 From: wescpy at gmail.com (wesley chun) Date: Mon, 13 Aug 2007 18:30:31 -0700 Subject: [Tutor] Security [Was: Re: Decoding] In-Reply-To: <46C06A77.7040803@tds.net> References: <46C06A77.7040803@tds.net> Message-ID: <78b3a9580708131830y492bf98cpadf7c474efe802fe@mail.gmail.com> > > The original poster posted a post with the following function: > > def dec(): > > import string > > message=raw_input("Enter the message to decode: ") > > result='' > > for x in string.split(message): > > result=result+chr(eval(x)) > > return result > > > > print dec() i echo everyone else's sentiments on the use of eval(), esp. in this example. it seems like it was created in the old Python 1.x days. a useful exercise for everyone here is to figure out what this piece of code is supposed to do, and refactor it so that it's safer and easier to understand. my suggestions would include: - remove reference to the string module and just use (string) methods - remove eval() - put together the string without using concatenation something like this would be better: result = ''.join([chr(x) for x in message.split()]) also, i think that user interaction should be kept out of "calculation functions." by that i mean that you can have code that does raw_input() and print, but the core functionality should just take input, say 'message' and return an object, all without user interaction. that way, you can reuse your code more easily in other applications where you desire this functionality. cheers, -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From wescpy at gmail.com Tue Aug 14 03:46:32 2007 From: wescpy at gmail.com (wesley chun) Date: Mon, 13 Aug 2007 18:46:32 -0700 Subject: [Tutor] Python Book Recommendations [Was:[Re: Security]] In-Reply-To: References: Message-ID: <78b3a9580708131846n19dd5b24w620c7508d2d7d769@mail.gmail.com> > > Having heard > > the recommendations on books for beginners i have ordered the book "Core > > Python Programming" by Wesley Chun, so comparing those two books which one > > is more suitable (recommended) for a beginner to both python and > > programming? if you are new to programming, then perhaps Core Python isn't the best book for you. the target audience is for those who already know how to program but want to learn Python as quickly and as in-depth as possible. this is not to say that you cannot benefit from the book as a newbie, but that it just isn't written directly for you. if you are a pure beginner, then: - alan's materials work great (the book is somewhat out-of-date but the tutorial is contemporary): http://www.freenetpages.co.uk/hp/alan.gauld - "how to think like a computer scientist" is also a good choice http://www.ibiblio.org/obp/thinkCS/python/english2e/html - if you have to have a book, then i've heard good things about dawson's "absolute beginner" book: http://www.courseptr.com/ptr_detail.cfm?isbn=1-59863-112-8 - magnus hetland has TWO online tutorials... the 'instant python' one is more for programmers but for newbies, you should read the 'instant hacking' one: http://hetland.org/writing/instant-hacking.html the zelle book is mainly for an undergraduate introduction to computer science, so if you want to learn programming but not get the "science" part of it yet, then you also need to look elsewhere. i suspect this (the CS part) is what begins in chapter 3. :-) > I think your local library is a great idea for checking out programming > books! Also, look into the Inter-library loan system for books that might > not be in your library branch. Most libraries can borrow books for you > from another branch within the system, or even from out-of-state. i second this recommendation. > Another resource is the local used-book stores. $40-$50 programming > books for $4-$5. They may have some highlighting or underlining, > but that doesn't usually make the content suffer. Often they'll > have the CD or floppy disk in the back cover. you can also check out http://half.com as well as eBay for popular books. hope this helps! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From rdm at rcblue.com Tue Aug 14 03:56:25 2007 From: rdm at rcblue.com (Dick Moores) Date: Mon, 13 Aug 2007 18:56:25 -0700 Subject: [Tutor] Python Book Recommendations [Was:[Re: Security]] In-Reply-To: References: Message-ID: <20070814015654.5EBCE1E4012@bag.python.org> At 01:17 PM 8/13/2007, bhaaluu wrote: >Finally, if you do find a computer programming book that you >think is the Philosopher's Stone, and you can't live without it, >check all the used-book stores that sell online at: > >http://used.addall.com Better, IMO, is BestBookDeal.com Dick Moores From khamid.nurdiev at gmail.com Tue Aug 14 08:21:15 2007 From: khamid.nurdiev at gmail.com (Khamid Nurdiev) Date: Tue, 14 Aug 2007 11:21:15 +0500 Subject: [Tutor] Python Book Recommendations [Was:[Re: Security]] In-Reply-To: References: Message-ID: This was really helpful. My message was sent just to find the book exactly like Alan's "Tutor" for the start. And can proceed to other books after it. Programming isn't for everyone! Until you find out whether or not > > it's for you, don't spend hundreds and thousands of dollars on > > computer programming books! =) > > It was just a try to find the proper book for a beginner and also when asked lots of people here recommended it for the beginner. As for me, I just followed the mind of more experienced people like the patient follows the advice of a doctor :-) Anyways thanks a lot, it is really nice that there is such a mailing list and such willing people to help. On 8/14/07, bhaaluu wrote: > > Greetings, > > The only Python Books I have are the ones that are freely > available for download from the Internet. Here is the list: > > Learning to Program (by Alan Gauld - a Tutor on this list.) > http://www.freenetpages.co.uk/hp/alan.gauld/index.htm > This book is also available for purchase in dead-tree form. > > How To Think Like a Computer Scientist: Learning with Python > http://ibiblio.org/obp/thinkCS/python/english2e/html/index.html > > Dive Into Python > http://www.diveintopython.org/ > > A Byte of Python > http://swaroopch.info/text/Byte_of_Python:Main_Page > > Python Documentation > http://docs.python.org/index.html > > Thinking in Python > http://mindview.net/Books/TIPython > > Text Processing in Python > http://gnosis.cx/TPiP/ > > Your best bet may be the "Learning to Program" book by Alan Gauld. > Also there are a ton of tutorials on the Internet, many of which will > get you up to speed with the basic stuff in a hurry. > > On 8/13/07, Khamid Nurdiev wrote: > > It is Good that you have the book because i have a few questions > concerning > > the books again. This book by M. Zelle is getting really difficult > shortly > > after that section (also as i see the examples are getting fewer) but it > was > > easy till that part, so the question is: is it to me or is the rest of > the > > book indeed explained not well(not like the beginning parts)?. > > I call that the "Chapter 3 Syndrome." > They start out the book holding your hand, and explaining > everything nicely... then around Chapter 3 the author gets > tired of going so slowly, and the pace picks up and leaves me > behind. =) > > > Having heard > > the recommendations on books for beginners i have ordered the book "Core > > Python Programming" by Wesley Chun, so comparing those two books which > one > > is more suitable (recommended) for a beginner to both python and > > programming? > Programming isn't for everyone! Until you find out whether or notit's for > you, don't spend hundreds and thousands of dollars on computer programming > books! =) > Here in our local library, the first edition of "Core python programming" > > is available so i guess i will use it till I receive the second edition, > but > > i think it might take like a month, if not more till it gets to where i > > live. Is there much difference between the first and second editions? > And > > also one more book, i haven't ordered it yet, is the "Python from novice > to > > professional" by Magnus Lie Hetland, is it worth ordering and studying > for a > > complete noob? > > I think your local library is a great idea for checking out programming > books! Also, look into the Inter-library loan system for books that might > not be in your library branch. Most libraries can borrow books for you > from another branch within the system, or even from out-of-state. > > Another resource is the local used-book stores. $40-$50 programming > books for $4-$5. They may have some highlighting or underlining, > but that doesn't usually make the content suffer. Often they'll > have the CD or floppy disk in the back cover. > > Finally, if you do find a computer programming book that you > think is the Philosopher's Stone, and you can't live without it, > check all the used-book stores that sell online at: > > http://used.addall.com > > > > > thanks for your answers. > > > > You're welcome. =) > -- > bhaaluu at gmail dot com > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070814/390877d2/attachment-0001.htm From khamid.nurdiev at gmail.com Tue Aug 14 08:23:07 2007 From: khamid.nurdiev at gmail.com (Khamid Nurdiev) Date: Tue, 14 Aug 2007 11:23:07 +0500 Subject: [Tutor] Python Book Recommendations [Was:[Re: Security]] In-Reply-To: <78b3a9580708131846n19dd5b24w620c7508d2d7d769@mail.gmail.com> References: <78b3a9580708131846n19dd5b24w620c7508d2d7d769@mail.gmail.com> Message-ID: I see it now, thanks for the detailed explanation. On 8/14/07, wesley chun wrote: > > > > Having heard > > > the recommendations on books for beginners i have ordered the book > "Core > > > Python Programming" by Wesley Chun, so comparing those two books which > one > > > is more suitable (recommended) for a beginner to both python and > > > programming? > > if you are new to programming, then perhaps Core Python isn't the best > book for you. the target audience is for those who already know how > to program but want to learn Python as quickly and as in-depth as > possible. this is not to say that you cannot benefit from the book as > a newbie, but that it just isn't written directly for you. > > if you are a pure beginner, then: > > - alan's materials work great (the book is somewhat out-of-date but > the tutorial is contemporary): > http://www.freenetpages.co.uk/hp/alan.gauld > > - "how to think like a computer scientist" is also a good choice > http://www.ibiblio.org/obp/thinkCS/python/english2e/html > > - if you have to have a book, then i've heard good things about > dawson's "absolute beginner" book: > http://www.courseptr.com/ptr_detail.cfm?isbn=1-59863-112-8 > > - magnus hetland has TWO online tutorials... the 'instant python' one > is more for programmers but for newbies, you should read the 'instant > hacking' one: > http://hetland.org/writing/instant-hacking.html > > the zelle book is mainly for an undergraduate introduction to computer > science, so if you want to learn programming but not get the "science" > part of it yet, then you also need to look elsewhere. i suspect this > (the CS part) is what begins in chapter 3. :-) > > > > I think your local library is a great idea for checking out programming > > books! Also, look into the Inter-library loan system for books that > might > > not be in your library branch. Most libraries can borrow books for you > > from another branch within the system, or even from out-of-state. > > i second this recommendation. > > > > Another resource is the local used-book stores. $40-$50 programming > > books for $4-$5. They may have some highlighting or underlining, > > but that doesn't usually make the content suffer. Often they'll > > have the CD or floppy disk in the back cover. > > you can also check out http://half.com as well as eBay for popular books. > > hope this helps! > -- wesley > - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - > "Core Python Programming", Prentice Hall, (c)2007,2001 > http://corepython.com > > wesley.j.chun :: wescpy-at-gmail.com > python training and technical consulting > cyberweb.consulting : silicon valley, ca > http://cyberwebconsulting.com > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070814/6ebf8107/attachment.html From khamid.nurdiev at gmail.com Tue Aug 14 08:26:09 2007 From: khamid.nurdiev at gmail.com (Khamid Nurdiev) Date: Tue, 14 Aug 2007 11:26:09 +0500 Subject: [Tutor] Security [Was: Re: Decoding] In-Reply-To: References: <46C06A77.7040803@tds.net> Message-ID: I guess i will start out with your tutorial, hope it won't get as difficult as the previous one :-) thanks On 8/14/07, Alan Gauld wrote: > > > "Khamid Nurdiev" wrote > > > This book by M. Zelle is getting really difficult shortly > > after that section > > I can't comment on the specific book but unfortunately its > a common phenomenon that "beginner" books start of easy > then suddenly get much harder. This is partly because it is > very hard for an experienced programmer to think like a true > beginner, there is just so much we take for granted as obvious. > > > the recommendations on books for beginners i have ordered the book > > "Core > > Python Programming" by Wesley Chun, so comparing those two books > > which one > > is more suitable (recommended) for a beginner to both python and > > programming? > > Wes' book is a very good book on Python, personally I think it might > be quite fast paced and detailed for a beginner to programming but > there are plenty tutorials on the web for that, including mine! :-) > > > Here in our local library, the first edition of "Core python > > programming" > > is available so i guess i will use it till I receive the second > > edition, ... > > . Is there much difference between the first and second editions? > > In the detauil yes but not in the fundamental principles. Especially > the early chapters seem pretty similar. Mind you I've only looked > at the second edition in depth, I've only seen the first edition in > book > stores... > > > also one more book, i haven't ordered it yet, is the "Python from > > novice to > > professional" by Magnus Lie Hetland, is it worth ordering and > > studying for a > > complete noob? > > No idea but you really don't want too many introductory texts, > you will rarely look at them once you learn how to program. > (Wes' book is a good exception since he has a lot of "under the > covers" > stuff about how python works which even experienced pythonistas can > use) > > HTH, > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.freenetpages.co.uk/hp/alan.gauld > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070814/7d750bf0/attachment.htm From timmichelsen at gmx-topmail.de Tue Aug 14 10:54:00 2007 From: timmichelsen at gmx-topmail.de (Tim Michelsen) Date: Tue, 14 Aug 2007 10:54:00 +0200 Subject: [Tutor] FAQ [Was Re: Python Book Recommendations [Was:....]] In-Reply-To: References: Message-ID: Hello, is there a FAQ for this list where we could put all these recommendations? Thanks, Timmie From ms at cerenity.org Tue Aug 14 13:04:41 2007 From: ms at cerenity.org (Michael Sparks) Date: Tue, 14 Aug 2007 12:04:41 +0100 Subject: [Tutor] Security [Was: Re: Decoding] In-Reply-To: <003101c7de12$63454490$bffce004@JSLAPTOP> References: <200708140024.15719.ms@cerenity.org> <003101c7de12$63454490$bffce004@JSLAPTOP> Message-ID: <200708141204.42495.ms@cerenity.org> Tiger12506, You are COMPLETELY missing the point. The __following__ code > >> > foo = raw_input(...) > >> > x = eval(foo) ONLY works if the user has console access to the machine. If they have console access to the machine AND you're worried about them damaging it THEN an eval(raw_input( ...)) construct is the least of your worries. I'm not referring to text taken from * a network connection * a file * a web form * a P2P network I was JUST referring to the ONE context of immediately eval'ing user input. (an unlikely one at that) Where you say this: > But if you parse a text file that you haven't reviewed... that's possible. You're talking about a completely different context. Taking data from a network socket and using eval there is again a different context from above. Using it as a generic data conversion tool is again a different context. In those 3 contexts, yes, anyone would agree that using eval is extremely unwise at best. In the context of evaluating something which someone types at a console though? On Tuesday 14 August 2007 02:28, Tiger12506 wrote: > > On Monday 13 August 2007 22:39, Tiger12506 wrote: > >> > foo = raw_input(...) > >> > x = eval(foo) > > > > ... > > > >> Let your program run on your machine and I'll walk by, type in this > >> string, > >> and hit enter. We'll see how much of an exception it is when you can't > >> boot > >> your XP machine anymore. > >> ;-) > > > > Who cares? I don't run XP :-D > > I'm sure the equivalent can be done on different operating systems. Actually, decent operating systems prevent that sort of problem. A way to trash a linux machine would be to wipe /lib/libc.* on Mac OS X , wipe /usr/lib/libc.dylib . Let's see if it works on a linux machine: >>> file("/lib/libc.so.6","w").close() Traceback (most recent call last): File "", line 1, in IOError: [Errno 13] Permission denied: '/lib/libc.so.6' How about on a Mac OS X machine: >>> file("/usr/lib/libc.dylib", "w").close() Traceback (most recent call last): File "", line 1, in ? IOError: [Errno 13] Permission denied: '/usr/lib/libc.dylib' Yes, of course if I was logged in as root on either it'd work. I could do far more damage far more easily though if I was. > > Seriously though, if typing: > >> "file('boot.ini','w').close()" > > > > Into an "eval prompt" worked then equally leaving a python interpreter > > open > > would be dumb, let alone a console. > > It does work. Try it with a simple file "temp.txt" for example. You can run > any function call if the string is parsed with eval. Notice I did not say > "type into an eval prompt type loop" I mean entirely if the string is > parsed with eval. I know just how powerful eval is. It's damn usefully powerful. You have changed the context here from the context I was talking about. I was stating that *IF* the following can cause damage: > >> > foo = raw_input(...) > >> > x = eval(foo) *AND* you are worried about that damage *BECAUSE* you believe the user is malicious, THEN the above code is the least of your worries. > > Quite frankly anyone getting worried about this: > >> > foo = raw_input(...) > >> > x = eval(foo) > > > > Is pretty over anxious IMO. "Gosh, the person at the console might be > > able to > > get python do something which they can do anyway". > > Again. Anytime the function is parsed with eval, you can run *any* python > function that is in the scope that the eval function is being executed > from. Security risks are never simple. Of course they can do it with a > python console window open. But if you are worried about security you don't > allow them access to the python console. You ecapsulate it. Yes, I know. I was talking solely about a context where they clearly DO have access to the console, and that worrying about this was the least of your worries. It's like saying "you left the door unlocked, you're going to get robbed", when you're missing that the people you're not trusting are inside the house watching the TV & drinking your coffee and you're leaving them there alone. Leaving the doors on a house unlocked is generally unwise when you go out (not least due to invalidating insurance). It's totally irrelevant if you leave it with people in the house you expect to rob you. > But what if you > use eval in a library function you write, which is used to parse some > input? Peer to peer networks, http servers, even text files that you try to > parse could be corrupted to cause your computer damage. These are ALL different contexts from the one I was talking about. None of these example are this context: > >> > foo = raw_input(...) > >> > x = eval(foo) I maintain that this: eval(raw_input(...)) in the vast majority of cases is as safe as letting the user have access to the machine in the first place. Your examples here: > use eval in a library function you write, which is used to parse some > input? Peer to peer networks, http servers, even text files that you try to > parse could be corrupted to cause your computer damage. Are NOT the same as sitting the user down in front of the machine. Therefore eval is a risk. > The point is that eval is a security risk "greater than other > implementations" that is-using int() is much more secure than eval(). It is only a security risk if the data source is untrusted. I maintain that if you put a user down in front of a machine where they can run arbitrary programs, then eval(raw_input( ...)) isn't a big deal. > > (This is rather distinct from taking random crap from someone not on the > > local > > console and just doing it (eg from a network connection/external > > resource)) > > > > If the user wishes to trash their own machine, using an eval prompt is a > > rather bizarre way to go about it. > > Sometimes it's not what they want to do. Kiosks centers are a good example. Yes, I raised that as rare example. However those don't tend to use raw_input. They tend to use a local web browser locked in kiosk mode or custom application. And despite raising that example myself, I've yet to see any kiosk using python's raw_input on a console as an input source so far. Maybe you have odder kiosks where you are. > But if you parse a text file that you haven't reviewed... that's possible. Gosh, another completely different context, wonder if its relevant ;) In case you've missed it: * Rule: eval is for the majority of uses a potentially gaping security hole * Exception proving rule: eval based on user input of a user sitting at the keyboard able to run programs cf code with the form: eval(raw_input( ...)) where that user can run arbitrary programs on the machine. (which they normally would be able to if they can interact with "raw_input"). Code is never a security risk. Code in context almost always has a security risk. The level of risk has to be weighed against other risks. If the user can trash a machine because they're physically preset, what they type in an eval loop is the least of your worries. Michael. From rdm at rcblue.com Tue Aug 14 14:06:41 2007 From: rdm at rcblue.com (Dick Moores) Date: Tue, 14 Aug 2007 05:06:41 -0700 Subject: [Tutor] Graphing the random.gauss distribution Message-ID: <20070814120652.DC1D71E401A@bag.python.org> Kent Johnson posted this to Tutor list Aug 8, 2007 (): ============================================ > Python provides you with a pseudo random number generator whose output > values are uniformly distributed between the input parameters. What you > are dealing with in fish weights or test scores or other natural > phenomena is most likely a normal distribution. Check out Wikipedia's > normal distribution entry. The math is really juicy. You may end up > with a recipe for the Python Cookbook. No need for all that, use random.gauss() Kent ============================================ I hadn't noticed gauss was there in the Random module. I got to wondering if I could graph the distribution. This code produces a nice bell-curve-seeming curve (on its side). Takes about 80 secs to run on my computer. To fit your situation, the length of the bars can be shortened or lengthened by decreasing or increasing, respectively, the divisor of gaussCalls in line 5, "barLengthAdjuster = gaussCalls//2600". Dick Moores ============================== from random import gauss mean = 100 std = 10 gaussCalls = 10000000 barLengthAdjuster = gaussCalls//2600 d = [] for k in range(200): d.append([k, 0]) for k in xrange(gaussCalls): n = int(gauss(mean, std)) d[n][1] += 1 for c in d: barLength = c[1]//barLengthAdjuster print barLength, "=", c[0], c[1] ================================ From kent37 at tds.net Tue Aug 14 14:25:49 2007 From: kent37 at tds.net (Kent Johnson) Date: Tue, 14 Aug 2007 08:25:49 -0400 Subject: [Tutor] FAQ [Was Re: Python Book Recommendations [Was:....]] In-Reply-To: References: Message-ID: <46C19F4D.1000603@tds.net> Tim Michelsen wrote: > Hello, > is there a FAQ for this list Sort of: http://effbot.org/pyfaq/tutor-index.htm > where we could put all these recommendations? A better place is perhaps the Python wiki which is editable: http://wiki.python.org/moin/PythonBooks http://wiki.python.org/moin/BeginnersGuide/NonProgrammers http://wiki.python.org/moin/BeginnersGuide/Programmers Kent From duncan at thermal.esa.int Tue Aug 14 15:40:09 2007 From: duncan at thermal.esa.int (Duncan Gibson) Date: Tue, 14 Aug 2007 15:40:09 +0200 Subject: [Tutor] converting a source package into a dll/shared library? Message-ID: <20070814154009.76b9ce57.duncan@thermal.esa.int> Is it possible to convert a Python package, with __init__.py and related python modules, into a single DLL or shared library that can be imported in the same way? We have used py2exe and cx_freeze to create a complete executable, but we are curious whether there is a middle way between this single executable and distributing all of the source files. I've been searching the documentation and web but haven't yet found the magic combination of keywords that throws up what we want. Does such a possibility exist? If yes, can someone provide me a pointer? The Background: We have developed a demonstration tool in Python that parses input data for ToolA written by CompanyA, converts to our own internal neutral format, and can write in CompanyB's ToolB format. Now that the proof of concept has been shown, the companies want to integrate the conversion directly in their tools, but providing the code for ToolA to CompanyB raises some issues, and similarly the other way. Providing a DLL of the ToolA reader to CompanyB, and a DLL of the ToolB writer to CompanyA might be one way around these issues, but it's not clear whether this is easy to achieve. Cheers Duncan From kent37 at tds.net Tue Aug 14 15:47:07 2007 From: kent37 at tds.net (Kent Johnson) Date: Tue, 14 Aug 2007 09:47:07 -0400 Subject: [Tutor] Graphing the random.gauss distribution In-Reply-To: <20070814120652.DC1D71E401A@bag.python.org> References: <20070814120652.DC1D71E401A@bag.python.org> Message-ID: <46C1B25B.10307@tds.net> Dick Moores wrote: > Kent Johnson posted this to Tutor list Aug 8, 2007 > (): > > ============================================ > > Python provides you with a pseudo random number generator whose output > > values are uniformly distributed between the input parameters. What you > > are dealing with in fish weights or test scores or other natural > > phenomena is most likely a normal distribution. Check out Wikipedia's > > normal distribution entry. The math is really juicy. You may end up > > with a recipe for the Python Cookbook. > > No need for all that, use random.gauss() > > Kent > ============================================ > > I hadn't noticed gauss was there in the Random module. I got to > wondering if I could graph the distribution. This code produces a > nice bell-curve-seeming curve (on its side). Takes about 80 secs to > run on my computer. To fit your situation, the length of the bars can > be shortened or lengthened by decreasing or increasing, respectively, > the divisor of gaussCalls in line 5, "barLengthAdjuster = gaussCalls//2600". > > Dick Moores > > ============================== > from random import gauss > mean = 100 > std = 10 > gaussCalls = 10000000 > barLengthAdjuster = gaussCalls//2600 > > d = [] > for k in range(200): > d.append([k, 0]) This could be a list comprehension: d = [ [k, 0] for k in range(200) ] but there is no need to keep the array index in the array so this is simpler: d = [0] * 200 > for k in xrange(gaussCalls): > n = int(gauss(mean, std)) > d[n][1] += 1 This becomes just d[n] += 1 > > for c in d: > barLength = c[1]//barLengthAdjuster > print barLength, "=", c[0], c[1] Use enumerate() to get the indices as well as the list contents. This version prints an actual bar as well: for i, count in enumerate(d): barLength = count//barLengthAdjuster print i, '*' * barLength, count Kent From kent37 at tds.net Tue Aug 14 16:51:11 2007 From: kent37 at tds.net (Kent Johnson) Date: Tue, 14 Aug 2007 10:51:11 -0400 Subject: [Tutor] converting a source package into a dll/shared library? In-Reply-To: <20070814154009.76b9ce57.duncan@thermal.esa.int> References: <20070814154009.76b9ce57.duncan@thermal.esa.int> Message-ID: <46C1C15F.7060308@tds.net> Duncan Gibson wrote: > Is it possible to convert a Python package, with __init__.py and > related python modules, into a single DLL or shared library that can > be imported in the same way? > We have used py2exe and cx_freeze to create a complete executable, > but we are curious whether there is a middle way between this single > executable and distributing all of the source files. You can get a modest degree of obscurity by distributing the .pyc bytecode files instead of the .py source. These can still be decompiled and reverse engineered but it is more effort. I suppose you could rewrite some or all of the code into the Python dialect supported by Pyrex and compile it that way. Pyrex is "a language specially designed for writing Python extension modules." The docs say "Almost any piece of Python code is also valid Pyrex code." So it might not be too hard to compile your Python source into an extension module using Pyrex. http://www.cosc.canterbury.ac.nz/greg.ewing/python/Pyrex/ Kent From brunson at brunson.com Tue Aug 14 17:48:09 2007 From: brunson at brunson.com (Eric Brunson) Date: Tue, 14 Aug 2007 09:48:09 -0600 Subject: [Tutor] Security [Was: Re: Decoding] In-Reply-To: <200708141204.42495.ms@cerenity.org> References: <200708140024.15719.ms@cerenity.org> <003101c7de12$63454490$bffce004@JSLAPTOP> <200708141204.42495.ms@cerenity.org> Message-ID: <46C1CEB9.1020309@brunson.com> Michael Sparks wrote: > Tiger12506, > > > You are COMPLETELY missing the point. The __following__ code > > >>>>> foo = raw_input(...) >>>>> x = eval(foo) >>>>> > > ONLY works if the user has console access to the machine. > > If they have console access to the machine > AND you're worried about them damaging it > THEN an eval(raw_input( ...)) construct is the least of your worries. > > I'm not referring to text taken from > * a network connection > * a file > * a web form > * a P2P network > > I was JUST referring to the ONE context of immediately eval'ing user input. > (an unlikely one at that) > No, I think you're missing the point. If the program was not interacting with the user through the console, then why would you be using raw_input()? raw_input() is used to get user input from the controlling terminal. Am I missing some other use for raw_input()? Using eval() on untrusted input of any kind is a security risk. Reading the rest of your email, I get the feeling that what you're saying is: if a user has access to "the console", then using eval( raw_input() ) is the least of your worries because the person can do anything they want. Is that your assertion? If it is, then it's an invalid argument. raw_input() is not only useful on "the console", it can be used to interact with any terminal and can be done securely so that exiting the program is either impossible, or restarts the program or else simply disconnects from the terminal and leaves the user with no access at all. The only thing I can imagine is that you're stuck in some DOS mindset that if you're able to type into "the console" then you have ultimate access to the machine, which is not the case when using a true multi-user operating system like *nix or VMS. But, most strange to me is why you're this fired up over such a simple issue. It seems to me like just a misunderstanding. From brunson at brunson.com Tue Aug 14 17:48:46 2007 From: brunson at brunson.com (Eric Brunson) Date: Tue, 14 Aug 2007 09:48:46 -0600 Subject: [Tutor] Security [Was: Re: Decoding] In-Reply-To: <200708132255.46883.ms@cerenity.org> References: <200708131746.57338.ms@cerenity.org> <46C0C4BC.1000402@tds.net> <200708132255.46883.ms@cerenity.org> Message-ID: <46C1CEDE.6050801@brunson.com> Michael Sparks wrote: > On Monday 13 August 2007 21:53, Kent Johnson wrote: > >> Hmm...could be a remote connection such as ssh, which precludes the >> sledgehammer though probably not the sort of mischief you can get into >> with eval()...perhaps there are untrusted remote connections where >> eval() would still be a significant risk, I don't know... >> > > If they can ssh into a box, the likelihood of that ssh connection *only* > allowing them access to run that single python program strikes me as > vanishingly small :-) > Unless you set it up that way specifically, i.e. making the interactive python program their login shell or specifying it to be run in their .ssh/config. > Generally speaking I agree that eval is a good opportunity for problems, but > if its in response to raw_input, I think the likelihood of it being the > biggest potential security problem is low :) > > (After all, if they're ssh'ing in, they're more likely to ssh in, *then* run > the code. They could happily delete and trash all sorts of things either > inside or outside python. They could even write their own scripts to assist > them in their devilish plans too, far exceeding the minor demon of eval ;-) > > Eval can however be an amazingly useful function, especially when combined > with exec. > > > Michael. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From humbolt at comcast.net Tue Aug 14 17:59:46 2007 From: humbolt at comcast.net (Robert H. Haener IV) Date: Tue, 14 Aug 2007 11:59:46 -0400 Subject: [Tutor] Python Book Recommendations [Was:[Re: Security]] In-Reply-To: <78b3a9580708131846n19dd5b24w620c7508d2d7d769@mail.gmail.com> References: <78b3a9580708131846n19dd5b24w620c7508d2d7d769@mail.gmail.com> Message-ID: <46C1D172.5040208@comcast.net> wesley chun wrote: >> Another resource is the local used-book stores. $40-$50 programming >> books for $4-$5. They may have some highlighting or underlining, >> but that doesn't usually make the content suffer. Often they'll >> have the CD or floppy disk in the back cover. > > you can also check out http://half.com as well as eBay for popular books. When I was putting together my "To Buy" list of Python books, I came across an online store with some great prices on new books. On my list, the discounts were $15 to $20 off of the direct price from the publisher (not counting $3 off Python Pocket Reference); their address is: http://www.bookpool.com I have yet to do business with them, but their 6 Month Rating on Reseller Ratings is 10/10 and their Lifetime Rating is 9.02/10. I feel I should also note that the discounts I mentioned were for the latest edition of each book on my list. -Robert From brunson at brunson.com Tue Aug 14 18:02:42 2007 From: brunson at brunson.com (Eric Brunson) Date: Tue, 14 Aug 2007 10:02:42 -0600 Subject: [Tutor] Security [Was: Re: Decoding] In-Reply-To: <200708132255.46883.ms@cerenity.org> References: <200708131746.57338.ms@cerenity.org> <46C0C4BC.1000402@tds.net> <200708132255.46883.ms@cerenity.org> Message-ID: <46C1D222.2070007@brunson.com> Michael Sparks wrote: > On Monday 13 August 2007 21:53, Kent Johnson wrote: > >> Hmm...could be a remote connection such as ssh, which precludes the >> sledgehammer though probably not the sort of mischief you can get into >> with eval()...perhaps there are untrusted remote connections where >> eval() would still be a significant risk, I don't know... >> > > If they can ssh into a box, the likelihood of that ssh connection *only* > allowing them access to run that single python program strikes me as > vanishingly small :-) > > Unless you set it up that way specifically, i.e. making the interactive python program their login shell or specifying it to be run in their .ssh/config. P.S. Michael, sorry for the double post to you, I missed the "reply all" button the first time. > Generally speaking I agree that eval is a good opportunity for problems, but > if its in response to raw_input, I think the likelihood of it being the > biggest potential security problem is low :) > > (After all, if they're ssh'ing in, they're more likely to ssh in, *then* run > the code. They could happily delete and trash all sorts of things either > inside or outside python. They could even write their own scripts to assist > them in their devilish plans too, far exceeding the minor demon of eval ;-) > > Eval can however be an amazingly useful function, especially when combined > with exec. > > > Michael. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at btinternet.com Tue Aug 14 18:03:49 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 14 Aug 2007 17:03:49 +0100 Subject: [Tutor] Security [Was: Re: Decoding] References: <200708140024.15719.ms@cerenity.org><003101c7de12$63454490$bffce004@JSLAPTOP> <200708141204.42495.ms@cerenity.org> Message-ID: "Michael Sparks" wrote > You are COMPLETELY missing the point. The __following__ code > >> >> > foo = raw_input(...) >> >> > x = eval(foo) > > ONLY works if the user has console access to the machine. Actually no. It applies to stdin which could be a console or a file. I agree that raw_input is *usually* applicable to a console but $ python myscript.py < mydirtydata.txt will leave me open to all sorts of vulnerabilities. And if the python script is embedded within a shell script then this scenario becomes quite common and a valid security threat. Regards, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Tue Aug 14 18:05:58 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 14 Aug 2007 17:05:58 +0100 Subject: [Tutor] FAQ [Was Re: Python Book Recommendations [Was:....]] References: Message-ID: "Tim Michelsen" wrote > is there a FAQ for this list where we could put all these > recommendations? Someone (Mike Hansen?) started one a while back, but like most such ventures the trick is in maintaining it! I'm not sure where it is or what the status is. Alan G From alan.gauld at btinternet.com Tue Aug 14 18:15:32 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 14 Aug 2007 17:15:32 +0100 Subject: [Tutor] converting a source package into a dll/shared library? References: <20070814154009.76b9ce57.duncan@thermal.esa.int> Message-ID: "Duncan Gibson" wrote > Is it possible to convert a Python package, with __init__.py and > related python modules, into a single DLL or shared library that can > be imported in the same way? Since you refer to DLLs I'll assume a Windoze platform. If so the answer is yes you can create an ActiveX/COM object. So if its accessibility to non Python code you are interested in grab a copy of Mark Hammonds Win32 book for details and examples. You can even go DCOM if thats significant. OTOH If its code obfuscation that worries you then Kent's suggestion of distributing the .pyc files is probably the best you can do. (Gordon MacMillan's installer may be able to build DLLs I'm not sure...) HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From rdm at rcblue.com Tue Aug 14 18:29:48 2007 From: rdm at rcblue.com (Dick Moores) Date: Tue, 14 Aug 2007 09:29:48 -0700 Subject: [Tutor] Graphing the random.gauss distribution In-Reply-To: <46C1B25B.10307@tds.net> References: <20070814120652.DC1D71E401A@bag.python.org> <46C1B25B.10307@tds.net> Message-ID: <20070814163130.10BAD1E4012@bag.python.org> At 06:47 AM 8/14/2007, Kent Johnson wrote: >Dick Moores wrote: > > Kent Johnson posted this to Tutor list Aug 8, 2007 > > (): > > > > ============================================ > > > Python provides you with a pseudo random number generator whose output > > > values are uniformly distributed between the input parameters. What you > > > are dealing with in fish weights or test scores or other natural > > > phenomena is most likely a normal distribution. Check out Wikipedia's > > > normal distribution entry. The math is really juicy. You may end up > > > with a recipe for the Python Cookbook. > > > > No need for all that, use random.gauss() > > > > Kent > > ============================================ > > > > I hadn't noticed gauss was there in the Random module. I got to > > wondering if I could graph the distribution. This code produces a > > nice bell-curve-seeming curve (on its side). Takes about 80 secs to > > run on my computer. To fit your situation, the length of the bars can > > be shortened or lengthened by decreasing or increasing, respectively, > > the divisor of gaussCalls in line 5, "barLengthAdjuster = > gaussCalls//2600". > > > > Dick Moores > > > > ============================== > > from random import gauss > > mean = 100 > > std = 10 > > gaussCalls = 10000000 > > barLengthAdjuster = gaussCalls//2600 > > > > d = [] > > for k in range(200): > > d.append([k, 0]) > >This could be a list comprehension: >d = [ [k, 0] for k in range(200) ] So you recommend using list comprehensions wherever possible? (I sure wouldn't have thought of that one..) >but there is no need to keep the array index in the array so this is >simpler: > >d = [0] * 200 > > > for k in xrange(gaussCalls): > > n = int(gauss(mean, std)) > > d[n][1] += 1 > >This becomes just > d[n] += 1 > > > > > for c in d: > > barLength = c[1]//barLengthAdjuster > > print barLength, "=", c[0], c[1] By the time my code got into my post, I had changed "print barLength * "=", c[0], c[1]" to "print barLength, "=", c[0], c[1]", thinking upon reading it over that the "*" was a mistake. :-( The code I didn't send DID make bars out of "="s. >Use enumerate() to get the indices as well as the list contents. This >version prints an actual bar as well: >for i, count in enumerate(d): > barLength = count//barLengthAdjuster > print i, '*' * barLength, count Ah, enumerate() is nice! I'd forgotten about it. And "*" IS better for bars than "=". I prefer the index (or integer) to come after the bar ends, and before the count. One reason is that if the index is at the base of the bar, at 100 and above, the bars get pushed out one character longer than they should be relative to the 99 or less bars. I suppose there's a way to handle this, but I couldn't think of it then (but see below). So this is my code now: ==================================== from random import gauss mean = 100 std = 10 gaussCalls =1000000 barLengthAdjuster = gaussCalls//2600 d = [0] * 200 for k in xrange(gaussCalls): n = int(gauss(mean, std)) d[n] += 1 for i, count in enumerate(d): barLength = count//barLengthAdjuster print '*' * barLength, i, count ===================================== This would solve the problem I mentioned above caused by putting the indices at the bases of the bars: for i, count in enumerate(d): barLength = count//barLengthAdjuster if i < 100: print "%d %s %d" % (i, '*' * barLength, count) # there are 2 spaces between %d and %s else: print "%d %s %d" % (i, '*' * barLength, count) Thanks very much, Kent, for taking the time to advise me on my code. Dick From rabidpoobear at gmail.com Tue Aug 14 18:44:37 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Tue, 14 Aug 2007 11:44:37 -0500 Subject: [Tutor] Security [Was: Re: Decoding] In-Reply-To: <46C1D222.2070007@brunson.com> References: <200708131746.57338.ms@cerenity.org> <46C0C4BC.1000402@tds.net> <200708132255.46883.ms@cerenity.org> <46C1D222.2070007@brunson.com> Message-ID: <46C1DBF5.9060803@gmail.com> Eric Brunson wrote: > Michael Sparks wrote: > >> On Monday 13 August 2007 21:53, Kent Johnson wrote: >> >> >>> Hmm...could be a remote connection such as ssh, which precludes the >>> sledgehammer though probably not the sort of mischief you can get into >>> with eval()...perhaps there are untrusted remote connections where >>> eval() would still be a significant risk, I don't know... >>> >>> >> If they can ssh into a box, the likelihood of that ssh connection *only* >> allowing them access to run that single python program strikes me as >> vanishingly small :-) >> >> >> > > Unless you set it up that way specifically, i.e. making the interactive > python program their login shell or specifying it to be run in their > .ssh/config. > > > P.S. > Michael, sorry for the double post to you, I missed the "reply all" > button the first time. > I don't think you missed on account of me receiving two e-mails as well. :) -Luke From brunson at brunson.com Tue Aug 14 18:46:47 2007 From: brunson at brunson.com (Eric Brunson) Date: Tue, 14 Aug 2007 10:46:47 -0600 Subject: [Tutor] Security [Was: Re: Decoding] In-Reply-To: <46C1DBF5.9060803@gmail.com> References: <200708131746.57338.ms@cerenity.org> <46C0C4BC.1000402@tds.net> <200708132255.46883.ms@cerenity.org> <46C1D222.2070007@brunson.com> <46C1DBF5.9060803@gmail.com> Message-ID: <46C1DC77.9010603@brunson.com> Luke Paireepinart wrote: > Eric Brunson wrote: >> Michael Sparks wrote: >> >>> On Monday 13 August 2007 21:53, Kent Johnson wrote: >>> >>>> Hmm...could be a remote connection such as ssh, which precludes the >>>> sledgehammer though probably not the sort of mischief you can get into >>>> with eval()...perhaps there are untrusted remote connections where >>>> eval() would still be a significant risk, I don't know... >>>> >>> If they can ssh into a box, the likelihood of that ssh connection >>> *only* allowing them access to run that single python program >>> strikes me as vanishingly small :-) >>> >>> >> >> Unless you set it up that way specifically, i.e. making the >> interactive python program their login shell or specifying it to be >> run in their .ssh/config. >> >> >> P.S. >> Michael, sorry for the double post to you, I missed the "reply all" >> button the first time. >> > I don't think you missed on account of me receiving two e-mails as > well. :) > -Luke Python: easy Email: hard ;-) From rabidpoobear at gmail.com Tue Aug 14 19:00:43 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Tue, 14 Aug 2007 12:00:43 -0500 Subject: [Tutor] Graphing the random.gauss distribution In-Reply-To: <20070814163130.10BAD1E4012@bag.python.org> References: <20070814120652.DC1D71E401A@bag.python.org> <46C1B25B.10307@tds.net> <20070814163130.10BAD1E4012@bag.python.org> Message-ID: <46C1DFBB.8090406@gmail.com> >> This could be a list comprehension: >> d = [ [k, 0] for k in range(200) ] >> > > So you recommend using list comprehensions wherever possible? (I sure > wouldn't have thought of that one..) > No, of course not! "wherever possible" would include [foo(25) for x in range(300)] in order to call foo 300 times. This is obviously a bad idea. Basically you use a list comprehension when you're building a list in a simple way. If it's more clear as a for loop, write it as a for loop. It's up to your consideration if the situation would benefit in readability from a list comp. >> but there is no need to keep the array index in the array so this is >> simpler: >> >> d = [0] * 200 >> >> >>> for k in xrange(gaussCalls): >>> n = int(gauss(mean, std)) >>> d[n][1] += 1 >>> >> This becomes just >> d[n] += 1 >> >> >>> for c in d: >>> barLength = c[1]//barLengthAdjuster >>> print barLength, "=", c[0], c[1] >>> > > By the time my code got into my post, I had changed "print barLength > * "=", c[0], c[1]" to "print barLength, "=", c[0], c[1]", thinking > upon reading it over that the "*" was a mistake. :-( The code I > didn't send DID make bars out of "="s. > Sure it did ;) >> Use enumerate() to get the indices as well as the list contents. This >> version prints an actual bar as well: >> for i, count in enumerate(d): >> barLength = count//barLengthAdjuster >> print i, '*' * barLength, count >> > > Ah, enumerate() is nice! I'd forgotten about it. And "*" IS better > for bars than "=". > > I prefer the index (or integer) to come after the bar ends, and > before the count. One reason is that if the index is at the base of > the bar, at 100 and above, the bars get pushed out one character > longer than they should be relative to the 99 or less bars. I suppose > there's a way to handle this, but I couldn't think of it then (but see below). > well, you already answered this yourself. > So this is my code now: > > ==================================== > from random import gauss > mean = 100 > std = 10 > gaussCalls =1000000 > barLengthAdjuster = gaussCalls//2600 > > d = [0] * 200 > > for k in xrange(gaussCalls): > n = int(gauss(mean, std)) > d[n] += 1 > > for i, count in enumerate(d): > barLength = count//barLengthAdjuster > print '*' * barLength, i, count > ===================================== > > This would solve the problem I mentioned above caused by putting the > indices at the bases of the bars: > > for i, count in enumerate(d): > barLength = count//barLengthAdjuster > if i < 100: > print "%d %s %d" % (i, '*' * barLength, count) # there are > 2 spaces between %d and %s > else: > print "%d %s %d" % (i, '*' * barLength, count) > > Thanks very much, Kent, for taking the time to advise me on my code. > > Dick > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From wescpy at gmail.com Tue Aug 14 19:27:00 2007 From: wescpy at gmail.com (wesley chun) Date: Tue, 14 Aug 2007 10:27:00 -0700 Subject: [Tutor] Python Book Recommendations [Was:[Re: Security]] In-Reply-To: <46C1D172.5040208@comcast.net> References: <78b3a9580708131846n19dd5b24w620c7508d2d7d769@mail.gmail.com> <46C1D172.5040208@comcast.net> Message-ID: <78b3a9580708141027g2ad8ff23pc6328cb52203f52b@mail.gmail.com> On 8/14/07, Robert H. Haener IV wrote: > When I was putting together my "To Buy" list of Python books, I came across an online store with some great prices on new books. [...]; their address is: http://www.bookpool.com > > [...] their 6 Month Rating on Reseller Ratings is 10/10 and their Lifetime Rating is 9.02/10. I feel I should also note that the discounts I mentioned were for the latest edition of each book on my list. robert, yes, this is a well-known bookstore, as seen lately by the post (and ensuing thread) from the past few days: http://mail.python.org/pipermail/tutor/2007-August/056230.html many technical people i know shop for their books there, including myself... they are usually less than Amazon. i'm not surprised by their high ratings. cheers, -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From kent37 at tds.net Tue Aug 14 19:28:34 2007 From: kent37 at tds.net (Kent Johnson) Date: Tue, 14 Aug 2007 13:28:34 -0400 Subject: [Tutor] Graphing the random.gauss distribution In-Reply-To: <20070814163127.JLYS3884.inaamta14.mail.tds.net@sccrmhc13.comcast.net> References: <20070814120652.DC1D71E401A@bag.python.org> <46C1B25B.10307@tds.net> <20070814163127.JLYS3884.inaamta14.mail.tds.net@sccrmhc13.comcast.net> Message-ID: <46C1E642.2040000@tds.net> Dick Moores wrote: > At 06:47 AM 8/14/2007, Kent Johnson wrote: >> This could be a list comprehension: >> d = [ [k, 0] for k in range(200) ] > > So you recommend using list comprehensions wherever possible? (I sure > wouldn't have thought of that one..) Not "whenever possible", no, but I find simple list comps (I count this one as simple) to be far more readable than the equivalent loop. Not only are they shorter but they read the way I think. If the list comp can't be easily written on one line, or has a complex condition, or has two for clauses, I find it less appealing and may write it as a for loop. I never use a list comp just for the side-effects; only when I actually want the list. > I prefer the index (or integer) to come after the bar ends, and before > the count. One reason is that if the index is at the base of the bar, at > 100 and above, the bars get pushed out one character longer than they > should be relative to the 99 or less bars. I suppose there's a way to > handle this, but I couldn't think of it then (but see below). Use string formatting or str.rjust(): In [1]: '%3d' % 10 Out[1]: ' 10' In [2]: '%3d' % 100 Out[2]: '100' In [4]: str(10).rjust(3) Out[4]: ' 10' > This would solve the problem I mentioned above caused by putting the > indices at the bases of the bars: > > for i, count in enumerate(d): > barLength = count//barLengthAdjuster > if i < 100: > print "%d %s %d" % (i, '*' * barLength, count) # there are 2 > spaces between %d and %s > else: > print "%d %s %d" % (i, '*' * barLength, count) Ouch. See above. Kent From rdm at rcblue.com Tue Aug 14 20:06:05 2007 From: rdm at rcblue.com (Dick Moores) Date: Tue, 14 Aug 2007 11:06:05 -0700 Subject: [Tutor] Question re Tutor List Etiquette Message-ID: <20070814180639.E639C1E4011@bag.python.org> When sending a reply to a post, to the list, should we also address the reply to the author of the post to which we are replying? (There's gotta be an easier way to say that..) If we do so, then the author gets a duplicate of our reply. I've run some statistics (but no more bar graphs ;-) ). My Eudora mailbox for Tutor contains 12,114 emails (I've deleted the duplicates I've received). Of these, 9,424 are replies. Of these replies, 4,338 (46%) were addressed ONLY to the list. So 54% WERE also sent to the author being replied to. Is there a rule about this? Or should one be made? Or does it matter? Replying only to the list takes a bit of trouble. The default behavior seems to be that the "Reply" button addresses the author only and not the list; "Reply to all" addresses both the list, the author, and any others included in the To: or Cc: headers of the post being replied to. Or at least that's how Eudora and Gmail work. Ten years ago or so I managed a Majordomo list, and I recall that it was possible for the list manager to configure the list to include a "Reply-To" header. If this would be possible for the admins to do with Tutor -- to include a "Reply-To: tutor at python.org" header in the posts sent out by the list, it would enable us to address a reply only to the list by hitting the "Reply" button. Dick Moores From rabidpoobear at gmail.com Tue Aug 14 20:37:46 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Tue, 14 Aug 2007 13:37:46 -0500 Subject: [Tutor] Question re Tutor List Etiquette In-Reply-To: <20070814180639.E639C1E4011@bag.python.org> References: <20070814180639.E639C1E4011@bag.python.org> Message-ID: <46C1F67A.8040805@gmail.com> Dick Moores wrote: > When sending a reply to a post, to the list, should we also address > the reply to the author of the post to which we are replying? > (There's gotta be an easier way to say that..) If we do so, then the > author gets a duplicate of our reply. > > I've run some statistics (but no more bar graphs ;-) ). My Eudora > mailbox for Tutor contains 12,114 emails (I've deleted the duplicates > I've received). Of these, 9,424 are replies. Of these replies, 4,338 > (46%) were addressed ONLY to the list. So 54% WERE also sent to the > author being replied to. > > Is there a rule about this? Or should one be made? Or does it matter? > > Replying only to the list takes a bit of trouble. The default > behavior seems to be that the "Reply" button addresses the author > only and not the list; "Reply to all" addresses both the list, the > author, and any others included in the To: or Cc: headers of the post > being replied to. Or at least that's how Eudora and Gmail work. > > Ten years ago or so I managed a Majordomo list, and I recall that it > was possible for the list manager to configure the list to include a > "Reply-To" header. If this would be possible for the admins to do > with Tutor -- to include a "Reply-To: tutor at python.org" header in the > posts sent out by the list, it would enable us to address a reply > only to the list by hitting the "Reply" button. > I don't get duplicates _ever_. -Luke From brunson at brunson.com Tue Aug 14 20:38:38 2007 From: brunson at brunson.com (Eric Brunson) Date: Tue, 14 Aug 2007 12:38:38 -0600 Subject: [Tutor] Question re Tutor List Etiquette In-Reply-To: <20070814180639.E639C1E4011@bag.python.org> References: <20070814180639.E639C1E4011@bag.python.org> Message-ID: <46C1F6AE.7050000@brunson.com> Dick Moores wrote: > When sending a reply to a post, to the list, should we also address > the reply to the author of the post to which we are replying? > (There's gotta be an easier way to say that..) If we do so, then the > author gets a duplicate of our reply. > > I've run some statistics (but no more bar graphs ;-) ). My Eudora > mailbox for Tutor contains 12,114 emails (I've deleted the duplicates > I've received). Of these, 9,424 are replies. Of these replies, 4,338 > (46%) were addressed ONLY to the list. So 54% WERE also sent to the > author being replied to. > > Is there a rule about this? Or should one be made? Or does it matter? > > Replying only to the list takes a bit of trouble. The default > behavior seems to be that the "Reply" button addresses the author > only and not the list; "Reply to all" addresses both the list, the > author, and any others included in the To: or Cc: headers of the post > being replied to. Or at least that's how Eudora and Gmail work. > > Ten years ago or so I managed a Majordomo list, and I recall that it > was possible for the list manager to configure the list to include a > "Reply-To" header. If this would be possible for the admins to do > with Tutor -- to include a "Reply-To: tutor at python.org" header in the > posts sent out by the list, it would enable us to address a reply > only to the list by hitting the "Reply" button. > If you search those 12,114 emails you'll find a discussion of this from about 6 weeks ago. Consensus was split, so the list manager chose to leave the policy unchanged. > Dick Moores > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Tue Aug 14 20:56:22 2007 From: kent37 at tds.net (Kent Johnson) Date: Tue, 14 Aug 2007 14:56:22 -0400 Subject: [Tutor] Question re Tutor List Etiquette In-Reply-To: <20070814180639.E639C1E4011@bag.python.org> References: <20070814180639.E639C1E4011@bag.python.org> Message-ID: <46C1FAD6.3000301@tds.net> Dick Moores wrote: > When sending a reply to a post, to the list, should we also address > the reply to the author of the post to which we are replying? > (There's gotta be an easier way to say that..) If we do so, then the > author gets a duplicate of our reply. This is configurable for each subscriber. Go to the tutor web page at http://mail.python.org/mailman/listinfo/tutor Enter your subscription email at the bottom where it says, "To unsubscribe from Tutor, get a password reminder, or change your subscription options enter your subscription email address:" Set "Avoid duplicate copies of messages?" to Yes. > Ten years ago or so I managed a Majordomo list, and I recall that it > was possible for the list manager to configure the list to include a > "Reply-To" header. If this would be possible for the admins to do > with Tutor -- to include a "Reply-To: tutor at python.org" header in the > posts sent out by the list, it would enable us to address a reply > only to the list by hitting the "Reply" button. Surely you have been reading the list long enough to know that this comes up every three months as a topic! It's not going to change. I'm not going to discuss it (and I hope no one else will either). Search the archives if you want to see previous discussions. Kent From rdm at rcblue.com Tue Aug 14 21:10:40 2007 From: rdm at rcblue.com (Dick Moores) Date: Tue, 14 Aug 2007 12:10:40 -0700 Subject: [Tutor] Graphing the random.gauss distribution In-Reply-To: <46C1E642.2040000@tds.net> References: <20070814120652.DC1D71E401A@bag.python.org> <46C1B25B.10307@tds.net> <20070814163127.JLYS3884.inaamta14.mail.tds.net@sccrmhc13.comcast.net> <46C1E642.2040000@tds.net> Message-ID: <20070814191111.43E001E4008@bag.python.org> At 10:28 AM 8/14/2007, you wrote: >Dick Moores wrote: > > At 06:47 AM 8/14/2007, Kent Johnson wrote: > >> This could be a list comprehension: > >> d = [ [k, 0] for k in range(200) ] > > > > So you recommend using list comprehensions wherever possible? (I sure > > wouldn't have thought of that one..) > >Not "whenever possible", no, but I find simple list comps (I count this >one as simple) to be far more readable than the equivalent loop. Not >only are they shorter but they read the way I think. > >If the list comp can't be easily written on one line, or has a complex >condition, or has two for clauses, I find it less appealing and may >write it as a for loop. I never use a list comp just for the >side-effects; only when I actually want the list. Got it. > > I prefer the index (or integer) to come after the bar ends, and before > > the count. One reason is that if the index is at the base of the bar, at > > 100 and above, the bars get pushed out one character longer than they > > should be relative to the 99 or less bars. I suppose there's a way to > > handle this, but I couldn't think of it then (but see below). > >Use string formatting or str.rjust(): >In [1]: '%3d' % 10 >Out[1]: ' 10' >In [2]: '%3d' % 100 >Out[2]: '100' >In [4]: str(10).rjust(3) >Out[4]: ' 10' So: for i, count in enumerate(d): barLength = count//barLengthAdjuster print "%3d %s %d" % (i, '*' * barLength, count) Or: for i, count in enumerate(d): barLength = count//barLengthAdjuster print str(i).rjust(3), '*' * barLength, count Right? (Anyway, they work!) Terrific! Two ways! > > This would solve the problem I mentioned above caused by putting the > > indices at the bases of the bars: > > > > for i, count in enumerate(d): > > barLength = count//barLengthAdjuster > > if i < 100: > > print "%d %s %d" % (i, '*' * barLength, count) # there are 2 > > spaces between %d and %s > > else: > > print "%d %s %d" % (i, '*' * barLength, count) > >Ouch. See above. Ouch? No like? (I know, your 2 ways are both easier.) Thanks much again, Kent. Dick From tomfitzyuk at gmail.com Tue Aug 14 21:11:33 2007 From: tomfitzyuk at gmail.com (Tom Fitzhenry) Date: Tue, 14 Aug 2007 20:11:33 +0100 Subject: [Tutor] Question re Tutor List Etiquette In-Reply-To: <20070814180639.E639C1E4011@bag.python.org> References: <20070814180639.E639C1E4011@bag.python.org> Message-ID: <20070814191133.GA4084@desktop> On Tue, Aug 14, 2007 at 11:06:05AM -0700, Dick Moores wrote: > Replying only to the list takes a bit of trouble. The default > behavior seems to be that the "Reply" button addresses the author > only and not the list; "Reply to all" addresses both the list, the > author, and any others included in the To: or Cc: headers of the post > being replied to. Or at least that's how Eudora and Gmail work. > > Ten years ago or so I managed a Majordomo list, and I recall that it > was possible for the list manager to configure the list to include a > "Reply-To" header. If this would be possible for the admins to do > with Tutor -- to include a "Reply-To: tutor at python.org" header in the > posts sent out by the list, it would enable us to address a reply > only to the list by hitting the "Reply" button. Mutt can be configured to recognize which emails are from a mailing list and provides a list-reply command which only replies to the list. http://www.mutt.org/doc/manual/manual-3.html#ss3.9 I've read Thunderbird have been planning a list-reply button, but could only find information on a plugin (and patch) which does this at the moment: http://alumnit.ca/wiki/index.php?page=ReplyToListThunderbirdExtension#toc3 About other mail clients, I don't know. Procmail can be configured to detect these duplicates and filter/delete/forward/etc. them: http://linuxbrit.co.uk/procmail/ (7th paragraph, "Now, here's a really useful rule, ...") I don't post that often so I don't get this that often, so it doesn't bother me that much, but I could see how it'd be annoying to those who post frequently. -- Tom Fitzhenry From rdm at rcblue.com Tue Aug 14 21:33:16 2007 From: rdm at rcblue.com (Dick Moores) Date: Tue, 14 Aug 2007 12:33:16 -0700 Subject: [Tutor] Question re Tutor List Etiquette In-Reply-To: <46C1FAD6.3000301@tds.net> References: <20070814180639.E639C1E4011@bag.python.org> <46C1FAD6.3000301@tds.net> Message-ID: <20070814193330.C34D01E401A@bag.python.org> At 11:56 AM 8/14/2007, Kent Johnson wrote: >Dick Moores wrote: > > When sending a reply to a post, to the list, should we also address > > the reply to the author of the post to which we are replying? > > (There's gotta be an easier way to say that..) If we do so, then the > > author gets a duplicate of our reply. > >This is configurable for each subscriber. Go to the tutor web page at >http://mail.python.org/mailman/listinfo/tutor > >Enter your subscription email at the bottom where it says, "To >unsubscribe from Tutor, get a password reminder, or change your >subscription options enter your subscription email address:" > >Set "Avoid duplicate copies of messages?" to Yes. Great! > > Ten years ago or so I managed a Majordomo list, and I recall that it > > was possible for the list manager to configure the list to include a > > "Reply-To" header. If this would be possible for the admins to do > > with Tutor -- to include a "Reply-To: tutor at python.org" header in the > > posts sent out by the list, it would enable us to address a reply > > only to the list by hitting the "Reply" button. > >Surely you have been reading the list long enough to know that this >comes up every three months as a topic! No, you can't assume that because I'm a long-term subscriber that I have always faithfully read the list. If I had, I'd be much better at Python than I am! > It's not going to change. I'm >not going to discuss it (and I hope no one else will either). Search the >archives if you want to see previous discussions. Well, I don't see that it's all that bad that I brought it up again. The newcomers undoubtedly will benefit from your advice, as I did. Or does the new welcome message mention how to avoid duplicate copies of messages? If not, it should. Dick From ms at cerenity.org Tue Aug 14 21:42:43 2007 From: ms at cerenity.org (Michael Sparks) Date: Tue, 14 Aug 2007 20:42:43 +0100 Subject: [Tutor] Security [Was: Re: Decoding] In-Reply-To: <46C1CEB9.1020309@brunson.com> References: <200708141204.42495.ms@cerenity.org> <46C1CEB9.1020309@brunson.com> Message-ID: <200708142042.43920.ms@cerenity.org> On Tuesday 14 August 2007 16:48, Eric Brunson wrote: ... > The only thing I can imagine is > that you're stuck in some DOS mindset that if you're able to type into > "the console" then you have ultimate access to the machine, which is not > the case when using a true multi-user operating system like *nix or VMS. > > But, most strange to me is why you're this fired up over such a simple > issue. ?It seems to me like just a misunderstanding. I'm not particularly fired up, text comes across much harsher than it looks. (Also people being particularly patronising, like you have above, is particularly irritating. Last time I used VMS was 12 years ago. I'm not missing your point or anyone else's, and I've not used DOS for 10 years so I'm hardly stuck in a DOS mindset (been developing under linux for over 10 years). Yes, there are a tiny set of scenarios where doing eval(raw_input(...)) could be a problem. The idea that its always a gaping security hole is completely bogus. The scenario's raised I've never once seen happen. Despite having seen a number of systems where you either ssh in or telnet into a specialise console (routers and other network appliances). What was irritating was I was saying: * Scenario A (and only that scenario) is hardly a risk considering in >99% of cases where the user can type something in response to eval(raw_input(...)) they have FAR more ways of causing problems. * The response I was getting a told was that this was wrong because *other scenarios* were dangerous. Yes, other scenarios are wrong. Denouncing a piece of code as a gaping security hole without discussing the context is irresponsible. That and being taught to suck eggs is irritating. I've been evaluating security of network systems for 10 years and coding for 25 years. After all piece of code is never a security risk by itself. It's how that code is deployed and used that _can_ be. Michael. From tmikk at umn.edu Tue Aug 14 21:23:14 2007 From: tmikk at umn.edu (Tonu Mikk) Date: Tue, 14 Aug 2007 14:23:14 -0500 Subject: [Tutor] Livewires - stuck on a class Message-ID: <46C20122.5090003@umn.edu> I made some progress on the Livewires robots game - I got as far as page 10 on the attached 5-robots.pdf file. I am stuck on creating more than one robot and having all the robots follow the player. I create more robots in this way which seems to work: class Robot: pass def place_robots(): global robot global robots robots = [] for x in 1,2,3: robot = Robot() robot.y = random_between(0,47)-0.5 robot.x = random_between(0,63)-0.5 robot.shape = box(10*robot.x, 10*robot.y,10*robot.x+10,10*robot.y+10) robot.junk = 0 robots.append(robot) Then I was hoping to repeat the sequence for moving the robots placed in the robots list by using this code: for x in robots: # code for moving the robots When I run the code, only one of the robots moves on the screen. I am not quite sure what I am doing wrong. Incidentally, I am finding the Livewires course to be quite challenging for a beginning programmer. It seems to introduce many advanced topics with little preparation. I am using other Internet based tutorials on the side, but still having trouble. I wonder if it is me being hmm - dumb, or is the Livewires just tricky. Thank you, Tonu -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: robotsarecoming-list.py Url: http://mail.python.org/pipermail/tutor/attachments/20070814/19e6aef4/attachment-0001.asc -------------- next part -------------- A non-text attachment was scrubbed... Name: 5-robots.pdf Type: application/pdf Size: 89939 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20070814/19e6aef4/attachment-0001.pdf From Barry.Carroll at datalogic.com Tue Aug 14 22:09:35 2007 From: Barry.Carroll at datalogic.com (Carroll, Barry) Date: Tue, 14 Aug 2007 13:09:35 -0700 Subject: [Tutor] Question re Tutor List Etiquette In-Reply-To: Message-ID: <2BBAEE949D384D40A2B851287ADB6A4307BD8F69@eugsrv400.psc.pscnet.com> > Date: Tue, 14 Aug 2007 12:33:16 -0700 > From: Dick Moores > Subject: Re: [Tutor] Question re Tutor List Etiquette > To: tutor at python.org > Message-ID: <20070814193330.C34D01E401A at bag.python.org> > Content-Type: text/plain; charset="us-ascii"; format=flowed > > At 11:56 AM 8/14/2007, Kent Johnson wrote: > >Dick Moores wrote: > > > When sending a reply to a post, to the list, should we also address > > > the reply to the author of the post to which we are replying? > > > (There's gotta be an easier way to say that..) If we do so, then the > > > author gets a duplicate of our reply. > > > >This is configurable for each subscriber. Go to the tutor web page at > >http://mail.python.org/mailman/listinfo/tutor > > > >Enter your subscription email at the bottom where it says, "To > >unsubscribe from Tutor, get a password reminder, or change your > >subscription options enter your subscription email address:" > > > >Set "Avoid duplicate copies of messages?" to Yes. > > Great! > > > > Ten years ago or so I managed a Majordomo list, and I recall that it > > > was possible for the list manager to configure the list to include a > > > "Reply-To" header. If this would be possible for the admins to do > > > with Tutor -- to include a "Reply-To: tutor at python.org" header in the > > > posts sent out by the list, it would enable us to address a reply > > > only to the list by hitting the "Reply" button. > > > >Surely you have been reading the list long enough to know that this > >comes up every three months as a topic! > > No, you can't assume that because I'm a long-term subscriber that I > have always faithfully read the list. If I had, I'd be much better at > Python than I am! > > > It's not going to change. I'm > >not going to discuss it (and I hope no one else will either). Search the > >archives if you want to see previous discussions. > > Well, I don't see that it's all that bad that I brought it up again. > The newcomers undoubtedly will benefit from your advice, as I did. Or > does the new welcome message mention how to avoid duplicate copies of > messages? If not, it should. > > Dick > > > > ------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > End of Tutor Digest, Vol 42, Issue 50 > ************************************* Greetings: I receive these messages as a digest, not individual e-mails. So for me the list is the sender. To reply to an author, I have to Fwd: and and copy the address manually. Since I almost never need to do that, it isn't a problem. Also, it keeps my my inbox uncluttered: half a dozen e-mails a day instead of scores. On the other hand, the compilation delay means that by the time I see a new question, it's nearly always been answered three times already. So y'all seldom get the benefit of my superior Pythonic advice. =8^) FWIW, it's nice to see this topic addressed for once without the usual accompanying flamage. I agree with Dick that this info should be added to the FAQ. Keep the frustration level down by providing the options up front. Regards, Barry barry.carroll at datalogic.com 541-302-1107 ________________________ We who cut mere stones must always be envisioning cathedrals. -Quarry worker's creed From brunson at brunson.com Tue Aug 14 22:34:51 2007 From: brunson at brunson.com (Eric Brunson) Date: Tue, 14 Aug 2007 14:34:51 -0600 Subject: [Tutor] Security [Was: Re: Decoding] In-Reply-To: <200708142042.43920.ms@cerenity.org> References: <200708141204.42495.ms@cerenity.org> <46C1CEB9.1020309@brunson.com> <200708142042.43920.ms@cerenity.org> Message-ID: <46C211EB.1020603@brunson.com> Whatever. I make it a point to discontinue any debate that degenerates into someone quoting their work experience to me. At that point you've basically told me that you are convinced you know better than I do and nothing I say will convince you otherwise, because you've been doing this for so long you couldn't possibly be wrong. No matter how many perfectly valid scenarios have been put forth, you've shot them down as being outlying border cases that can't compete with your assertion that if you have access to type at a keyboard, then your security is already compromised such that any damage done by eval(raw_input()) is trivial in comparison. I think the basic point that everyone has been making is: Using eval() on any uncontrolled input is a security risk, now matter what the source. Michael Sparks wrote: > On Tuesday 14 August 2007 16:48, Eric Brunson wrote: > ... > >> The only thing I can imagine is >> that you're stuck in some DOS mindset that if you're able to type into >> "the console" then you have ultimate access to the machine, which is not >> the case when using a true multi-user operating system like *nix or VMS. >> >> But, most strange to me is why you're this fired up over such a simple >> issue. It seems to me like just a misunderstanding. >> > > I'm not particularly fired up, text comes across much harsher than it looks. > (Also people being particularly patronising, like you have above, is > particularly irritating. Last time I used VMS was 12 years ago. I'm not > missing your point or anyone else's, and I've not used DOS for 10 years so > I'm hardly stuck in a DOS mindset (been developing under linux for over 10 > years). > > Yes, there are a tiny set of scenarios where doing eval(raw_input(...)) could > be a problem. The idea that its always a gaping security hole is completely > bogus. > > The scenario's raised I've never once seen happen. Despite having seen > a number of systems where you either ssh in or telnet into a specialise > console (routers and other network appliances). > > What was irritating was I was saying: > * Scenario A (and only that scenario) is hardly a risk considering > in >99% of cases where the user can type something in response to > eval(raw_input(...)) they have FAR more ways of causing problems. > > * The response I was getting a told was that this was wrong because > *other scenarios* were dangerous. > > Yes, other scenarios are wrong. Denouncing a piece of code as a gaping > security hole without discussing the context is irresponsible. > > That and being taught to suck eggs is irritating. I've been evaluating > security of network systems for 10 years and coding for 25 years. > > After all piece of code is never a security risk by itself. It's how that > code is deployed and used that _can_ be. > > > Michael. > > From hmm at woolgathering.cx Tue Aug 14 22:26:50 2007 From: hmm at woolgathering.cx (William O'Higgins Witteman) Date: Tue, 14 Aug 2007 16:26:50 -0400 Subject: [Tutor] Question re Tutor List Etiquette In-Reply-To: <20070814191133.GA4084@desktop> References: <20070814180639.E639C1E4011@bag.python.org> <20070814191133.GA4084@desktop> Message-ID: <20070814202650.GF3460@sillyrabbi.dyndns.org> On Tue, Aug 14, 2007 at 08:11:33PM +0100, Tom Fitzhenry wrote: >On Tue, Aug 14, 2007 at 11:06:05AM -0700, Dick Moores wrote: >> Replying only to the list takes a bit of trouble. The default >> behavior seems to be that the "Reply" button addresses the author >> only and not the list; "Reply to all" addresses both the list, the >> author, and any others included in the To: or Cc: headers of the post >> being replied to. Or at least that's how Eudora and Gmail work. What I have done is to inject a Reply-To header into each email with procmail, so that hitting reply does what I expect. Here's the rule I use: :0 * ^(From|To|Cc).*\@python.org { :0hf | /usr/bin/formail -A "Reply-To: tutor at python.org" :0 python/ } I like this approach because it does not require that the list change behaviour to what I consider to be the "right" thing (who cares what I think), but if the list decided to change their policy then nothing changes (the header would be changed to itself). -- yours, William From alan.gauld at btinternet.com Tue Aug 14 22:43:51 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 14 Aug 2007 21:43:51 +0100 Subject: [Tutor] Livewires - stuck on a class References: <46C20122.5090003@umn.edu> Message-ID: "Tonu Mikk" wrote > I create more robots in this way which seems to work: > class Robot: > pass By using an empty class you are losing m,uch of the power of classes. Try this: class Robot: def __init__(self, x, y, shape=None): self.x = x self.y = y robot.junk = 0 if shape == None: self.shape = box(10*x, 10*y, 10*x+10, 10*y+10) def place_robots(numRobots): return = [Robot(random_between(0,47)-0.5, random_between(0,63)-0.5) for x in range(numRobots)] And instead of your random fiunction you could use the standard library function random.randrange() > Then I was hoping to repeat the sequence for moving the robots > placed in > the robots list by using this code: > for x in robots: > # code for moving the robots > > When I run the code, only one of the robots moves on the screen. I > am > not quite sure what I am doing wrong. Without seeing the robot moving code neither are we. But as a hiunt try putting the code for moving a robot into the Robot class Then you should be abe to do for robot in robots: robot.move(x,y) > Incidentally, I am finding the Livewires course to be quite > challenging > for a beginning programmer. It seems to introduce many advanced > topics > with little preparation. I am using other Internet based tutorials > on > the side, but still having trouble. I wonder if it is me being > hmm - > dumb, or is the Livewires just tricky. >From what I've seen of posts about Livewires I think its quite a challenging course for a complete beginner. But OTOH it seems to be the one with the most fun problems! :-) BTW I just spotted this.... If this is the move code you were talking about then... > def move_robot(): > for x in robots: > while 1: > if robot.x + 0.5< player.x and robot.y +0.5< player.y: You are doing *for x in robots* but then moving *robot* not x. >From your robot placement code robot is set to the last robot you created so it will only ever mover that robot. To make this a method of the class you wuill need to pass the player object that you are comparing with. So the method will look like: class Robot: def __init__(...): as above def move(self, player): code as per the function but using self.x instead of robot.x etc Also it would be better IMHO to use if/elif rather than all those if/breaks. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Tue Aug 14 23:03:28 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 14 Aug 2007 22:03:28 +0100 Subject: [Tutor] Security [Was: Re: Decoding] References: <200708141204.42495.ms@cerenity.org> <46C1CEB9.1020309@brunson.com> <200708142042.43920.ms@cerenity.org> Message-ID: "Michael Sparks" wrote > Yes, there are a tiny set of scenarios where doing > eval(raw_input(...)) could > be a problem. The idea that its always a gaping security hole is > completely > bogus. The number of scenarios is not tiny but the likelihood of attack by that route is small. However we live in a world where ever increasing numbers of people are deliberately trying to find such opportunities and exploit them. For example in my own organisation we have over 100,000 users and have basic spyware logging their PC activity and we have over 1,000 attempted attacks per month - and that's just the employees! Not all of that is malicious, some of it is just accidental mis-typing/clicking etc. But some is deliberate attempts to access things they shouldn't or just to see if they can break it - it can be boring working the night shift in a call centre! :-). The problem is real even if not enormous and all programmers have a duty to learn how to avoid it. And that includes not using such open doors to vandalism as eval() etc. While very few would trash their own computer there are plenty employees happy to trash the company computer, especially since it often leads to an easy few hours until the tech guys fix it! > The scenario's raised I've never once seen happen. As I say we see it on a monthly basis many times. > * Scenario A (and only that scenario) is hardly a risk considering > in >99% of cases where the user can type something in response > to > eval(raw_input(...)) they have FAR more ways of causing > problems. This is true, and eval() is not the main risk in this scenario it's true, but it does still constitute a risk if its input can be read from stdin. > Denouncing a piece of code as a gaping security hole without > discussing the context is irresponsible. No, neglecting to mention that it is a gaping security hole would be irresponsible. It would however be good to add a context about exactly when and how it is dangerous. In the case of eval() that is *anywhere* that untrusted or indeterminate input can be supplied. > After all piece of code is never a security risk by itself. It's how > that > code is deployed and used that _can_ be. Hmmm, I'm not sure I buy that. It's a bit like saying a gun is not a safety risk, it's only how it's used. But the very presence of the gun itself poses a risk that it will be abused. Same with risky code, if it makes a breach possible then it is itself a risk. If the risk matures then it's an issue, but one which may be too late to deal with! -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From handel.d at gmail.com Tue Aug 14 22:06:55 2007 From: handel.d at gmail.com (David Handel) Date: Tue, 14 Aug 2007 16:06:55 -0400 Subject: [Tutor] Python Book Recommendations Message-ID: <724354bd0708141306u64120745ue342b205b111a6aa@mail.gmail.com> If you can afford it, Safari Books online is a wonderful resource. http://www.safaribooksonline.com/ I am using the $39.95 month to month "all you can eat" deal. You have unlimited access online to 100's of books from many IT publishers. It is great to cross read about the same subjects from many sources and to be able to cut and paste code right into your IDE and run it. Even a few months of immersion reading is worth it to get up and running. David Handel -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070814/64ce764f/attachment.html From christopher.henk at allisontransmission.com Tue Aug 14 23:07:01 2007 From: christopher.henk at allisontransmission.com (christopher.henk at allisontransmission.com) Date: Tue, 14 Aug 2007 17:07:01 -0400 Subject: [Tutor] Livewires - stuck on a class Message-ID: An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070814/07324729/attachment-0001.htm From tmikk at umn.edu Tue Aug 14 23:23:57 2007 From: tmikk at umn.edu (Tonu Mikk) Date: Tue, 14 Aug 2007 16:23:57 -0500 Subject: [Tutor] Livewires - stuck on a class In-Reply-To: References: Message-ID: <46C21D6D.9030705@umn.edu> christopher.henk at allisontransmission.com wrote: > >Then I was hoping to repeat the sequence for moving the robots placed > >in > >the robots list by using this code: > >for x in robots: > > # code for moving the robots > > Glancing at your code to move the robots. I don't see you using you x > from for x in robots. Since in your placement code robot is assigned > to a new robot each time through the loop, the placement works. In > your movement you don't change what robot is representing. > > I think you want to change you line: > for x in robots: > to become... > for robot in robots: > > Thank you! This did the trick. Tonu -- Tonu Mikk Educational Technology Consultant Digital Media Center - dmc.umn.edu tmikk at umn.edu 612 625-9221 From brian.wisti at gmail.com Tue Aug 14 23:39:16 2007 From: brian.wisti at gmail.com (Brian Wisti) Date: Tue, 14 Aug 2007 14:39:16 -0700 Subject: [Tutor] Python Book Recommendations In-Reply-To: References: <724354bd0708141306u64120745ue342b205b111a6aa@mail.gmail.com> Message-ID: On 8/14/07, Brian Wisti wrote: > > > On 8/14/07, David Handel wrote: > > > > If you can afford it, Safari Books online is a wonderful resource. > > http://www.safaribooksonline.com/ > > I am using the $39.95 month to month "all you can eat" deal. You have > > unlimited access online to 100's of books from many IT publishers. It is > > great to cross read about the same subjects from many sources and to be able > > to cut and paste code right into your IDE and run it. Even a few months of > > immersion reading is worth it to get up and running. > > David Handel > > > Check with your local library, too. The Seattle Public Library provides > access to a limited selection of the Safari books (stuff published in the > last 2 years from a handful of publishers). Maybe your region has similar > access. > > Kind Regards, > > Brian Wisti > http://coolnamehere.com/ > > ... and this was supposed to go to the list. I knew I shouldn't have ignored that thread. -- Brian Wisti -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070814/e3b99b80/attachment.html From keridee at jayco.net Wed Aug 15 00:52:03 2007 From: keridee at jayco.net (Tiger12506) Date: Tue, 14 Aug 2007 17:52:03 -0500 Subject: [Tutor] Security [Was: Re: Decoding] References: <200708141204.42495.ms@cerenity.org> <46C1CEB9.1020309@brunson.com> <200708142042.43920.ms@cerenity.org> Message-ID: <014901c7dec5$bf009b00$93fce004@JSLAPTOP> The point is that even though eval(raw_input()) is not a security threat, Alan's suggestion of myscript.py < some.txt might be. And even though the script written will not be a security issue, the *coding practice* that it teaches will lead to times when he does encounter that "tiny set of scenarios" in which the input for the script is potentially untrustworthy. Even though the risk is perhaps minimal to you, it still needs to be made known. An analogy is the threat of mercury, in which breathing the vapors can cumulatively lead to brain damage. However, in most quantities that people are freaking out over are far too small to be a threat. Don't go overboard, and yet *know* what is out there. I'll give an example. The boss gives two employees the simple jobs: You~ write a function grapher And You~ write an input file that graphs the common mathematical functions so that it can be run in his~ function grapher. The first guy uses eval to parse the text file because of its power. All he has to do is graph, eval takes care of turning the lines from the text file into function objects. The second notices the first guy's approach and sees a chance to move up in the world. He writes his file to his advantage. The two put the final result together and show the boss. The computer destroys important data that the company has worked on (not protected by the OS) and the first guy is fired because *his* program deleted stuff. Ouch. Be aware of security risks, not infatuated by them. eval() is not a risk by itself, but getting used to using it could lead to problems. Subtle things will always bite you more than things of which you are completely aware. JS From carroll at tjc.com Wed Aug 15 00:40:33 2007 From: carroll at tjc.com (Terry Carroll) Date: Tue, 14 Aug 2007 15:40:33 -0700 (PDT) Subject: [Tutor] Python Book Recommendations [Was:[Re: Security]] In-Reply-To: Message-ID: On Mon, 13 Aug 2007, bhaaluu wrote: > Programming isn't for everyone! Until you find out whether or not > it's for you, don't spend hundreds and thousands of dollars on > computer programming books! =) Programming isn't unique in that respect. I tried to learn Chinese a few years back. I'm not sure exactly how much I spent on dictionaries and books, but I think my Chinese vocabulary cost about $3 or $4 per word. I try not to buy too many Python books, but in the 4 years or so that I've been using it, I can count at least 4 I've bought new, and another 5 I've bought used. What I recommend is: 1) Get one book that's about Python, to learn from. An example, if you already know how to program, would be Wes's Core Python book. Try to pick one that's not too simple, because you'll want something that you can still use once you know the language; alternatively, go the library route to learn. 2) when you can do some simple stuff, you'll eventually want a reference book: probably either Martelli's Python in a Nutshell or Beazley's Python Essential reference. 3) for domain-specific work, get a book or books as needed. For example, you might want to pick up wxPython in Action if you're going to start writing wxPython GUIs; or Python & XML if you're doing XML work; etc. Actually, I've either relied on libraries for these, or opportunistically gotten a dirt-cheap used copy. I was idly curious about Jython, for example, and when I saw a used copy on sale for just a few bucks, I picked that up. > I think your local library is a great idea for checking out programming > books! Also, look into the Inter-library loan system for books that might > not be in your library branch. Most libraries can borrow books for you > from another branch within the system, or even from out-of-state. I'm currently reading the Definitive Guide to SQLite, to write my first database app. I second this approach. My copy is from the Sunnyvale Public Library, obtained from my local San Jose Public Library via interlibrary loan. I read the wxPython book from a library copy, too, before putting the money up to buy my own copy. From carroll at tjc.com Wed Aug 15 01:09:32 2007 From: carroll at tjc.com (Terry Carroll) Date: Tue, 14 Aug 2007 16:09:32 -0700 (PDT) Subject: [Tutor] Python Book Recommendations In-Reply-To: Message-ID: On Tue, 14 Aug 2007, Brian Wisti wrote: > Check with your local library, too. Or even your not-so-local library. > The Seattle Public Library provides access to a limited selection of the > Safari books (stuff published in the last 2 years from a handful of > publishers). Maybe your region has similar access. I just did a quick search of the San Jose catalog, and see a bunch of online Python-related books: Core Python Programming (2006, 2 copies) Game Programming with Python (2004) Programming Python (2006, 2 copies) Python Cookbook (2005, 2 copies) Python Essential reference (2006, 2 copies) Python in a Nutshell (2006, 2 copies) Python Phrasebook (2006, 2 copies) Python programming for the absolute beginner (2003) Python programming on Win32 (2000) Rapid web appplications with TurboGears (2006, 2 copies) Sams teach yourself Python in 24 hours (2000) Twisted network programming essentials (2005) Twisted network programming essentials (2006, 2 copies) And here's the kicker: The City of San Jose offers free library cards to all California residents or property owners. http://www.sjlibrary.org/legal/policies.htm?pID=313 So a lot of not-so-local readers can get access to this material. It's not nationwide or worldwide, but it's better than just being limited to San Jose. (Of course I don't know the practical aspects of getting a library card; can you do it by mail?) But leaving this particular library aside: see if there's a large library system that you're not personally a part of that you can use. For years, I lived in Santa Clara, not too far from San Jose. I used Santa Clara's own city library; the much larger San Jose library; the Santa Clara County library system (which provides a library to a number of cities in the county that prefer to be part of a larger system to operating their own); and even, for a while, the Santa Cruz County library system (when I used to work down that way). Libraries rock. Use them well, and you can rock, too. From fiyawerx at gmail.com Wed Aug 15 01:38:48 2007 From: fiyawerx at gmail.com (Fiyawerx) Date: Tue, 14 Aug 2007 19:38:48 -0400 Subject: [Tutor] Python Book Recommendations In-Reply-To: References: Message-ID: <1b31ae500708141638w77614014o6f382d0389bc69df@mail.gmail.com> My company has a subscription with the books24x7.com site, and I'm sure they offer individual accounts, but so far I'm ashamed that I've paid close to 200$ worth of computer books that I could have been accessing online for free. Including 'dummies' books, Teach yourself whatever, and just a multitude of other books. Just did a quick search for titles with 'python' and returned about 20. On 8/14/07, Terry Carroll wrote: > > On Tue, 14 Aug 2007, Brian Wisti wrote: > > > Check with your local library, too. > > Or even your not-so-local library. > > > The Seattle Public Library provides access to a limited selection of the > > Safari books (stuff published in the last 2 years from a handful of > > publishers). Maybe your region has similar access. > > I just did a quick search of the San Jose catalog, and see a bunch of > online Python-related books: > > Core Python Programming (2006, 2 copies) > Game Programming with Python (2004) > Programming Python (2006, 2 copies) > Python Cookbook (2005, 2 copies) > Python Essential reference (2006, 2 copies) > Python in a Nutshell (2006, 2 copies) > Python Phrasebook (2006, 2 copies) > Python programming for the absolute beginner (2003) > Python programming on Win32 (2000) > Rapid web appplications with TurboGears (2006, 2 copies) > Sams teach yourself Python in 24 hours (2000) > Twisted network programming essentials (2005) > Twisted network programming essentials (2006, 2 copies) > > And here's the kicker: > > The City of San Jose offers free library cards to all California > residents or property owners. > > http://www.sjlibrary.org/legal/policies.htm?pID=313 > > So a lot of not-so-local readers can get access to this material. It's > not nationwide or worldwide, but it's better than just being limited to > San Jose. (Of course I don't know the practical aspects of getting a > library card; can you do it by mail?) > > But leaving this particular library aside: see if there's a large library > system that you're not personally a part of that you can use. For years, > I lived in Santa Clara, not too far from San Jose. I used Santa Clara's > own city library; the much larger San Jose library; the Santa Clara > County library system (which provides a library to a number of cities in > the county that prefer to be part of a larger system to operating their > own); and even, for a while, the Santa Cruz County library system (when I > used to work down that way). > > Libraries rock. Use them well, and you can rock, too. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070814/b27bf875/attachment.htm From kent37 at tds.net Wed Aug 15 02:48:36 2007 From: kent37 at tds.net (Kent Johnson) Date: Tue, 14 Aug 2007 20:48:36 -0400 Subject: [Tutor] Python Book Recommendations [Was:[Re: Security]] In-Reply-To: References: Message-ID: <46C24D64.8010407@tds.net> Terry Carroll wrote: > What I recommend is: > > 1) Get one book that's about Python, to learn from. An example, if you > already know how to program, would be Wes's Core Python book. Try to pick > one that's not too simple, because you'll want something that you can > still use once you know the language; alternatively, go the library route > to learn. > > 2) when you can do some simple stuff, you'll eventually want a reference > book: probably either Martelli's Python in a Nutshell or Beazley's Python > Essential reference. I think I am in the minority, but I almost never use any Python reference book. It's not that I don't ever have to look anything up! I have a local copy of the Python HTML docs and shortcuts in the browser that let me find anything I need far faster than I could look it up in a book. If I can't find what I need in the standard docs, my next stop is probably Google or comp.lang.python or the Python Cookbook. I do own copies of of Python in a Nutshell, Python Essential Reference and Python Pocket Reference, I just find the online docs have much the same information in a much more accessible form. FWIW here are my Python bookmarks: module index - I don't actually use this one any more, see below file://localhost/Users/kent/Library/Documentation/Python-Docs-2.5/modindex.html built-in functions file://localhost/Users/kent/Library/Documentation/Python-Docs-2.5/lib/built-in-funcs.html built-in types - list, dict, string, etc file://localhost/Users/kent/Library/Documentation/Python-Docs-2.5/lib/types.html string methods file://localhost/Users/kent/Library/Documentation/Python-Docs-2.5/lib/string-methods.html overall doc index file://localhost/Users/kent/Library/Documentation/Python-Docs-2.5/index.html built-in exceptions file://localhost/Users/kent/Library/Documentation/Python-Docs-2.5/lib/module-exceptions.html comp.lang.python http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&c2coff=1&group=comp.lang.python I also have a shortcut set up so if I type py modulename in the Firefox address bar it takes me directly to the docs for that module. To do this, create a bookmark with this URL: file://localhost/Users/kent/Library/Documentation/Python-Docs-2.5/lib/module-%s.html and give it the keyword 'py'. Another shortcut looks up the module in the online docs, useful if I want to give a link to someone else: http://docs.python.org/lib/module-%s.html Kent From deliberatus at verizon.net Wed Aug 15 05:47:13 2007 From: deliberatus at verizon.net (Kirk Bailey) Date: Tue, 14 Aug 2007 23:47:13 -0400 Subject: [Tutor] xls file Message-ID: <46C27741.4050902@verizon.net> Ii want to read a xls file and use the data in part of it. What module would help make sense of one? -- Salute! -Kirk Bailey Think +-----+ | BOX | +-----+ knihT Fnord. From alan.gauld at btinternet.com Wed Aug 15 09:06:40 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 15 Aug 2007 08:06:40 +0100 Subject: [Tutor] xls file References: <46C27741.4050902@verizon.net> Message-ID: "Kirk Bailey" wrote > Ii want to read a xls file and use the data in part of it. What > module > would help make sense of one? If the data is straighforward you might find it easier to save it as a csv file first. But otherwise there is a module called pyexcelerator (I think?) which can work with Excel 97 and 95 formats. http://sourceforge.net/projects/pyexcelerator HTH, Alan G. From duncan at thermal.esa.int Wed Aug 15 10:41:44 2007 From: duncan at thermal.esa.int (Duncan Gibson) Date: Wed, 15 Aug 2007 10:41:44 +0200 Subject: [Tutor] converting a source package into a dll/shared library? In-Reply-To: <20070814154009.76b9ce57.duncan@thermal.esa.int> References: <20070814154009.76b9ce57.duncan@thermal.esa.int> Message-ID: <20070815104144.485e4792.duncan@thermal.esa.int> I asked: > Is it possible to convert a Python package, with __init__.py and > related python modules, into a single DLL or shared library that can > be imported in the same way? > > We have used py2exe and cx_freeze to create a complete executable, > but we are curious whether there is a middle way between this single > executable and distributing all of the source files. Kent suggested: K> You can get a modest degree of obscurity by distributing the .pyc K> bytecode files instead of the .py source. These can still be K> decompiled and reverse engineered but it is more effort. Yes we really just want to protect ourselves from giving code relating to various companies' products to their competitors, even though we wrote the code ourselves based on the behaviour of our own test input files for their tools. We don't want any company to feel that we have exposed any internal details about how their tools might work. We had already found the py_compile and compileall modules, and had even gone one further than .pyc files to create .pyo files because these have no docstrings either. We also found the dis module, but it is unlikely that anyone will to go to all the effort to disassemble and reverse engineer the code. K> I suppose you could rewrite some or all of the code into the Python K> dialect supported by Pyrex and compile it that way. That's something to remember for the future, but we already have 100K lines of code for the 6 different tool formats that we currently handle, so it would be non-trivial to change now. Alan also suggested: A> Since you refer to DLLs I'll assume a Windoze platform. A> If so the answer is yes you can create an ActiveX/COM object. A> A> So if its accessibility to non Python code you are interested A> in grab a copy of Mark Hammonds Win32 book for details A> and examples. You can even go DCOM if thats significant. It's a demonstrator project, so we've written the whole thing in Python for the rapid development side, and so far we have not had to worry about accessing non-Python code. Each company only needs to see how we've mapped their own tool formats into our neutral format. Actual integration in their non-Python code will be a completely different story involving an alternate code generator spitting out C/C++... Thanks for confirming our ideas and the extra feedback. Duncan From sli1que at yahoo.com Wed Aug 15 12:28:51 2007 From: sli1que at yahoo.com (Eric Walker) Date: Wed, 15 Aug 2007 03:28:51 -0700 (PDT) Subject: [Tutor] xls file In-Reply-To: Message-ID: <128799.10162.qm@web60117.mail.yahoo.com> Alan Gauld wrote: "Kirk Bailey" wrote > Ii want to read a xls file and use the data in part of it. What > module > would help make sense of one? If the data is straighforward you might find it easier to save it as a csv file first. But otherwise there is a module called pyexcelerator (I think?) which can work with Excel 97 and 95 formats. http://sourceforge.net/projects/pyexcelerator HTH, Alan G. _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor Try this. I found it on the web. (xlrd package) I think you don't even need windows to use these. I tried it and it works well. http://www.lexicon.net/sjmachin/xlrd.htm http://cheeseshop.python.org/pypi/xlrd --------------------------------- Ready for the edge of your seat? Check out tonight's top picks on Yahoo! TV. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070815/198f9d2e/attachment.html From vincent.gulinao at gmail.com Wed Aug 15 17:20:15 2007 From: vincent.gulinao at gmail.com (Vincent Gulinao) Date: Wed, 15 Aug 2007 23:20:15 +0800 Subject: [Tutor] Class Attribute "Overloading?" Message-ID: Sorry, I just started experimenting on Python classes... Is there any way a reference to a class attribute ([class].[attribute]) be treated like a method ([class].[method]())? I have a class with DB component. Some of its attributes are derived from DB and I find it impractical to derive all at once upon __init__. Of course we can use dictionary-like syntax ([class]["[attribute]"]) and use __getitem__, checking for existence and None of the attribute before deriving the value from the DB. But I think [class].[attribute] is more conventional (Is it?). Or someone suggest a more Pythonic way. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070815/3965a677/attachment.htm From rob.andrews at gmail.com Wed Aug 15 17:45:30 2007 From: rob.andrews at gmail.com (Rob Andrews) Date: Wed, 15 Aug 2007 10:45:30 -0500 Subject: [Tutor] KeyError list? Message-ID: <8d757d2e0708150845me245f97o7aa5b4491fbf2b64@mail.gmail.com> Is there a comprehensive list of dictionary KeyError meanings? I could sure use one these days and haven't had much luck tracking one down yet. -Rob From rdm at rcblue.com Wed Aug 15 18:43:52 2007 From: rdm at rcblue.com (Dick Moores) Date: Wed, 15 Aug 2007 09:43:52 -0700 Subject: [Tutor] Python Book Recommendations In-Reply-To: <1b31ae500708141638w77614014o6f382d0389bc69df@mail.gmail.co m> References: <1b31ae500708141638w77614014o6f382d0389bc69df@mail.gmail.com> Message-ID: <20070815164423.E73161E4018@bag.python.org> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070815/5c398a7b/attachment.htm From wescpy at gmail.com Wed Aug 15 19:14:20 2007 From: wescpy at gmail.com (wesley chun) Date: Wed, 15 Aug 2007 10:14:20 -0700 Subject: [Tutor] Class Attribute "Overloading?" In-Reply-To: References: Message-ID: <78b3a9580708151014j3a0e253bi615c1edd67a34634@mail.gmail.com> > Is there any way a reference to a class attribute ([class].[attribute]) be > treated like a method ([class].[method]())? > : > Of course we can use dictionary-like syntax ([class]["[attribute]"]) and use > __getitem__, checking for existence and None of the attribute before > deriving the value from the DB. But I think [class].[attribute] is more > conventional (Is it?). Or someone suggest a more Pythonic way. i'm not sure exactly what you're asking, but let me say the following: - you can use the Boolean hasattr() to determine if any object (not just classes) have an attribute, e.g., hasattr(MyClass, 'anAttr') - if myInstance is an instance of MyClass, e.g., if the Boolean isinstance(myInstance, MyClass) returns true, then you can also do hasattr(myInstance, 'anAttr'). (or 'self' if this code is defined within a method) - you can use the Boolean callable() to determine if it can be "called," or executed like a function, e.g., is hasattr(self, 'anAttr') and callable(self.anAttr): self.anAttr(...) hasattr(), isinstance(), callable()... 3 useful built-in functions... hopefully this helps... -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From tmikk at umn.edu Wed Aug 15 19:19:54 2007 From: tmikk at umn.edu (Tonu Mikk) Date: Wed, 15 Aug 2007 12:19:54 -0500 Subject: [Tutor] Livewires - stuck on a class In-Reply-To: References: <46C20122.5090003@umn.edu> Message-ID: <46C335BA.3010703@umn.edu> Alan Gauld wrote: > "Tonu Mikk" wrote > > >> I create more robots in this way which seems to work: >> class Robot: >> pass >> > > By using an empty class you are losing m,uch of the power of classes. > > I would need to learn more to handle the classes better. In this case, I am following the Livewires tutorial pretty closely which uses an empty class. >> def move_robot(): >> for x in robots: >> while 1: >> if robot.x + 0.5< player.x and robot.y +0.5< player.y: >> > > You are doing *for x in robots* but then moving *robot* not x. > Yes, that was my mistake. I changed the line to "for robot in robots:" and now it works! > > Also it would be better IMHO to use if/elif rather than all those > if/breaks. > I followed your advice here. It does make the code a bit more clear. Thanks a lot, Tonu From wescpy at gmail.com Wed Aug 15 19:20:03 2007 From: wescpy at gmail.com (wesley chun) Date: Wed, 15 Aug 2007 10:20:03 -0700 Subject: [Tutor] KeyError list? In-Reply-To: <8d757d2e0708150845me245f97o7aa5b4491fbf2b64@mail.gmail.com> References: <8d757d2e0708150845me245f97o7aa5b4491fbf2b64@mail.gmail.com> Message-ID: <78b3a9580708151020q244e9047qaa1a4336c577a80@mail.gmail.com> > Is there a comprehensive list of dictionary KeyError meanings? > > I could sure use one these days and haven't had much luck tracking one down yet. can you give us an example of what you're looking for? generally: exception KeyError: Raised when a mapping (dictionary) key is not found in the set of existing keys from: http://www.python.org/doc/2.5/lib/module-exceptions.html in other words, you tried to access an element of a dictionary with a key that is not in that dict. using the get method [e.g., myDict.get(key, 'N/A')] is a better way to avoid these exceptions than just trying to get something with myDict[key]. -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From kent37 at tds.net Wed Aug 15 19:43:16 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 15 Aug 2007 13:43:16 -0400 Subject: [Tutor] Class Attribute "Overloading?" In-Reply-To: References: Message-ID: <46C33B34.3050906@tds.net> Vincent Gulinao wrote: > Sorry, I just started experimenting on Python classes... > > Is there any way a reference to a class attribute ([class].[attribute]) > be treated like a method ([class].[method]())? > > I have a class with DB component. Some of its attributes are derived > from DB and I find it impractical to derive all at once upon __init__. > > Of course we can use dictionary-like syntax ([class]["[attribute]"]) and > use __getitem__, checking for existence and None of the attribute before > deriving the value from the DB. But I think [class].[attribute] is more > conventional (Is it?). Or someone suggest a more Pythonic way. I think you are looking for either __getattr__() or properties. __getattr__() lets you intercept access to atttributes that are not found via the usual attribute lookup. It is useful for delegation which I think is what you are trying to do. e.g. class Proxy(object): def __init__(self, delegate): self.delegate = delegate def __getattr__(self, attr): return getattr(self.delegate, attr) then with p = Proxy(realObject) p.x becomes p.delegate.x i.e. realObject.x http://docs.python.org/ref/attribute-access.html Properties OTOH let you customize access to a particular attribute so p.x becomes a method call. http://www.python.org/download/releases/2.2/descrintro/#property Kent From kent37 at tds.net Wed Aug 15 19:44:28 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 15 Aug 2007 13:44:28 -0400 Subject: [Tutor] KeyError list? In-Reply-To: <8d757d2e0708150845me245f97o7aa5b4491fbf2b64@mail.gmail.com> References: <8d757d2e0708150845me245f97o7aa5b4491fbf2b64@mail.gmail.com> Message-ID: <46C33B7C.20401@tds.net> Rob Andrews wrote: > Is there a comprehensive list of dictionary KeyError meanings? ?? AFAIK there is only one meaning for KeyError - the key was not found in the dict. From the docs: "Raised when a mapping (dictionary) key is not found in the set of existing keys." Kent From timmichelsen at gmx-topmail.de Wed Aug 15 20:00:28 2007 From: timmichelsen at gmx-topmail.de (Tim Michelsen) Date: Wed, 15 Aug 2007 20:00:28 +0200 Subject: [Tutor] Python Book Recommendations [Was:[Re: Security]] In-Reply-To: References: Message-ID: Hello list, thanks to everybody who shared their experience with books and their usefulness. I think with regard to the other thread that passed lately: Books with exercises and problems to solve - http://article.gmane.org/gmane.comp.python.tutor/42394 we must admit there are two type of learners: * real programming beginners/novices who take Python to enter the world of programmin or need to program only to solve some specific problems that are arising in other areas of work like scientific data analysis, modelling or engineering * computer professionals who are very familiar with programming and already know some lingos. They need a different learning approach than the first group. I for instance belong to the first group. I need Python for effective data manipulation & analysis or program customatization/scripting within other programs, etc. I bought "Python Scripting for Comuptional Science" by H. Langtangen. While this book adresses exctly my needs as far as the content and spcialization is concerned I want to start off learning with a book that helps me to pick up easier. Learning -- which is a auto-learning and free choice in my case -- should be fun! Therefore I am consindering to buy "Python Programming for the Absolute Beginner". Did anyone here use this book for leaning? Is it easy enough for a non-programmer while not being too light? Kind regards, Tim From alan.gauld at btinternet.com Wed Aug 15 20:17:30 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 15 Aug 2007 19:17:30 +0100 Subject: [Tutor] converting a source package into a dll/shared library? References: <20070814154009.76b9ce57.duncan@thermal.esa.int> <20070815104144.485e4792.duncan@thermal.esa.int> Message-ID: "Duncan Gibson" wrote > Alan also suggested: > A> So if its accessibility to non Python code you are interested > A> in grab a copy of Mark Hammonds Win32 book for details Actually I meant to say So if its accessibiity *from* non python code.... But since that doesn't appear to be an issue either... As to access to the internal data would it be difficult to parameterise it so that each companies data is in a local config file? That way even if the dissasemble the code it won't help? Alan G From alan.gauld at btinternet.com Wed Aug 15 20:28:27 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 15 Aug 2007 19:28:27 +0100 Subject: [Tutor] Class Attribute "Overloading?" References: Message-ID: "Vincent Gulinao" wrote > Is there any way a reference to a class attribute > ([class].[attribute]) be > treated like a method ([class].[method]())? Yes, classes are just objects and their attributes are too. class Test: pass def f(self): print 'howdy!' Test.foo = f t = Test() # creae an instance t.foo() # access the class method Creating actual class methods at runtime and calling them via the class is something I haven't tried but it might be possible... Yep it works: class Test: pass Test.foo = staticmethod(lambda: 'hello') Test.foo() 'hello' HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From bgailer at alum.rpi.edu Wed Aug 15 20:27:55 2007 From: bgailer at alum.rpi.edu (bob gailer) Date: Wed, 15 Aug 2007 11:27:55 -0700 Subject: [Tutor] KeyError list? In-Reply-To: <8d757d2e0708150845me245f97o7aa5b4491fbf2b64@mail.gmail.com> References: <8d757d2e0708150845me245f97o7aa5b4491fbf2b64@mail.gmail.com> Message-ID: <46C345AB.4000207@alum.rpi.edu> Rob Andrews wrote: > Is there a comprehensive list of dictionary KeyError meanings? > >>> d = {1:2} >>> d[1] 2 >>> d[2] KeyError AFAIK that's it. From bgailer at alum.rpi.edu Wed Aug 15 20:29:45 2007 From: bgailer at alum.rpi.edu (bob gailer) Date: Wed, 15 Aug 2007 11:29:45 -0700 Subject: [Tutor] Class Attribute "Overloading?" In-Reply-To: References: Message-ID: <46C34619.40909@alum.rpi.edu> Vincent Gulinao wrote: > > Sorry, I just started experimenting on Python classes... > > Is there any way a reference to a class attribute > ([class].[attribute]) be treated like a method ([class].[method]())? > Attributes are objects. A method is an object. If you want to know something more specific, please rephrase the question. I for one don't really know what you want. > > I have a class with DB component. Some of its attributes are derived > from DB and I find it impractical to derive all at once upon __init__. > > Of course we can use dictionary-like syntax ([class]["[attribute]"]) > and use __getitem__, checking for existence and None of the attribute > before deriving the value from the DB. But I think [class].[attribute] > is more conventional (Is it?). Or someone suggest a more Pythonic way. > From alan.gauld at btinternet.com Wed Aug 15 20:30:27 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 15 Aug 2007 19:30:27 +0100 Subject: [Tutor] KeyError list? References: <8d757d2e0708150845me245f97o7aa5b4491fbf2b64@mail.gmail.com> Message-ID: "Rob Andrews" wrote > Is there a comprehensive list of dictionary KeyError meanings? I don't understand the question Rob. A KeyError means the key used wasn't found in the dictionary What other meanings are you thinking of? Alan G. From noufal at airtelbroadband.in Wed Aug 15 20:58:06 2007 From: noufal at airtelbroadband.in (Noufal Ibrahim) Date: Thu, 16 Aug 2007 00:28:06 +0530 Subject: [Tutor] Class Attribute "Overloading?" In-Reply-To: References: Message-ID: <46C34CBE.3040206@airtelbroadband.in> Vincent Gulinao wrote: > > > Sorry, I just started experimenting on Python classes... > > Is there any way a reference to a class attribute ([class].[attribute]) > be treated like a method ([class].[method]())? > > I have a class with DB component. Some of its attributes are derived > from DB and I find it impractical to derive all at once upon __init__. > > Of course we can use dictionary-like syntax ([class]["[attribute]"]) and > use __getitem__, checking for existence and None of the attribute before > deriving the value from the DB. But I think [class].[attribute] is more > conventional (Is it?). Or someone suggest a more Pythonic way. > Do you simply want to dynamically create class attributes? If so, you can use setattr. Something like this class foo(object): def __init__(self, *args): for i in args: setattr(self,i,"Hello=%s"%i) x=foo("a","b","c") print x.a,x.b,x.c will print Hello=a Hello=b Hello=c -- ~noufal From paulo_quaglio at yahoo.com Wed Aug 15 17:26:45 2007 From: paulo_quaglio at yahoo.com (Paulo Quaglio) Date: Wed, 15 Aug 2007 08:26:45 -0700 (PDT) Subject: [Tutor] open multiple files Message-ID: <501789.94479.qm@web52206.mail.re2.yahoo.com> Hi everyone - I'm beginning to learn how to program in python. I need to process several text files simultaneously. The program needs to open several files (like a corpus) and output the total number of words. I can do that with just one file but not the whole directory. I tried glob but it didn't work. Your ideas are greatly appreciated. Thanks, Paulo -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070815/45961519/attachment.htm From vanneth at yahoo.com Wed Aug 15 19:08:13 2007 From: vanneth at yahoo.com (Vanneth Tea) Date: Wed, 15 Aug 2007 10:08:13 -0700 (PDT) Subject: [Tutor] Need help on "How to Think Like a Computer Scientist: Learning with Python". Message-ID: <111866.81435.qm@web62401.mail.re1.yahoo.com> Hello All, I am new to computer programming and chose to learn Python. Now I am stuck with certain codes that I need help. Please let me know if there is an answer list to the exercises in "How to Think Like a Computer Scientist: Learning with Python." I followed and did good on most of the exercises but I have been stuck on a few of them which burned me up after spending days and nights trying to make them works. I hope you understand the feeling when you are stuck and need a drop of water to keep alive. I really appreciate any assistance you can give. Thanks. ____________________________________________________________________________________ Fussy? Opinionated? Impossible to please? Perfect. Join Yahoo!'s user panel and lay it on us. http://surveylink.yahoo.com/gmrs/yahoo_panel_invite.asp?a=7 From vincent.gulinao at gmail.com Wed Aug 15 20:59:20 2007 From: vincent.gulinao at gmail.com (Vincent Gulinao) Date: Thu, 16 Aug 2007 02:59:20 +0800 Subject: [Tutor] Class Attribute "Overloading?" In-Reply-To: <46C34619.40909@alum.rpi.edu> References: <46C34619.40909@alum.rpi.edu> Message-ID: Sorry about that. I want something like: class foo: def __init__(self): self.attr1 = None def get_attr1(self): if not self.attr1: attr1 = self.attr1 = attr1 return self.attr1 such that: foo_instance = foo() then: foo_instance.get_attr1() and foo_instance.attr1 gets the same value. Such that you get to derive attr1 only as needed and just once, both outside and within foo class. Or is it a bad idea or just plain ugly to do something like that? If it is, kindly suggest better approach. Thanks. On 8/16/07, bob gailer wrote: > > Vincent Gulinao wrote: > > > > Sorry, I just started experimenting on Python classes... > > > > Is there any way a reference to a class attribute > > ([class].[attribute]) be treated like a method ([class].[method]())? > > > Attributes are objects. A method is an object. If you want to know > something more specific, please rephrase the question. > > I for one don't really know what you want. > > > > I have a class with DB component. Some of its attributes are derived > > from DB and I find it impractical to derive all at once upon __init__. > > > > Of course we can use dictionary-like syntax ([class]["[attribute]"]) > > and use __getitem__, checking for existence and None of the attribute > > before deriving the value from the DB. But I think [class].[attribute] > > is more conventional (Is it?). Or someone suggest a more Pythonic way. > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070816/03f8e9ae/attachment-0001.html From kent37 at tds.net Wed Aug 15 23:13:01 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 15 Aug 2007 17:13:01 -0400 Subject: [Tutor] Class Attribute "Overloading?" In-Reply-To: <46C34619.40909@alum.rpi.edu> References: <46C34619.40909@alum.rpi.edu> Message-ID: <46C36C5D.9080909@tds.net> bob gailer wrote: > Vincent Gulinao wrote: >> Sorry, I just started experimenting on Python classes... >> >> Is there any way a reference to a class attribute >> ([class].[attribute]) be treated like a method ([class].[method]())? >> > Attributes are objects. A method is an object. If you want to know > something more specific, please rephrase the question. > I for one don't really know what you want. And since wesley, Alan and I have given completely different answers, I guess none of us know. A clearer question is clearly needed. Kent From amadeo.bellotti at gmail.com Wed Aug 15 23:27:52 2007 From: amadeo.bellotti at gmail.com (Amadeo Bellotti) Date: Wed, 15 Aug 2007 17:27:52 -0400 Subject: [Tutor] Need help on "How to Think Like a Computer Scientist: Learning with Python". In-Reply-To: <111866.81435.qm@web62401.mail.re1.yahoo.com> References: <111866.81435.qm@web62401.mail.re1.yahoo.com> Message-ID: I don't know of any answer list but one you can ask for help here or what I do when I have a question i stop working on it for anywhere from an hour to a week and go back to it you will solve it if you solve it in your sleep well thats a whole other issue but that does happen. -Amadeo On 8/15/07, Vanneth Tea wrote: > > Hello All, > > I am new to computer programming and chose to learn > Python. Now I am stuck with certain codes that I need > help. Please let me know if there is an answer list > to the exercises in "How to Think Like a Computer > Scientist: Learning with Python." > > I followed and did good on most of the exercises but I > have been stuck on a few of them which burned me up > after spending days and nights trying to make them > works. > > I hope you understand the feeling when you are stuck > and need a drop of water to keep alive. I really > appreciate any assistance you can give. > > Thanks. > > > > > > > ____________________________________________________________________________________ > Fussy? Opinionated? Impossible to please? Perfect. Join Yahoo!'s user > panel and lay it on us. > http://surveylink.yahoo.com/gmrs/yahoo_panel_invite.asp?a=7 > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070815/c046b6fb/attachment.htm From bhaaluu at gmail.com Wed Aug 15 23:29:07 2007 From: bhaaluu at gmail.com (bhaaluu) Date: Wed, 15 Aug 2007 17:29:07 -0400 Subject: [Tutor] Need help on "How to Think Like a Computer Scientist: Learning with Python". In-Reply-To: <111866.81435.qm@web62401.mail.re1.yahoo.com> References: <111866.81435.qm@web62401.mail.re1.yahoo.com> Message-ID: Greetings, I think the accepted way to get help on this list is to post the code you're having problems with, showing what you've done, the error messages you're getting, and an explanation of what you're trying to do, the input, output expected, and so forth. It is helpful for the Tutors to also know the platform/version you're working on (MS-XP, Linux kernel 2.6, Mac OSX), as well as the version of Python you're using 2.2, 2.3, 2.4, 2.5.... -- bhaaluu at gmail dot com On 8/15/07, Vanneth Tea wrote: > Hello All, > > I am new to computer programming and chose to learn > Python. Now I am stuck with certain codes that I need > help. Please let me know if there is an answer list > to the exercises in "How to Think Like a Computer > Scientist: Learning with Python." > > I followed and did good on most of the exercises but I > have been stuck on a few of them which burned me up > after spending days and nights trying to make them > works. > > I hope you understand the feeling when you are stuck > and need a drop of water to keep alive. I really > appreciate any assistance you can give. > > Thanks. > > > > > > ____________________________________________________________________________________ > Fussy? Opinionated? Impossible to please? Perfect. Join Yahoo!'s user panel and lay it on us. http://surveylink.yahoo.com/gmrs/yahoo_panel_invite.asp?a=7 > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From brunson at brunson.com Wed Aug 15 23:29:54 2007 From: brunson at brunson.com (Eric Brunson) Date: Wed, 15 Aug 2007 15:29:54 -0600 Subject: [Tutor] Need help on "How to Think Like a Computer Scientist: Learning with Python". In-Reply-To: <111866.81435.qm@web62401.mail.re1.yahoo.com> References: <111866.81435.qm@web62401.mail.re1.yahoo.com> Message-ID: <46C37052.5000305@brunson.com> I don't know of an answer key, but feel free to post questions about what you're having trouble with and we'd be happy to discuss various approaches among the list members. Vanneth Tea wrote: > Hello All, > > I am new to computer programming and chose to learn > Python. Now I am stuck with certain codes that I need > help. Please let me know if there is an answer list > to the exercises in "How to Think Like a Computer > Scientist: Learning with Python." > > I followed and did good on most of the exercises but I > have been stuck on a few of them which burned me up > after spending days and nights trying to make them > works. > > I hope you understand the feeling when you are stuck > and need a drop of water to keep alive. I really > appreciate any assistance you can give. > > Thanks. > > > > > > ____________________________________________________________________________________ > Fussy? Opinionated? Impossible to please? Perfect. Join Yahoo!'s user panel and lay it on us. http://surveylink.yahoo.com/gmrs/yahoo_panel_invite.asp?a=7 > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Wed Aug 15 23:32:57 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 15 Aug 2007 17:32:57 -0400 Subject: [Tutor] Need help on "How to Think Like a Computer Scientist: Learning with Python". In-Reply-To: <111866.81435.qm@web62401.mail.re1.yahoo.com> References: <111866.81435.qm@web62401.mail.re1.yahoo.com> Message-ID: <46C37109.90106@tds.net> Vanneth Tea wrote: > Hello All, > > I am new to computer programming and chose to learn > Python. Now I am stuck with certain codes that I need > help. Where are you stuck? We should be able to help you here if you can be more specific. It helps us to help you if you can show us - the code you have tried - what happens when you run the code - the specific error message and traceback, if that is what you get - what you want to happen Kent From kent37 at tds.net Wed Aug 15 23:33:46 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 15 Aug 2007 17:33:46 -0400 Subject: [Tutor] open multiple files In-Reply-To: <501789.94479.qm@web52206.mail.re2.yahoo.com> References: <501789.94479.qm@web52206.mail.re2.yahoo.com> Message-ID: <46C3713A.1040504@tds.net> Paulo Quaglio wrote: > Hi everyone - > I'm beginning to learn how to program in python. I need to process > several text files simultaneously. The program needs to open several > files (like a corpus) and output the total number of words. I can do > that with just one file but not the whole directory. I tried glob but it > didn't work. Your ideas are greatly appreciated. Can you show us what you have so far? Is this a homework problem? Kent From fiveholiday55 at hotmail.com Wed Aug 15 23:55:03 2007 From: fiveholiday55 at hotmail.com (Henry Dominik) Date: Wed, 15 Aug 2007 22:55:03 +0100 Subject: [Tutor] Need help on "How to Think Like a Computer Scientist:Learning with Python". References: <111866.81435.qm@web62401.mail.re1.yahoo.com> Message-ID: We've all been there. But what exactly is the problem you're having? Its really hard to know what sort of help you require if you didn't tell us what the problem is. Please help us to help you! Ciao ----- Original Message ----- From: "Vanneth Tea" To: Sent: Wednesday, August 15, 2007 6:08 PM Subject: [Tutor] Need help on "How to Think Like a Computer Scientist:Learning with Python". > Hello All, > > I am new to computer programming and chose to learn > Python. Now I am stuck with certain codes that I need > help. Please let me know if there is an answer list > to the exercises in "How to Think Like a Computer > Scientist: Learning with Python." > > I followed and did good on most of the exercises but I > have been stuck on a few of them which burned me up > after spending days and nights trying to make them > works. > > I hope you understand the feeling when you are stuck > and need a drop of water to keep alive. I really > appreciate any assistance you can give. > > Thanks. > > > > > > > ____________________________________________________________________________________ > Fussy? Opinionated? Impossible to please? Perfect. Join Yahoo!'s user > panel and lay it on us. > http://surveylink.yahoo.com/gmrs/yahoo_panel_invite.asp?a=7 > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Wed Aug 15 23:57:14 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 15 Aug 2007 17:57:14 -0400 Subject: [Tutor] Class Attribute "Overloading?" In-Reply-To: References: <46C34619.40909@alum.rpi.edu> Message-ID: <46C376BA.8070009@tds.net> Vincent Gulinao wrote: > Sorry about that. I want something like: > > class foo: > > def __init__(self): > > self.attr1 = None > > > def get_attr1(self): > > if not self.attr1: > > attr1 = > > self.attr1 = attr1 > > return self.attr1 > > > such that: > > foo_instance = foo() > > then: > > foo_instance.get_attr1() > > and > > foo_instance.attr1 > > gets the same value. > > > Such that you get to derive attr1 only as needed and just once, both > outside and within foo class. I would do it like this: class Foo(object): def __getattr__(self, attr): if not : raise AttributeError( "'%s' object has no attribute '%s'" % (self.__class__.__name__, attr)) value = setattr(self, attr, value) return value You don't need to init attr1 and you don't need get_attr1(). The first time you try to read foo.attr1, there will be no attr1 attribute so __getattr(self, 'attr1') will be called. You read the value from the database and save it as an ordinary attribute; future accesses will read the ordinary attribute and skip the __getattr__() call. Kent From john at fouhy.net Thu Aug 16 00:09:42 2007 From: john at fouhy.net (John Fouhy) Date: Thu, 16 Aug 2007 10:09:42 +1200 Subject: [Tutor] xls file In-Reply-To: <46C3213B.6050709@verizon.net> References: <46C27741.4050902@verizon.net> <5e58f2e40708142057u6b6dadb3oe59814c30d242541@mail.gmail.com> <46C3213B.6050709@verizon.net> Message-ID: <5e58f2e40708151509uc2f1a26o2982f554b1477ee9@mail.gmail.com> Really? What are you having trouble with? I have used pyexcelerator under Windows without problems. -- John. On 16/08/07, Kirk Bailey wrote: > looks good. works bad; this is a windows workplace. ouch. Advice please > (other than change operating systems)? > > John Fouhy wrote: > > On 15/08/07, Kirk Bailey wrote: > >> Ii want to read a xls file and use the data in part of it. What module > >> would help make sense of one? > > > > I have used pyExcelerator in the past. You can find it with google. > > > > Sample usage: > > > > import pyExcelerator > > workbook = pyExcelerator.parse_xls('filename.xls') > > worksheet = workbook['Sheet 1'] > > # print cells A1 and B1 > > print worksheet[(0,0)], worksheet[(0,1)] > > > > -- > Salute! > -Kirk Bailey > Think > +-----+ > | BOX | > +-----+ > knihT > > Fnord. > From rdm at rcblue.com Thu Aug 16 00:43:02 2007 From: rdm at rcblue.com (Dick Moores) Date: Wed, 15 Aug 2007 15:43:02 -0700 Subject: [Tutor] Need to convert 1,987,087,234,456 to an int Message-ID: <20070815224322.D7D031E4013@bag.python.org> If a line in a script has n = "1,987,087,234,456" It's simple to convert the string, "1,987,087,234,456" to an int, but I can't figure out how to do it for n = 1,987,087,234,456 # no quotes (I want to be able to type in big ints using commas--much easier to see that I've typed correctly) Python sees 1,987,077,234,456 as a tuple: >>>type(1,987,077,234,456) But: >>>type(1,987,087,234,456) File "", line 1 type(1,987,087,234,456) ^ SyntaxError: invalid token (My wild guess is that 087 is octal.) Anyway, I need to convert things such as 1,987,077,234,456 to ints. This will do it: (m can also be an int such as 1987077234456) if type(m) == tuple: mAsStr = "" for part in m: part = str(part) mAsStr += part m = int(mAsStr) So this is fine as long as none of the parts of the tuple is of the form 08X (where X is from 0-9). What to do? Thanks, Dick Moores From dkuhlman at rexx.com Thu Aug 16 00:50:00 2007 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Wed, 15 Aug 2007 15:50:00 -0700 Subject: [Tutor] open multiple files In-Reply-To: <501789.94479.qm@web52206.mail.re2.yahoo.com> References: <501789.94479.qm@web52206.mail.re2.yahoo.com> Message-ID: <20070815225000.GA37886@cutter.rexx.com> On Wed, Aug 15, 2007 at 08:26:45AM -0700, Paulo Quaglio wrote: > Hi everyone - > I'm beginning to learn how to program in python. I need to > process several text files simultaneously. The program needs to > open several files (like a corpus) and output the total number > of words. I can do that with just one file but not the whole > directory. I tried glob but it didn't work. Your ideas are > greatly appreciated. Thanks, Here is a pattern that you might use (if I understand your problem correctly): import glob names = glob.glob('*.txt') for name in names: infile = open(name, 'r') etc. etc infile.close() Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman From keridee at jayco.net Thu Aug 16 02:08:20 2007 From: keridee at jayco.net (Tiger12506) Date: Wed, 15 Aug 2007 19:08:20 -0500 Subject: [Tutor] open multiple files References: <501789.94479.qm@web52206.mail.re2.yahoo.com> Message-ID: <004a01c7df99$91f6a800$f6fce004@JSLAPTOP> > Hi everyone - > I'm beginning to learn how to program in python. I need to process > several text files simultaneously. The program needs to open several files > (like a corpus) and output the total number of words. I can do that with > just one file but not the whole directory. I tried glob but it didn't > work. Your ideas are greatly appreciated. Thanks, > Paulo What do you have so far? I don't just want to give you an answer. You say that glob didn't work... Probably because you are not realizing that glob returns a list of filenames, and you can't open a whole list at a time. You'll have to use a loop or something similar. JS From keridee at jayco.net Thu Aug 16 02:22:33 2007 From: keridee at jayco.net (Tiger12506) Date: Wed, 15 Aug 2007 19:22:33 -0500 Subject: [Tutor] Class Attribute "Overloading?" References: <46C34619.40909@alum.rpi.edu> Message-ID: <00b301c7df9b$8e1eda20$f6fce004@JSLAPTOP> > Sorry about that. I want something like: > > class foo: > > def __init__(self): > > self.attr1 = None > > > def get_attr1(self): > > if not self.attr1: > > attr1 = > > self.attr1 = attr1 > > return self.attr1 > > > such that: > > foo_instance = foo() > > then: > > foo_instance.get_attr1() > > and > > foo_instance.attr1 > > gets the same value. > > Such that you get to derive attr1 only as needed and just once, both > outside > and within foo class. > > Or is it a bad idea or just plain ugly to do something like that? If it > is, > kindly suggest better approach. > > Thanks. It's a little ugly but not too bad. What you are describing are properties. class Foo: def _get_attr1(self): if not self.attr1: attr1 = TheValue return attr1 def _set_attr1(self, value): self.attr1 = value ChangeDBFunction(value) attr1 = property(self._get_attr1,self._setattr1,None,None) I think that will work. The docs seem to suggest that you should subclass `object`. JS From alan.gauld at btinternet.com Thu Aug 16 01:28:30 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 16 Aug 2007 00:28:30 +0100 Subject: [Tutor] Class Attribute "Overloading?" References: <46C34619.40909@alum.rpi.edu> Message-ID: "Vincent Gulinao" wrote in message news:fcc3e6170708151159lf302c3er636eabb627606f23 at mail.gmail.com... > Sorry about that. I want something like: > > class foo: > > def __init__(self): > self.attr1 = None > def get_attr1(self): > if not self.attr1: > attr1 = > self.attr1 = attr1 > return self.attr1 > > such that: > foo_instance = foo() > foo_instance.get_attr1() > foo_instance.attr1 > > gets the same value. That looks like an ideal candidate for a "property". Using a property you can treat it as a data item but behind the scenes call a getter and setter method. In your case the getter would be the method you have above and the setter could write the new value to the database, if needed. Thus after defining the property attr1 you access like: foo_instance = Foo() print foo.attr1 # executes the getter foo.attr1 = 42 # executes the setter HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Thu Aug 16 01:33:34 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 16 Aug 2007 00:33:34 +0100 Subject: [Tutor] open multiple files References: <501789.94479.qm@web52206.mail.re2.yahoo.com> Message-ID: "Paulo Quaglio" wrote > I'm beginning to learn how to program in python. > I need to process several text files simultaneously. Do you really mean simultaneously or just all in the same execution of the program? ie The one program run opens each file in sequence and reports the total?. > The program needs to open several files (like a corpus) > and output the total number of words. OK, That sounds straightforward. > I can do that with just one file but not the whole directory. > I tried glob but it didn't work. glob usually works so I assume you mean that you didn't get it to do what you wanted? Recall that glob returns a list of filenames. You need to iterate over that list processing each file in turn. Can you show us a nbbit more of how you tried it? The code should be short enough that you can post it here on the list. Also post any error messages (the whole message not a summary). HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Thu Aug 16 01:37:01 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 16 Aug 2007 00:37:01 +0100 Subject: [Tutor] Need help on "How to Think Like a Computer Scientist:Learning with Python". References: <111866.81435.qm@web62401.mail.re1.yahoo.com> Message-ID: "Vanneth Tea" wrote > have been stuck on a few of them which burned me up > after spending days and nights trying ... > I hope you understand the feeling when you are stuck Yep we all understand and sympathise. But before we can help you we need some more information. Like: what are you trying to do and what is not working. Post short code examples and full error messages. Don't assume we know what the tutorial exercises are, provide the context of the problem too. If you do that there is a very good chance we can help you. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Thu Aug 16 01:38:50 2007 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Wed, 15 Aug 2007 23:38:50 +0000 (GMT) Subject: [Tutor] Fw: KeyError list? Message-ID: <418009.25451.qm@web86115.mail.ird.yahoo.com> Forwarding to list for completeness ----- Forwarded Message ---- From: Rob Andrews To: Alan Gauld Sent: Wednesday, 15 August, 2007 10:32:30 PM Subject: Re: [Tutor] KeyError list? I guess I couldn't believe it was that simple. ;-) Sorry for the delayed, brief reply. I'm on my Treo while my workstation appends data to a sizable collection of demographic data. -Rob -- Libertarian Party of Mississippi: http://mslp.org -------------- next part -------------- I guess I couldn't believe it was that simple. ;-) Sorry for the delayed, brief reply. I'm on my Treo while my workstation appends data to a sizable collection of demographic data. -Rob -- Libertarian Party of Mississippi: http://mslp.org From rabidpoobear at gmail.com Thu Aug 16 02:26:44 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Wed, 15 Aug 2007 19:26:44 -0500 Subject: [Tutor] Need help on "How to Think Like a Computer Scientist: Learning with Python". In-Reply-To: <111866.81435.qm@web62401.mail.re1.yahoo.com> References: <111866.81435.qm@web62401.mail.re1.yahoo.com> Message-ID: <46C399C4.9070107@gmail.com> Vanneth Tea wrote: > Hello All, > > I am new to computer programming and chose to learn > Python. Now I am stuck with certain codes that I need > help. Please let me know if there is an answer list > to the exercises in "How to Think Like a Computer > Scientist: Learning with Python." > > I followed and did good on most of the exercises but I > have been stuck on a few of them which burned me up > after spending days and nights trying to make them > works. > > I hope you understand the feeling when you are stuck > and need a drop of water to keep alive. I really > appreciate any assistance you can give. > I don't know if there's a site specifically for that book - check google maybe? As far as specific questions go, though, if you let us know what problem you're having we'd love to try to help you fix it. -Luke From dgj502 at york.ac.uk Thu Aug 16 02:49:58 2007 From: dgj502 at york.ac.uk (dgj502 at york.ac.uk) Date: 16 Aug 2007 01:49:58 +0100 Subject: [Tutor] Getting Date/Time from a file and using it in calculations Message-ID: Hello there Messing around with certain time and datetime objects, I have managed to subtract a date/time from the present time thusly: from time import * import datetime one = datetime.datetime.now() two = datetime.datetime(2007, 8, 29, 11, 15, 00) difference = one - two print difference However, I have to take a date from a file and then insert it to where two should be, however to no success. I have managed to get a string containing the above date/time, but that is as far as I've gotten without it not working. Does anyone have any ideas on how to do this properly? Also I wish to display the result only in seconds left, rather than the current result, which just displays days/hours/minutes/seconds/milliseconds left, but am again struggling to progress. Any help would be amazingly appreciated :) Thanks again -Dave From kent37 at tds.net Thu Aug 16 03:49:59 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 15 Aug 2007 21:49:59 -0400 Subject: [Tutor] Class Attribute "Overloading?" In-Reply-To: <00b301c7df9b$8e1eda20$f6fce004@JSLAPTOP> References: <46C34619.40909@alum.rpi.edu> <00b301c7df9b$8e1eda20$f6fce004@JSLAPTOP> Message-ID: <46C3AD47.6070809@tds.net> Tiger12506 wrote: > It's a little ugly but not too bad. What you are describing are properties. > > class Foo: should be class Foo(object): > def _get_attr1(self): > if not self.attr1: > attr1 = TheValue > return attr1 You have to use a different name for the actual data attribute and the property (stack overflow, anyone?), and you didn't save the value. if not self._attr1: self._attr1 = TheValue return self._attr1 > def _set_attr1(self, value): > self.attr1 = value > ChangeDBFunction(value) > attr1 = property(self._get_attr1,self._setattr1,None,None) A read-only property might be more appropriate (no _set_attr1). > > I think that will work. The docs seem to suggest that you should subclass > `object`. That is required. Properties do not work correctly with old-style classes (not derived from object). Kent From kent37 at tds.net Thu Aug 16 03:51:31 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 15 Aug 2007 21:51:31 -0400 Subject: [Tutor] Class Attribute "Overloading?" In-Reply-To: References: <46C34619.40909@alum.rpi.edu> Message-ID: <46C3ADA3.9050501@tds.net> Alan Gauld wrote: > "Vincent Gulinao" wrote in message > news:fcc3e6170708151159lf302c3er636eabb627606f23 at mail.gmail.com... >> Sorry about that. I want something like: >> >> class foo: >> >> def __init__(self): >> self.attr1 = None >> def get_attr1(self): >> if not self.attr1: >> attr1 = >> self.attr1 = attr1 >> return self.attr1 >> >> such that: >> foo_instance = foo() >> foo_instance.get_attr1() >> foo_instance.attr1 >> >> gets the same value. > > > That looks like an ideal candidate for a "property". I guess the requirements are still not clear. If there is just one attribute to be read from the database, a property will work well. If the OP wants to delegate many attributes, the __getattr__ approach might be simpler. Kent From john at fouhy.net Thu Aug 16 03:58:06 2007 From: john at fouhy.net (John Fouhy) Date: Thu, 16 Aug 2007 13:58:06 +1200 Subject: [Tutor] Need to convert 1,987,087,234,456 to an int In-Reply-To: <20070815224322.D7D031E4013@bag.python.org> References: <20070815224322.D7D031E4013@bag.python.org> Message-ID: <5e58f2e40708151858n7b27b1eer114df2ff86b21bb6@mail.gmail.com> On 16/08/07, Dick Moores wrote: > Python sees 1,987,077,234,456 as a tuple: > >>>type(1,987,077,234,456) > Hmm, not for me: >>> type(1,987,077,234,456) Traceback (most recent call last): File "", line 1, in TypeError: type() takes 1 or 3 arguments What python are you using? (2.5.1 for me) > I need to convert things such as 1,987,077,234,456 to ints. You could do this: >>> def decomma(*t): ... return int(''.join(str(i) for i in t)) ... Thus: >>> decomma(1,234,567) 1234567 Of course, if you have: >>> n = 1,234,567 Then you can't do this: >>> decomma(n) Instead, do this: >>> decomma(*n) 1234567 -- John. From rdm at rcblue.com Thu Aug 16 04:31:37 2007 From: rdm at rcblue.com (Dick Moores) Date: Wed, 15 Aug 2007 19:31:37 -0700 Subject: [Tutor] Need to convert 1,987,087,234,456 to an int In-Reply-To: <5e58f2e40708151858n7b27b1eer114df2ff86b21bb6@mail.gmail.co m> References: <20070815224322.D7D031E4013@bag.python.org> <5e58f2e40708151858n7b27b1eer114df2ff86b21bb6@mail.gmail.com> Message-ID: <20070816023215.1DB791E4002@bag.python.org> At 06:58 PM 8/15/2007, John Fouhy wrote: >On 16/08/07, Dick Moores wrote: > > Python sees 1,987,077,234,456 as a tuple: > > >>>type(1,987,077,234,456) > > > >Hmm, not for me: > > >>> type(1,987,077,234,456) >Traceback (most recent call last): > File "", line 1, in >TypeError: type() takes 1 or 3 arguments Tried again just now, and I got what you got. However: >>>m = 1,987,077,234,456 >>>type(m) == tuple True >What python are you using? (2.5.1 for me) XP, Python 2.5, editor is Ulipad > > I need to convert things such as 1,987,077,234,456 to ints. > >You could do this: > > >>> def decomma(*t): >... return int(''.join(str(i) for i in t)) >... > >Thus: > > >>> decomma(1,234,567) >1234567 That's cool! However, it doesn't solve the problem in my original post. >>> t = 1,987,087,234,456 File "", line 1 t = 1,987,087,234,456 ^ SyntaxError: invalid token >>> def decomma(*t): return int(''.join(str(i) for i in t)) >>> decomma(1,987,087,234,456) File "", line 1 decomma(1,987,087,234,456) ^ SyntaxError: invalid token Dick From wescpy at gmail.com Thu Aug 16 04:35:05 2007 From: wescpy at gmail.com (wesley chun) Date: Wed, 15 Aug 2007 19:35:05 -0700 Subject: [Tutor] Fw: KeyError list? In-Reply-To: <418009.25451.qm@web86115.mail.ird.yahoo.com> References: <418009.25451.qm@web86115.mail.ird.yahoo.com> Message-ID: <78b3a9580708151935t52bdf9f8s26f7959ca5343ec@mail.gmail.com> > I guess I couldn't believe it was that simple. ;-) now if you had asked about the meanings of *all* exceptions (including warnings), or perhaps all the SMTP exceptions in smtplib, that would another matter. ;-) cheers, -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From rob.andrews at gmail.com Thu Aug 16 04:53:32 2007 From: rob.andrews at gmail.com (Rob Andrews) Date: Wed, 15 Aug 2007 21:53:32 -0500 Subject: [Tutor] Fw: KeyError list? In-Reply-To: <78b3a9580708151935t52bdf9f8s26f7959ca5343ec@mail.gmail.com> References: <418009.25451.qm@web86115.mail.ird.yahoo.com> <78b3a9580708151935t52bdf9f8s26f7959ca5343ec@mail.gmail.com> Message-ID: <8d757d2e0708151953k137a2ba3l4aa49c1335a4e82d@mail.gmail.com> At my current day job, I'm handed a wild variety of data from customers, and most of it hasn't been normalized in any reasonable way. File formats are inconsistent, numbers of fields are randomly inconsistent with the headers, etc. Attempting to massage these into files I can process has involved a lot of "throw-away" scripting, and I've caught myself doing some really questionable things with basic data structures, leading to my original question. Dictionary key errors have been the most common here lately, popping up in a fairly wide range of circumstances due to seemingly random data. On 8/15/07, wesley chun wrote: > > I guess I couldn't believe it was that simple. ;-) > > now if you had asked about the meanings of *all* exceptions (including > warnings), or perhaps all the SMTP exceptions in smtplib, that would > another matter. ;-) From brunson at brunson.com Thu Aug 16 04:53:16 2007 From: brunson at brunson.com (Eric Brunson) Date: Wed, 15 Aug 2007 20:53:16 -0600 Subject: [Tutor] Getting Date/Time from a file and using it in calculations In-Reply-To: References: Message-ID: <46C3BC1C.7090409@brunson.com> dgj502 at york.ac.uk wrote: > Hello there > > Messing around with certain time and datetime objects, I have managed to > subtract a date/time from the present time thusly: > datetime is definitely a module that takes a little getting used to. > from time import * > (Bad form) > import datetime > > one = datetime.datetime.now() > two = datetime.datetime(2007, 8, 29, 11, 15, 00) > > difference = one - two > > print difference > > However, I have to take a date from a file and then insert it to where two > should be, however to no success. I have managed to get a string containing > the above date/time, but that is as far as I've gotten without it not > working. > You don't show the format of the date string, but I'll show an example: >>> from datetime import datetime >>> start = datetime.strptime( '10:24:03 2006-11-01', '%H:%M:%S %Y-%m-%d' ) >>> end = datetime.strptime( '11:10:33 2006-11-01', '%H:%M:%S %Y-%m-%d' ) >>> delta = end - start >>> print delta.seconds 2790 Is that what you need? Take a skim through the library reference for the entire module. The result of the subtraction is a timedelta object, you kind of need to know what's available overall to be able to pick out the right functionality. Hope that helps, e. > Does anyone have any ideas on how to do this properly? > > Also I wish to display the result only in seconds left, rather than the > current result, which just displays days/hours/minutes/seconds/milliseconds > left, but am again struggling to progress. > > Any help would be amazingly appreciated :) > > Thanks again > > -Dave > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From john at fouhy.net Thu Aug 16 04:57:27 2007 From: john at fouhy.net (John Fouhy) Date: Thu, 16 Aug 2007 14:57:27 +1200 Subject: [Tutor] Need to convert 1,987,087,234,456 to an int In-Reply-To: <20070816023215.1DB791E4002@bag.python.org> References: <20070815224322.D7D031E4013@bag.python.org> <5e58f2e40708151858n7b27b1eer114df2ff86b21bb6@mail.gmail.com> <20070816023215.1DB791E4002@bag.python.org> Message-ID: <5e58f2e40708151957k2e75c2f8h3605b9adb69a5bba@mail.gmail.com> On 16/08/07, Dick Moores wrote: > That's cool! However, it doesn't solve the problem in my original post. > > >>> t = 1,987,087,234,456 > File "", line 1 > t = 1,987,087,234,456 > ^ > SyntaxError: invalid token Hmm, yes. Any integer starting with a 0 is octal, which means that using '8' or '9' is a syntax error. Also, even if you don't get the syntax error, the numbers will come out differently. >>> decomma(1,024) 120 It'll be fixed in Python 3000 :-) -- John. From rdm at rcblue.com Thu Aug 16 05:12:03 2007 From: rdm at rcblue.com (Dick Moores) Date: Wed, 15 Aug 2007 20:12:03 -0700 Subject: [Tutor] Need to convert 1,987,087,234,456 to an int In-Reply-To: <5e58f2e40708151858n7b27b1eer114df2ff86b21bb6@mail.gmail.co m> References: <20070815224322.D7D031E4013@bag.python.org> <5e58f2e40708151858n7b27b1eer114df2ff86b21bb6@mail.gmail.com> Message-ID: <20070816031212.341901E4016@bag.python.org> At 06:58 PM 8/15/2007, John Fouhy wrote: >What python are you using? (2.5.1 for me) 2.5. If I install 2.51 will it install itself "over" my 2.5? Or will it set itself up in a separate Python 251 folder/directory? Dick From mwalsh at groktech.org Thu Aug 16 05:12:17 2007 From: mwalsh at groktech.org (Martin Walsh) Date: Wed, 15 Aug 2007 22:12:17 -0500 Subject: [Tutor] Getting Date/Time from a file and using it in calculations In-Reply-To: References: Message-ID: <46C3C091.4000407@groktech.org> dgj502 at york.ac.uk wrote: > Hello there > > Messing around with certain time and datetime objects, I have managed to > subtract a date/time from the present time thusly: > > from time import * > import datetime > > one = datetime.datetime.now() > two = datetime.datetime(2007, 8, 29, 11, 15, 00) > > difference = one - two > > print difference > > However, I have to take a date from a file and then insert it to where two > should be, however to no success. I have managed to get a string containing > the above date/time, but that is as far as I've gotten without it not > working. > > Does anyone have any ideas on how to do this properly? > > Also I wish to display the result only in seconds left, rather than the > current result, which just displays days/hours/minutes/seconds/milliseconds > left, but am again struggling to progress. Have a look at time.strptime (and time.mktime) -- you may be able to drop datetime entirely. Here is my attempt (not tested): import time time_string = '2007/08/15 22:10:21' one = time.time() # now two = time.mktime(time.strptime(time_string, '%Y/%m/%d %H:%M:%S')) # difference in seconds (float) difference = one - two HTH, Marty From rdm at rcblue.com Thu Aug 16 05:14:38 2007 From: rdm at rcblue.com (Dick Moores) Date: Wed, 15 Aug 2007 20:14:38 -0700 Subject: [Tutor] Need to convert 1,987,087,234,456 to an int In-Reply-To: <5e58f2e40708151858n7b27b1eer114df2ff86b21bb6@mail.gmail.co m> References: <20070815224322.D7D031E4013@bag.python.org> <5e58f2e40708151858n7b27b1eer114df2ff86b21bb6@mail.gmail.com> Message-ID: <20070816031504.57AA91E4002@bag.python.org> At 06:58 PM 8/15/2007, John Fouhy wrote: >You could do this: > > >>> def decomma(*t): >... return int(''.join(str(i) for i in t)) What's that asterisk doing in decomma(*t)? Where do I go in the docs to look it up? Thanks, Dick From sli1que at yahoo.com Thu Aug 16 05:23:59 2007 From: sli1que at yahoo.com (Eric Walker) Date: Wed, 15 Aug 2007 20:23:59 -0700 (PDT) Subject: [Tutor] Need to convert 1,987,087,234,456 to an int In-Reply-To: <20070816031504.57AA91E4002@bag.python.org> Message-ID: <529214.43243.qm@web60121.mail.yahoo.com> I am a newbie but think its for variable input. Allows you to enter any number with commas in it and still work properly. Since it thinks the number is a tuple, then depending on the number your tuple could vary in length. Eric Walker Dick Moores wrote: At 06:58 PM 8/15/2007, John Fouhy wrote: >You could do this: > > >>> def decomma(*t): >... return int(''.join(str(i) for i in t)) What's that asterisk doing in decomma(*t)? Where do I go in the docs to look it up? Thanks, Dick _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor --------------------------------- Ready for the edge of your seat? Check out tonight's top picks on Yahoo! TV. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070815/ea5bdadd/attachment.html From john at fouhy.net Thu Aug 16 05:35:54 2007 From: john at fouhy.net (John Fouhy) Date: Thu, 16 Aug 2007 15:35:54 +1200 Subject: [Tutor] Need to convert 1,987,087,234,456 to an int In-Reply-To: <1187234059_47639@NIT-MAIL-101> References: <20070815224322.D7D031E4013@bag.python.org> <5e58f2e40708151858n7b27b1eer114df2ff86b21bb6@mail.gmail.com> <1187234059_47639@NIT-MAIL-101> Message-ID: <5e58f2e40708152035p7af2cc0elc6ea478eccc26204@mail.gmail.com> On 16/08/07, Dick Moores wrote: > What's that asterisk doing in decomma(*t)? Where do I go in the docs > to look it up? You can find it in the tutorial: http://docs.python.org/tut/node6.html#SECTION006740000000000000000 Or see my post here: http://mail.python.org/pipermail/tutor/2007-April/053725.html -- John. From brunson at brunson.com Thu Aug 16 05:37:20 2007 From: brunson at brunson.com (Eric Brunson) Date: Wed, 15 Aug 2007 21:37:20 -0600 Subject: [Tutor] Need to convert 1,987,087,234,456 to an int In-Reply-To: <20070816031504.57AA91E4002@bag.python.org> References: <20070815224322.D7D031E4013@bag.python.org> <5e58f2e40708151858n7b27b1eer114df2ff86b21bb6@mail.gmail.com> <20070816031504.57AA91E4002@bag.python.org> Message-ID: <46C3C670.3060405@brunson.com> Dick Moores wrote: > At 06:58 PM 8/15/2007, John Fouhy wrote: > >> You could do this: >> >> >>>>> def decomma(*t): >>>>> >> ... return int(''.join(str(i) for i in t)) >> > > What's that asterisk doing in decomma(*t)? Where do I go in the docs > to look it up? > > It's the opposite of "def f( *args )" It's easiest to show by example: >>> def f( *args ): ... print args ... >>> f( 1 ) (1,) >>> f( 1, 2, 3 ) (1, 2, 3) >>> f( (1, 2, 3) ) ((1, 2, 3),) >>> f( *(1, 2, 3) ) (1, 2, 3) This is your brain on python. Any questions? :-) > Thanks, > > Dick > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From rdm at rcblue.com Thu Aug 16 07:13:10 2007 From: rdm at rcblue.com (Dick Moores) Date: Wed, 15 Aug 2007 22:13:10 -0700 Subject: [Tutor] Need to convert 1,987,087,234,456 to an int In-Reply-To: <46C3C670.3060405@brunson.com> References: <20070815224322.D7D031E4013@bag.python.org> <5e58f2e40708151858n7b27b1eer114df2ff86b21bb6@mail.gmail.com> <20070816031504.57AA91E4002@bag.python.org> <46C3C670.3060405@brunson.com> Message-ID: <20070816051439.0AB011E4002@bag.python.org> To Eric Walker, John Fouhy, and Eric Brunson: Thanks very much. I think I'm beginning to get it. At least I was able to write a couple of functions that do what I wanted: ========================= def f(n,m,*args): x = n*m for arg in args: product = arg*x x = product print product numbers = 10, 6, 7 f(3,4,*numbers) # ------------------------------------------ def g(*args): n = 0 for arg in args: sum = n + arg n = sum print sum numbers = 10, 6, 7, 5, 100 g(*numbers) ============================ They give me 5040 and 128, respectively. Dick From rdm at rcblue.com Thu Aug 16 07:54:15 2007 From: rdm at rcblue.com (Dick Moores) Date: Wed, 15 Aug 2007 22:54:15 -0700 Subject: [Tutor] Python Book Recommendations [Was:[Re: Security]] In-Reply-To: <46C24D64.8010407@tds.net> References: <46C24D64.8010407@tds.net> Message-ID: <20070816055447.E22C91E4010@bag.python.org> At 05:48 PM 8/14/2007, Kent Johnson wrote: >I also have a shortcut set up so if I type > py modulename >in the Firefox address bar it takes me directly to the docs for that >module. To do this, create a bookmark with this URL: >file://localhost/Users/kent/Library/Documentation/Python-Docs-2.5/lib/module-%s.html > >and give it the keyword 'py'. Great tips, Kent! I especially appreciate this one. Dick From duncan at thermal.esa.int Thu Aug 16 09:23:06 2007 From: duncan at thermal.esa.int (Duncan Gibson) Date: Thu, 16 Aug 2007 09:23:06 +0200 Subject: [Tutor] converting a source package into a dll/shared library? In-Reply-To: References: <20070814154009.76b9ce57.duncan@thermal.esa.int> <20070815104144.485e4792.duncan@thermal.esa.int> Message-ID: <20070816092306.20965b66.duncan@thermal.esa.int> Alan asked me: > As to access to the internal data would it be difficult to > parameterise it so that each companies data is in a > local config file? That way even if the dissasemble > the code it won't help? Unfortunately no. The input files are human readable geometrical models. Each tool has a different way of defining the basic shapes, coordinate systems and transformations, material properties, etc. so there's a lot of knowledge embedded in each of the reader modules to allow conversion from each tool's format to our own neutral format. We don't want to expose knowledge of the internals of one tool to its competitors. Anyway, this is now off-topic for this list so I'll stop here. Thanks for the help and suggestions. Duncan From alan.gauld at btinternet.com Thu Aug 16 10:07:08 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 16 Aug 2007 09:07:08 +0100 Subject: [Tutor] Need to convert 1,987,087,234,456 to an int References: <20070815224322.D7D031E4013@bag.python.org> Message-ID: "Dick Moores" wrote > I can't figure out how to do it for > n = 1,987,087,234,456 # no quotes > (I want to be able to type in big ints using commas--much easier to > see that I've typed correctly) I don't think you can. You are basically asking "how can I break the syntax rules?" http://docs.python.org/ref/integers.html > >>>type(1,987,087,234,456) > File "", line 1 > type(1,987,087,234,456) > ^ > SyntaxError: invalid token > (My wild guess is that 087 is octal.) Yes, see the reference above. An octal number is defined as starting with zero and followed by valid octal digits. That's why your scheme to use commas can't ever work - you are trying to change the language. Its a bit like deciding that you don;t like commas as list seperators and would prefer to use something else: [ 1 ? 2 ? 3 ? 4] Unfortunately that's not valid Python anmd it won't allow it. Same with invalid octal numbers... Sorry, Alan G. From timmichelsen at gmx-topmail.de Thu Aug 16 11:18:10 2007 From: timmichelsen at gmx-topmail.de (Tim Michelsen) Date: Thu, 16 Aug 2007 11:18:10 +0200 Subject: [Tutor] Python Book Recommendations [Was:[Re: Security]] In-Reply-To: References: Message-ID: <46C41652.8000706@gmx-topmail.de> Hey bhaaluu and list, > Have you seen this site yet? > > http://osl.iu.edu/~lums/swc/ Many many thanks for this link. Although it should be the most obvious to head to the source (python.org) I didn't go there. The above mentioned tutorial seem to cover exactly what I need and where I want do dig deeper it gives valuable references and links for futher readings. I'd recommend this to any non-programmer who likes to learn python to solve his "real-life" computer problems that arise in his/her science field of origin like earth/geo science, biology, physics or engineering. Once I will have finished this tutorial I may decide whether I by another book or not. > Another site that seems really helpful for scientists wanting > to learn Python is: > http://www.pasteur.fr/formation/infobio/python/ This one had already been mentioned on this thread, I guess. Regards, Timmie From tpc247 at gmail.com Thu Aug 16 11:56:54 2007 From: tpc247 at gmail.com (tpc247 at gmail.com) Date: Thu, 16 Aug 2007 02:56:54 -0700 Subject: [Tutor] unicode and character sets Message-ID: dear fellow Python enthusiasts, I recently wrote a script that grabs a file containing a list of ISO defined countries and creates an html select element. That's all well and good, and everything seems to work fine, except for one little nagging problem: http://en.wikipedia.org/wiki/Aland_Islands I use the Wikipedia url because I'm conscious of the fact that people reading this email might not be able to see the character I am having trouble displaying correctly, the LATIN CAPITAL LETTER A WITH RING ABOVE character. After reading the following article: http://www.joelonsoftware.com/articles/Unicode.html I realize the following: It does not make sense to have a string without knowing what encoding it uses. There is no such thing as plain text. Ok. Fine. In Mozilla, by clicking on View, Character Encoding, I find out that the text in the file I grab from: http://www.iso.ch/iso/en/prods-services/iso3166ma/02iso-3166-code-lists/index.html is encoded in ISO-8859-1. So I go about changing Python's default encoding according to: http://www.diveintopython.org/xml_processing/unicode.html and voila: >>> import sys >>> sys.getdefaultencoding() 'iso-8859-1' >>> BUT the LATIN CAPITAL LETTER A WITH RING ABOVE character still displays in IDLE as \xc5 ! I can get the character to display correctly if I type: print "\xc5" which is fine if I am simply going to copy and paste the select element into my html file. However, I want to be able to dynamically generate the html form page and have the character in question display correctly in the web browser. In case you're wondering, I've already done my due diligence to ensure the character set is ISO-8859-1 in my web server as well as in the html file: - in my html file, I put in: - I restarted apache after changing httpd.conf to add the line: AddDefaultCharset ISO-8859-1 The problem, of course, is that if I run my script that creates the select element in IDLE I continue to see the output: Am I doing something wrong ? def create_bidirectional_dicts_from_latest_ISO_countries(): import urllib ISO3166_FILE_URL = " http://www.iso.ch/iso/en/prods-services/iso3166ma/02iso-3166-code-lists/list-en1-semic.txt " a2_to_name = {} name_to_a2 = {} file_obj = urllib.urlopen(ISO3166_FILE_URL) for line in file_obj: if line.startswith("This list") or line.isspace(): pass else: a_list = line.split(';') ISO_name = a_list[0].title() ISO_a2 = a_list[1].strip() a2_to_name[ISO_a2] = ISO_name name_to_a2[ISO_name] = ISO_a2 file_obj.close() return a2_to_name, name_to_a2 def create_select_element_from_dict(name, a_dict, default_value=None): parent_wrapper = "" child_wrapper = "\t\n%s" element_template = "\t\n" default_element = "\t\n" a_str = "" for key in sorted(a_dict.keys()): if default_value and a_dict[key] == default_value: a_str = a_str + default_element % (default_value, key) a_str = a_str + element_template % (a_dict[key], key) c_w_instance = child_wrapper % a_str return parent_wrapper % (name, c_w_instance) a2_to_name, name_to_a2 = create_bidirectional_dicts_from_latest_ISO_countries() a_select = create_select_element_from_dict("country", name_to_a2) -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070816/5c6ccce1/attachment-0001.htm From kent37 at tds.net Thu Aug 16 13:58:59 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 16 Aug 2007 07:58:59 -0400 Subject: [Tutor] Fw: KeyError list? In-Reply-To: <8d757d2e0708151953k137a2ba3l4aa49c1335a4e82d@mail.gmail.com> References: <418009.25451.qm@web86115.mail.ird.yahoo.com> <78b3a9580708151935t52bdf9f8s26f7959ca5343ec@mail.gmail.com> <8d757d2e0708151953k137a2ba3l4aa49c1335a4e82d@mail.gmail.com> Message-ID: <46C43C03.7020404@tds.net> Rob Andrews wrote: > Attempting to massage these into files I can process has involved a > lot of "throw-away" scripting, and I've caught myself doing some > really questionable things with basic data structures, leading to my > original question. Dictionary key errors have been the most common > here lately, popping up in a fairly wide range of circumstances due to > seemingly random data. Do you know about dict.get()? It will return None or a default value of your choice if a key is missing. Might be helpful... In [1]: d={1: 2} In [2]: d[1] Out[2]: 2 In [3]: d[2] ------------------------------------------------------------ Traceback (most recent call last): File "", line 1, in : 2 In [4]: d.get(2) (no output, i.e. None) In [5]: d.get(2, 100) Out[5]: 100 Kent From kent37 at tds.net Thu Aug 16 14:11:34 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 16 Aug 2007 08:11:34 -0400 Subject: [Tutor] unicode and character sets In-Reply-To: References: Message-ID: <46C43EF6.1060609@tds.net> tpc247 at gmail.com wrote: > http://www.joelonsoftware.com/articles/Unicode.html > > I realize the following: It does not make sense to have a string without > knowing what encoding it uses. There is no such thing as plain text. Good start! > > Ok. Fine. In Mozilla, by clicking on View, Character Encoding, I find > out that the text in the file I grab from: > > http://www.iso.ch/iso/en/prods-services/iso3166ma/02iso-3166-code-lists/index.html > > is encoded in ISO-8859-1. So I go about changing Python's default > encoding according to: > > http://www.diveintopython.org/xml_processing/unicode.html I don't think this is necessary. Did it actually fix anything? Changing the default encoding is not recommended because it makes your scripts non-portable. > BUT the LATIN CAPITAL LETTER A WITH RING ABOVE character still displays > in IDLE as \xc5 ! I can get the character to display correctly if I type: > > print "\xc5" In many cases IDLE will display the repr() of a string which shows any non-ascii character as a hexidecimal escape. It is actually the correct character. print does not use the repr() so it displays correctly. > which is fine if I am simply going to copy and paste the select element > into my html file. However, I want to be able to dynamically generate > the html form page and have the character in question display correctly > in the web browser. > > The problem, of course, is that if I run my script that creates the > select element in IDLE I continue to see the output: > > > > Am I doing something wrong ? No, actually you are doing great. This is correct output, it is just not displaying in the form you expect. The data is correct. Kent From rdm at rcblue.com Thu Aug 16 14:22:54 2007 From: rdm at rcblue.com (Dick Moores) Date: Thu, 16 Aug 2007 05:22:54 -0700 Subject: [Tutor] Need to convert 1,987,087,234,456 to an int In-Reply-To: <595984.82278.qm@web86112.mail.ird.yahoo.com> References: <595984.82278.qm@web86112.mail.ird.yahoo.com> Message-ID: <20070816122318.C0BAF1E4002@bag.python.org> At 02:41 AM 8/16/2007, Alan Gauld wrote: >But Python 3000 is a semi mythical fancy that doesn't exist and may >never exist. >It is where all the ills of Python will be cured. Saying it is in Python 3000 >is usually a synonym for it won't be "fixed" anytime soon! But have you seen what Guido says? "We're closing in on the first Python 3000 alpha release (promised for the end of August)." Semi-mythical fancy? Dick From rob.andrews at gmail.com Thu Aug 16 14:57:40 2007 From: rob.andrews at gmail.com (Rob Andrews) Date: Thu, 16 Aug 2007 07:57:40 -0500 Subject: [Tutor] Fw: KeyError list? In-Reply-To: <46C43C03.7020404@tds.net> References: <418009.25451.qm@web86115.mail.ird.yahoo.com> <78b3a9580708151935t52bdf9f8s26f7959ca5343ec@mail.gmail.com> <8d757d2e0708151953k137a2ba3l4aa49c1335a4e82d@mail.gmail.com> <46C43C03.7020404@tds.net> Message-ID: <8d757d2e0708160557h1d3c2d05p67385862bac061d2@mail.gmail.com> I wasn't familiar with it prior to this thread, as previously I'd had the good fortune to use normalized data. I guess more pristine data environments spoiled me into writing less robust code. So although I asked what turned out to be the wrong question, I seem to be getting a consensus answer I'm sure I'll have a chance to put to the test over and over here. On 8/16/07, Kent Johnson wrote: > Do you know about dict.get()? It will return None or a default value of > your choice if a key is missing. Might be helpful... From kent37 at tds.net Thu Aug 16 15:46:46 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 16 Aug 2007 09:46:46 -0400 Subject: [Tutor] Python 3000 In-Reply-To: <20070816122318.C0BAF1E4002@bag.python.org> References: <595984.82278.qm@web86112.mail.ird.yahoo.com> <20070816122318.C0BAF1E4002@bag.python.org> Message-ID: <46C45546.9060507@tds.net> Dick Moores wrote: > At 02:41 AM 8/16/2007, Alan Gauld wrote: >> But Python 3000 is a semi mythical fancy that doesn't exist and may >> never exist. >> It is where all the ills of Python will be cured. Saying it is in Python 3000 >> is usually a synonym for it won't be "fixed" anytime soon! > > But have you seen what Guido says? > > "We're closing in on the first Python 3000 alpha release (promised > for the end of August)." > > > Semi-mythical fancy? Python 3000 is very real. As Dick points out, it is nearing an alpha release. Last I heard there were just a handful of failing tests that needed to be fixed before the release. http://www.artima.com/weblogs/viewpost.jsp?thread=211842 You can check out the code and build your own copy if you want. Dozens of Py3K PEPs have been written, 15 have been implemented - see the 3xxx-numbered PEPs here: http://www.python.org/dev/peps/ Google is sponsoring a Py3K sprint next week that has 21 people signed up including many names you would probably recognize. http://wiki.python.org/moin/GoogleSprint Yes, at one time Python 3000 was "a semi mythical fancy that doesn't exist and may never exist" but that is no longer true. I think the turning point was when GvR was hired by Google and started working on Py3K during paid hours instead of in his free time. Kent From vincent.gulinao at gmail.com Thu Aug 16 15:50:51 2007 From: vincent.gulinao at gmail.com (Vincent Gulinao) Date: Thu, 16 Aug 2007 21:50:51 +0800 Subject: [Tutor] Class Attribute "Overloading?" In-Reply-To: <00b301c7df9b$8e1eda20$f6fce004@JSLAPTOP> References: <46C34619.40909@alum.rpi.edu> <00b301c7df9b$8e1eda20$f6fce004@JSLAPTOP> Message-ID: I see, I think "property" is what I'm looking for. But how would you design it yourself (you said it's a little ugly, I love to hear better ideas)? My only concern is to avoid unnecessary DB accesses (or any other expensive processes). Thanks. On 8/16/07, Tiger12506 wrote: > > > > Sorry about that. I want something like: > > > > class foo: > > > > def __init__(self): > > > > self.attr1 = None > > > > > > def get_attr1(self): > > > > if not self.attr1: > > > > attr1 = > > > > self.attr1 = attr1 > > > > return self.attr1 > > > > > > such that: > > > > foo_instance = foo() > > > > then: > > > > foo_instance.get_attr1() > > > > and > > > > foo_instance.attr1 > > > > gets the same value. > > > > Such that you get to derive attr1 only as needed and just once, both > > outside > > and within foo class. > > > > Or is it a bad idea or just plain ugly to do something like that? If it > > is, > > kindly suggest better approach. > > > > Thanks. > > It's a little ugly but not too bad. What you are describing are > properties. > > class Foo: > def _get_attr1(self): > if not self.attr1: > attr1 = TheValue > return attr1 > def _set_attr1(self, value): > self.attr1 = value > ChangeDBFunction(value) > attr1 = property(self._get_attr1,self._setattr1,None,None) > > I think that will work. The docs seem to suggest that you should subclass > `object`. > JS > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070816/7019d0a0/attachment.html From wormwood_3 at yahoo.com Thu Aug 16 16:24:11 2007 From: wormwood_3 at yahoo.com (wormwood_3) Date: Thu, 16 Aug 2007 07:24:11 -0700 (PDT) Subject: [Tutor] Python Book Recommendations [Was:[Re: Security]] Message-ID: <210686.64741.qm@web32402.mail.mud.yahoo.com> Yeah, I loved this! I did not even know you could put variables and keywords in bookmarks like this. Awesomely cool. For anyone interested in more details, Lifehacker has a great article on this, associated plugins, tips and tricks: http://lifehacker.com/software/bookmarks/hack-attack-firefox-and-the-art-of-keyword-bookmarking-196779.php _________________________________ ----- Original Message ---- From: Dick Moores To: Python Tutor List Sent: Thursday, August 16, 2007 1:54:15 AM Subject: Re: [Tutor] Python Book Recommendations [Was:[Re: Security]] At 05:48 PM 8/14/2007, Kent Johnson wrote: >I also have a shortcut set up so if I type > py modulename >in the Firefox address bar it takes me directly to the docs for that >module. To do this, create a bookmark with this URL: >file://localhost/Users/kent/Library/Documentation/Python-Docs-2.5/lib/module-%s.html > >and give it the keyword 'py'. Great tips, Kent! I especially appreciate this one. Dick _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From Mike.Hansen at atmel.com Thu Aug 16 17:37:35 2007 From: Mike.Hansen at atmel.com (Mike Hansen) Date: Thu, 16 Aug 2007 09:37:35 -0600 Subject: [Tutor] FAQ [Was Re: Python Book Recommendations [Was:....]] In-Reply-To: References: Message-ID: <57B026980605A64F9B23484C5659E32E983C39@poccso.US.ad.atmel.com> > -----Original Message----- > From: tutor-bounces at python.org > [mailto:tutor-bounces at python.org] On Behalf Of Alan Gauld > Sent: Tuesday, August 14, 2007 10:06 AM > To: tutor at python.org > Subject: Re: [Tutor] FAQ [Was Re: Python Book Recommendations > [Was:....]] > > > "Tim Michelsen" wrote > > > is there a FAQ for this list where we could put all these > > recommendations? > > Someone (Mike Hansen?) started one a while back, but like most such > ventures the trick is in maintaining it! I'm not sure where it is or > what the > status is. > > Alan G > I'm a couple of days behind on my reading of the tutor list. The tutor FAQ used to reside at http://pyfaq.infogami.com/, but its new home is http://effbot.org/pyfaq/tutor-index.htm. I thought I remember seeing some of the questions on the python.org site, but I can't seem to find them now. I thought the original intent was to make it into a wiki to allow it to be easily updated, but I'm not sure what became of that. I just compiled the content and got list member's feedback. I got the ball rolling and hoped others would update and add questions as desired. Of course, I also hoped that it would be a good resource to direct people to common questions. Kent's suggestion of updating the following wiki pages is probably best: http://wiki.python.org/moin/PythonBooks http://wiki.python.org/moin/BeginnersGuide/NonProgrammers http://wiki.python.org/moin/BeginnersGuide/Programmers Mike From alan.gauld at btinternet.com Thu Aug 16 11:53:03 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 16 Aug 2007 10:53:03 +0100 Subject: [Tutor] Python Book Recommendations [Was:[Re: Security]] References: <46C41652.8000706@gmx-topmail.de> Message-ID: "Tim Michelsen" wrote >> Have you seen this site yet? >> >> http://osl.iu.edu/~lums/swc/ A new one to me. its not bad but does contain some downright misleading bits, for example a quick scan of the functions topic yielded: --------------- Python copies variables' values when passing them to functions a.. Since Booleans, numbers, and strings can't be updated, a function can't affect its caller's values b.. But if you pass a list to a function, the function will operate on the original list, not a copy ---------------- The first line is plain wrong. Python doesn't copy values it always uses references, its just that some objects are immutable while others are mutable. This is a common cause of confusion for beginners and this statement won't help. And the last line suggests that Python behaves inconsistently (which it doesn't) but doesn't clarify any of the "exceptions" other than lists - the same is actually true of any mutable type So, as ever, use with care and check with the official docs if in doubt. But otherwise a fairly polished tutorial with a fairly specific audience in mind. Alan g. From alan.gauld at btinternet.com Thu Aug 16 18:54:48 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 16 Aug 2007 17:54:48 +0100 Subject: [Tutor] Need to convert 1,987,087,234,456 to an int References: <595984.82278.qm@web86112.mail.ird.yahoo.com> <20070816122318.C0BAF1E4002@bag.python.org> Message-ID: "Dick Moores" wrote > At 02:41 AM 8/16/2007, Alan Gauld wrote: >>But Python 3000 is a semi mythical fancy that doesn't exist and may >>never exist. > > "We're closing in on the first Python 3000 alpha release (promised > for the end of August)." > > > Semi-mythical fancy? I take it back, it looks like they are finally doing something. I've been reading about Python 3000 for at least 5 years now and just kind of assumed it was an idealist wish list rather than a reality. Having said that I still think most of the things that I see written about being "in 3000" are wishful thinking rather than actual scoped features! Alan G. From jaggojaggo at yahoo.com Thu Aug 16 19:11:14 2007 From: jaggojaggo at yahoo.com (Jaggo) Date: Thu, 16 Aug 2007 10:11:14 -0700 (PDT) Subject: [Tutor] Simple way to compare Two lists In-Reply-To: Message-ID: <620041.15132.qm@web52506.mail.re2.yahoo.com> Thank you Kent, Michael, Tom and anyone else I'm forgetting who took time to reply. I don't work quite so fast, very limited personal computer time means I only do it on weekends, I read through your suggestions and eventually found a way to speed-up the proccess through sorting the Two lists, then manually iterating through each of them. This way I've completely canceled the need to compare Two lists: instead just ensuring I start from a point not taken in One list and having to only check whether Item not in BigList. [If anyone's interested, I should have the script finished and thoroughly tested on, ah, next weekend, and I could post a link here.] Again, Thx. -Omer. Message: 1 Date: Fri, 10 Aug 2007 08:11:47 -0400 From: Kent Johnson Subject: Re: [Tutor] Simple way to compare Two lists To: Tom Fitzhenry , tutor at python.org Message-ID: <46BC5603.9060703 at tds.net> Content-Type: text/plain; charset=ISO-8859-1; format=flowed Tom Fitzhenry wrote: > On Fri, Aug 10, 2007 at 02:54:44AM -0700, Jaggo wrote: >> Can anyone think of any better way? > > If SmallList and BigList are sorted (in order), there is a faster method: > > def IsAPartOfList(SmallList,BigList): > for i in BigList: > for j in SmallList: > if i==j: > return true > if i>j: > break > return false > > (I'm not sure how encouraged using break statements are, so wait for a tutor to > answer) break is fine! If the list you are searching is sorted you can use the bisect module to do a binary search instead of the linear search above. > If one list is already sorted but the other isn't, it may still be faster to > sort the unsorted list then use the method above. I don't think BigList has to be sorted in the above algorithm. If both lists are sorted I suppose you could write it like a merge sort, walking along both lists looking for a match. Kent --------------------------------- Park yourself in front of a world of choices in alternative vehicles. Visit the Yahoo! Auto Green Center. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070816/0ff18c39/attachment.htm From gslindstrom at gmail.com Thu Aug 16 21:02:10 2007 From: gslindstrom at gmail.com (Greg Lindstrom) Date: Thu, 16 Aug 2007 14:02:10 -0500 Subject: [Tutor] PyCon 2008 - Call for Tutorial Ideas Message-ID: Hey Everyone- I posted this to the python list, but then thought the tutor list might be a better place to get ideas. So.... It's hard to believe, but the planning for PyCon 2008 is underway. PyCon, an annual gathering of Python enthusiasts -- nearly 600 in Dallas last year -- will be held in Chicago next March 14-16, with one full "pre-conference" day, March 13, set aside for tutorials; classes given by Python honchos on various topics. These sessions last 3 hours (plus a break) and in general are more detailed than the talks given during the actual conference. Right now, we need to know what YOU want to see covered in these sessions. Testing, GUI, web-apps, database, basic Python, advanced Python, objects, anything and everything Python is on the table at this point. We have to narrow the field down to 10 or 15 and then find qualified presenters, so now is the time to start gathering ideas. What tutorials would YOU like to see offered? Please response to: pycon-tutorials at python.org Thanks, Greg Lindstrom Tutorial Coordinator, PyCon 2008 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070816/0fa63571/attachment.htm From wescpy at gmail.com Thu Aug 16 21:28:12 2007 From: wescpy at gmail.com (wesley chun) Date: Thu, 16 Aug 2007 12:28:12 -0700 Subject: [Tutor] Python Book Recommendations [Was:[Re: Security]] In-Reply-To: References: <46C41652.8000706@gmx-topmail.de> Message-ID: <78b3a9580708161228l24bbd757i65507541b7c1d98e@mail.gmail.com> > Python copies variables' values when passing them to functions > a.. Since Booleans, numbers, and strings can't be updated, a > function can't affect its caller's values > b.. But if you pass a list to a function, the function will operate > on the original list, not a copy > ---------------- > > The first line is plain wrong. Python doesn't copy values it always uses references, > its just that some objects are immutable while others are mutable. This is a > common cause of confusion for beginners and this statement won't help. And > the last line suggests that Python behaves inconsistently (which it doesn't) but > doesn't clarify any of the "exceptions" other than lists - the same is actually > true of any mutable type i completely agree with alan on this. whoever wrote it does *not* know Python very well. they seem to be "guessing" based on their previous experience with other programming languages that are "categorized" into either "call by reference" or "call by value". in python, *everything* is call by reference, but the reality is that the mutability is the real source of truth. a simple call to id() from the caller and the called function will show that they are indeed the exact same object. (why else would i spend an entire chapter on this in Core Python?!?) getting confused by both of these (call by XX vs. mutability) is the source of many many bugs in Python, and if you can get past this, those bugs would never exist (or have never existed), leaving you in a much more peaceful state of mind. :-) cheers, -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From kent37 at tds.net Thu Aug 16 21:34:44 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 16 Aug 2007 15:34:44 -0400 Subject: [Tutor] PyCon 2008 - Call for Tutorial Ideas In-Reply-To: References: Message-ID: <46C4A6D4.9060404@tds.net> Greg Lindstrom wrote: > What tutorials would YOU like to see offered? Please response to: > pycon-tutorials at python.org Maybe intermediate Python? I have been giving a series of presentations to my local Python SIG about topics that are widely applicable but often overlooked by beginners. The talks have been very well received. I don't know if it would make a three-hour presentation...the current topics are here: http://personalpages.tds.net/~kent37/kk/index.html Kent From kent37 at tds.net Thu Aug 16 21:45:30 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 16 Aug 2007 15:45:30 -0400 Subject: [Tutor] Python Book Recommendations [Was:[Re: Security]] In-Reply-To: <78b3a9580708161228l24bbd757i65507541b7c1d98e@mail.gmail.com> References: <46C41652.8000706@gmx-topmail.de> <78b3a9580708161228l24bbd757i65507541b7c1d98e@mail.gmail.com> Message-ID: <46C4A95A.5080801@tds.net> wesley chun wrote: > in python, *everything* is call by reference Not sure I really want to get into this, but here goes... Python passes object references by value. This is not the same as call by reference. With call by reference, *assignment* to a function parameter changes the value seen by the caller. This is not possible in Python. Lots of analysis here: http://effbot.org/zone/call-by-object.htm Kent From bhaaluu at gmail.com Thu Aug 16 22:13:56 2007 From: bhaaluu at gmail.com (bhaaluu) Date: Thu, 16 Aug 2007 16:13:56 -0400 Subject: [Tutor] Python Book Recommendations [Was:[Re: Security]] In-Reply-To: <78b3a9580708161228l24bbd757i65507541b7c1d98e@mail.gmail.com> References: <46C41652.8000706@gmx-topmail.de> <78b3a9580708161228l24bbd757i65507541b7c1d98e@mail.gmail.com> Message-ID: Greetings, The site in question ( http://osl.iu.edu/~lums/swc/ ) is listed at ( http://python.org/ ) on the right-hand sidebar entitled: Using Python For... # Education # pyBiblio, Software Carpentry Course Perhaps these concerns should be directed to either the maintainers of Python.Org ( http://python.org/ ), or to the author of the Software Carpentry Course? The course is available under an open license, AND This work [SWC] has been made possible by a grant from the Python Software Foundation, and by support from the University of Toronto. Your concerns sound serious enough to warrant corrections being made to the tutorial? -- bhaaluu at gmail dot com On 8/16/07, wesley chun wrote: > > Python copies variables' values when passing them to functions > > a.. Since Booleans, numbers, and strings can't be updated, a > > function can't affect its caller's values > > b.. But if you pass a list to a function, the function will operate > > on the original list, not a copy > > ---------------- > > > > The first line is plain wrong. Python doesn't copy values it always uses references, > > its just that some objects are immutable while others are mutable. This is a > > common cause of confusion for beginners and this statement won't help. And > > the last line suggests that Python behaves inconsistently (which it doesn't) but > > doesn't clarify any of the "exceptions" other than lists - the same is actually > > true of any mutable type > > > i completely agree with alan on this. whoever wrote it does *not* > know Python very well. they seem to be "guessing" based on their > previous experience with other programming languages that are > "categorized" into either "call by reference" or "call by value". > > in python, *everything* is call by reference, but the reality is that > the mutability is the real source of truth. a simple call to id() > from the caller and the called function will show that they are indeed > the exact same object. (why else would i spend an entire chapter on > this in Core Python?!?) getting confused by both of these (call by XX > vs. mutability) is the source of many many bugs in Python, and if you > can get past this, those bugs would never exist (or have never > existed), leaving you in a much more peaceful state of mind. :-) > > cheers, > -- wesley > - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - > "Core Python Programming", Prentice Hall, (c)2007,2001 > http://corepython.com > > wesley.j.chun :: wescpy-at-gmail.com > python training and technical consulting > cyberweb.consulting : silicon valley, ca > http://cyberwebconsulting.com > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From spmcinerney at hotmail.com Thu Aug 16 23:48:46 2007 From: spmcinerney at hotmail.com (Stephen McInerney) Date: Thu, 16 Aug 2007 14:48:46 -0700 Subject: [Tutor] Efficiency of Doxygen on Python vs C++? Message-ID: My friend said the runtime efficiency of Doxygen on his build was much worse on the Python code than the C++ code, i.e. it took ages to parse the Python code. Anyone agree/disagree, or have any efficiency tips on how to structure things for decent Doxygen performance? (I haven't used Doxygen myself and I don't have access to the build in question). Regards, Stephen _________________________________________________________________ Learn.Laugh.Share. Reallivemoms is right place! http://www.reallivemoms.com?ocid=TXT_TAGHM&loc=us From wescpy at gmail.com Fri Aug 17 00:33:41 2007 From: wescpy at gmail.com (wesley chun) Date: Thu, 16 Aug 2007 15:33:41 -0700 Subject: [Tutor] Python Book Recommendations [Was:[Re: Security]] In-Reply-To: <46C4A95A.5080801@tds.net> References: <46C41652.8000706@gmx-topmail.de> <78b3a9580708161228l24bbd757i65507541b7c1d98e@mail.gmail.com> <46C4A95A.5080801@tds.net> Message-ID: <78b3a9580708161533y62df6241x49643d7a78a9c30a@mail.gmail.com> > > in python, *everything* is call by reference > > Python passes object references by value. This is not the same as call > by reference. With call by reference, *assignment* to a function > parameter changes the value seen by the caller. This is not possible in > Python. that's great clarification... you are right on. memory references (as in C) are different from object references in Python, and yes, it's the object references that are passed and up to the object's mutability on whether assignment to that object is possible. -wesley From alan.gauld at btinternet.com Fri Aug 17 01:00:18 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 17 Aug 2007 00:00:18 +0100 Subject: [Tutor] Efficiency of Doxygen on Python vs C++? References: Message-ID: "Stephen McInerney" wrote > My friend said the runtime efficiency of Doxygen on his build was > much > worse on the Python code than the C++ code, i.e. it took ages to > parse > the Python code. > > Anyone agree/disagree, or have any efficiency tips on how to > structure > things for decent Doxygen performance? Until your post I had never heard of it. Having read the wiki article I gather its a Javadoc style documentation generator. Not being a fan of such beasts I doubt I'd be inclined to use it, but why is performamce an issue for a documentation generator? Presumably you only need to generate the documents periodically - say once a day - rather than with every build? In-code documentation is what is being used to create the docs so you can use that in day to day coding - one reason I find doc generators fairly useless! Documentation should be about what the comments don;t say not merely a comment and interface extraction. IMHO of course :-) Alan G. From spmcinerney at hotmail.com Fri Aug 17 01:43:26 2007 From: spmcinerney at hotmail.com (Stephen McInerney) Date: Thu, 16 Aug 2007 16:43:26 -0700 Subject: [Tutor] Efficiency of Doxygen on Python vs C++? In-Reply-To: Message-ID: My friend clarifies: "It's not the efficiency of doxygen that's the question. The problem is that you can add fields to objects as you go in Python so you need to do a deep analysis of the code to determine the class structure which you don't have to do with C++ (or Java)." He mentioned numbers like maybe ~20+x slower on lines-of-code for Python vs C++. A second friend of mine who is an XML/Java enthusiast echoed similar comments about scalability in large builds with weakly-typed dynamic languages such as Python. (I said "why doesn't doxygen have optional pragmas to annotate the type of tricky class members to the tool?") Has anyone used Doxygen and can comment? (Alan - their build setup was generating the docs every nightly build. Yes it sounds like overkill and an inefficient setup, but notwithstanding that I'm interested in the question as stands.) Thanks, Stephen >"Stephen McInerney" wrote > > > My friend said the runtime efficiency of Doxygen on his build was > > much > > worse on the Python code than the C++ code, i.e. it took ages to > > parse > > the Python code. > > > > Anyone agree/disagree, or have any efficiency tips on how to > > structure > > things for decent Doxygen performance? > >Until your post I had never heard of it. >Having read the wiki article I gather its a Javadoc style >documentation >generator. Not being a fan of such beasts I doubt I'd be inclined to >use >it, but why is performamce an issue for a documentation generator? > >Presumably you only need to generate the documents periodically >- say once a day - rather than with every build? In-code documentation >is >what is being used to create the docs so you can use that in day to >day coding - one reason I find doc generators fairly useless! > >Documentation should be about what the comments don;t say not >merely a comment and interface extraction. IMHO of course :-) > >Alan G. _________________________________________________________________ A new home for Mom, no cleanup required. All starts here. http://www.reallivemoms.com?ocid=TXT_TAGHM&loc=us From spmcinerney at hotmail.com Fri Aug 17 02:01:43 2007 From: spmcinerney at hotmail.com (Stephen McInerney) Date: Thu, 16 Aug 2007 17:01:43 -0700 Subject: [Tutor] Simple way to compare Two lists In-Reply-To: <620041.15132.qm@web52506.mail.re2.yahoo.com> Message-ID: Sorting both lists is unnecessary and not very scalable (order(NlogN)). Assuming the lists do not contain duplicates, just turn the longer one into a dict and check that each element of the shorter list in that dict (e.g. "if j not in BigList: return false") Since dict lookup is constant-time O(1), this approach is O(M) i.e. speed is linear in the length of the shorter list; and memory requirement is O(N+M) i.e. linear in the length of the longer list. If M<From: Jaggo >Reply-To: jaggojaggo at yahoo.com >To: tutor at python.org >Subject: Re: [Tutor] Simple way to compare Two lists >Date: Thu, 16 Aug 2007 10:11:14 -0700 (PDT) > >Thank you Kent, Michael, Tom and anyone else I'm forgetting who took time >to reply. > >I don't work quite so fast, very limited personal computer time means I >only do it on weekends, > >I read through your suggestions and eventually found a way to speed-up the >proccess through sorting the Two lists, then manually iterating through >each of them. This way I've completely canceled the need to compare Two >lists: instead just ensuring I start from a point not taken in One list and >having to only check whether Item not in BigList. > >[If anyone's interested, I should have the script finished and thoroughly >tested on, ah, next weekend, and I could post a link here.] > >Again, Thx. >-Omer. > >Message: 1 >Date: Fri, 10 Aug 2007 08:11:47 -0400 >From: Kent Johnson >Subject: Re: [Tutor] Simple way to compare Two lists >To: Tom Fitzhenry , tutor at python.org >Message-ID: <46BC5603.9060703 at tds.net> >Content-Type: text/plain; charset=ISO-8859-1; format=flowed > >Tom Fitzhenry wrote: > > On Fri, Aug 10, 2007 at 02:54:44AM -0700, Jaggo wrote: > >> Can anyone think of any better way? > > > > If SmallList and BigList are sorted (in order), there is a faster >method: > > > > def IsAPartOfList(SmallList,BigList): > > for i in BigList: > > for j in SmallList: > > if i==j: > > return true > > if i>j: > > break > > return false > > > > (I'm not sure how encouraged using break statements are, so wait for a >tutor to > > answer) > >break is fine! If the list you are searching is sorted you can use the >bisect module to do a binary search instead of the linear search above. > > > If one list is already sorted but the other isn't, it may still be >faster to > > sort the unsorted list then use the method above. > >I don't think BigList has to be sorted in the above algorithm. If both >lists are sorted I suppose you could write it like a merge sort, walking >along both lists looking for a match. > >Kent > > > > >--------------------------------- >Park yourself in front of a world of choices in alternative vehicles. >Visit the Yahoo! Auto Green Center. >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor _________________________________________________________________ See what you?re getting into?before you go there http://newlivehotmail.com/?ocid=TXT_TAGHM_migration_HM_viral_preview_0507 From dkc at grfx.com Fri Aug 17 00:30:25 2007 From: dkc at grfx.com (Kevin Cameron) Date: Thu, 16 Aug 2007 15:30:25 -0700 Subject: [Tutor] Efficiency of Doxygen on Python vs C++? In-Reply-To: References: Message-ID: <46C4D001.8090406@grfx.com> Stephen McInerney wrote: > My friend said the runtime efficiency of Doxygen on his build was much > worse on the Python code than the C++ code, i.e. it took ages to parse > the Python code. It's not the efficiency of doxygen that's the question. The problem is that you can add fields to objects as you go in Python so you need to do a deep analysis of the code to determine the class structure which you don't have to do with C++ (or Java). Kev. > > Anyone agree/disagree, or have any efficiency tips on how to structure > things for decent Doxygen performance? > > (I haven't used Doxygen myself and I don't have access to the build in > question). > > Regards, > Stephen > > _________________________________________________________________ > Learn.Laugh.Share. Reallivemoms is right place! > http://www.reallivemoms.com?ocid=TXT_TAGHM&loc=us > -- http://www.grfx.com mailto:dkc at grfx.com From kent37 at tds.net Fri Aug 17 04:01:34 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 16 Aug 2007 22:01:34 -0400 Subject: [Tutor] Python Book Recommendations [Was:[Re: Security]] In-Reply-To: <78b3a9580708161533y62df6241x49643d7a78a9c30a@mail.gmail.com> References: <46C41652.8000706@gmx-topmail.de> <78b3a9580708161228l24bbd757i65507541b7c1d98e@mail.gmail.com> <46C4A95A.5080801@tds.net> <78b3a9580708161533y62df6241x49643d7a78a9c30a@mail.gmail.com> Message-ID: <46C5017E.2070906@tds.net> wesley chun wrote: > that's great clarification... you are right on. memory references (as > in C) are different from object references in Python, and yes, it's > the object references that are passed and up to the object's > mutability on whether assignment to that object is possible. As long as I'm nitpicking...well, I guess I don't know what you mean by assignment to an object. Assignment is to names, not objects. There is nothing you can do in a function to bind a new object to a name in the caller. (Well, maybe some deep hackery with stack frames but nothing you can do in normal code.) If the passed object is mutable you can change its value and the caller will see the new value, but it is still the same object. Wesley I have no doubt you understand this, I'm just trying to be careful with the language because people are listening... Kent From kent37 at tds.net Fri Aug 17 04:06:13 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 16 Aug 2007 22:06:13 -0400 Subject: [Tutor] Efficiency of Doxygen on Python vs C++? In-Reply-To: <46C4D001.8090406@grfx.com> References: <46C4D001.8090406@grfx.com> Message-ID: <46C50295.2070602@tds.net> Kevin Cameron wrote: > Stephen McInerney wrote: >> My friend said the runtime efficiency of Doxygen on his build was much >> worse on the Python code than the C++ code, i.e. it took ages to parse >> the Python code. > It's not the efficiency of doxygen that's the question. The problem is > that you can add fields to objects as you go in Python so you need to do > a deep analysis of the code to determine the class structure which you > don't have to do with C++ (or Java). So doxygen is actually doing this deep analysis? Kent From jim at well.com Fri Aug 17 05:01:43 2007 From: jim at well.com (jim stockford) Date: Thu, 16 Aug 2007 20:01:43 -0700 Subject: [Tutor] Simple way to compare Two lists In-Reply-To: References: Message-ID: Why is a dict lookup constant time. I.e. if there's a loop that walks a (shorter) list and compares each element with each element of a dict, what's going on to make this faster than an outer loop walking a list and an inner loop walking a second list? On Aug 16, 2007, at 5:01 PM, Stephen McInerney wrote: > > Sorting both lists is unnecessary and not very scalable (order(NlogN)). > > Assuming the lists do not contain duplicates, > just turn the longer one into a dict and check that each element of the > shorter list in that dict (e.g. "if j not in BigList: return false") > Since dict lookup is constant-time O(1), this approach is O(M) > i.e. speed is linear in the length of the shorter list; > and memory requirement is O(N+M) i.e. linear in the length > of the longer list. If M< > Stephen > > >> From: Jaggo >> Reply-To: jaggojaggo at yahoo.com >> To: tutor at python.org >> Subject: Re: [Tutor] Simple way to compare Two lists >> Date: Thu, 16 Aug 2007 10:11:14 -0700 (PDT) >> >> Thank you Kent, Michael, Tom and anyone else I'm forgetting who took >> time to reply. >> >> I don't work quite so fast, very limited personal computer time means >> I only do it on weekends, >> >> I read through your suggestions and eventually found a way to >> speed-up the proccess through sorting the Two lists, then manually >> iterating through each of them. This way I've completely canceled the >> need to compare Two lists: instead just ensuring I start from a point >> not taken in One list and having to only check whether Item not in >> BigList. >> >> [If anyone's interested, I should have the script finished and >> thoroughly tested on, ah, next weekend, and I could post a link >> here.] >> >> Again, Thx. >> -Omer. >> >> Message: 1 >> Date: Fri, 10 Aug 2007 08:11:47 -0400 >> From: Kent Johnson >> Subject: Re: [Tutor] Simple way to compare Two lists >> To: Tom Fitzhenry , tutor at python.org >> Message-ID: <46BC5603.9060703 at tds.net> >> Content-Type: text/plain; charset=ISO-8859-1; format=flowed >> >> Tom Fitzhenry wrote: >> > On Fri, Aug 10, 2007 at 02:54:44AM -0700, Jaggo wrote: >> >> Can anyone think of any better way? >> > >> > If SmallList and BigList are sorted (in order), there is a faster >> method: >> > >> > def IsAPartOfList(SmallList,BigList): >> > for i in BigList: >> > for j in SmallList: >> > if i==j: >> > return true >> > if i>j: >> > break >> > return false >> > >> > (I'm not sure how encouraged using break statements are, so wait >> for a tutor to >> > answer) >> >> break is fine! If the list you are searching is sorted you can use the >> bisect module to do a binary search instead of the linear search >> above. >> >> > If one list is already sorted but the other isn't, it may still be >> faster to >> > sort the unsorted list then use the method above. >> >> I don't think BigList has to be sorted in the above algorithm. If both >> lists are sorted I suppose you could write it like a merge sort, >> walking >> along both lists looking for a match. >> >> Kent >> >> >> >> >> --------------------------------- >> Park yourself in front of a world of choices in alternative vehicles. >> Visit the Yahoo! Auto Green Center. > > >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor > > _________________________________________________________________ > See what you?re getting into > before you go there > http://newlivehotmail.com/? > ocid=TXT_TAGHM_migration_HM_viral_preview_0507 > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From spmcinerney at hotmail.com Fri Aug 17 05:01:17 2007 From: spmcinerney at hotmail.com (Stephen McInerney) Date: Thu, 16 Aug 2007 20:01:17 -0700 Subject: [Tutor] Efficiency of Doxygen on Python vs C++? In-Reply-To: <46C50295.2070602@tds.net> Message-ID: Yes but it's still a canonical question about analysis of weakly-typed dynamic languages, since my Java friend makes separate comments about scalability when analyzing large builds - he claims 1-5m lines of code is a threshold. >From: Kent Johnson >To: Kevin Cameron >CC: tutor at python.org >Subject: Re: [Tutor] Efficiency of Doxygen on Python vs C++? >Date: Thu, 16 Aug 2007 22:06:13 -0400 > >Kevin Cameron wrote: > > Stephen McInerney wrote: > >> My friend said the runtime efficiency of Doxygen on his build was much > >> worse on the Python code than the C++ code, i.e. it took ages to parse > >> the Python code. > > It's not the efficiency of doxygen that's the question. The problem is > > that you can add fields to objects as you go in Python so you need to do > > a deep analysis of the code to determine the class structure which you > > don't have to do with C++ (or Java). > >So doxygen is actually doing this deep analysis? > >Kent _________________________________________________________________ Puzzles, trivia teasers, word scrambles and more. Play for your chance to win! http://club.live.com/home.aspx?icid=CLUB_hotmailtextlink From spmcinerney at hotmail.com Fri Aug 17 05:53:58 2007 From: spmcinerney at hotmail.com (Stephen McInerney) Date: Thu, 16 Aug 2007 20:53:58 -0700 Subject: [Tutor] Simple way to compare Two lists In-Reply-To: Message-ID: Jim & Jaggo - Dict lookup is (essentially) constant-time because the hashing function computes which unique bucket a given entry will correspond to. (Hashing functions are usually polynomials involving prime numbers. Can assume that the computation of the hash value is constant-time) So there is no linear table-walking in dict lookup. Walking the shorter list will thus be faster in general, esp if M< Message-ID: <578995.53479.qm@web52206.mail.re2.yahoo.com> Hi everyone, Thanks for all suggestions. Let me just preface this by saying that I?m new to both python and programming. I started learning 3 months ago with online tutorials and reading the questions you guys post. So, thank you all very, very much and I apologize if I?m doing something really stupid..:-) OK. I?ve solved the problem of opening several files to process ?as a batch? with glob.glob(). Only now did I realize that the program and files need to be in the same folder . Now I have another problem. 1- I want to open several files and count the total number of words. If I do this with only 1 file, it works great. With several files ( now with glob), it outputs the total count for each file individually and not the whole corpus (see comment in the program below). 2- I also want the program to output a word frequency list (we do this a lot in corpus linguistics). When I do this with only one file, the program works great (with a dictionary). With several files, I end up with several frequency lists, one for each file. This sounds like a loop type of problem, doesn?t it? I looked at the indentations too and I can?t find what the problem is. Your comments, suggestions, etc are greatly appreciated. Thanks again for all your help. Paulo Here goes what I have. # The program is intended to output a word frequency list (including all words in all files) and the total word count def sortfile(): # I created a function filename = glob.glob('*.txt') # this works great! Thanks! for allfiles in filename: infile = open(allfiles, 'r') lines = list(infile) infile.close() words = [] # initializes list of words wordcounter = 0 for line in lines: line = line.lower() # after this, I have some clunky code to get rid of punctuation words = words + line.split() wordfreq = [words.count(wrd)for wrd in words] # counts the freq of each word in a list dictionary = dict(zip(words, wordfreq)) frequency_list = [(dictionary[key], key)for key in dictionary] frequency_list.sort() frequency_list.reverse() for item in frequency_list: wordcounter = wordcounter + 1 print item print "Total # of words:", wordcounter # this will give the word count of the last file the program reads. print "Total # of words:", wordcounter # if I put it here, I get the total count after each file sortfile() -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070816/1c0241ea/attachment.htm From tpc247 at gmail.com Fri Aug 17 07:39:44 2007 From: tpc247 at gmail.com (tpc247 at gmail.com) Date: Thu, 16 Aug 2007 22:39:44 -0700 Subject: [Tutor] unicode and character sets In-Reply-To: <46C43EF6.1060609@tds.net> References: <46C43EF6.1060609@tds.net> Message-ID: On 8/16/07, Kent Johnson wrote: > > tpc247 at gmail.com wrote: > > Good start! thanks, one of the good folks at metafiler provided the link to an excellent introductory article I don't think this is necessary. Did it actually fix anything? Changing > the default encoding is not recommended because it makes your scripts > non-portable. indeed, putting the sitecustomize.py script in site-packages did nothing to help me generate a script that would print out the non-ASCII character in IDLE, and, if what you say is correct, may very well introduce new problems. In many cases IDLE will display the repr() of a string which shows any > non-ascii character as a hexidecimal escape. It is actually the correct > character. print does not use the repr() so it displays correctly. ah, I see. Any string not ASCII encoded, generated by my script in IDLE, will be displayed as hexadecimal. Essentially, I was in a round house trying to find the corner ! No, actually you are doing great. This is correct output, it is just not > displaying in the form you expect. The data is correct. after reading your email, I wrote a follow-up script that wrote the generated output to a file in my Apache document root, and eureka, I was able to get the result I desired. Thanks for your help. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070816/539f2c65/attachment.html From tpc247 at gmail.com Fri Aug 17 07:41:00 2007 From: tpc247 at gmail.com (tpc247 at gmail.com) Date: Thu, 16 Aug 2007 22:41:00 -0700 Subject: [Tutor] unicode and character sets In-Reply-To: References: <46C43EF6.1060609@tds.net> Message-ID: On 8/16/07, tpc247 at gmail.com wrote: > > > > thanks, one of the good folks at metafiler provided the link to an > excellent introductory article > > correction: metafilter -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070816/9860ce03/attachment.htm From alan.gauld at btinternet.com Fri Aug 17 09:20:44 2007 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Fri, 17 Aug 2007 07:20:44 +0000 (GMT) Subject: [Tutor] Efficiency of Doxygen on Python vs C++? Message-ID: <118910.21423.qm@web86108.mail.ird.yahoo.com> > My friend clarifies: "It's not the efficiency of doxygen that's the > question. The problem is that you can add fields to objects as you go in > Python so you need to do a deep analysis of the code to determine the class > structure which you don't have to do with C++ (or Java)." That's true itds one of the "benefits" of a dynamic language, but it does make the code harder to parse. > He mentioned numbers like maybe ~20+x slower on lines-of-code > for Python vs C++. That sounds high, I would have expected no more than 5-10 times longer. But of course against that we have the advantage that there will be far fewer lines to parse in a Python project, typically only a third or a quarter of the number of lines - sometimes less than that. > A second friend of mine who is an XML/Java enthusiast echoed similar > comments about scalability in large builds with weakly-typed dynamic > languages such as Python. The concept of a "large build" doesn't really exist in an interpreted language like Python. OTOH I probably wouldn't usePython for a very large project - say over a million lines of code in C++ - for a variety of other reasons. eg. Python could do it but the coordination of multi team projects becomes harder without tools like static type checking. Alan G From alan.gauld at btinternet.com Fri Aug 17 09:39:11 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 17 Aug 2007 08:39:11 +0100 Subject: [Tutor] Simple way to compare Two lists References: Message-ID: "jim stockford" wrote > Why is a dict lookup constant time. I.e. if there's a > loop that walks a (shorter) list and compares each > element with each element of a dict, what's going > on to make this faster than an outer loop walking > a list and an inner loop walking a second list? A dict is essentially random access, the interpreter can find the item in a single jump(*) whereas with a list it must cycle through the entire list. So an 'in' check with a dict is basically a single indexing operation. An 'in' check with a list is a pass through, on average, half the list. Against that has to be factored the overhead of converting the big list to a dict of course. Where one list is much shorter than the other a loop check of the lists may work out faster but in most cases the dict check should win out. Finally, the dict solution breaks down where there are multiple entries of the same value since a dict needs unique keys. If you had two lists with a high number of duplicate entries then it could give a false positive depending on your definition of how the comparison should work. But as in all performance related issues, don't optimise until you have a problem and use measurement to check results. (*) Actually hashing algorithms often wind up with a few entries against a hash node so it is a jump plus an iteration over a few elements. But it is only a few, on a thousand element dict you might find some nodes with two or three entries but not more. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Fri Aug 17 09:59:07 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 17 Aug 2007 08:59:07 +0100 Subject: [Tutor] Efficiency of Doxygen on Python vs C++? References: <46C50295.2070602@tds.net> Message-ID: "Stephen McInerney" wrote > Yes but it's still a canonical question about analysis of > weakly-typed > dynamic languages, since my Java friend makes separate comments > about scalability when analyzing large builds - he claims 1-5m lines > of > code is a threshold. There is no doubt that analyzing large projects in dynamic languages (its not much to do with strong or weak typing IMHO) is always more difficult than in classical static languages. There used to be huge complaints about C because it needed a two-pass compiler whereas Pascal was designed to be compiled in a single pass - one reason Delphi can compete with VB in build speed! However because of the expressive power of these languages you very rarely get huge projects. Based on anecdotal evidence only I doubt if thare are any Python projects with over 1m lines of code. A 1m line Python project would be equivalent in function to a 5m+ line project in C++ or Java, and there aren't that many of those! Also at these sizes execution speed usually becomes a priority and interpreted languages are invariably slower in that area. Once you get over 10 million lines (C++ eqiuiv) the only languages I've seen being used are C++, ADA and COBOL which are all specifically designed for that scale of project. (There may be a few big Java projects around but I've never seen one that size) Also on projects this big the actual coding effort becomes vanishingly small, often less than 10% of the total effort, whereas on small projects coding can be as much as 30% or more. So in small projects the choice of language has a much bigger impact. Its an old fashioned enineering trade off - speed of construction v speed of execution. And if analyzing code is of importance then that becomes one more factor. In an increasing number of modern projects speed of construction is top priority. (Ease of maintenance is another factor too and interpreted languages also tend to win out there) HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From rabidpoobear at gmail.com Fri Aug 17 10:08:09 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Fri, 17 Aug 2007 03:08:09 -0500 Subject: [Tutor] Opening Multiple Files In-Reply-To: <578995.53479.qm@web52206.mail.re2.yahoo.com> References: <578995.53479.qm@web52206.mail.re2.yahoo.com> Message-ID: <46C55769.7070004@gmail.com> Paulo Quaglio wrote: > Hi everyone, > Thanks for all suggestions. Let me just preface this by saying that > I?m new to both python and programming. I started learning 3 months > ago with online tutorials and reading the questions you guys post. So, > thank you all very, very much?and I apologize if I?m doing something > really stupid..:-) OK. I?ve solved the problem of opening several > files to process ?as a batch? with glob.glob(). Only now did I realize > that the program and files need to be in the same folder?. Now I have > another problem. > 1- I want to open several files and count the total number of words. > If I do this with only 1 file, it works great. With several files ( > now with glob), it outputs the total count for each file individually > and not the whole corpus (see comment in the program below). > 2- I also want the program to output a word frequency list (we do this > a lot in corpus linguistics). When I do this with only one file, the > program works great (with a dictionary). With several files, I end up > with several frequency lists, one for each file. This sounds like a > loop type of problem, doesn?t it? I looked at the indentations too and > I can?t find what the problem is. Your comments, suggestions, etc are > greatly appreciated. Thanks again for all your help. Paulo > Here goes what I have. I'm going to make some general observations as well as try to answer your original question. > # The program is intended to output a word frequency list (including > all words in all files) and the total word count > def sortfile(): # I created a function I think analyze_corpus or something in this vein would be a better name, because this doesn't sort files as far as I can tell. > filename = glob.glob('*.txt') # this works great! Thanks! This is not really a file name but a list, so filelist would be more appropriate, or just files > for allfiles in filename: 'allfiles' is not a very appropriate name. Each time through the loop, the variable 'allfiles' contains a different item from the 'filename' list. it doesn't contain all the files simultaneously. 'fileobj' or something of this sort would be better. 'file' is a reserved keyword, however. > infile = open(allfiles, 'r') > lines = list(infile) It would be more clear to me what you're doing if you used the file object method 'readlines' lines = infile.readlines() This might also be more efficient, or it might be less efficient, or it might be doing the same thing. readlines is what I usually see here, though. > infile.close() > words = [] # initializes list of words > wordcounter = 0 > for line in lines: here your iterator name is more appropriate, because it's singular (which it should be, because it's a single object it's bound to - exceptions would be when iterating over lists of lists, for example) > line = line.lower() # after this, I have some clunky code to get rid > of punctuation > words = words + line.split() You should probably use the 'append' method of the list, words.append(line.split()) As far as removing punctuation, you can just build your whole words list in one line, like so: words = [''.join([x for x in word if x.isalpha()]) for word in line.split()] replace isalpha with isalnum if you want to match numbers too. Note that this makes blank words as a side-effect. It's too late in the night for me to come up with a fix for this, but you probably shouldn't use that list comprehension anyway, especially if you have no idea what it's doing. > wordfreq = [words.count(wrd)for wrd in words] # counts the freq of > each word in a list put a space between 'words.count(wrd)' and 'for' so it's clearer what's happening. I'm assuming words.count is defined somewhere else that you didn't include? I don't know if list comprehension is the best way to do this, because words could contain redundant entries. > dictionary = dict(zip(words, wordfreq)) > frequency_list = [(dictionary[key], key)for key in dictionary] Why do you need to make a dictionary here? why not just use the zip(words,wordfreq) directly? > frequency_list.sort() > frequency_list.reverse() > for item in frequency_list: > wordcounter = wordcounter + 1 > print item > print "Total # of words:", wordcounter # this will give the word count > of the last file the program reads. > print "Total # of words:", wordcounter # if I put it here, I get the > total count after each file Don't just put it random places, think about what your loop is doing and how to fix the problem. Your outer-most loop is looping over each file. within this loop you count the number of words in the file. Logically, for a total tally of the number of words in all files, you'd have a variable defined before the start of the loop, and then add the tally of each file's words to the total tally variable. Does this make sense? Can you figure out how to do this? Not sure what your frequency problem is. Try to abstract what your code is doing to as high a level as you can, and it should be easier to understand. > sortfile() P.S. next time use a more standard font or include your code as an attachment. preferably the attachment. It was hard to read, and I suspect this will reduce your number of replies a decent amount. I wouldn't have even read this if someone else had replied already, simply because the font is hard to read. -Luke From alan.gauld at btinternet.com Fri Aug 17 10:11:43 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 17 Aug 2007 09:11:43 +0100 Subject: [Tutor] Opening Multiple Files References: <578995.53479.qm@web52206.mail.re2.yahoo.com> Message-ID: "Paulo Quaglio" wrote > I've solved the problem of opening several files to process "as a > batch" > with glob.glob(). Only now did I realize that the program and files > need to be in the same folder.. They don't but you do need to pass a valid path to open() Thus if your code is running from folder X and the files are in folder Y you need to tell open to open Y/filename rather than just filename. Similarly you need to tell glob to glob(Y/pattern) The other possibility is to change the working directory to Y using os.chdir(Y) > 1- I want to open several files and count the total number of > words. > If I do this with only 1 file, it works great. With several files > ( now with glob), > it outputs the total count for each file individually and not the > whole corpus So you will need to store that result in a variable and add the totals: total = 0 for file in filelist: result = linesInFile(file) print file, ": ", result # might not need/want this total += result print total > 2- I also want the program to output a word frequency list > (we do this a lot in corpus linguistics). When I do this with only > one file, > the program works great (with a dictionary). With several files, I > end up > with several frequency lists, one for each file. Make the dictionary outside your loop and pass it into the full analysis program: # PSEUDO CODE ONLY! words = {} total = 0 for file in Flist words, count = analyzeFile(file, words) total += count print total for word in words: print word, ':', words[word] def AnalyzeFile(f, w) linecount = 0 for line in f: for word in line.split() w[word] = w.get(word,0) + 1 return w,linecount > This sounds like a loop type of problem, doesn't it? No it sounds like a variable position problem, and possibly a namespace issue too. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From spmcinerney at hotmail.com Fri Aug 17 11:22:02 2007 From: spmcinerney at hotmail.com (Stephen McInerney) Date: Fri, 17 Aug 2007 02:22:02 -0700 Subject: [Tutor] Efficiency of Doxygen on Python vs C++? In-Reply-To: <118910.21423.qm@web86108.mail.ird.yahoo.com> Message-ID: Hi Alan, > > My friend clarifies: "It's not the efficiency of doxygen that's the > > question. The problem is that you can add fields to objects as you go in > > Python so you need to do a deep analysis of the code to determine the >class > > structure which you don't have to do with C++ (or Java)." > >That's true it's one of the "benefits" of a dynamic language, but it does >make the code harder to parse. Is this not just evidence of a very bad Python coding style? Should we not always declare *all* class fields in the class definition by assigning to them, even if the assignment is token or dummy i.e. 'None', "", [], {} etc. > > He mentioned numbers like maybe ~20+x slower on lines-of-code > > for Python vs C++. > >That sounds high, I would have expected no more than 5-10 times longer. >But of course against that we have the advantage that there will be far >fewer >lines to parse in a Python project, typically only a third or a quarter of >the number of lines - sometimes less than that. Can you cite us a literature source for saying that Python is 3-4x more expressive per line-of-code than C++? Would come in handy for evangelizing. > > A second friend of mine who is an XML/Java enthusiast echoed similar > > comments about scalability in large builds with weakly-typed dynamic > > languages such as Python. > >The concept of a "large build" doesn't really exist in an interpreted >language like Python. OTOH I probably wouldn't usePython for a >very large project - say over a million lines of code in C++ - for a >variety of other reasons. eg. Python could do it but the coordination of >multi team projects becomes harder without tools like static type >checking. Has anyone ever tried pragmas for hinting about member types as I suggested? Stephen _________________________________________________________________ A new home for Mom, no cleanup required. All starts here. http://www.reallivemoms.com?ocid=TXT_TAGHM&loc=us From duncan at thermal.esa.int Fri Aug 17 13:37:27 2007 From: duncan at thermal.esa.int (Duncan Gibson) Date: Fri, 17 Aug 2007 13:37:27 +0200 Subject: [Tutor] Efficiency of Doxygen on Python vs C++? In-Reply-To: References: <118910.21423.qm@web86108.mail.ird.yahoo.com> Message-ID: <20070817133727.6f853669.duncan@thermal.esa.int> > Is this not just evidence of a very bad Python coding style? > Should we not always declare *all* class fields in the class definition > by assigning to them, even if the assignment is token or dummy > i.e. 'None', "", [], {} etc. this is one of the many things that pylint can warn you about. It's like pychecker but customisable for your coding standards. See http://www.logilab.org/project/eid/857 Cheers Duncan From kent37 at tds.net Fri Aug 17 13:43:42 2007 From: kent37 at tds.net (Kent Johnson) Date: Fri, 17 Aug 2007 07:43:42 -0400 Subject: [Tutor] Efficiency of Doxygen on Python vs C++? In-Reply-To: References: Message-ID: <46C589EE.20904@tds.net> Stephen McInerney wrote: > Hi Alan, > >>> My friend clarifies: "It's not the efficiency of doxygen that's the >>> question. The problem is that you can add fields to objects as you go in >>> Python so you need to do a deep analysis of the code to determine the >> class >>> structure which you don't have to do with C++ (or Java)." >> That's true it's one of the "benefits" of a dynamic language, but it does >> make the code harder to parse. > > Is this not just evidence of a very bad Python coding style? > Should we not always declare *all* class fields in the class definition > by assigning to them, even if the assignment is token or dummy > i.e. 'None', "", [], {} etc. Not necessarily. Python *is* highly dynamic. It's not just limited to simple data attributes. Base classes can be determined at runtime, methods can be added to classes or redefined, metaclasses can do all kinds of magic, etc etc. > Can you cite us a literature source for saying that Python is 3-4x more > expressive per line-of-code than C++? > Would come in handy for evangelizing. See http://wiki.python.org/moin/LanguageComparisons The Prechelt paper is a research paper. Some of the other links provide examples where you can draw your own conclusions. I have done a few comparisons of Python with Java here: http://personalpages.tds.net/~kent37/stories/00017.html Kent From cbc at unc.edu Fri Aug 17 17:19:19 2007 From: cbc at unc.edu (Chris Calloway) Date: Fri, 17 Aug 2007 11:19:19 -0400 Subject: [Tutor] Python Book Recommendations [Was:[Re: Security]] In-Reply-To: References: <46C41652.8000706@gmx-topmail.de> <78b3a9580708161228l24bbd757i65507541b7c1d98e@mail.gmail.com> Message-ID: <46C5BC77.6060601@unc.edu> bhaaluu wrote: > Perhaps these concerns should be directed to either the > maintainers of Python.Org ( http://python.org/ ), or to > the author of the Software Carpentry Course? I sent a pointer both to the lead maintainer (Dr. Greg Wilson at Univ. Toronto) and to Titus Brown who, along with Chris Lasher, is having a Software Carpentry sprint at SciPy'07 at Caltech tomorrow. So this is a timely observation. :) Titus wrote back that it "sure does sound wrong," so I would bet on it getting fixed tomorrow. SWC has been around since 1998. It started as an 800KUSD Dept. of Energy project at Los Alamos for a design competition with cash prizes. It resulted in several tools including Roundup and SCons. It received 27KUSD in funding from the PSF in 2006. It is taught to scientists at Univ of Toronto, Indiana Univ, and Caltech. Dr. Wilson wrote about it in the magazine of Sigma Xi: http://www.americanscientist.org/template/AssetDetail/assetid/48548 It has moved around a lot. It's current official home is on scipy.org: http://www.swc.scipy.org/ There are several links to older SWC URLs on python.org. None of them are in the wiki where they could be easily fixed, however. -- Sincerely, Chris Calloway http://www.seacoos.org office: 332 Chapman Hall phone: (919) 962-4323 mail: Campus Box #3300, UNC-CH, Chapel Hill, NC 27599 From brunson at brunson.com Fri Aug 17 11:53:19 2007 From: brunson at brunson.com (Eric Brunson) Date: Fri, 17 Aug 2007 03:53:19 -0600 Subject: [Tutor] Efficiency of Doxygen on Python vs C++? In-Reply-To: References: Message-ID: <46C5700F.9060105@brunson.com> Stephen McInerney wrote: > Hi Alan, > > >>> My friend clarifies: "It's not the efficiency of doxygen that's the >>> question. The problem is that you can add fields to objects as you go in >>> Python so you need to do a deep analysis of the code to determine the >>> >> class >> >>> structure which you don't have to do with C++ (or Java)." >>> >> That's true it's one of the "benefits" of a dynamic language, but it does >> make the code harder to parse. >> > > Is this not just evidence of a very bad Python coding style? > Should we not always declare *all* class fields in the class definition > by assigning to them, even if the assignment is token or dummy > i.e. 'None', "", [], {} etc. > > Absolutely not. I have several classes that build themselves dynamically at runtime. As an example, one of them reads the data dictionary of a database. You may as well suggest that you define all your dictionary keys at the beginning of the program. >>> He mentioned numbers like maybe ~20+x slower on lines-of-code >>> for Python vs C++. >>> >> That sounds high, I would have expected no more than 5-10 times longer. >> But of course against that we have the advantage that there will be far >> fewer >> lines to parse in a Python project, typically only a third or a quarter of >> the number of lines - sometimes less than that. >> > > Can you cite us a literature source for saying that Python is 3-4x more > expressive per line-of-code than C++? > Would come in handy for evangelizing. > > >>> A second friend of mine who is an XML/Java enthusiast echoed similar >>> comments about scalability in large builds with weakly-typed dynamic >>> languages such as Python. >>> >> The concept of a "large build" doesn't really exist in an interpreted >> language like Python. OTOH I probably wouldn't usePython for a >> very large project - say over a million lines of code in C++ - for a >> variety of other reasons. eg. Python could do it but the coordination of >> multi team projects becomes harder without tools like static type >> checking. >> > > Has anyone ever tried pragmas for hinting about member types as I suggested? > > Stephen > > _________________________________________________________________ > A new home for Mom, no cleanup required. All starts here. > http://www.reallivemoms.com?ocid=TXT_TAGHM&loc=us > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at btinternet.com Fri Aug 17 19:24:59 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 17 Aug 2007 18:24:59 +0100 Subject: [Tutor] Efficiency of Doxygen on Python vs C++? References: <118910.21423.qm@web86108.mail.ird.yahoo.com> Message-ID: "Stephen McInerney" wrote >>lines to parse in a Python project, typically only a third or a >>quarter of >>the number of lines - sometimes less than that. > > Can you cite us a literature source for saying that Python is 3-4x > more > expressive per line-of-code than C++? I don't have any literature to hand that gives those figures but in Code Complete (Sec 3.5) Steve McConnell gives siome relatie figures which indicates that TurboBasic is about twice as effective as C per line and given my experience comparing Python to TurboBasic I'd figure Python to be at east twice as effective as TB. On the two projects that I have done comparisons with Java the ratio has been about 3 times less code in Python - but both small samples - less than 1000 lines of Java, 300+ lines of Python. And my one comparison with C++ gave a 5 fold improvement but is not a fair comparison since much of the C++ was providing class equivalents for Python dictionaries, which I know I could have bought if I'd looked hard enough. I think there are some studies of SmallTalk productivity which suggested that ST was around 5 times more effective than C, and I'd guess Python was nearly as effective as ST. So that kind of ties in too, but still based mainly on my experience I'm afraid. Not much help but something. Alan G. From spmcinerney at hotmail.com Fri Aug 17 22:15:00 2007 From: spmcinerney at hotmail.com (Stephen McInerney) Date: Fri, 17 Aug 2007 13:15:00 -0700 Subject: [Tutor] Efficiency of Doxygen on Python vs C++? In-Reply-To: <46C5700F.9060105@brunson.com> Message-ID: Eric, you misunderstood my point. I said you make a **token** assignment in the class defn simply to do two things: - 1) identify all the members in one place - 2) annotate each member's type, as much as you can e.g.: class C s = [] d = {} ot = (None, None) I didn't say you make the actual assignment. Obviously you can't in most cases. Regards, Stephen >From: Eric Brunson >>Is this not just evidence of a very bad Python coding style? >>Should we not always declare *all* class fields in the class definition >>by assigning to them, even if the assignment is token or dummy >>i.e. 'None', "", [], {} etc. >> >> > >Absolutely not. I have several classes that build themselves dynamically >at runtime. As an example, one of them reads the data dictionary of a >database. You may as well suggest that you define all your dictionary keys >at the beginning of the program. _________________________________________________________________ A new home for Mom, no cleanup required. All starts here. http://www.reallivemoms.com?ocid=TXT_TAGHM&loc=us From alan.gauld at btinternet.com Sat Aug 18 00:14:46 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 17 Aug 2007 23:14:46 +0100 Subject: [Tutor] Efficiency of Doxygen on Python vs C++? References: <46C5700F.9060105@brunson.com> Message-ID: "Stephen McInerney" wrote > Eric, you misunderstood my point. > I said you make a **token** assignment in the class defn simply > to do two things: > - 1) identify all the members in one place > - 2) annotate each member's type, as much as you can I'm sure Eric can explain for himself but what I think he was saying was that his classes define themselves at runtime. They read the names of the fields and type information from the database metadata and create the attributes accordingly. Thus he doesn't know what his class attributes will be until the program runs. He may not even know the names of his classes until he reads the database tablenames. This is exactly the kind of tricky coding that is possible in a dynamic language which is next tio impossible in static compiled code, unless you write your own 'little language interpreter' inside the compiled program. This kind of abstract meta programming is extremely tricky to get right but at least it's possible in something like Python. But it makes analyzing the code very complex since much of the working code is being created by the config code at runtime. I've never actually tried this in Python but have done similar things in Lisp. In C++ you usually have to create classes in advance for every possible eventuality then use a factory class (or big switch statement) to create the desitred instances. That's a lot of excess code which is still less reliable and robust. Of course I could be misreading Eric's intent... Alan G. From wescpy at gmail.com Sat Aug 18 01:32:42 2007 From: wescpy at gmail.com (wesley chun) Date: Fri, 17 Aug 2007 16:32:42 -0700 Subject: [Tutor] Python Book Recommendations [Was:[Re: Security]] In-Reply-To: <46C5017E.2070906@tds.net> References: <46C41652.8000706@gmx-topmail.de> <78b3a9580708161228l24bbd757i65507541b7c1d98e@mail.gmail.com> <46C4A95A.5080801@tds.net> <78b3a9580708161533y62df6241x49643d7a78a9c30a@mail.gmail.com> <46C5017E.2070906@tds.net> Message-ID: <78b3a9580708171632i6bdd64cesde073b1e40777dc7@mail.gmail.com> > > up to the object's > > mutability on whether assignment to that object is possible. > > As long as I'm nitpicking...well, I guess I don't know what you mean by > assignment to an object. Assignment is to names, not objects. There is > nothing you can do in a function to bind a new object to a name in the > caller. nope, it's not as complicated as you've made it... i only meant to describe that you can modify mutable objects (and not immutable ones). in other words, if you have myList = [1, 2, 3], you can say myList[0] = 4. i'm assigning integer 4 to the myList object as its 1st element at index 0 -- that's what my wording meant. i realized later that i could have been more clear because of what you said, binding names to objects. and yes, everyone needs to be more careful with their wording as to not confuse others. -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From brunson at brunson.com Sat Aug 18 02:37:54 2007 From: brunson at brunson.com (Eric Brunson) Date: Fri, 17 Aug 2007 18:37:54 -0600 Subject: [Tutor] Efficiency of Doxygen on Python vs C++? In-Reply-To: References: <46C5700F.9060105@brunson.com> Message-ID: <46C63F62.4020003@brunson.com> We're definitely on the same wavelength, Alan. :-) Alan Gauld wrote: > "Stephen McInerney" wrote > > >> Eric, you misunderstood my point. >> I said you make a **token** assignment in the class defn simply >> to do two things: >> - 1) identify all the members in one place >> - 2) annotate each member's type, as much as you can >> > > I'm sure Eric can explain for himself but what I think he was saying > was that his classes define themselves at runtime. They read the > names of the fields and type information from the database metadata > and create the attributes accordingly. Thus he doesn't know what > his class attributes will be until the program runs. He may not even > know the names of his classes until he reads the database > tablenames. > > This is exactly the kind of tricky coding that is possible in a > dynamic > language which is next tio impossible in static compiled code, unless > you write your own 'little language interpreter' inside the compiled > program. This kind of abstract meta programming is extremely tricky > to get right but at least it's possible in something like Python. > But it makes analyzing the code very complex since much of the > working code is being created by the config code at runtime. > > I've never actually tried this in Python but have done similar things > in Lisp. In C++ you usually have to create classes in advance for > every possible eventuality then use a factory class (or big switch > statement) to create the desitred instances. That's a lot of excess > code which is still less reliable and robust. > > Of course I could be misreading Eric's intent... > > Alan G. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From spmcinerney at hotmail.com Sat Aug 18 04:52:57 2007 From: spmcinerney at hotmail.com (Stephen McInerney) Date: Fri, 17 Aug 2007 19:52:57 -0700 Subject: [Tutor] Efficiency of Doxygen on Python vs C++? In-Reply-To: <46C63F62.4020003@brunson.com> Message-ID: Oh ok, I see. Yes I've also programmed classes that dynamically declare themselves (mine was for XML parsing). Presumably static analyzers like Doxygen etc. can't handle those so they lie outside the scope of what we were discussing. I was asking if it's a recognized good programming practice to declare and initialize *all* members in the class defn. I think I'm hearing a general yes on that - any other opinions? Stephen >From: Eric Brunson >To: Alan Gauld >CC: tutor at python.org >Subject: Re: [Tutor] Efficiency of Doxygen on Python vs C++? >Date: Fri, 17 Aug 2007 18:37:54 -0600 > > >We're definitely on the same wavelength, Alan. :-) > >Alan Gauld wrote: > > "Stephen McInerney" wrote > > > > > >> Eric, you misunderstood my point. > >> I said you make a **token** assignment in the class defn simply > >> to do two things: > >> - 1) identify all the members in one place > >> - 2) annotate each member's type, as much as you can > >> > > > > I'm sure Eric can explain for himself but what I think he was saying > > was that his classes define themselves at runtime. They read the > > names of the fields and type information from the database metadata > > and create the attributes accordingly. Thus he doesn't know what > > his class attributes will be until the program runs. He may not even > > know the names of his classes until he reads the database > > tablenames. > > > > This is exactly the kind of tricky coding that is possible in a > > dynamic > > language which is next tio impossible in static compiled code, unless > > you write your own 'little language interpreter' inside the compiled > > program. This kind of abstract meta programming is extremely tricky > > to get right but at least it's possible in something like Python. > > But it makes analyzing the code very complex since much of the > > working code is being created by the config code at runtime. > > > > I've never actually tried this in Python but have done similar things > > in Lisp. In C++ you usually have to create classes in advance for > > every possible eventuality then use a factory class (or big switch > > statement) to create the desitred instances. That's a lot of excess > > code which is still less reliable and robust. > > > > Of course I could be misreading Eric's intent... > > > > Alan G. > > > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor _________________________________________________________________ Puzzles, trivia teasers, word scrambles and more. Play for your chance to win! http://club.live.com/home.aspx?icid=CLUB_hotmailtextlink From kent37 at tds.net Sat Aug 18 06:06:19 2007 From: kent37 at tds.net (Kent Johnson) Date: Sat, 18 Aug 2007 00:06:19 -0400 Subject: [Tutor] Efficiency of Doxygen on Python vs C++? In-Reply-To: References: Message-ID: <46C6703B.3060402@tds.net> Stephen McInerney wrote: > I was asking if it's a recognized good programming practice to > declare and initialize *all* members in the class defn. What do you mean by "initialize *all* members in the class defn"? Your original example was not syntactically correct Python. You wrote: class C s = [] d = {} ot = (None, None) If by this you meant to define all the variables at class scope: class C: s = [] d = {} ot = (None, None) then I would say emphatically no, this is not even common practice, let alone a recognized best practice. If you mean to initialize the variables in the __init__() method: class C: def __init__(self): self.s = [] self.d = {} self.ot = (None, None) maybe this is more common but I don't think I have ever seen it recommended to initialize all variables in the __init__() method. Certainly there are times when it makes sense to have some of the initialization in other methods that are called from __init__(). So if by "recognized good programming practice" you mean something like "commonly recommended" I would say no, it is not. > I think I'm hearing a general yes on that - any other opinions? Not sure where you think you are hearing a yes, I am hearing a lot of objections. Kent From rdm at rcblue.com Sat Aug 18 06:28:08 2007 From: rdm at rcblue.com (Dick Moores) Date: Fri, 17 Aug 2007 21:28:08 -0700 Subject: [Tutor] Python Book Recommendations [Was:[Re: Security]] In-Reply-To: <46C5BC77.6060601@unc.edu> References: <46C41652.8000706@gmx-topmail.de> <78b3a9580708161228l24bbd757i65507541b7c1d98e@mail.gmail.com> <46C5BC77.6060601@unc.edu> Message-ID: <20070818043022.0B37E1E4002@bag.python.org> At 08:19 AM 8/17/2007, Chris Calloway wrote: >bhaaluu wrote: > > Perhaps these concerns should be directed to either the > > maintainers of Python.Org ( http://python.org/ ), or to > > the author of the Software Carpentry Course? > >I sent a pointer both to the lead maintainer (Dr. Greg Wilson at Univ. >Toronto) and to Titus Brown who, along with Chris Lasher, is having a >Software Carpentry sprint at SciPy'07 at Caltech tomorrow. So this is a >timely observation. :) Titus wrote back that it "sure does sound wrong," >so I would bet on it getting fixed tomorrow. > >SWC has been around since 1998. It started as an 800KUSD Dept. of Energy >project at Los Alamos for a design competition with cash prizes. It >resulted in several tools including Roundup and SCons. It received >27KUSD in funding from the PSF in 2006. It is taught to scientists at >Univ of Toronto, Indiana Univ, and Caltech. Dr. Wilson wrote about it in >the magazine of Sigma Xi: > >http://www.americanscientist.org/template/AssetDetail/assetid/48548 > >It has moved around a lot. It's current official home is on scipy.org: > >http://www.swc.scipy.org/ > >There are several links to older SWC URLs on python.org. None of them >are in the wiki where they could be easily fixed, however. Chris, THANK YOU, especially for the link, . My thanks also to Alan, Wesley, and bhaaluu. What a great list Tutor is! An appreciative noob, Dick Moores From rdm at rcblue.com Sat Aug 18 08:11:18 2007 From: rdm at rcblue.com (Dick Moores) Date: Fri, 17 Aug 2007 23:11:18 -0700 Subject: [Tutor] What is a "symbolic debugger" Message-ID: <20070818061146.BADA31E4002@bag.python.org> In the "Python Book Recommendations [Was:[Re: Security]]" thread, Chris Calloway included a link to the American Scientist article, "Where's the Real Bottleneck in Scientific Computing?". In that article I saw a term, "symbolic debugger", I had been wondering about for a while. Google was of little help (to me, at least), and searching Wikipedia on "symbolic debugger" gets me the Debugger article "Redirected from Symbolic debugger". I'm beginning to think that the debugger I want to learn, WinPdb, is also a symbolic debugger, but what's "symbolic" about it? Thanks, Dick Moores From alan.gauld at btinternet.com Sat Aug 18 10:07:30 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 18 Aug 2007 09:07:30 +0100 Subject: [Tutor] Efficiency of Doxygen on Python vs C++? References: <46C63F62.4020003@brunson.com> Message-ID: "Stephen McInerney" wrote > I was asking if it's a recognized good programming practice to > declare and initialize *all* members in the class defn. > I think I'm hearing a general yes on that - any other opinions? It depends on what you mean by the class definition. In general attributes are defined in the classes methods, and since they are part of the class definition then I'd say yes its general practice. I'd go further and say its bad practice to define class/instance attributes outside the class unless you have a good reason to do so - such as dynamically creating classes at run time. Thus: class foo: def __init__(self, x, y): self.x = x self.y = y f = foo(22,66) Is preferable to class foo: pass f = foo() f.x = 22 f.y = 66 But there are occasions when adding attributes dynamically can be a sensible approach - your own example of parsing XML is a good example. But because there are always exceptions you won't see many people making hard and fast rules about such things in Python. Alan G From alan.gauld at btinternet.com Sat Aug 18 10:13:59 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 18 Aug 2007 09:13:59 +0100 Subject: [Tutor] What is a "symbolic debugger" References: <20070818061146.BADA31E4002@bag.python.org> Message-ID: "Dick Moores" wrote > article I saw a term, "symbolic debugger", I had been wondering > about for a while. Google was of little help (to me, at least), and Its a debugger that undestand symbols, in other words it can read the symbol table produced by a compiler/interpreter. Most debuggers nowadays are symbolic, but in the early days they weren't and you had to debug all code at the assembler/memory address level. If you want to have fun with that try loading a simple program into the DOS DEBUG command and stepping through it examining the memory image as you go., It is decidedly non symbolic! Or on Linux/Unix you may be able to use adb. adb is often using for debugging core dumps from programs that haven't been compiled with the -g debug flag or have had the symbol table 'strip'ed. > that the debugger I want to learn, WinPdb, is also a symbolic > debugger, but what's "symbolic" about it? Yes Python debuggers are all symbolic. They can understand your variable names etc so you can say break foo instead of break [0x25698567] HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From rdm at rcblue.com Sat Aug 18 10:33:50 2007 From: rdm at rcblue.com (Dick Moores) Date: Sat, 18 Aug 2007 01:33:50 -0700 Subject: [Tutor] The Python 2.5 Quick Reference In-Reply-To: References: Message-ID: <20070818083626.10DBB1E4002@bag.python.org> I was wondering if the Python 2.5 Quick Reference, by Richard Gruet, wouldn't make a suitable addition to a list of useful Python references. It seems to be very well-done to me. It comes in various forms. See http://rgruet.free.fr/. I find I prefer . Using Firefox, I "captured" this to my "ScrapBook" and open it with a shortcut key set to: file:///C:/Documents%20and%20Settings/Riley/Application%20Data/Mozilla/Firefox/Profiles/7nl3fxen.default/ScrapBook/data/20070818011939/index.html BTW Python.org references only a very early antecedent of this PQR, from 1995: . At least that's the only one I could find.. From the "Front Matter" section of Python 2.5 Quick Reference: Last modified on June 23, 2007 14 Dec 2006, upgraded by Richard Gruet for Python 2.5 17 Feb 2005, upgraded by Richard Gruet for Python 2.4 03 Oct 2003, upgraded by Richard Gruet for Python 2.3 11 May 2003, rev 4 upgraded by Richard Gruet for Python 2.2 (restyled by Andrei) 7 Aug 2001 upgraded by Simon Brunning for Python 2.1 16 May 2001 upgraded by Richard Gruet and Simon Brunning for Python 2.0 18 Jun 2000 upgraded by Richard Gruet for Python 1.5.2 30 Oct 1995 created by Chris Hoffmann for Python 1.3 Dick Moores From spmcinerney at hotmail.com Sat Aug 18 11:38:51 2007 From: spmcinerney at hotmail.com (Stephen McInerney) Date: Sat, 18 Aug 2007 02:38:51 -0700 Subject: [Tutor] Efficiency of Doxygen on Python vs C++? In-Reply-To: <46C6703B.3060402@tds.net> Message-ID: Kent, >>I was asking if it's a recognized good programming practice to >>declare and initialize *all* members in the class defn. > >What do you mean by "initialize *all* members in the class defn"? - obviously I meant to say do it in the __init__() method, I wrote the snippet as I was rushing out the door to an exam, but I think the intent was clear. >If you mean to initialize the variables in the __init__() method: >maybe this is more common but I don't think I have ever seen it recommended >to initialize all variables in the __init__() method. Certainly there are >times when it makes sense to have some of the initialization in other >methods that are called from __init__(). I only said "make a token dummy assignment in __init__() to hint to the static analyzer the name and expected type, I didn't say "you must do all the actual initialization itself in __init__()". In the context of the original question "where and how should we assign class members in order to flag member names and types to static analyzers like Doxygen or pylint?" I understood that people were agreeing "Yes, assigning each member token values in the __init__() method is a good practice". > > I think I'm hearing a general yes on that - any other opinions? >Not sure where you think you are hearing a yes, I am hearing a lot of >objections. No they didn't - they said that this cannot be done for true dynamic code, which is true, but obviously doesn't apply to working with static analysis tools, which is what the question was about. Regards, Stephen _________________________________________________________________ Messenger Caf? ? open for fun 24/7. Hot games, cool activities served daily. Visit now. http://cafemessenger.com?ocid=TXT_TAGHM_AugHMtagline From rdm at rcblue.com Sat Aug 18 11:53:15 2007 From: rdm at rcblue.com (Dick Moores) Date: Sat, 18 Aug 2007 02:53:15 -0700 Subject: [Tutor] What is a "symbolic debugger" In-Reply-To: References: <20070818061146.BADA31E4002@bag.python.org> Message-ID: <20070818095338.108B31E4002@bag.python.org> At 01:13 AM 8/18/2007, Alan Gauld wrote: >"Dick Moores" wrote > > > article I saw a term, "symbolic debugger", I had been wondering > > about for a while. Google was of little help (to me, at least), and > >Its a debugger that undestand symbols, in other words it can read >the symbol table produced by a compiler/interpreter. Ah. And that sent me to / >Most debuggers nowadays are symbolic, but in the early days >they weren't and you had to debug all code at the assembler/memory >address level. > >If you want to have fun with that try loading a simple program into >the DOS DEBUG command and stepping through it examining >the memory image as you go., It is decidedly non symbolic! Is that something I should be able to do on Win XP? Would I use debug at the command line? >Or on Linux/Unix you may be able to use adb. adb is often using >for debugging core dumps from programs that haven't been >compiled with the -g debug flag or have had the symbol table >'strip'ed. > > > that the debugger I want to learn, WinPdb, is also a symbolic > > debugger, but what's "symbolic" about it? > >Yes Python debuggers are all symbolic. >They can understand your variable names etc so you can say > >break foo > >instead of > >break [0x25698567] I'll take "break foo" any day. Thanks very much, Alan! Dick Moores XP, Python 2.5, editor is Ulipad From alan.gauld at btinternet.com Sat Aug 18 13:06:46 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 18 Aug 2007 12:06:46 +0100 Subject: [Tutor] [OFF TOPIC] Re: What is a "symbolic debugger" References: <20070818061146.BADA31E4002@bag.python.org> <20070818095338.108B31E4002@bag.python.org> Message-ID: This is miles away from Python but some might find it fun/educational. "Dick Moores" wrote >>If you want to have fun with that try loading a simple program into >>the DOS DEBUG command and stepping through it examining >>the memory image as you go., It is decidedly non symbolic! > > Is that something I should be able to do on Win XP? Would I use > debug > at the command line? You could, but it would be complex since you would be debugging the python interpreter while it executes your script. Its probably easier to try it on one of the simpler DOS commands like edlin.exe (or better still write hello world in C and compile it and debug that. That way its small enough you should be able to spot the string in the ASCII part of the memory dump...) In a DOS prompt CD to C:\WINDOWS\System32 Run > CD C:\WINDOWS\SYSTEM32 > DEBUG EDLIN.EXE - At the '-' prompt type '?' to get a list of commands. Try the 'd' and 'u' commands for starters. If you feel really bold (and patient!) you might try stepping through using 't'. The IP register contains the Instruction Pointer for monitoring progress... Anything else is a bit risky unless you know what you are doing! I had to write my first C program using edlin and debug it using DEBUG. It's good for the soul, or so they tell me... Shortly after I gort a copy of Wordstar and the Microsoft C compiler with sdb - such luxury... :-) Alan G. From kent37 at tds.net Sat Aug 18 13:42:53 2007 From: kent37 at tds.net (Kent Johnson) Date: Sat, 18 Aug 2007 07:42:53 -0400 Subject: [Tutor] The Python 2.5 Quick Reference In-Reply-To: <20070818083626.10DBB1E4002@bag.python.org> References: <20070818083626.10DBB1E4002@bag.python.org> Message-ID: <46C6DB3D.6080903@tds.net> Dick Moores wrote: > I was wondering if the Python 2.5 Quick Reference, by Richard Gruet, > wouldn't make a suitable addition to a list of useful Python > references. It has a link on the top-level documentation page at python.org: http://www.python.org/doc/ Kent From kent37 at tds.net Sat Aug 18 13:55:54 2007 From: kent37 at tds.net (Kent Johnson) Date: Sat, 18 Aug 2007 07:55:54 -0400 Subject: [Tutor] Efficiency of Doxygen on Python vs C++? In-Reply-To: References: Message-ID: <46C6DE4A.1050703@tds.net> Stephen McInerney wrote: > Kent, > >>> I was asking if it's a recognized good programming practice to >>> declare and initialize *all* members in the class defn. >> >> What do you mean by "initialize *all* members in the class defn"? > - obviously I meant to say do it in the __init__() method, > I wrote the snippet as I was rushing out the door to an exam, > but I think the intent was clear. It was definitely not clear to me. Judging from his latest reply it doesn't seem to be clear to Alan either. >> If you mean to initialize the variables in the __init__() method: >> maybe this is more common but I don't think I have ever seen it >> recommended to initialize all variables in the __init__() method. >> Certainly there are times when it makes sense to have some of the >> initialization in other methods that are called from __init__(). > > I only said "make a token dummy assignment in __init__() to hint > to the static analyzer the name and expected type, I didn't say > "you must do all the actual initialization itself in __init__()". So if an attribute is initialized in a different method would you still put a dummy initializer in __init__()? > > In the context of the original question > "where and how should we assign class members in order > to flag member names and types to static analyzers like > Doxygen or pylint?" > I understood that people were agreeing > "Yes, assigning each member token values in the __init__() > method is a good practice". I honestly don't see how you can conclude that. My post was the first one that mentioned __init__() at all. You have been talking about the class definition which could mean "anywhere in the scope of the class statement" or, as I thought you might mean, "anywhere in the scope of the class statement that is not in a method". I personally would never interpret "class definition" to mean the __init__() method. I really am trying to understand what you are asking, it is not clear to me at all. Kent From rdm at rcblue.com Sat Aug 18 14:25:20 2007 From: rdm at rcblue.com (Dick Moores) Date: Sat, 18 Aug 2007 05:25:20 -0700 Subject: [Tutor] The Python 2.5 Quick Reference Message-ID: <20070818122528.440E71E400C@bag.python.org> At 04:42 AM 8/18/2007, Kent Johnson wrote: >Dick Moores wrote: >>I was wondering if the Python 2.5 Quick Reference, by Richard >>Gruet, wouldn't make a suitable addition to a list of useful Python >>references. > >It has a link on the top-level documentation page at python.org: >http://www.python.org/doc/ Ah, I see it now. Good. BTW do you think the PQR is an accurate and useful reference, Kent? Dick From brunson at brunson.com Sat Aug 18 18:54:57 2007 From: brunson at brunson.com (Eric Brunson) Date: Sat, 18 Aug 2007 10:54:57 -0600 Subject: [Tutor] Efficiency of Doxygen on Python vs C++? In-Reply-To: References: Message-ID: <46C72461.2080504@brunson.com> Stephen McInerney wrote: > Kent, > > >>> I was asking if it's a recognized good programming practice to >>> declare and initialize *all* members in the class defn. >>> >> What do you mean by "initialize *all* members in the class defn"? >> > - obviously I meant to say do it in the __init__() method, > I wrote the snippet as I was rushing out the door to an exam, > but I think the intent was clear. > > >> If you mean to initialize the variables in the __init__() method: >> maybe this is more common but I don't think I have ever seen it recommended >> to initialize all variables in the __init__() method. Certainly there are >> times when it makes sense to have some of the initialization in other >> methods that are called from __init__(). >> > > I only said "make a token dummy assignment in __init__() to hint > to the static analyzer the name and expected type, I didn't say > "you must do all the actual initialization itself in __init__()". > I guess my only thought is that this "static analyzer" is simply a holdover from your Java/C++ programming experience. It just doesn't really make sense in a dynamic language. I'd rather spend my time actually writing the documentation than litter my code so some other software can do it for me. I'm not saying it isn't a good idea in Java, I'm just not sold on the concept in python. Just write doc strings, people have already written utilities to parse and display them. > In the context of the original question > "where and how should we assign class members in order > to flag member names and types to static analyzers like > Doxygen or pylint?" > I understood that people were agreeing > "Yes, assigning each member token values in the __init__() > method is a good practice". > > >>> I think I'm hearing a general yes on that - any other opinions? >>> >> Not sure where you think you are hearing a yes, I am hearing a lot of >> objections. >> > > No they didn't - they said that this cannot be done for true dynamic code, > which is true, but obviously doesn't apply to working with > static analysis tools, which is what the question was about. > > Regards, > Stephen > > _________________________________________________________________ > Messenger Caf? ? open for fun 24/7. Hot games, cool activities served daily. > Visit now. http://cafemessenger.com?ocid=TXT_TAGHM_AugHMtagline > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From pierre.cutellic at gmail.com Sat Aug 18 19:23:51 2007 From: pierre.cutellic at gmail.com (pierre cutellic) Date: Sat, 18 Aug 2007 19:23:51 +0200 Subject: [Tutor] Need some help about pywin32. Message-ID: <3c8b20230708181023k5c9e7b2ew3d560d763c24310a@mail.gmail.com> Hi, I'm actually working with many softwares for 3D-CAD-modeling, like Blender and Rhino, and i have heard about pywin32 and makepy which can define Rhinoscript command but really don't know how to do. This is something which could be really usefull (and a super saving-time tip!!) for me to command both Rhino and Blender by the same interface and language; and in order to share data from softwrares in general. Does anybody could explain me how to process? Or maybe any good tutorial about that? Best regards. Pierre. - -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070818/d27d2b1f/attachment.html From strider1551 at gmail.com Sun Aug 19 05:44:06 2007 From: strider1551 at gmail.com (Adam A. Zajac) Date: Sat, 18 Aug 2007 23:44:06 -0400 Subject: [Tutor] getting the size of an open TarFile object Message-ID: <20070818234406.47bc6098@lavos> Hello all, I've been working with the tarfile module and just noticed an apparent flaw in my own logic. I wanted to add files to the tar until it neared a certain file size. After every addition I would use os.path.getsize(). What I noticed today is that I could add a file to the tar without the tar's size changing. I'm assuming that because the TarFile object is not closed, finding its size that way isn't reliable. The first thing I tried was using flush(), but TarFile objects apparently don't do that. I also can't close the object and reopen it for appending because TarFile objects can't append if the tar is compressed. And finally, I can't predict the compression ratio, so I can't merely keep track of the size of the individual files without a huge gap to my target size. I'm giving up on it for the night. Anyone have any thoughts? Adam From kent37 at tds.net Sun Aug 19 13:39:43 2007 From: kent37 at tds.net (Kent Johnson) Date: Sun, 19 Aug 2007 07:39:43 -0400 Subject: [Tutor] getting the size of an open TarFile object In-Reply-To: <20070818234406.47bc6098@lavos> References: <20070818234406.47bc6098@lavos> Message-ID: <46C82BFF.5010004@tds.net> Adam A. Zajac wrote: > Hello all, > > I've been working with the tarfile module and just noticed an apparent > flaw in my own logic. I wanted to add files to the tar until it neared > a certain file size. After every addition I would use > os.path.getsize(). What I noticed today is that I could add a file to > the tar without the tar's size changing. I'm assuming that because the > TarFile object is not closed, finding its size that way isn't reliable. > > The first thing I tried was using flush(), but TarFile objects > apparently don't do that. I also can't close the object and reopen it > for appending because TarFile objects can't append if the tar is > compressed. And finally, I can't predict the compression ratio, so I > can't merely keep track of the size of the individual files without a > huge gap to my target size. > > I'm giving up on it for the night. Anyone have any thoughts? Something to try, just from looking at the docs and the code: You can open the output file yourself and pass it to tarfile.open(). Then you could use f.tell() to get an idea how many bytes have been written. The file-like object being used by the tarfile is stored in its fileobj attribute so maybe you can flush that before the tell(). HTH, Kent From timmichelsen at gmx-topmail.de Sun Aug 19 20:50:10 2007 From: timmichelsen at gmx-topmail.de (Tim Michelsen) Date: Sun, 19 Aug 2007 20:50:10 +0200 Subject: [Tutor] Python Book Recommendations [Was:[Re: Security]] In-Reply-To: <20070818043022.0B37E1E4002@bag.python.org> References: <46C41652.8000706@gmx-topmail.de> <78b3a9580708161228l24bbd757i65507541b7c1d98e@mail.gmail.com> <46C5BC77.6060601@unc.edu> <20070818043022.0B37E1E4002@bag.python.org> Message-ID: Hello, >> Univ of Toronto, Indiana Univ, and Caltech. Dr. Wilson wrote about it in >> the magazine of Sigma Xi: >> >> http://www.americanscientist.org/template/AssetDetail/assetid/48548 >> >> It has moved around a lot. It's current official home is on scipy.org: >> >> http://www.swc.scipy.org/ >> >> There are several links to older SWC URLs on python.org. None of them >> are in the wiki where they could be easily fixed, however. > > Chris, THANK YOU, especially for the link, . > > My thanks also to Alan, Wesley, and bhaaluu. What a great list Tutor is! Me too, I want to second Dick Moore and thank y'all for sending this out! How nice that the SWC gets updated and improved! @Dick, as another noob, I wish you success in stepping into Python ;-) From johnnyjiv at gmail.com Sun Aug 19 22:46:33 2007 From: johnnyjiv at gmail.com (Johnny Jelinek IV) Date: Sun, 19 Aug 2007 15:46:33 -0500 Subject: [Tutor] Data Gathering Message-ID: Hi, I was wondering if something like this is possible; Can I create a python script that will connect to a website to use it's search features to gather information for me? For example, if I wanted information about a movie from imdb, or something from wikipedia, but didn't want to go to the website, could I create a program to let me search and it would output data from those sites to me in my program? Thanks! --Johnny -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070819/3c6f084a/attachment.html From john at fouhy.net Mon Aug 20 01:27:58 2007 From: john at fouhy.net (John Fouhy) Date: Mon, 20 Aug 2007 11:27:58 +1200 Subject: [Tutor] Data Gathering In-Reply-To: References: Message-ID: <5e58f2e40708191627n7c4e84bfjccd1970c84b8cc04@mail.gmail.com> On 20/08/07, Johnny Jelinek IV wrote: > I was wondering if something like this is possible; Can I create a python > script that will connect to a website to use it's search features to gather > information for me? For example, if I wanted information about a movie from > imdb, or something from wikipedia, but didn't want to go to the website, > could I create a program to let me search and it would output data from > those sites to me in my program? You can. To figure out how to do this, you will need to understand the basics of HTML; in particular, form submission. You'll then need to look into python libraries like urllib. (actually, with some sites, you could get by without form submission. Eg, for Wikipedia, you would just need to fetch the url 'http://en.wikipedia.org/wiki/Special:Search?search=%s' % searchString) -- John. From kent37 at tds.net Mon Aug 20 02:20:49 2007 From: kent37 at tds.net (Kent Johnson) Date: Sun, 19 Aug 2007 20:20:49 -0400 Subject: [Tutor] Data Gathering In-Reply-To: References: Message-ID: <46C8DE61.8080808@tds.net> Johnny Jelinek IV wrote: > Hi, > > I was wondering if something like this is possible; Can I create a > python script that will connect to a website to use it's search features > to gather information for me? For example, if I wanted information > about a movie from imdb, or something from wikipedia, but didn't want to > go to the website, could I create a program to let me search and it > would output data from those sites to me in my program? For IMDB specifically there are a couple of Python packages that will fetch the data for you. http://imdbpy.sourceforge.net/ http://pypi.python.org/pypi/IMDb/0.1.2 In general, you will have to learn about form submission using urllib or urllib2 and HTML parsing with perhaps BeautifulSoup. A few links to help: http://docs.python.org/dev/howto/urllib2.html http://www.crummy.com/software/BeautifulSoup/documentation.html Kent From janos.juhasz at VELUX.com Mon Aug 20 08:27:19 2007 From: janos.juhasz at VELUX.com (=?ISO-8859-1?Q?J=E1nos_Juh=E1sz?=) Date: Mon, 20 Aug 2007 08:27:19 +0200 Subject: [Tutor] iterate list items as lvalue In-Reply-To: Message-ID: Dear Tutors! I know a python list is a mutable object. >>> array = [1,2,3,4,5] So I can modify any item in it. >>> for index in range(len(array)): array[index] *= 2 ... >>> array [2, 4, 6, 8, 10] So I typed this: >>> for item in array: item *= 2 ... >>> array [1, 2, 3, 4, 5] It confused me a little, so made another test. >>> item1 = array[0] >>> item1 1 >>> item1 = 'changed' >>> array [2, 4, 6, 8, 10] >>> item1 'changed' So I feel that, the iteration goes over on inmutable objects. But how can I iterate the iterate the items as mutable object, like the pointers in C ? Is the only way to manage the iteration with indexes ? Or is it any trick like >>> for item in array[:]: item *= 2 ... but isn't a trick :( >>> array [2, 4, 6, 8, 10] Yours sincerely, J?nos Juh?sz From pine508 at hotmail.com Mon Aug 20 09:17:08 2007 From: pine508 at hotmail.com (Che M) Date: Mon, 20 Aug 2007 03:17:08 -0400 Subject: [Tutor] SQLite database creation bafflement In-Reply-To: Message-ID: Hi, I am trying to simply create an SQLite database with Python. I find that when I try to create a new database file, *sometimes* it lets me do it, and sometimes it doesn't, and the only thing I am changing is the name of the database. I am baffled as to why some names appear to work and some don't. For example, this will create a brand new database on the desktop: import sqlite3 conn = sqlite3.connect('C:\Documents and Settings\user\Desktop\mydatabase.db') But running *this*--only thing different is the database's name--gives the error, as shown: import sqlite3 conn = sqlite3.connect('C:\Documents and Settings\user\Desktop\adatabase.db') Traceback (most recent call last): File "C:/Documents and Settings/user/Desktop/sqlitetester", line 5, in conn = sqlite3.connect('C:\Documents and Settings\user\Desktop\adatabase.db') OperationalError: unable to open database file The only thing that is different is one is called "mydatabase.db" (works) and the other is called "adatabase.db" (doesn't work). I've tested lots of different names, and it seems random to me what will work and what won't. E.g., "banana.db" and "apple.db" don't work, but "peach.db" and "pear.db" do It is also consistent with each name (that is, if I am successful and then remove the .db file from the desktop, that name will always work again to create a new .db file). None of this makes any sense: it should be able to use anything, shouldn't it? I assume I am missing something obvious. Any help would help restore sanity to acceptable levels. Thanks. _________________________________________________________________ Booking a flight? Know when to buy with airfare predictions on MSN Travel. http://travel.msn.com/Articles/aboutfarecast.aspx&ocid=T001MSN25A07001 From alan.gauld at btinternet.com Mon Aug 20 12:11:50 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 20 Aug 2007 11:11:50 +0100 Subject: [Tutor] iterate list items as lvalue References: Message-ID: "J?nos Juh?sz" wrote > So I can modify any item in it. > >>> for index in range(len(array)): array[index] *= 2 > ... > >>> array > [2, 4, 6, 8, 10] > > So I typed this: > >>> for item in array: item *= 2 This is equivalent to index = 0 while index < len(array): item = array[index] # references the content of the array item = item * 2 # assigns a new value to item, no change to the array content index +=1 > It confused me a little, so made another test. > >>> item1 = array[0] > >>> item1 > 1 > >>> item1 = 'changed' > >>> array > [2, 4, 6, 8, 10] > >>> item1 > 'changed' This shows that you can assign item1 to the array content and you can change the assignment to something else, all without affecting the list itself > But how can I iterate the iterate the items as mutable object, > like the pointers in C ? > Is the only way to manage the iteration with indexes ? If you want to change the contents of the array then you need to access the array, so yes you need the index. > Or is it any trick like > >>> for item in array[:]: item *= 2 That only creates a new temporary list referencing the same objects as the original it doesn't change anything in the existing one. The normal way to change a single item, in a lst is to use the index. If you are doing bulk changes use a list comprehension to build a new list: >>> array = [1,2,3,4,5] >>> print array [1, 2, 3, 4, 5] >>> array[2] = 9 >>> print array [1, 2, 9, 4, 5] >>> array = [n*2 for n in array] >>> print array [2, 4, 18, 8, 10] >>> HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Mon Aug 20 12:14:17 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 20 Aug 2007 11:14:17 +0100 Subject: [Tutor] SQLite database creation bafflement References: Message-ID: "Che M" wrote > don't. For example, this will create a brand new database on the > desktop: > > conn = sqlite3.connect('C:\Documents and > Settings\user\Desktop\mydatabase.db') > > But running *this*--only thing different is the database's > name--gives the > error, as shown: > > conn = sqlite3.connect('C:\Documents and > Settings\user\Desktop\adatabase.db') Could be that you are hitting the DOS naming issue. Try making your path names raw strings or use forward slashesinstead of backslashes. Python/SQLite may not like the \a character... But I'm guessing. HTH, Alan G. From rschroev_nospam_ml at fastmail.fm Mon Aug 20 12:48:27 2007 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Mon, 20 Aug 2007 12:48:27 +0200 Subject: [Tutor] SQLite database creation bafflement In-Reply-To: References: Message-ID: Che M schreef: > Hi, I am trying to simply create an SQLite database with Python. I find > that when I try to create a new database file, *sometimes* it lets me do it, > and sometimes it doesn't, and the only thing I am changing is the name of > the database. I am baffled as to why some names appear to work and some > don't. For example, this will create a brand new database on the desktop: > > import sqlite3 > conn = sqlite3.connect('C:\Documents and > Settings\user\Desktop\mydatabase.db') > > But running *this*--only thing different is the database's name--gives the > error, as shown: > > import sqlite3 > conn = sqlite3.connect('C:\Documents and > Settings\user\Desktop\adatabase.db') > > Traceback (most recent call last): > File "C:/Documents and Settings/user/Desktop/sqlitetester", line 5, in > > conn = sqlite3.connect('C:\Documents and > Settings\user\Desktop\adatabase.db') > OperationalError: unable to open database file Backslashes in Python string literals function as escape characters, meaning that some combinations of backslash + another character are interpreted specially; for example, \a is an ASCII Bell. See the table at http://docs.python.org/ref/strings.html for a complete list. There are different ways to work around the issue: - Use slashes instead of backslashes, as you would do on Unix. Windows accepts slashes almost everywhere (a notable exception being the command line). - Use double backslashes: \\ in a string literal is actually a single \ - Use raw strings: in raw strings, backslashes are only used to escape quotes and always remain in the string. You can make a raw string by prefixing the string with r or R, for example: conn = sqlite3.connect(r'C:\Documents and Settings\user\Desktop\mydb.db'). A gotcha is that you can't use a backslash as the last character of the string. - Use os.path.join(): that function inserts the correct slashes for the platform you're using, but it's not very readable for literals: conn = sqlite3.connect(os.path.join('C:', 'Documents and Settings', 'user', 'Desktop', 'mydb.db')) > The only thing that is different is one is called "mydatabase.db" (works) > and the other is called "adatabase.db" (doesn't work). > > I've tested lots of different names, and it seems random to me what will > work and what won't. E.g., "banana.db" and "apple.db" don't work, but > "peach.db" and "pear.db" do It is also consistent with each name (that is, > if I am successful and then remove the .db file from the desktop, that name > will always work again to create a new .db file). It will become clear if you look at the table mentioned above: \b and \a have a special meaning, while \p doesn't, so \p is interpreted literally. -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From wormwood_3 at yahoo.com Mon Aug 20 15:40:33 2007 From: wormwood_3 at yahoo.com (wormwood_3) Date: Mon, 20 Aug 2007 06:40:33 -0700 (PDT) Subject: [Tutor] Loop optimization Message-ID: <17709.15963.qm@web32410.mail.mud.yahoo.com> Hello tutors, I am trying to understand the best cases in which to use for loops, list comprehensions, generators, and iterators. I have a rather simple process that I made initially as a for loop: self.potdomains = [] for word in self.dictcontents: self.potdomains.append(word + suffix1) self.potdomains.append(word + suffix2) So I setup an empty list, and then for each item in a list already made, I add something to the end of that item, and then append the new form to another list. What I am wondering is, would it be better in any way to do it using a for loop like this, or instead to use a list comprehension (which would just add readability, not change the logic, I believe), or a generator, or an iterator. My current thought it that a generator would be more useful if I needed to have more control over the process while running, perhaps to add error checking or some other potential interruption. But in purely in terms of running speed, which option would be best? Thanks all! -Sam From kent37 at tds.net Mon Aug 20 15:58:14 2007 From: kent37 at tds.net (Kent Johnson) Date: Mon, 20 Aug 2007 09:58:14 -0400 Subject: [Tutor] Loop optimization In-Reply-To: <17709.15963.qm@web32410.mail.mud.yahoo.com> References: <17709.15963.qm@web32410.mail.mud.yahoo.com> Message-ID: <46C99DF6.8020705@tds.net> wormwood_3 wrote: > Hello tutors, > > I am trying to understand the best cases in which to use for loops, list comprehensions, generators, and iterators. I have a rather simple process that I made initially as a for loop: > > self.potdomains = [] > for word in self.dictcontents: > self.potdomains.append(word + suffix1) > self.potdomains.append(word + suffix2) > > What I am wondering is, would it be better in any way to do it using > a for loop like this, or instead to use a list comprehension (which would > just add readability, not change the logic, I believe), I think what you have is pretty clear. I can't think of a way to do this with a single list comprehension because you add two items to the list each time through the loop. You could use a list comp and a generator expression, but the order of entries in the result will be different: self.potdomains = [ word + suffix1 for word in self.dictcontents ] self.potdomains.extend(word + suffix2 for word in self.dictcontents) > or a generator, def suffixGen(words): for word in words: yield word + suffix1 yield word + suffix2 self.potdomains = list(suffixGen(self.dictcontents)) > or an iterator. My current thought it that a generator would be more > useful if I needed to have more control over the process while running, > perhaps to add error checking or some other potential interruption. But > in purely in terms of running speed, which option would be best? The only way to know for sure is to try it with your data. Use the timeit module to test. My guess is that an optimized version of your code will be fastest, something like potdomains = [] append_ = potdomains.append for word in self.dictcontents: append_(word+suffix1) append_(word+suffix2) self.potdomains = potdomains This takes all attribute lookups out of the loop. Put this in a function (method) and make sure suffix1 and suffix2 are local variables (probably function parameters). Then test :-) Kent From wormwood_3 at yahoo.com Mon Aug 20 16:26:24 2007 From: wormwood_3 at yahoo.com (wormwood_3) Date: Mon, 20 Aug 2007 07:26:24 -0700 (PDT) Subject: [Tutor] Loop optimization Message-ID: <958898.35095.qm@web32412.mail.mud.yahoo.com> >I think what you have is pretty clear. I can't think of a way to do this >with a single list comprehension because you add two items to the list >each time through the loop. You could use a list comp and a generator >expression, but the order of entries in the result will be different: >self.potdomains = [ word + suffix1 for word in self.dictcontents ] >self.potdomains.extend(word + suffix2 for word in self.dictcontents) I see what you mean now. I think in this case adding a list comprehension into the mix makes it less readable! >> or a generator, >def suffixGen(words): > for word in words: > yield word + suffix1 > yield word + suffix2 > >self.potdomains = list(suffixGen(self.dictcontents)) To me, in terms of immediate readability, the generator version seems best, at least as you have written it. >The only way to know for sure is to try it with your data. Use the >timeit module to test. It did not know of this module. It will be quite helpful, thanks! (I had been setting a variable to time.time() before a process I needed to time, and then another after, and subtracting them...:-) ) >This takes all attribute lookups out of the loop. Put this in a function >(method) and make sure suffix1 and suffix2 are local variables (probably >function parameters). Then test :-) I will do so tonight and report back. Thanks, Sam From cbc at unc.edu Mon Aug 20 16:56:01 2007 From: cbc at unc.edu (Chris Calloway) Date: Mon, 20 Aug 2007 10:56:01 -0400 Subject: [Tutor] Python Book Recommendations [Was:[Re: Security]] In-Reply-To: References: <46C41652.8000706@gmx-topmail.de> <78b3a9580708161228l24bbd757i65507541b7c1d98e@mail.gmail.com> <46C5BC77.6060601@unc.edu> <20070818043022.0B37E1E4002@bag.python.org> Message-ID: <46C9AB81.7090208@unc.edu> Tim Michelsen wrote: > How nice that the SWC gets updated and improved! I heard from Chris Lasher at the SWC Sprint on Saturday. Turns out there is a bug collector for SWC and this bug has been documented for some time: http://projects.scipy.org/swc/ticket/88 Chris reported, "Will have this fixed by the end of the sprint today, provided we get commit access figured out." Follow progress here: http://projects.scipy.org/swc/roadmap It looks like most of the changesets have been about getting SWC svn access ironed out at its new home at scipy.org. Chris Lasher is also making podcasts out of SWC: http://showmedo.com/videos/series?name=bfNi2X3Xg -- Sincerely, Chris Calloway http://www.seacoos.org office: 332 Chapman Hall phone: (919) 962-4323 mail: Campus Box #3300, UNC-CH, Chapel Hill, NC 27599 From noufal at airtelbroadband.in Mon Aug 20 16:58:39 2007 From: noufal at airtelbroadband.in (Noufal Ibrahim) Date: Mon, 20 Aug 2007 20:28:39 +0530 Subject: [Tutor] iterate list items as lvalue In-Reply-To: References: Message-ID: <46C9AC1F.9070804@airtelbroadband.in> J?nos Juh?sz wrote: > Dear Tutors! > > I know a python list is a mutable object. >>>> array = [1,2,3,4,5] > > So I can modify any item in it. >>>> for index in range(len(array)): array[index] *= 2 > ... >>>> array > [2, 4, 6, 8, 10] > > So I typed this: >>>> for item in array: item *= 2 > ... >>>> array > [1, 2, 3, 4, 5] You usually don't do things like that in python as far as I know. You just work on a generated modified list. foo = range(1,6) for i in [x*2 for x in foo]: do_whatever_you_want_with(i) -- ~noufal From trilokgk at gmail.com Mon Aug 20 18:01:28 2007 From: trilokgk at gmail.com (Trilok Khairnar) Date: Mon, 20 Aug 2007 21:31:28 +0530 Subject: [Tutor] iterate list items as lvalue In-Reply-To: <46C9AC1F.9070804@airtelbroadband.in> References: <46C9AC1F.9070804@airtelbroadband.in> Message-ID: <002901c7e343$60d1e1b0$f92d580a@persistent.co.in> It also seems fair to do the following (if the modified list is to be used more than once - to avoid building the modified list more than once)? array = [item*2 for item in array] # instead of >>>> for item in array: item *= 2 Regards, Trilok -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Noufal Ibrahim Sent: Monday, August 20, 2007 8:29 PM To: J?nos Juh?sz Cc: tutor at python.org Subject: Re: [Tutor] iterate list items as lvalue J?nos Juh?sz wrote: > Dear Tutors! > > I know a python list is a mutable object. >>>> array = [1,2,3,4,5] > > So I can modify any item in it. >>>> for index in range(len(array)): array[index] *= 2 > ... >>>> array > [2, 4, 6, 8, 10] > > So I typed this: >>>> for item in array: item *= 2 > ... >>>> array > [1, 2, 3, 4, 5] You usually don't do things like that in python as far as I know. You just work on a generated modified list. foo = range(1,6) for i in [x*2 for x in foo]: do_whatever_you_want_with(i) -- ~noufal _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From deliberatus at verizon.net Mon Aug 20 17:08:58 2007 From: deliberatus at verizon.net (Kirk Bailey) Date: Mon, 20 Aug 2007 11:08:58 -0400 Subject: [Tutor] xls file In-Reply-To: <46C27741.4050902@verizon.net> References: <46C27741.4050902@verizon.net> Message-ID: <46C9AE8A.1040307@verizon.net> ok, I installed XLRD and can load a xls file; it works quite well BTW. Now it is returning Unicode objects. I need to strip that to a simple string value. Is there a recommended way or module for handling Unicode objects? Kirk Bailey wrote: > Ii want to read a xls file and use the data in part of it. What module > would help make sense of one? > > > -- Salute! -Kirk Bailey Think +-----+ | BOX | +-----+ knihT Fnord. From pine508 at hotmail.com Mon Aug 20 18:56:19 2007 From: pine508 at hotmail.com (Che M) Date: Mon, 20 Aug 2007 12:56:19 -0400 Subject: [Tutor] SQLite database creation bafflement In-Reply-To: Message-ID: Thank you Alan and Roel for the insight, and Roel thank you for all the suggested ways to get around it. It's always nice when something goes from making no sense to making complete sense in a snap. Che _________________________________________________________________ Booking a flight? Know when to buy with airfare predictions on MSN Travel. http://travel.msn.com/Articles/aboutfarecast.aspx&ocid=T001MSN25A07001 From ricaraoz at gmail.com Mon Aug 20 20:14:24 2007 From: ricaraoz at gmail.com (=?ISO-8859-2?Q?Ricardo_Ar=E1oz?=) Date: Mon, 20 Aug 2007 15:14:24 -0300 Subject: [Tutor] iterate list items as lvalue In-Reply-To: <46C9AC1F.9070804@airtelbroadband.in> References: <46C9AC1F.9070804@airtelbroadband.in> Message-ID: <46C9DA00.4060801@bigfoot.com> Noufal Ibrahim wrote: > J?nos Juh?sz wrote: >> Dear Tutors! >> >> I know a python list is a mutable object. >>>>> array = [1,2,3,4,5] >> So I can modify any item in it. >>>>> for index in range(len(array)): array[index] *= 2 >> ... >>>>> array >> [2, 4, 6, 8, 10] >> >> So I typed this: >>>>> for item in array: item *= 2 >> ... >>>>> array >> [1, 2, 3, 4, 5] > > You usually don't do things like that in python as far as I know. > > You just work on a generated modified list. > > foo = range(1,6) > for i in [x*2 for x in foo]: > do_whatever_you_want_with(i) > What about : array = [1,2,3,4,5] array = [i * 2 for i in array] From kent37 at tds.net Mon Aug 20 20:53:03 2007 From: kent37 at tds.net (Kent Johnson) Date: Mon, 20 Aug 2007 14:53:03 -0400 Subject: [Tutor] xls file In-Reply-To: <46C9AE8A.1040307@verizon.net> References: <46C27741.4050902@verizon.net> <46C9AE8A.1040307@verizon.net> Message-ID: <46C9E30F.2010704@tds.net> Kirk Bailey wrote: > ok, I installed XLRD and can load a xls file; it works quite well BTW. Now > it is returning Unicode objects. I need to strip that to a simple string > value. Is there a recommended way or module for handling Unicode objects? What kind of characters are in the Excel file? What do you want to do with non-ascii characters? Some options: unicodeData.decode('ascii') # Will choke if any non-ascii characters unicodeData.decode('ascii', 'ignore') # Will throw away non-ascii characters unicodeData.decode('ascii', 'replace') # Will replace non-ascii characters with '?' Also of interest: http://www.crummy.com/cgi-bin/msm/map.cgi/ASCII%2C+Dammit http://groups.google.com/group/comp.lang.python/msg/159a41b3e6bae313?hl=en& Kent From dkuhlman at rexx.com Mon Aug 20 22:32:48 2007 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Mon, 20 Aug 2007 13:32:48 -0700 Subject: [Tutor] iterate list items as lvalue In-Reply-To: <46C9DA00.4060801@bigfoot.com> References: <46C9AC1F.9070804@airtelbroadband.in> <46C9DA00.4060801@bigfoot.com> Message-ID: <20070820203248.GA87297@cutter.rexx.com> On Mon, Aug 20, 2007 at 03:14:24PM -0300, Ricardo Ar?oz wrote: [snip] > > You just work on a generated modified list. > > > > foo = range(1,6) > > for i in [x*2 for x in foo]: > > do_whatever_you_want_with(i) > > > > What about : > > array = [1,2,3,4,5] > array = [i * 2 for i in array] > Good solution. However, consider the following: >>> array = [1,2,3,4,5] >>> array2 = array >>> array = [i * 2 for i in array] >>> array [2, 4, 6, 8, 10] >>> array2 [1, 2, 3, 4, 5] So, did you want array2 to change, or not? Your solution is a good one for situations where you do *not* want array2 to change. Here is a solution that changes the object that both array and array2 refer to: >>> array = [1, 2, 3, 4, 5] >>> array2 = array >>> for idx, item in enumerate(array): array[idx] = item * 2 >>> array [2, 4, 6, 8, 10] >>> array2 [2, 4, 6, 8, 10] Basically, this modifies the list "in place", rather than making a new list from the old one. Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman From kent37 at tds.net Mon Aug 20 22:55:23 2007 From: kent37 at tds.net (Kent Johnson) Date: Mon, 20 Aug 2007 16:55:23 -0400 Subject: [Tutor] iterate list items as lvalue In-Reply-To: <20070820203248.GA87297@cutter.rexx.com> References: <46C9AC1F.9070804@airtelbroadband.in> <46C9DA00.4060801@bigfoot.com> <20070820203248.GA87297@cutter.rexx.com> Message-ID: <46C9FFBB.8070207@tds.net> Dave Kuhlman wrote: > Consider the following: > > >>> array = [1,2,3,4,5] > >>> array2 = array > >>> array = [i * 2 for i in array] > >>> array > [2, 4, 6, 8, 10] > >>> array2 > [1, 2, 3, 4, 5] > > So, did you want array2 to change, or not? > > Here is a solution that changes the object that both array and > array2 refer to: > > >>> array = [1, 2, 3, 4, 5] > >>> array2 = array > >>> for idx, item in enumerate(array): > array[idx] = item * 2 > >>> array > [2, 4, 6, 8, 10] > >>> array2 > [2, 4, 6, 8, 10] > > Basically, this modifies the list "in place", rather than making a > new list from the old one. Another way to do this is to assign to a slice of array: array[:] = [ item*2 for item in array ] Kent From ricaraoz at gmail.com Tue Aug 21 00:03:58 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Mon, 20 Aug 2007 19:03:58 -0300 Subject: [Tutor] iterate list items as lvalue In-Reply-To: <46C9FFBB.8070207@tds.net> References: <46C9AC1F.9070804@airtelbroadband.in> <46C9DA00.4060801@bigfoot.com> <20070820203248.GA87297@cutter.rexx.com> <46C9FFBB.8070207@tds.net> Message-ID: <46CA0FCE.1000502@bigfoot.com> Kent Johnson wrote: > Dave Kuhlman wrote: >> Consider the following: >> >> >>> array = [1,2,3,4,5] >> >>> array2 = array >> >>> array = [i * 2 for i in array] >> >>> array >> [2, 4, 6, 8, 10] >> >>> array2 >> [1, 2, 3, 4, 5] >> >> So, did you want array2 to change, or not? >> >> Here is a solution that changes the object that both array and >> array2 refer to: >> >> >>> array = [1, 2, 3, 4, 5] >> >>> array2 = array >> >>> for idx, item in enumerate(array): >> array[idx] = item * 2 >> >>> array >> [2, 4, 6, 8, 10] >> >>> array2 >> [2, 4, 6, 8, 10] >> >> Basically, this modifies the list "in place", rather than making a >> new list from the old one. > > Another way to do this is to assign to a slice of array: > > array[:] = [ item*2 for item in array ] > > Kent Thanks, hadn't really thought about having a copy of array (guess I'm too much of a n00b). Really simple and elegant way of solving it though. From wormwood_3 at yahoo.com Tue Aug 21 02:21:52 2007 From: wormwood_3 at yahoo.com (wormwood_3) Date: Mon, 20 Aug 2007 17:21:52 -0700 (PDT) Subject: [Tutor] Loop optimization Message-ID: <187699.93199.qm@web32408.mail.mud.yahoo.com> I ran a few tests, with the following results: 1. Timing using the time module: * Using for loop, src code: import time start = time.time() for word in self.dictcontents: self.potdomains.append(word + suffix1) self.potdomains.append(word + suffix2) end = time.time() runtime = end - start print "Using time(), for loop took %s s" % runtime ** I obtained the following results (using the full agid-4 dictionary, ~112K entries): python domainspotter.py --file resources/agid-4/infl.txt Using time(), for loop took 0.132480859756 s python domainspotter.py --file resources/agid-4/infl.txt Using time(), for loop took 0.143032073975 s python domainspotter.py --file resources/agid-4/infl.txt Using time(), for loop took 0.135424137115 s * Using generator, src code: def suffixGen(self, words): suffix1 = ".com" suffix2 = ".net" for word in words: yield word + suffix1 yield word + suffix2 def domainify(self): self.potdomains = [] words = self.dictcontents import time start = time.time() self.potdomains = list(CheckDomains.suffixGen(self, words)) end = time.time() runtime = end - start print "Using time(), generator took %s s" % runtime ** I obtained the following results (using the full agid-4 dictionary, ~112K entries): python domainspotter.py --file resources/agid-4/infl.txt Using time(), generator took 0.0830721855164 s python domainspotter.py --file resources/agid-4/infl.txt Using time(), generator took 0.0818212032318 s python domainspotter.py --file resources/agid-4/infl.txt Using time(), generator took 0.0830278396606 s This revealed that the generator seemed to be much faster, around 60% faster. I then wanted to try both possibilities with the timeit module, but was unable to get it working. I will start a new thread on that next, however, in case anyone has any further thoughts on the for loop versus generator issue. -Sam From kent37 at tds.net Tue Aug 21 02:50:34 2007 From: kent37 at tds.net (Kent Johnson) Date: Mon, 20 Aug 2007 20:50:34 -0400 Subject: [Tutor] Loop optimization In-Reply-To: <187699.93199.qm@web32408.mail.mud.yahoo.com> References: <187699.93199.qm@web32408.mail.mud.yahoo.com> Message-ID: <46CA36DA.6040300@tds.net> wormwood_3 wrote: > I ran a few tests, with the following results: > > 1. Timing using the time module: > * Using for loop, src code: > import time > start = time.time() > for word in self.dictcontents: > self.potdomains.append(word + suffix1) > self.potdomains.append(word + suffix2) > end = time.time() > runtime = end - start > print "Using time(), for loop took %s s" % runtime > > ** I obtained the following results (using the full agid-4 dictionary, ~112K entries): > python domainspotter.py --file resources/agid-4/infl.txt > Using time(), for loop took 0.132480859756 s > python domainspotter.py --file resources/agid-4/infl.txt > Using time(), for loop took 0.143032073975 s > python domainspotter.py --file resources/agid-4/infl.txt > Using time(), for loop took 0.135424137115 s > > * Using generator, src code: > def suffixGen(self, words): > suffix1 = ".com" > suffix2 = ".net" > for word in words: > yield word + suffix1 > yield word + suffix2 > def domainify(self): > self.potdomains = [] > words = self.dictcontents > import time > start = time.time() > self.potdomains = list(CheckDomains.suffixGen(self, words)) > end = time.time() > runtime = end - start > print "Using time(), generator took %s s" % runtime > > ** I obtained the following results (using the full agid-4 dictionary, ~112K entries): > python domainspotter.py --file resources/agid-4/infl.txt > Using time(), generator took 0.0830721855164 s > python domainspotter.py --file resources/agid-4/infl.txt > Using time(), generator took 0.0818212032318 s > python domainspotter.py --file resources/agid-4/infl.txt > Using time(), generator took 0.0830278396606 s > > > This revealed that the generator seemed to be much faster, around 60% faster. You should try an optimized for loop: append_ = self.potdomains.append_ s1_ = suffix1 s2_ = suffix2 for word in self.dictcontents: append_(word + s1_) append_(word + s2_) This will take out some of the difference at least. Note that if you are using this as part of your domainspotter project and you will be running a whois request on each of these names, any time you save in this loop will be completely overshadowed by the time for the whois request. So in this case the 'best' loop is probably the most readable one, not the one that shaves .05 seconds off the running time. It's still fun to play with optimization, but don't take it too seriously until you know it will make a difference in the final program. Kent From orest.kozyar at gmail.com Tue Aug 21 05:13:51 2007 From: orest.kozyar at gmail.com (Orest Kozyar) Date: Mon, 20 Aug 2007 23:13:51 -0400 Subject: [Tutor] Accesing "column" of a 2D list Message-ID: <001b01c7e3a1$4d54ee80$3507fa12@issphoenix> I've got a "2D" list (essentially a list of lists where all sublists are of the same length). The sublists are polymorphic. One "2D" list I commonly work with is: [ [datetime object, float, int, float], [datetime object, float, int, float], [datetime object, float, int, float] ] I'd like to be able to quickly accumulate the datetime column into a list. Is there a simple/straightforward syntax (such as list[:][0]) to do this, or do we need to use a for loop? I expect what I have in mind is similar to the Python array type, except it would be polymorphic. Thanks, Orest From witham.ian at gmail.com Tue Aug 21 05:46:13 2007 From: witham.ian at gmail.com (Ian Witham) Date: Tue, 21 Aug 2007 15:46:13 +1200 Subject: [Tutor] Accesing "column" of a 2D list In-Reply-To: <001b01c7e3a1$4d54ee80$3507fa12@issphoenix> References: <001b01c7e3a1$4d54ee80$3507fa12@issphoenix> Message-ID: This looks like a job for List Comprehensions! >>> list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] >>> new_list = [item[1] for item in list] >>> new_list [2, 5, 8] >>> looks good? Ian On 8/21/07, Orest Kozyar wrote: > > I've got a "2D" list (essentially a list of lists where all sublists are > of > the same length). The sublists are polymorphic. One "2D" list I commonly > work with is: > > [ [datetime object, float, int, float], > [datetime object, float, int, float], > [datetime object, float, int, float] ] > > I'd like to be able to quickly accumulate the datetime column into a list. > Is there a simple/straightforward syntax (such as list[:][0]) to do this, > or > do we need to use a for loop? I expect what I have in mind is similar to > the Python array type, except it would be polymorphic. > > Thanks, > Orest > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070821/19390a8c/attachment.htm From tpc247 at gmail.com Tue Aug 21 06:04:52 2007 From: tpc247 at gmail.com (tpc247 at gmail.com) Date: Mon, 20 Aug 2007 21:04:52 -0700 Subject: [Tutor] operating system key-bindings that call Python scripts Message-ID: I have a particular date time format I use for making entries in various logs I maintain, and ideally what I'd like is for my operating system (Windows or Linux) to recognize that every time I type, say, -'C' '1', a Python script I wrote will execute and out will pop the current date time in my desired format. I want this to happen not just in my Xemacs text editor buffer, but inside a textfield for, say, the Gmail application in Mozilla, in Python IDLE, in the Google desktop search bar and at the command line. At LinuxWorld I asked three of the people from the San Francisco Linux users group about doing this in Ubuntu, and here is what I could ascertain: *) the Apple OS is ideally suited to doing what you want, and necessitates learning AppleScript. In Windows or Linux it's a lot more complicated to bind a sequence of keys to call a Python program that generates output in any graphical window and, in fact, it may be impossible or more trouble than it's worth *) at the prompt you can execute the Python program to output the date time in your desired format, but to do this in Gnome or KDE is a different story *) within the browser environment you can write a Mozilla Firefox extension that may allow you to call Python scripts, but this necessitates learning XUL Have any of you ever successfully engineered an operating system key-binding that calls a Python script and directs the output where the cursor is in any graphical window in Windows and Linux ? In Ubuntu I followed the advice in this article: http://ekith.com/index.php?option=com_content&task=view&id=10181 but found that System/Preferences/Keyboard Shortcuts does not allow you to define your own action. I created launchers for my Python scripts but clicking on them seemed to have no effect. I guess my expectation should be the answer is no, in which case I'd be happy just to find out if it's possible to create key-bindings in Xemacs to call a Python program. I have a feeling the answer to this query is no as well, in which case my next step is to port the following to elisp: def output_current_datetime_in_my_desired_format(): import datetime print datetime.datetime.now().strftime("%d%b%Y%a %I:%M%p").upper() def output_current_time_in_my_desired_format(): import datetime print datetime.datetime.now().strftime("%I:%M%p").upper().rjust(20) -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070820/1a51f90f/attachment.htm From alan.gauld at btinternet.com Tue Aug 21 09:53:46 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 21 Aug 2007 08:53:46 +0100 Subject: [Tutor] operating system key-bindings that call Python scripts References: Message-ID: wrote > (Windows or Linux) to recognize that every time I type, say, > -'C' '1', > a Python script I wrote will execute and out will pop the current > date time Ctrl-C is a particularly difficult combination since in many OS it is the system interrupt but if you went for a somewhat less controversial choice like Ctrl-T say, then it becomes a little bit easier to achieve. > in my desired format. I want this to happen not just in my Xemacs > text > editor buffer, but inside a textfield for, say, the Gmail > application in > Mozilla, in Python IDLE, in the Google desktop search bar and at the > command > line. This is truly difficult since each application has its own mechanism for grabbing keystrokes. Xemacs indeed has two mechanisms, one for console mode and one for GUI mode! The GUI has its own key handling events (but subverts system combinations like Ctrl-C as mentioned above) and the OS command line is the hardest of all unless you restrict it to a GUI console window in which case you can catch it at the GUI level. Alternatively you can write your own shell! Catching the keypresses at a global level in a GUI is possible but you then have the problem of identifying the original target widget and manipulating that after running your python code. You also need to post on the original keystroke since the target application might use it for something else! > *) the Apple OS is ideally suited to doing what you want, and > necessitates > learning AppleScript. True. > In Windows or Linux it's a lot more complicated to > bind a sequence of keys to call a Python program that generates > output in > any graphical window Linux largely depends on the GUI in use. Most sit on top of X and could be manipulated at that level but it involves very low level coding in C. Windows is not too difficult to catch the keystrokes and execute a python script (use WinExec() ) but getting the result back into your target application will be tricky, probably involving use of a lot of PostMessage events. > and, in fact, it may be impossible or more trouble than > it's worth Certainly difficult and very open to a trial and error approach and even then could result in some spectacularly unpredictable behaviour that could seriously damage your applications/data! Basically you are trying to change the OS behaviour. Its the OS job to detect key presses and direct them to their destination, to change that you have to interact at a fundamental level with the OS keyhandling. > Have any of you ever successfully engineered an operating system > key-binding Yes, done this in VB and C++ > that calls a Python script and directs the output where the cursor > is in any > graphical window in Windows and Linux ? I've separately routed characters to another window in Windoze using VB. > I guess my expectation should be the answer is no, in which case I'd > be > happy just to find out if it's possible to create key-bindings in > Xemacs to > call a Python program. Calling Python is easy because there are standard emacs functions for executing a shell command (which includes python) and for scraping the output into a text buffer and pasting that wherever you want. But it will involve some elisp. But most of what you want is not possible in pure python (except possibly in Windows) it will require a fair bit of coding in C, elisp, Applescript etc as well > well, in which case my next step is to port the following to elisp: > > def output_current_datetime_in_my_desired_format(): > import datetime > print datetime.datetime.now().strftime("%d%b%Y%a > %I:%M%p").upper() Frankly, for emacs, that would be the easiest since the elisp required to call your Python is almost certainly harder than the elisp to print some formated date/time stuff! And every emacs user should know the basics of elisp, without it you are losing a large part of the power of emacs! HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From pgreisen at gmail.com Tue Aug 21 10:53:12 2007 From: pgreisen at gmail.com (Per Jr. Greisen) Date: Tue, 21 Aug 2007 10:53:12 +0200 Subject: [Tutor] Convert bmp to mpeg Message-ID: Hi, I would like to make a method where I give a number of bmp-file as argument and than create a mpeg format from these - is that possible with python and which packages should I use? Thanks in advance -- Best regards Per Jr. Greisen -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070821/7d9b59dc/attachment.htm From alan.gauld at btinternet.com Tue Aug 21 11:09:22 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 21 Aug 2007 10:09:22 +0100 Subject: [Tutor] Convert bmp to mpeg References: Message-ID: "Per Jr. Greisen" wrote > I would like to make a method where I give a number of bmp-file as > argument > and than create a mpeg format from these - is that possible with > python and > which packages should I use? MPEG is normally used for video (MP3 excepted) but if JPEG is OK then PIL should do what you need. Read about it here: http://www.pythonware.com/library/pil/handbook/index.htm Most of the mpeg libraries seem to be for decoding or extracting information only. You might find that its simpler to use the ImageMagick (not Python) toolset does what you want. http://www.imagemagick.org/script/index.php HTH, Alan G. From kent37 at tds.net Tue Aug 21 12:40:45 2007 From: kent37 at tds.net (Kent Johnson) Date: Tue, 21 Aug 2007 06:40:45 -0400 Subject: [Tutor] Accesing "column" of a 2D list In-Reply-To: References: <001b01c7e3a1$4d54ee80$3507fa12@issphoenix> Message-ID: <46CAC12D.4040003@tds.net> Ian Witham wrote: > This looks like a job for List Comprehensions! > > >>> list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] > >>> new_list = [item[1] for item in list] > >>> new_list > [2, 5, 8] > >>> Alternately, if you want *all* columns, you can use zip() to transpose the lists: In [1]: lst = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] In [2]: zip(*lst) Out[2]: [(1, 4, 7), (2, 5, 8), (3, 6, 9)] PS. Don't use 'list' as the name of a list, it shadows the builtin 'list' which is the of list. Similarly, avoid str, dict, set and file as names. Kent > looks good? > > Ian > > On 8/21/07, *Orest Kozyar* > wrote: > > I've got a "2D" list (essentially a list of lists where all sublists > are of > the same length). The sublists are polymorphic. One "2D" list I > commonly > work with is: > > [ [datetime object, float, int, float], > [datetime object, float, int, float], > [datetime object, float, int, float] ] > > I'd like to be able to quickly accumulate the datetime column into a > list. > Is there a simple/straightforward syntax (such as list[:][0]) to do > this, or > do we need to use a for loop? I expect what I have in mind is > similar to > the Python array type, except it would be polymorphic. > > Thanks, > Orest > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From brunson at brunson.com Tue Aug 21 17:16:20 2007 From: brunson at brunson.com (Eric Brunson) Date: Tue, 21 Aug 2007 09:16:20 -0600 Subject: [Tutor] Convert bmp to mpeg In-Reply-To: References: Message-ID: <46CB01C4.70106@brunson.com> Per Jr. Greisen wrote: > Hi, > > I would like to make a method where I give a number of bmp-file as > argument and than create a mpeg format from these - is that possible > with python and which packages should I use? On my platform the ffmpeg suite is one of the de facto standards for creating or manipulating mpegs. The PyMedia project purports to provide an interface to this library, check it out here: http://pymedia.org/faq.html > > Thanks in advance > -- > Best regards > Per Jr. Greisen > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From strider1551 at gmail.com Tue Aug 21 17:52:08 2007 From: strider1551 at gmail.com (Adam A. Zajac) Date: Tue, 21 Aug 2007 11:52:08 -0400 Subject: [Tutor] getting the size of an open TarFile object In-Reply-To: <46C82BFF.5010004@tds.net> References: <20070818234406.47bc6098@lavos> <46C82BFF.5010004@tds.net> Message-ID: <20070821115208.3021f859@lavos> > > I've been working with the tarfile module and just noticed an > > apparent flaw in my own logic. I wanted to add files to the tar > > until it neared a certain file size. After every addition I would > > use os.path.getsize(). What I noticed today is that I could add a > > file to the tar without the tar's size changing. I'm assuming that > > because the TarFile object is not closed, finding its size that way > > isn't reliable. > > > > The first thing I tried was using flush(), but TarFile objects > > apparently don't do that. I also can't close the object and reopen > > it for appending because TarFile objects can't append if the tar is > > compressed. And finally, I can't predict the compression ratio, so > > I can't merely keep track of the size of the individual files > > without a huge gap to my target size. > > > > I'm giving up on it for the night. Anyone have any thoughts? > > Something to try, just from looking at the docs and the code: > > You can open the output file yourself and pass it to tarfile.open(). > Then you could use f.tell() to get an idea how many bytes have been > written. The file-like object being used by the tarfile is stored in > its fileobj attribute so maybe you can flush that before the tell(). > > HTH, > Kent That's a brilliant thought. I played with it, and it does seem to give me a more accurate report; in the end, though, it's still not exact. Oh well. For now I'm just putting in a "buffer" and assuming that the archive is 1M larger than whatever it tells me. That seems to keep it from going over at the cost of having a little space that could have been used otherwise. From alan.gauld at btinternet.com Tue Aug 21 18:21:43 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 21 Aug 2007 17:21:43 +0100 Subject: [Tutor] Convert bmp to mpeg References: <46CB01C4.70106@brunson.com> Message-ID: "Eric Brunson" wrote >> I would like to make a method where I give a number of bmp-file as >> argument and than create a mpeg format from these - is that >> possible >> with python and which packages should I use? > > On my platform the ffmpeg suite is one of the de facto standards for > creating or manipulating mpegs. The PyMedia project purports to > provide > an interface to this library, check it out here: > http://pymedia.org/faq.html > Looks like one of the tutorial examples does exactly what was asked. Thanks for the link, I hadn't looked at pymedia before. Alan G. From fiyawerx at gmail.com Tue Aug 21 21:35:32 2007 From: fiyawerx at gmail.com (Fiyawerx) Date: Tue, 21 Aug 2007 15:35:32 -0400 Subject: [Tutor] operating system key-bindings that call Python scripts In-Reply-To: References: Message-ID: <1b31ae500708211235t7d102f0fy7f46c2c14a67049d@mail.gmail.com> Noob here, but just wondering, would it be hard for you to have the program instead of insert the text for you, copy it to your clipboard? It would add a step, but then you could do something like [, ctrl-v] to paste into whatever window you're in. Some keyboards like logitech's g15 allow special binding to macro keys I believe, so you may have something like that to use, or even some sort of free macro program to run your python program, which copies your special timestamp to the clipboard. Or even just throw it in your launcher or quick-launch bar, click it, then paste wherever. On 8/21/07, Alan Gauld wrote: > > wrote > > > (Windows or Linux) to recognize that every time I type, say, > > -'C' '1', > > a Python script I wrote will execute and out will pop the current > > date time > > Ctrl-C is a particularly difficult combination since in many OS it > is the system interrupt but if you went for a somewhat less > controversial > choice like Ctrl-T say, then it becomes a little bit easier to > achieve. > > > in my desired format. I want this to happen not just in my Xemacs > > text > > editor buffer, but inside a textfield for, say, the Gmail > > application in > > Mozilla, in Python IDLE, in the Google desktop search bar and at the > > command > > line. > > This is truly difficult since each application has its own mechanism > for > grabbing keystrokes. Xemacs indeed has two mechanisms, one for > console mode and one for GUI mode! The GUI has its own key > handling events (but subverts system combinations like Ctrl-C as > mentioned above) and the OS command line is the hardest of all unless > you restrict it to a GUI console window in which case you can catch > it at the GUI level. Alternatively you can write your own shell! > > Catching the keypresses at a global level in a GUI is possible but you > then have the problem of identifying the original target widget and > manipulating that after running your python code. You also need to > post on the original keystroke since the target application might > use it for something else! > > > *) the Apple OS is ideally suited to doing what you want, and > > necessitates > > learning AppleScript. > > True. > > > In Windows or Linux it's a lot more complicated to > > bind a sequence of keys to call a Python program that generates > > output in > > any graphical window > > Linux largely depends on the GUI in use. Most sit on top of X and > could > be manipulated at that level but it involves very low level coding in > C. > > Windows is not too difficult to catch the keystrokes and execute a > python script (use WinExec() ) but getting the result back into your > target application will be tricky, probably involving use of a lot of > PostMessage events. > > > and, in fact, it may be impossible or more trouble than > > it's worth > > Certainly difficult and very open to a trial and error approach and > even > then could result in some spectacularly unpredictable behaviour that > could seriously damage your applications/data! Basically you are > trying > to change the OS behaviour. Its the OS job to detect key presses and > direct them to their destination, to change that you have to interact > at a fundamental level with the OS keyhandling. > > > Have any of you ever successfully engineered an operating system > > key-binding > > Yes, done this in VB and C++ > > > that calls a Python script and directs the output where the cursor > > is in any > > graphical window in Windows and Linux ? > > I've separately routed characters to another window in Windoze using > VB. > > > I guess my expectation should be the answer is no, in which case I'd > > be > > happy just to find out if it's possible to create key-bindings in > > Xemacs to > > call a Python program. > > Calling Python is easy because there are standard emacs functions for > executing a shell command (which includes python) and for scraping > the output into a text buffer and pasting that wherever you want. But > it > will involve some elisp. > > But most of what you want is not possible in pure python (except > possibly in Windows) it will require a fair bit of coding in C, > elisp, > Applescript etc as well > > > well, in which case my next step is to port the following to elisp: > > > > def output_current_datetime_in_my_desired_format(): > > import datetime > > print datetime.datetime.now().strftime("%d%b%Y%a > > %I:%M%p").upper() > > Frankly, for emacs, that would be the easiest since the elisp required > to call your Python is almost certainly harder than the elisp to print > some formated date/time stuff! > > And every emacs user should know the basics of elisp, without it > you are losing a large part of the power of emacs! > > HTH, > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.freenetpages.co.uk/hp/alan.gauld > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070821/04e7c85d/attachment.htm From fiyawerx at gmail.com Tue Aug 21 22:30:17 2007 From: fiyawerx at gmail.com (Fiyawerx) Date: Tue, 21 Aug 2007 16:30:17 -0400 Subject: [Tutor] Data Gathering In-Reply-To: References: Message-ID: <1b31ae500708211330r5e5f1b58u931d32f9137aa66d@mail.gmail.com> I've used Twill for similar applications also, and I found this with a quick google.. http://twill.idyll.org/python-api.html For what I've used it, it works wonders. On 8/19/07, Johnny Jelinek IV wrote: > > Hi, > > I was wondering if something like this is possible; Can I create a python > script that will connect to a website to use it's search features to gather > information for me? For example, if I wanted information about a movie from > imdb, or something from wikipedia, but didn't want to go to the website, > could I create a program to let me search and it would output data from > those sites to me in my program? > > Thanks! > > --Johnny > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070821/52ef5d84/attachment-0001.htm From tinoloc at gmail.com Tue Aug 21 22:53:09 2007 From: tinoloc at gmail.com (Tino Dai) Date: Tue, 21 Aug 2007 16:53:09 -0400 Subject: [Tutor] subprocess and su Message-ID: Hi there, I'm have a tough time figuring out how to get su and subprocess working. I have PIPE=subprocess.pipe sbp=subprocess.Popen (["su","-",stdin=PIPE,stdout=PIPE,close_fds=True,shell=True) how I thought that it was supposed to work was it would allow me to use sbp.communicate() to send stuff to the stdin, and get information out. What do get is a prompt ask for my password. Does anybody have an example that I can see (I have already check most of the entries in google( or should I just use pexpect instead? -Thanks, Tino -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070821/e6c603b4/attachment.htm From brunson at brunson.com Tue Aug 21 22:57:46 2007 From: brunson at brunson.com (Eric Brunson) Date: Tue, 21 Aug 2007 14:57:46 -0600 Subject: [Tutor] subprocess and su In-Reply-To: References: Message-ID: <46CB51CA.2030705@brunson.com> Tino Dai wrote: > Hi there, > > I'm have a tough time figuring out how to get su and subprocess > working. I have > > PIPE=subprocess.pipe > > sbp=subprocess.Popen(["su","-",stdin=PIPE,stdout=PIPE,close_fds=True,shell=True) > > > how I thought that it was supposed to work was it would allow me to > use sbp.communicate() to > send stuff to the stdin, and get information out. What do get is a > prompt ask for my password. I think you have the right understanding of Popen, you seem to be missing out on "su". What happens when you type "su -" on the command line? > Does > anybody have an example that I can see (I have already check most of > the entries in google( or should > I just use pexpect instead? > > -Thanks, > Tino > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at btinternet.com Wed Aug 22 01:04:35 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 22 Aug 2007 00:04:35 +0100 Subject: [Tutor] subprocess and su References: Message-ID: "Tino Dai" wrote > PIPE=subprocess.pipe Not sure why you need this? > sbp=subprocess.Popen > (["su","-",stdin=PIPE,stdout=PIPE,close_fds=True,shell=True) and I'm not sure what that [ is doing in there? I assume you meant to have a closing ] after the "-"? Have you looked at the examples in the module documents? They cover most common usages. > sbp.communicate() to send stuff to the stdin, and get information > out. What do get is a prompt ask for my password. su may be spitting the prompt out to stderr. This is quite common for Unix programs and you might have to assign Popen.stderr to PIPE and read that too. Otherwise you seem to be on the right track. Oddly I just tried some experiments and I can't get subprocess to work with the stdout=PIPE option, it used to... Anyone have any idea what my obvious mistake is? ---------------- import subprocess as sub po = sub.Popen('ls -l', shell=True, stdout=sub.PIPE) ---------------- gives: Traceback (most recent call last): File "", line 1, in ? File "C:\Python24\lib\subprocess.py", line 533, in __init__ (p2cread, p2cwrite, File "C:\Python24\lib\subprocess.py", line 593, in _get_handles p2cread = self._make_inheritable(p2cread) File "C:\Python24\lib\subprocess.py", line 634, in _make_inheritable DUPLICATE_SAME_ACCESS) TypeError: an integer is required ---------------------- It works without the stdout argument. Puzzled... Alan G From alan.gauld at btinternet.com Wed Aug 22 05:43:00 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 22 Aug 2007 04:43:00 +0100 Subject: [Tutor] subprocess and su References: Message-ID: "Alan Gauld" wrote > Oddly I just tried some experiments and I can't get subprocess > to work with the stdout=PIPE option, it used to... > > Anyone have any idea what my obvious mistake is? > > Traceback (most recent call last): > File "", line 1, in ? > File "C:\Python24\lib\subprocess.py", line 533, in __init__ > (p2cread, p2cwrite, > File "C:\Python24\lib\subprocess.py", line 593, in _get_handles > p2cread = self._make_inheritable(p2cread) > File "C:\Python24\lib\subprocess.py", line 634, in > _make_inheritable > DUPLICATE_SAME_ACCESS) > TypeError: an integer is required Its a PyCrust issue, the code works fine in any of my other shells. Not sure why PyCrust barfs but it does. I might try posting on the wxPython list to see if I get an answer... Alan G From srikanth007m at gmail.com Wed Aug 22 11:23:25 2007 From: srikanth007m at gmail.com (chinni) Date: Wed, 22 Aug 2007 02:23:25 -0700 Subject: [Tutor] Need Some Help Message-ID: Hi All, I am new to python.i need some help about python.i want to learn python so plz guide me from where can i start.so,that i can learn and under stand quickly. -- Best Regards, M.Srikanth Kumar, -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070822/a0813e4e/attachment.htm From meiermic at ee.ethz.ch Wed Aug 22 12:53:41 2007 From: meiermic at ee.ethz.ch (Michael Meier) Date: Wed, 22 Aug 2007 12:53:41 +0200 Subject: [Tutor] subprocess and su In-Reply-To: References: Message-ID: <1187780021.7175.15.camel@sputnik> > how I thought that it was supposed to work was it would allow me to use > sbp.communicate() to > send stuff to the stdin, and get information out. What do get is a prompt > ask for my password. I believe that su does not read its input from stdin but from its controlling tty. So you'd have to open a pseudo terminal: have a look at the pty module. cheers, Michael From kent37 at tds.net Wed Aug 22 13:22:22 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 22 Aug 2007 07:22:22 -0400 Subject: [Tutor] Need Some Help In-Reply-To: References: Message-ID: <46CC1C6E.2070105@tds.net> chinni wrote: > Hi All, > > I am new to python.i need some help about python.i want to learn python > so plz guide me from where can i start.so,that i can learn and under > stand quickly. Read one of the tutorials here: http://wiki.python.org/moin/BeginnersGuide/NonProgrammers Ask questions on this list when you get stuck. Kent From kent37 at tds.net Wed Aug 22 13:31:19 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 22 Aug 2007 07:31:19 -0400 Subject: [Tutor] xls file In-Reply-To: <46CBB393.5040401@verizon.net> References: <46C27741.4050902@verizon.net> <46C9AE8A.1040307@verizon.net> <46C9E30F.2010704@tds.net> <46CBB393.5040401@verizon.net> Message-ID: <46CC1E87.1030801@tds.net> Kirk Bailey wrote: > I extracted cell 0,0 and it is > >>> x > u'Bob Dobbs' > >>> > > So I did this: > >>> str(x) > 'Bob Dobbs' > >>> > >>> b[1:-1] > 'ob Dobb' > >>> > oops... well,then i did this > >>> print b > Bob Dobbs > >>> > which is as I need it. any use to the rest of the list? You have discovered that the read-eval-print loop of the interpreter prints repr(obj). repr() is kind of a programmer's view of something; it often gives a representation of an object that you could use as input to the interpreter. Specifically, for strings, repr(someString) includes the quotes that you see printed in the interpreter. You will also sometimes see backslash escapes like '\xe9' in the repr() of a string. On the other hand, when you explicitly print a string, the characters of the string are output directly to the terminal (stdout). Any special characters are interpreted by the terminal rather that being escaped, and the quotes are not added. This is useful behaviour but it can be very confusing to newcomers. Kent PS Please use Reply All to reply to the list. From janos.juhasz at VELUX.com Wed Aug 22 15:50:53 2007 From: janos.juhasz at VELUX.com (=?ISO-8859-1?Q?J=E1nos_Juh=E1sz?=) Date: Wed, 22 Aug 2007 15:50:53 +0200 Subject: [Tutor] iterate list items as lvalue Message-ID: Dear All, I would like to thanks for your responds. Ricardo Ar?oz wrote: Kent Johnson wrote: > Dave Kuhlman wrote: >> Consider the following: >> >> >>> array = [1,2,3,4,5] >> >>> array2 = array >> >>> array = [i * 2 for i in array] >> >>> array >> [2, 4, 6, 8, 10] >> >>> array2 >> [1, 2, 3, 4, 5] >> >> So, did you want array2 to change, or not? >> >> Here is a solution that changes the object that both array and >> array2 refer to: >> >> >>> array = [1, 2, 3, 4, 5] >> >>> array2 = array >> >>> for idx, item in enumerate(array): >> array[idx] = item * 2 >> >>> array >> [2, 4, 6, 8, 10] >> >>> array2 >> [2, 4, 6, 8, 10] >> >> Basically, this modifies the list "in place", rather than making a >> new list from the old one. > > Another way to do this is to assign to a slice of array: > > array[:] = [ item*2 for item in array ] > > Kent Thanks, hadn't really thought about having a copy of array (guess I'm too much of a n00b). Really simple and elegant way of solving it though. I have played the way Kent showed. >>> array = [1, 2, 3, 4, 5] >>> array[2] = [item+5 for item in array] >>> array [1, 2, [6, 7, 8, 9, 10], 4, 5] >>> array = [1, 2, 3, 4, 5] >>> array[2:2] = [item+5 for item in array] >>> array [1, 2, 6, 7, 8, 9, 10, 3, 4, 5] Even more interesting >>> array = [1, 2, 3, 4, 5] >>> array[3:2] = ['new','members', 'in', 'the', 'list'] >>> array [1, 2, 3, 'new', 'members', 'in', 'the', 'list', 4, 5] Yours sincerely, Janos Juhasz From zmachinez at gmail.com Wed Aug 22 17:15:57 2007 From: zmachinez at gmail.com (z machinez) Date: Wed, 22 Aug 2007 11:15:57 -0400 Subject: [Tutor] Table Joins Message-ID: Hi All: I have the following tables selected from a database: a1 a2 each table are of the same column length, same col names. How do I combine or concatenate these tables ? So, I would like to have a3 = a1, a2 # combining all the rows into one formal table Just not sure how to do that in Python. Thanks! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070822/d7c8c794/attachment.htm From carroll at tjc.com Wed Aug 22 17:51:44 2007 From: carroll at tjc.com (Terry Carroll) Date: Wed, 22 Aug 2007 08:51:44 -0700 (PDT) Subject: [Tutor] Table Joins In-Reply-To: Message-ID: On Wed, 22 Aug 2007, z machinez wrote: > Hi All: > > I have the following tables selected from a database: > > a1 > > a2 > > each table are of the same column length, same col names. How do I combine > or concatenate these tables ? So, I would like to have > > a3 = a1, a2 # combining all the rows into one formal table If a1 and a2 are both lists, my first approach would have been to convert them to sets and take their union (converting to tuples along the way to make them hashable): >>> a1 = [[1, 'a'], [2, 'b'], [3, 'c'], [4, 'd'], [5, 'e']] >>> a2 = [[1, 'a'], [5, 'e'], [9, 'i'], [15, 'o'], [21, 'u']] >>> t1 = [tuple(x) for x in a1] >>> t2 = [tuple(x) for x in a2] >>> s1 = set(t1) >>> s2 = set(t2) >>> s3 = s1.union(s2) You can see the combination is all done now: >>> s3 set([(5, 'e'), (4, 'd'), (9, 'i'), (3, 'c'), (2, 'b'), (21, 'u'), (1, 'a'), (15, 'o')]) All that's left is to get them back into a list of lists: >>> a3 = [list(x) for x in list(s3)] >>> a3 [[5, 'e'], [4, 'd'], [9, 'i'], [3, 'c'], [2, 'b'], [21, 'u'], [1, 'a'], [15, 'o']] And you can sort them if you want a more rational order: >>> a3.sort() >>> a3 [[1, 'a'], [2, 'b'], [3, 'c'], [4, 'd'], [5, 'e'], [9, 'i'], [15, 'o'], [21, 'u']] Now, if you want to maintain the origianl two lists' order, interleaving as you go, this approach won't work, and you're instead going to have to do it with a couple nested loops (I think). If you want to pull them out of the database as a single table.... I was wondering that myself the other day. I was planning on looking into whether you could just do a FULL OUTER JOIN (which is essentially a union operation) on both tables. I haven't checked that out, yet; you might want to look into it. From carroll at tjc.com Wed Aug 22 18:22:36 2007 From: carroll at tjc.com (Terry Carroll) Date: Wed, 22 Aug 2007 09:22:36 -0700 (PDT) Subject: [Tutor] Table Joins In-Reply-To: Message-ID: On Wed, 22 Aug 2007, Terry Carroll wrote: > If you want to pull them out of the database as a single table.... > I was wondering that myself the other day. I was planning on looking > into whether you could just do a FULL OUTER JOIN (which is essentially a > union operation) on both tables. I haven't checked that out, yet; you > might want to look into it. Actually, I'm making this much too hard (especially as I think SQLite, the only SQL database I have access to, apparently does not directly support FULL OUTER JOIN). But I just discovered the UNION keyword on the SELECT statement: sqlite> create table a1 (v1 int primary key, v2 text); sqlite> create table a2 (v1 int primary key, v2 text); sqlite> insert into a1 values(1, 'a'); sqlite> insert into a1 values(2, 'b'); sqlite> insert into a1 values(3, 'c'); sqlite> insert into a1 values(4, 'd'); sqlite> insert into a1 values(5, 'e'); sqlite> insert into a2 values(1, 'a'); sqlite> insert into a2 values(5, 'e'); sqlite> insert into a2 values(9, 'i'); sqlite> insert into a2 values(15, 'o'); sqlite> insert into a2 values(21, 'u'); sqlite> select * from a1; 1|a 2|b 3|c 4|d 5|e sqlite> select * from a2; 1|a 5|e 9|i 15|o 21|u sqlite> select * from a1 union select * from a2; 1|a 2|b 3|c 4|d 5|e 9|i 15|o 21|u Would that do what the OP wanted? You'd have to make the union select a Python call, of course. From kent37 at tds.net Wed Aug 22 19:05:05 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 22 Aug 2007 13:05:05 -0400 Subject: [Tutor] Table Joins In-Reply-To: References: Message-ID: <46CC6CC1.7020801@tds.net> z machinez wrote: > Hi All: > > I have the following tables selected from a database: > > a1 > > a2 > > each table are of the same column length, same col names. How do I > combine or concatenate these tables ? So, I would like to have > > a3 = a1, a2 # combining all the rows into one formal table > > Just not sure how to do that in Python. Terry's ideas are good but it might be as simple as a3 = a1 + a2 if you don't need to worry about duplicates. Kent From Barry.Carroll at datalogic.com Wed Aug 22 19:34:25 2007 From: Barry.Carroll at datalogic.com (Carroll, Barry) Date: Wed, 22 Aug 2007 10:34:25 -0700 Subject: [Tutor] Need Some Help In-Reply-To: Message-ID: <2BBAEE949D384D40A2B851287ADB6A4307D8D91B@eugsrv400.psc.pscnet.com> > -----Original Message----- > Date: Wed, 22 Aug 2007 02:23:25 -0700 > From: chinni > Subject: [Tutor] Need Some Help > To: tutor at python.org > Message-ID: > > Content-Type: text/plain; charset="iso-8859-1" > > Hi All, > > I am new to python.i need some help about python.i want to learn python so > plz guide me from where can i start.so,that i can learn and under stand > quickly. > > -- > Best Regards, > M.Srikanth Kumar, > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: > http://mail.python.org/pipermail/tutor/attachments/20070822/a0813e4e/att ac > hment-0001.htm > > ------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > End of Tutor Digest, Vol 42, Issue 74 > ************************************* Welcome to Python. the best introduction to Python I've seen is this one: Learning to Program by Alan Gauld http://www.freenetpages.co.uk/hp/alan.gauld/ It is freely available online and is clear and easy to understand. Even better, the author is a regular contributor on this forum. You can ask questions here and get answers direct form here. There are also a number of other Python experts here, all of whom are happy to assist as they can. (I'm not one of the experts. Just a moderately good programmer who likes and uses Python regularly,) HTH Regards, Barry barry.carroll at datalogic.com 541-302-1107 ________________________ We who cut mere stones must always be envisioning cathedrals. -Quarry worker's creed From wormwood_3 at yahoo.com Thu Aug 23 02:08:01 2007 From: wormwood_3 at yahoo.com (wormwood_3) Date: Wed, 22 Aug 2007 17:08:01 -0700 (PDT) Subject: [Tutor] Floating Confusion Message-ID: <256497.74947.qm@web32402.mail.mud.yahoo.com> Dear Tutors, Reading through Wesley's delightful Core Python Programming, I came across something I have not been able to grasp yet. Some introductory code: >>> 1 1 >>> 1.1 1.1000000000000001 >>> print 1 1 >>> print 1.1 1.1 The second case is, of course, what is throwing me. By having a decimal point, "1.1" is a float type, and apparently it cannot be represented by binary floating point numbers accurately. I must admit that I do not understand why this is the case. Would anyone be able to enlighten me? -Sam From kent37 at tds.net Thu Aug 23 02:36:01 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 22 Aug 2007 20:36:01 -0400 Subject: [Tutor] Floating Confusion In-Reply-To: <256497.74947.qm@web32402.mail.mud.yahoo.com> References: <256497.74947.qm@web32402.mail.mud.yahoo.com> Message-ID: <46CCD671.2050006@tds.net> wormwood_3 wrote: >>>> 1.1 > 1.1000000000000001 > The second case is, of course, what is throwing me. By having a > decimal point, "1.1" is a float type, and apparently it cannot be > represented by binary floating point numbers accurately. I must admit > that I do not understand why this is the case. Would anyone be able > to enlighten me? http://docs.python.org/tut/node16.html http://effbot.org/pyfaq/why-are-floating-point-calculations-so-inaccurate.htm Kent From carroll at tjc.com Thu Aug 23 02:42:39 2007 From: carroll at tjc.com (Terry Carroll) Date: Wed, 22 Aug 2007 17:42:39 -0700 (PDT) Subject: [Tutor] Table Joins In-Reply-To: <46CC6CC1.7020801@tds.net> Message-ID: On Wed, 22 Aug 2007, Kent Johnson wrote: > Terry's ideas are good but it might be as simple as > a3 = a1 + a2 > if you don't need to worry about duplicates. Doh! I was thinking the no duplicates was part of it, but you're right; that's nowhere in the OP's question. From cbc at unc.edu Thu Aug 23 03:07:28 2007 From: cbc at unc.edu (Chris Calloway) Date: Wed, 22 Aug 2007 21:07:28 -0400 Subject: [Tutor] Floating Confusion In-Reply-To: <256497.74947.qm@web32402.mail.mud.yahoo.com> References: <256497.74947.qm@web32402.mail.mud.yahoo.com> Message-ID: <46CCDDD0.7080705@unc.edu> wormwood_3 wrote: > The second case is, of course, what is throwing me. By having a decimal point, "1.1" is a float type, and apparently it cannot be represented by binary floating point numbers accurately. I must admit that I do not understand why this is the case. Would anyone be able to enlighten me? This is fairly standard computer science, not just Python. If you take freshman Fortran for scientists, you will eat, sleep, and breath this stuff. Is one tenth any power of 2? Like how 2**-1 is 0.5? Or how 2**-2 is 0.25? Or 2**-3 is 0.125? Or 2**-4 is 0.0625. Oops, we went right by 0.1. Any binary representation of one tenth will have a round-off error in the mantissa. See http://docs.python.org/tut/node16.html for a Pythonic explanation. See http://en.wikipedia.org/wiki/IEEE_floating-point_standard for how it is implemented on most platforms. This problem was solved in Python 2.4 with the introduction of the Decimal module into the standard library: http://docs.python.org/lib/module-decimal.html http://www.python.org/dev/peps/pep-0327/ -- Sincerely, Chris Calloway http://www.seacoos.org office: 332 Chapman Hall phone: (919) 962-4323 mail: Campus Box #3300, UNC-CH, Chapel Hill, NC 27599 From amonroe at columbus.rr.com Thu Aug 23 02:40:55 2007 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Wed, 22 Aug 2007 20:40:55 -0400 Subject: [Tutor] A fun puzzle Message-ID: <156304361588.20070822204055@columbus.rr.com> I wrote a lame, but working script to solve this in a few minutes. A fun puzzle. http://weblogs.asp.net/jgalloway/archive/2006/11/08/Code-Puzzle-_2300_1-_2D00_-What-numbers-under-one-million-are-divisible-by-their-reverse_3F00_.aspx Alan From john at fouhy.net Thu Aug 23 03:22:52 2007 From: john at fouhy.net (John Fouhy) Date: Thu, 23 Aug 2007 13:22:52 +1200 Subject: [Tutor] A fun puzzle In-Reply-To: <156304361588.20070822204055@columbus.rr.com> References: <156304361588.20070822204055@columbus.rr.com> Message-ID: <5e58f2e40708221822u5124e5b7u27c3ab4de824f4cf@mail.gmail.com> On 23/08/07, R. Alan Monroe wrote: > I wrote a lame, but working script to solve this in a few minutes. A > fun puzzle. > > http://weblogs.asp.net/jgalloway/archive/2006/11/08/Code-Puzzle-_2300_1-_2D00_-What-numbers-under-one-million-are-divisible-by-their-reverse_3F00_.aspx >>> [n for n in xrange(1,1000001) if str(n) != str(n)[::-1] and n % int(str(n)[::-1]) == 0 and n % 10 != 0] [8712, 9801, 87912, 98901, 879912, 989901] :-) -- John. From brunson at brunson.com Thu Aug 23 03:40:25 2007 From: brunson at brunson.com (Eric Brunson) Date: Wed, 22 Aug 2007 19:40:25 -0600 Subject: [Tutor] A fun puzzle In-Reply-To: <156304361588.20070822204055@columbus.rr.com> References: <156304361588.20070822204055@columbus.rr.com> Message-ID: <46CCE589.2060005@brunson.com> R. Alan Monroe wrote: > I wrote a lame, but working script to solve this in a few minutes. A > fun puzzle. > > http://weblogs.asp.net/jgalloway/archive/2006/11/08/Code-Puzzle-_2300_1-_2D00_-What-numbers-under-one-million-are-divisible-by-their-reverse_3F00_.aspx > > Fun! for x in xrange(1, 1000000): if x%10 == 0: continue reverse = int( str( x )[::-1] ) if reverse == x or reverse > x: continue if not x%reverse: print x 8712 9801 87912 98901 879912 989901 I thought I'd do it in a single list comprehension, but in order to do that I had to calculate the reverse multiple times. > Alan > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From john at fouhy.net Thu Aug 23 03:55:39 2007 From: john at fouhy.net (John Fouhy) Date: Thu, 23 Aug 2007 13:55:39 +1200 Subject: [Tutor] A fun puzzle In-Reply-To: References: <156304361588.20070822204055@columbus.rr.com> <5e58f2e40708221822u5124e5b7u27c3ab4de824f4cf@mail.gmail.com> Message-ID: <5e58f2e40708221855ida685eepa2c3bbad401ccbff@mail.gmail.com> On 23/08/07, Ian Witham wrote: > An interesting sequence! I assumed the next two numbers would be 8799912, > 9899901 Hmm... http://www.research.att.com/~njas/sequences/?q=8712%2C+9801%2C+87912%2C+98901%2C+879912%2C+989901&language=english&go=Search http://mathworld.wolfram.com/Reversal.html -- John. From kent37 at tds.net Thu Aug 23 04:34:17 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 22 Aug 2007 22:34:17 -0400 Subject: [Tutor] A fun puzzle In-Reply-To: <156304361588.20070822204055@columbus.rr.com> References: <156304361588.20070822204055@columbus.rr.com> Message-ID: <46CCF229.9000802@tds.net> R. Alan Monroe wrote: > I wrote a lame, but working script to solve this in a few minutes. A > fun puzzle. FWIW here is my fastest solution: from itertools import chain def compute(): str_=str; int_=int; slice_=slice(None, None, -1) for x in chain(xrange(1, 1000001, 10), xrange(2, 1000001, 10), xrange(3, 1000001, 10), xrange(4, 1000001, 10), xrange(5, 1000001, 10), xrange(6, 1000001, 10), xrange(7, 1000001, 10), xrange(8, 1000001, 10), xrange(9, 1000001, 10)): rev = int_(str_(x)[slice_]) if rev>=x: continue if not x % rev: print x, compute() Kent From jeff at san-dc.com Thu Aug 23 05:46:46 2007 From: jeff at san-dc.com (Jeff Johnson) Date: Wed, 22 Aug 2007 20:46:46 -0700 Subject: [Tutor] [SPAM] A fun puzzle In-Reply-To: <156304361588.20070822204055@columbus.rr.com> Message-ID: <006b01c7e538$3b0856c0$5f01a8c0@dcsoftware.local> > -----Original Message----- > From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf > Of R. Alan Monroe > Sent: Wednesday, August 22, 2007 5:41 PM > To: Python Tutorlist > Subject: [SPAM] [Tutor] A fun puzzle > Importance: Low > > I wrote a lame, but working script to solve this in a few minutes. A > fun puzzle. > > http://weblogs.asp.net/jgalloway/archive/2006/11/08/Code-Puzzle-_2300_1- > _2D00_-What-numbers-under-one-million-are-divisible-by-their- > reverse_3F00_.aspx > > > Alan > Here's mine and it does in fact yield the same six numbers! Since I am learning Python, these challenges are important to me. I really appreciate people posting "problems" that we can solve. I enjoy the solutions even more. def reverse(n): rev = 0 while n > 0: rev = (rev * 10) + (n % 10) n = n / 10 return rev def main(): for i in range(1, 1000000): j = reverse(i) if (i <> j) and (i % 10 <> 0) and (i % j == 0): print str(i) main() Jeff Johnson jeff at san-dc.com 623-582-0323 Fax 623-869-0675 No virus found in this outgoing message. Checked by AVG Free Edition. Version: 7.5.484 / Virus Database: 269.12.1/965 - Release Date: 8/21/2007 4:02 PM -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 4232 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20070822/b1cb43e2/attachment.bin From deliberatus at verizon.net Thu Aug 23 05:23:03 2007 From: deliberatus at verizon.net (Kirk Bailey) Date: Wed, 22 Aug 2007 23:23:03 -0400 Subject: [Tutor] xls file In-Reply-To: <46C9E30F.2010704@tds.net> References: <46C27741.4050902@verizon.net> <46C9AE8A.1040307@verizon.net> <46C9E30F.2010704@tds.net> Message-ID: <46CCFD97.3030603@verizon.net> here s one line from a spreadsheet, as saved in python; [text:u'Bob Dobbs', number:0.0, number:1.0, text:u'n/0!', number:0.0, number:0.0, number:0.0, number:0.0, number:0.0, number:0.0] [text:u'Connie Dobbs', number:22.0, number:4.0, number:0.17000000000000001, number:11.0, number:0.5, number:6.0, number:0.28000000000000003, number:29.0, number:0.080000000000000002] I extracted cell 0,0 and it is >>> x u'Bob Dobbs' >>> So I did this: >>> str(x) 'Bob Dobbs' >>> >>> b[1:-1] 'ob Dobb' >>> oops... well,then i did this >>> print b Bob Dobbs >>> which is as I need it. any use to the rest of the list? Kent Johnson wrote: > Kirk Bailey wrote: >> ok, I installed XLRD and can load a xls file; it works quite well BTW. >> Now it is returning Unicode objects. I need to strip that to a simple >> string value. Is there a recommended way or module for handling >> Unicode objects? > > What kind of characters are in the Excel file? What do you want to do > with non-ascii characters? > > Some options: > unicodeData.decode('ascii') # Will choke if any non-ascii characters > unicodeData.decode('ascii', 'ignore') # Will throw away non-ascii > characters > unicodeData.decode('ascii', 'replace') # Will replace non-ascii > characters with '?' > > Also of interest: > http://www.crummy.com/cgi-bin/msm/map.cgi/ASCII%2C+Dammit > http://groups.google.com/group/comp.lang.python/msg/159a41b3e6bae313?hl=en& > > Kent > > -- Salute! -Kirk Bailey Think +-----+ | BOX | +-----+ knihT Fnord. From rabidpoobear at gmail.com Thu Aug 23 08:45:01 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Thu, 23 Aug 2007 01:45:01 -0500 Subject: [Tutor] Floating Confusion In-Reply-To: <46CCDDD0.7080705@unc.edu> References: <256497.74947.qm@web32402.mail.mud.yahoo.com> <46CCDDD0.7080705@unc.edu> Message-ID: <46CD2CED.20204@gmail.com> Chris Calloway wrote: > wormwood_3 wrote: > >> The second case is, of course, what is throwing me. By having a decimal point, "1.1" is a float type, and apparently it cannot be represented by binary floating point numbers accurately. I must admit that I do not understand why this is the case. Would anyone be able to enlighten me? >> > > This is fairly standard computer science, not just Python. If you take > freshman Fortran for scientists, you will eat, sleep, and breath this stuff. > > Is one tenth any power of 2? > > Like how 2**-1 is 0.5? Or how 2**-2 is 0.25? Or 2**-3 is 0.125? Or 2**-4 > is 0.0625. Oops, we went right by 0.1. > > Any binary representation of one tenth will have a round-off error in > the mantissa. > I've always wondered: There are numbers in Decimal that can't be represented accurately in Binary without infinite precision. But it doesn't go the other way. Rational base-2 numbers are rational base-10 numbers. I'm supposing this is because base-10 is a higher base than base-2. So I've wondered that, even though Pi is an irrational number in base-10, is it possible that it's a simple (rational) number in a higher base? I mean, I suppose a base of Pi would result in Pi being 1, but what about integer bases? Is there some kind of theory that relates to this and why there's not a higher base with an easy representation of Pi? I'd be interested to read about this but I'm not sure what to look for. -Luke From alan.gauld at btinternet.com Thu Aug 23 09:52:17 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 23 Aug 2007 08:52:17 +0100 Subject: [Tutor] Floating Confusion References: <256497.74947.qm@web32402.mail.mud.yahoo.com> Message-ID: "wormwood_3" wrote >>>> 1.1 > 1.1000000000000001 > "1.1" is a float type, and apparently it cannot be represented by > binary floating point numbers accurately. > I must admit that I do not understand why this is the case. This isn't just a problem in binary. Consider using normal decimal the cases of 1/7 or 1/3. There cannot be represented by any fixed number of decimal digits. 1/3 is 0.3333333.... to infinity and 1/7 is 0.142857142857..... repeating. In binary the denominator of the fraction must be a power of 2 (2,4,8,16 etc) for it to be accurately represented, otherwise you will get an approximation. Thus 1/10 could be approximated by 102/1024 = 0.09961 with a fairly small error (4/1024 = 0.00039). We can reduce the error still further by using bigger numbers, thus 6554/65536 = 0.100006 The best we can do in Python is use 2**64 as the denominator and the best approximation of 2**64/10 as the numerator, which gives the result above: >>> n= (2**64)/10 >>> n 1844674407370955161L >>> float(n)/(2**64) 0.10000000000000001 But we can never eliminate the error entirely because no power of two is also a power of 10. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Thu Aug 23 12:35:39 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 23 Aug 2007 06:35:39 -0400 Subject: [Tutor] Floating Confusion In-Reply-To: <46CD2CED.20204@gmail.com> References: <256497.74947.qm@web32402.mail.mud.yahoo.com> <46CCDDD0.7080705@unc.edu> <46CD2CED.20204@gmail.com> Message-ID: <46CD62FB.1060600@tds.net> Luke Paireepinart wrote: > I've always wondered: > There are numbers in Decimal that can't be represented accurately in > Binary without infinite precision. > But it doesn't go the other way. Rational base-2 numbers are rational > base-10 numbers. I'm supposing this is because base-10 is a higher base > than base-2. It is because 10 is an exact multiple of 2, not just because it is larger. The place values of a decimal fraction are (1/10)**n. The place values of a binary fraction are (1/2)**n or (5/10)**n. So any binary fraction can be rewritten as a decimal fraction. > So I've wondered that, even though Pi is an irrational number in > base-10, is it possible that it's a simple (rational) number in a higher > base? No. First, rational vs irrational has nothing to do with whether it can be represented in a particular base. 1/7 is rational but has no finite representation as a decimal fraction. pi is a transcendental number which means it is not the solution of any polynomial equation with rational coefficients. In particular, it is not rational. But any number that can be represented as a 'decimal' fraction in any (rational) base is rational so this is not possible with pi. > I mean, I suppose a base of Pi would result in Pi being 1, but what > about integer bases? > Is there some kind of theory that relates to this and why there's not a > higher base with an easy representation of Pi? http://en.wikipedia.org/wiki/Transcendental_numbers Kent From rdm at rcblue.com Thu Aug 23 16:52:41 2007 From: rdm at rcblue.com (Dick Moores) Date: Thu, 23 Aug 2007 07:52:41 -0700 Subject: [Tutor] A fun puzzle In-Reply-To: <46CCF229.9000802@tds.net> References: <156304361588.20070822204055@columbus.rr.com> <46CCF229.9000802@tds.net> Message-ID: <20070823145247.92A561E400B@bag.python.org> At 07:34 PM 8/22/2007, Kent Johnson wrote: >FWIW here is my fastest solution: > >01 from itertools import chain >02 def compute(): >03 str_=str; int_=int; slice_=slice(None, None, -1) >04 for x in chain(xrange(1, 1000001, 10), xrange(2, 1000001, 10), >05 xrange(3, 1000001, 10), xrange(4, 1000001, 10), xrange(5, 1000001, 10), >06 xrange(6, 1000001, 10), xrange(7, 1000001, 10), xrange(8, 1000001, 10), >07 xrange(9, 1000001, 10)): >08 rev = int_(str_(x)[slice_]) >09 if rev>=x: continue >10 if not x % rev: >11 print x, >12 compute() Kent, thanks for showing us itertools.chain(). By using it you keep x from being assigned an integer divisible by 10 (thereby faster), which of course means no need for if n % 10 == 0: continue Again faster. And at first I thought your use of str_, int_, and slice_ were pretty weird; instead of your line 08, why not just use the straightforward rev = int(str(x)[::-1]) but on upon testing I see they all make their respective contributions to speed. But I don't understand why. Why is your line 08 faster than "rev = int(str(x)[::-1])"? BTW I also thought that for x in chain(xrange(1, 1000001, 10), xrange(2, 1000001, 10), xrange(3, 1000001, 10), xrange(4, 1000001, 10), xrange(5, 1000001, 10), xrange(6, 1000001, 10), xrange(7, 1000001, 10), xrange(8, 1000001, 10), xrange(9, 1000001, 10)): pass MUST take longer than for x in xrange(1000000): pass because there appears to be so much more going on, but their timings are essentially identical. Dick Moores XP, Python 2.5, editor is Ulipad ====================================== Bagdad Weather From kent37 at tds.net Thu Aug 23 17:20:38 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 23 Aug 2007 11:20:38 -0400 Subject: [Tutor] A fun puzzle In-Reply-To: <20070823145247.92A561E400B@bag.python.org> References: <156304361588.20070822204055@columbus.rr.com> <46CCF229.9000802@tds.net> <20070823145247.92A561E400B@bag.python.org> Message-ID: <46CDA5C6.4080705@tds.net> Dick Moores wrote: > At 07:34 PM 8/22/2007, Kent Johnson wrote: >> FWIW here is my fastest solution: >> >> 01 from itertools import chain >> 02 def compute(): >> 03 str_=str; int_=int; slice_=slice(None, None, -1) >> 04 for x in chain(xrange(1, 1000001, 10), xrange(2, 1000001, 10), >> 05 xrange(3, 1000001, 10), xrange(4, 1000001, 10), xrange(5, 1000001, 10), >> 06 xrange(6, 1000001, 10), xrange(7, 1000001, 10), xrange(8, 1000001, 10), >> 07 xrange(9, 1000001, 10)): >> 08 rev = int_(str_(x)[slice_]) >> 09 if rev>=x: continue >> 10 if not x % rev: >> 11 print x, >> 12 compute() > And at first I thought your use of str_, int_, and slice_ were pretty > weird; instead of your line 08, why not just use the straightforward > > rev = int(str(x)[::-1]) > > but on upon testing I see they all make their respective > contributions to speed. > > But I don't understand why. Why is your line 08 faster than "rev = > int(str(x)[::-1])"? Two reasons. First, looking up a name that is local to a function is faster than looking up a global name. To find the value of 'str', the interpreter has to look at the module namespace, then the built-in namespace. These are each dictionary lookups. Local values are stored in an array and accessed by offset so it is much faster. Second, the slice notation [::-1] actually creates a slice object and passes that to the __getitem__() method of the object being sliced. The slice is created each time through the loop. My code explicitly creates and caches the slice object so it can be reused each time. > > BTW I also thought that > > for x in chain(xrange(1, 1000001, 10), xrange(2, 1000001, 10), > xrange(3, 1000001, 10), xrange(4, 1000001, 10), xrange(5, 1000001, 10), > xrange(6, 1000001, 10), xrange(7, 1000001, 10), xrange(8, 1000001, 10), > xrange(9, 1000001, 10)): > pass > > MUST take longer than > > for x in xrange(1000000): > pass > > because there appears to be so much more going on, but their timings > are essentially identical. Well for one thing it is looping 9/10 of the number of iterations. Also, chain() doesn't have to do much, it just forwards the values returned by the underlying iterators to the caller, and all the itertools methods are written in C to be fast. If you read comp.lang.python you will often see creative uses of itertools in optimizations. Kent From wescpy at gmail.com Thu Aug 23 17:28:52 2007 From: wescpy at gmail.com (wesley chun) Date: Thu, 23 Aug 2007 08:28:52 -0700 Subject: [Tutor] [ANN] Python courses this Fall Message-ID: <78b3a9580708230828k56953a91j1cdb4059db258ed4@mail.gmail.com> Folks, I'd like to announce my final Python courses for 2007: Need to get up-to-speed with Python as quickly as possible? Come join me, Wesley Chun, author of Prentice-Hall's well-received "Core Python Programming," for another set of courses this Fall in beautiful Northern California! This will be the final set for 2007... if you miss these, you'll have to wait until next year. I look forward to meeting you! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - (COMPREHENSIVE) INTRODUCTION TO PYTHON: Mon-Wed, 2007 Oct 8-10 This is course is meant for those new to Python and/or want to get more in-depth formal training. We will immerse you in the world of Python in only a few days. We will show you more than just its syntax (which you don't really need a book to learn, right?). Knowing more about how Python works under the covers, including the relationship between data objects and memory management, will make you a much more effective Python programmer coming out of the gate. 3 hands-on labs each day will help hammer the concepts home. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - INTERNET PROGRAMMING WITH PYTHON: Sat, 2007 Oct 13 This 1-day course will introduce current Python programmers to 3 distinct areas of Internet programming, each in self-contained modules with a set of lab exercises following each lecture topic: Network Programming using Sockets -- Underneath all of today's network protocols, i.e., HTTP, FTP, RDBMS, IM, e-mail, etc., lies the main communication mechanism, sockets. Here, we introduce client/server architecture and how to program sockets using Python. Internet Client Programming -- One level above the socket layer are well-known Internet protocols such as FTP, NNTP, POP3, and SMTP. In this section, we learn how to create Internet clients of these protocols to transfer files, send and receive e-mail, and read Usenet newsgroup postings. Web/CGI Programming -- Yes, pure CGI is "sooo yesterday," but before you jump on all the web framework bandwagons, it's a good idea to learn basics and the basis of how all web servers deliver dynamic content back to the client browser so that you can appreciate all the work that is done on your behalf by a more fully-featured frame- work. Time-permitting, we will also give a high-level overview of one of the more popular Python web frameworks, Django. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - WHERE: near the San Francisco Airport (SFO/San Bruno), CA, USA WEB: http://cyberwebconsulting.com (click "Python Training") LOCALS: easy freeway (101/280/380) with lots of parking plus public transit (BART and CalTrain) access via the San Bruno stations, easily accessible from all parts of the Bay Area VISITORS: free shuttle to/from the airport, free high-speed internet, free breakfast and regular evening receptions; fully-equipped suites See website for costs, venue info, and registration. Discounts are available for multiple registrations as well as for teachers/students. We have only 12 more spots for the intro course, and 18 for the 1-day seminar. Hope to see you there! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From rdm at rcblue.com Thu Aug 23 18:46:35 2007 From: rdm at rcblue.com (Dick Moores) Date: Thu, 23 Aug 2007 09:46:35 -0700 Subject: [Tutor] A fun puzzle In-Reply-To: <46CDA5C6.4080705@tds.net> References: <156304361588.20070822204055@columbus.rr.com> <46CCF229.9000802@tds.net> <20070823145247.92A561E400B@bag.python.org> <46CDA5C6.4080705@tds.net> Message-ID: <20070823164730.7EBB41E400B@bag.python.org> At 08:20 AM 8/23/2007, Kent Johnson wrote: >Dick Moores wrote: >>At 07:34 PM 8/22/2007, Kent Johnson wrote: >>>FWIW here is my fastest solution: >>> >>>01 from itertools import chain >>>02 def compute(): >>>03 str_=str; int_=int; slice_=slice(None, None, -1) >>>04 for x in chain(xrange(1, 1000001, 10), xrange(2, 1000001, 10), >>>05 xrange(3, 1000001, 10), xrange(4, 1000001, 10), xrange(5, 1000001, 10), >>>06 xrange(6, 1000001, 10), xrange(7, 1000001, 10), xrange(8, 1000001, 10), >>>07 xrange(9, 1000001, 10)): >>>08 rev = int_(str_(x)[slice_]) >>>09 if rev>=x: continue >>>10 if not x % rev: >>>11 print x, >>>12 compute() > >>And at first I thought your use of str_, int_, and slice_ were >>pretty weird; instead of your line 08, why not just use the straightforward >>rev = int(str(x)[::-1]) >>but on upon testing I see they all make their respective >>contributions to speed. >>But I don't understand why. Why is your line 08 faster than "rev = >>int(str(x)[::-1])"? > >Two reasons. First, looking up a name that is local to a function is >faster than looking up a global name. To find the value of 'str', >the interpreter has to look at the module namespace, then the >built-in namespace. These are each dictionary lookups. Local values >are stored in an array and accessed by offset so it is much faster. Wow, what DON'T you understand? Please explain "accessed by offset". >Second, the slice notation [::-1] actually creates a slice object >and passes that to the __getitem__() method of the object being >sliced. The slice is created each time through the loop. My code >explicitly creates and caches the slice object so it can be reused each time. >>BTW I also thought that >>for x in chain(xrange(1, 1000001, 10), xrange(2, 1000001, 10), >>xrange(3, 1000001, 10), xrange(4, 1000001, 10), xrange(5, 1000001, 10), >>xrange(6, 1000001, 10), xrange(7, 1000001, 10), xrange(8, 1000001, 10), >>xrange(9, 1000001, 10)): >> pass >>MUST take longer than >>for x in xrange(1000000): >> pass >>because there appears to be so much more going on, but their >>timings are essentially identical. > >Well for one thing it is looping 9/10 of the number of iterations. This time I added "xrange(10, end, 10)" and did the timing using the template in the timeit module: template = """ def inner(_it, _timer): _t0 = _timer() from itertools import chain end = 1000000 for _i in _it: for x in chain(xrange(1, end, 10), xrange(2, end, 10), xrange(3, end, 10), xrange(4, end, 10), xrange(5, end, 10), xrange(6, end, 10), xrange(7, end, 10), xrange(8, end, 10), xrange(9, end, 10), xrange(10, end, 10)): pass _t1 = _timer() return _t1 - _t0 """ This gets always close to 71 msec per loop. template = """ def inner(_it, _timer): _t0 = _timer() end = 1000000 for _i in _it: for x in xrange(end): pass _t1 = _timer() return _t1 - _t0 """ This gets always close to 84 msec per loop. So they're not the same! And yours is the faster one! Because itertools.chain() is written in C, I suppose. > Also, chain() doesn't have to do much, it just forwards the values > returned by the underlying iterators to the caller, and all the > itertools methods are written in C to be fast. If you read > comp.lang.python you will often see creative uses of itertools in > optimizations. I just did a search on "itertools" in the comp.lang.python group at Google Groups, and got 1,940 hits. . That should keep me busy! Dick ====================================== Bagdad Weather From kent37 at tds.net Thu Aug 23 20:49:15 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 23 Aug 2007 14:49:15 -0400 Subject: [Tutor] A fun puzzle In-Reply-To: <20070823164730.7EBB41E400B@bag.python.org> References: <156304361588.20070822204055@columbus.rr.com> <46CCF229.9000802@tds.net> <20070823145247.92A561E400B@bag.python.org> <46CDA5C6.4080705@tds.net> <20070823164730.7EBB41E400B@bag.python.org> Message-ID: <46CDD6AB.2030207@tds.net> Dick Moores wrote: >> Two reasons. First, looking up a name that is local to a function is >> faster than looking up a global name. To find the value of 'str', >> the interpreter has to look at the module namespace, then the >> built-in namespace. These are each dictionary lookups. Local values >> are stored in an array and accessed by offset so it is much faster. > > Wow, what DON'T you understand? Lots, actually :-) There is a whole 'nother tier or two of Python expert above me that I can't touch. I just parrot back what I hear them saying. :-) > Please explain "accessed by offset". IIUC an array is allocated on the call stack to hold references to the local variables. (Anticipating you next question: http://en.wikipedia.org/wiki/Stack_frame) To get the value of the local variable the runtime just has to look up the correct entry in the array. The bytecode has the offset into the array. This is very quick - an indexed lookup. Normal attribute access such as a module or builtin has to read the value out of a dict which is much more expensive, even with Python's optimized dicts. > This time I added "xrange(10, end, 10)" and did the timing using the > template in the timeit module: > > template = """ > def inner(_it, _timer): > _t0 = _timer() > from itertools import chain > end = 1000000 > for _i in _it: > for x in chain(xrange(1, end, 10), xrange(2, end, 10), > xrange(3, end, 10), xrange(4, end, 10), xrange(5, end, 10), > xrange(6, end, 10), xrange(7, end, 10), xrange(8, end, 10), > xrange(9, end, 10), xrange(10, end, 10)): > pass > _t1 = _timer() > return _t1 - _t0 > """ > This gets always close to 71 msec per loop. > > > template = """ > def inner(_it, _timer): > _t0 = _timer() > end = 1000000 > for _i in _it: > for x in xrange(end): > pass > _t1 = _timer() > return _t1 - _t0 > """ > This gets always close to 84 msec per loop. > > So they're not the same! And yours is the faster one! Because > itertools.chain() is written in C, I suppose. That is very strange. I did a simple timer with time.time() and found that my original (1-9) version was consistently a little slower than the simple xrange(). And xrange is written in C too, and the chain version adds a layer over xrange. You should check your code carefully, that is a very surprising result. > I just did a search on "itertools" in the comp.lang.python group at > Google Groups, and got 1,940 hits. . That > should keep me busy! Have fun! Kent From 3dbernard at gmail.com Thu Aug 23 22:09:04 2007 From: 3dbernard at gmail.com (Bernard Lebel) Date: Thu, 23 Aug 2007 16:09:04 -0400 Subject: [Tutor] Converting code to string Message-ID: <61d0e2b40708231309h6757d90cy7c76f3279f9d758d@mail.gmail.com> Hello, I'm looking for a way to convert Python code into a string. For example, let say I have this function: def myFunc(): print 'hello world' Now in the same module, I'd like to take this function and convert it into a string: """def myFunc(): print 'hello world'\n""" Thanks Bernard From kent37 at tds.net Thu Aug 23 22:52:23 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 23 Aug 2007 16:52:23 -0400 Subject: [Tutor] Converting code to string In-Reply-To: <61d0e2b40708231309h6757d90cy7c76f3279f9d758d@mail.gmail.com> References: <61d0e2b40708231309h6757d90cy7c76f3279f9d758d@mail.gmail.com> Message-ID: <46CDF387.7080406@tds.net> Bernard Lebel wrote: > Hello, > > I'm looking for a way to convert Python code into a string. > > For example, let say I have this function: > > def myFunc(): > print 'hello world' > > > Now in the same module, I'd like to take this function and convert it > into a string: > > """def myFunc(): > print 'hello world'\n""" Try inspect.getsource(myFunc). But why? Kent From bhaaluu at gmail.com Thu Aug 23 22:54:44 2007 From: bhaaluu at gmail.com (bhaaluu) Date: Thu, 23 Aug 2007 16:54:44 -0400 Subject: [Tutor] Converting code to string In-Reply-To: <61d0e2b40708231309h6757d90cy7c76f3279f9d758d@mail.gmail.com> References: <61d0e2b40708231309h6757d90cy7c76f3279f9d758d@mail.gmail.com> Message-ID: Greetings, The following is from: http://www.hetland.org/coding/ ################## Self-Printing One-Liner If you run this one-liner at a command prompt, it should print out a copy of itself (write it as one continuous line, without the line break): python -c "x='python -c %sx=%s; print x%%(chr(34),repr(x),chr(34))%s'; print x%(chr(34),repr(x),chr(34))" Not very useful, but kinda fun? I just saw some other self-printing programs and thought it would be interesting to make a one-liner version. ################## Hopefully helpful! -- bhaaluu at gmail dot com On 8/23/07, Bernard Lebel <3dbernard at gmail.com> wrote: > Hello, > > I'm looking for a way to convert Python code into a string. > > For example, let say I have this function: > > def myFunc(): > print 'hello world' > > > Now in the same module, I'd like to take this function and convert it > into a string: > > """def myFunc(): > print 'hello world'\n""" > > > > Thanks > Bernard > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From rabidpoobear at gmail.com Thu Aug 23 22:56:20 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Thu, 23 Aug 2007 15:56:20 -0500 Subject: [Tutor] Converting code to string In-Reply-To: <61d0e2b40708231309h6757d90cy7c76f3279f9d758d@mail.gmail.com> References: <61d0e2b40708231309h6757d90cy7c76f3279f9d758d@mail.gmail.com> Message-ID: <46CDF474.3000407@gmail.com> Bernard Lebel wrote: > Hello, > > I'm looking for a way to convert Python code into a string. > > For example, let say I have this function: > > def myFunc(): > print 'hello world' > > > Now in the same module, I'd like to take this function and convert it > into a string: > > """def myFunc(): > print 'hello world'\n""" > Why do you need to do this? and why within the same module? From alan.gauld at btinternet.com Thu Aug 23 23:06:14 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 23 Aug 2007 22:06:14 +0100 Subject: [Tutor] Converting code to string References: <61d0e2b40708231309h6757d90cy7c76f3279f9d758d@mail.gmail.com> Message-ID: "Bernard Lebel" <3dbernard at gmail.com> wrote > I'm looking for a way to convert Python code into a string. Read the file as text? You can find the file by checking the __file__ attribute of a module. > Now in the same module, I'd like to take this function and convert > it > into a string: If its the same file then you implicitly know the name of the file, so long as nobody renames it. > """def myFunc(): > print 'hello world'\n""" ########### foo.py ######### def f(x): print g(x) src = open('foo.py').read() if __name__ == "__main__": print src ############################ There are fancier tricks you could use but for simple things that might work? Depends on what exactly you need it for. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From 3dbernard at gmail.com Thu Aug 23 23:14:41 2007 From: 3dbernard at gmail.com (Bernard Lebel) Date: Thu, 23 Aug 2007 17:14:41 -0400 Subject: [Tutor] Converting code to string In-Reply-To: <46CDF387.7080406@tds.net> References: <61d0e2b40708231309h6757d90cy7c76f3279f9d758d@mail.gmail.com> <46CDF387.7080406@tds.net> Message-ID: <61d0e2b40708231414m35daefearff7003a3b7d2aed5@mail.gmail.com> Hi Kent, When try your approach, I get an IOError. >>> import inspect >>> def myFunc(): ... print 'hello world' ... >>> >>> s = inspect.getsource(myFunc) Traceback (most recent call last): File "", line 1, in ? File "C:\Python24\lib\inspect.py", line 552, in getsource lines, lnum = getsourcelines(object) File "C:\Python24\lib\inspect.py", line 541, in getsourcelines lines, lnum = findsource(object) File "C:\Python24\lib\inspect.py", line 410, in findsource raise IOError('could not get source code') IOError: could not get source code Why? Because I'm using an API (the Softimage|XSI scripting API) where I have to create a custom GUI (using that API's GUI toolkit). I have to attach a logic callback to a number of widgets that can change from one execution to the next. The only way to do that, in that API, is to define the callback functions "on-the-fly". And to define such a callback, the API requires that the function must be represented as a string. All strings are then joined and "injected" (the terminology used in the doc) into the GUI object. Since the XSI API also supports JScript, it is my feeling that this part of the GUI toolkit was designed with JScript's toString() method in mind, which works beautifully. I'm looking to do the same in Python. Thanks! Bernard On 8/23/07, Kent Johnson wrote: > Bernard Lebel wrote: > > Hello, > > > > I'm looking for a way to convert Python code into a string. > > > > For example, let say I have this function: > > > > def myFunc(): > > print 'hello world' > > > > > > Now in the same module, I'd like to take this function and convert it > > into a string: > > > > """def myFunc(): > > print 'hello world'\n""" > > Try inspect.getsource(myFunc). But why? > > Kent > From flaper87 at gmail.com Thu Aug 23 23:36:42 2007 From: flaper87 at gmail.com (Flaper87) Date: Thu, 23 Aug 2007 17:36:42 -0400 Subject: [Tutor] capturing process's status with python Message-ID: Hi everybody! i would like to know how can i capture the system process's status with python, i need to know if they are sleeping, zombie or runing. I use Debian lenny, GNU/Linux thanks -- Flavio Percoco Premoli, A.K.A. [Flaper87] http://www.flaper87.com Usuario Linux registrado #436538 Geek by nature, Linux by choice, Debian of course. Key Fingerprint: CFC0 C67D FF73 463B 7E55 CF43 25D1 E75B E2DB 15C7 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070823/afef5bc2/attachment.htm From brunson at brunson.com Thu Aug 23 23:50:59 2007 From: brunson at brunson.com (Eric Brunson) Date: Thu, 23 Aug 2007 15:50:59 -0600 Subject: [Tutor] Converting code to string In-Reply-To: <61d0e2b40708231414m35daefearff7003a3b7d2aed5@mail.gmail.com> References: <61d0e2b40708231309h6757d90cy7c76f3279f9d758d@mail.gmail.com> <46CDF387.7080406@tds.net> <61d0e2b40708231414m35daefearff7003a3b7d2aed5@mail.gmail.com> Message-ID: <46CE0143.9090002@brunson.com> Bernard Lebel wrote: > Hi Kent, > > When try your approach, I get an IOError. > > >>>> import inspect >>>> def myFunc(): >>>> > ... print 'hello world' > ... > >>>> s = inspect.getsource(myFunc) >>>> > Traceback (most recent call last): > File "", line 1, in ? > File "C:\Python24\lib\inspect.py", line 552, in getsource > lines, lnum = getsourcelines(object) > File "C:\Python24\lib\inspect.py", line 541, in getsourcelines > lines, lnum = findsource(object) > File "C:\Python24\lib\inspect.py", line 410, in findsource > raise IOError('could not get source code') > IOError: could not get source code > My guess is that's because you're doing it interactively. Try putting that in a file and it should work. > > > Why? Because I'm using an API (the Softimage|XSI scripting API) where > I have to create a custom GUI (using that API's GUI toolkit). > > I have to attach a logic callback to a number of widgets that can > change from one execution to the next. > > The only way to do that, in that API, is to define the callback > functions "on-the-fly". And to define such a callback, the API > requires that the function must be represented as a string. All > strings are then joined and "injected" (the terminology used in the > doc) into the GUI object. > Then why not just define them as text strings? Then you can inject them, or if you need to execute them outside of the API, you can still compile and run them. If that's not a good idea, them my next thought would be to put all these callbacks in a single file. You then have the options of importing the functions from the file (module), or to parse the file assigning the functions to a dictionary indexed by the name of the function. You make it seem like it wasn't your choice to use this API, but without knowing more about it, it sounds incredibly lame. > Since the XSI API also supports JScript, it is my feeling that this > part of the GUI toolkit was designed with JScript's toString() method > in mind, which works beautifully. I'm looking to do the same in > Python. > > > Thanks! > Bernard > > > > > > > On 8/23/07, Kent Johnson wrote: > >> Bernard Lebel wrote: >> >>> Hello, >>> >>> I'm looking for a way to convert Python code into a string. >>> >>> For example, let say I have this function: >>> >>> def myFunc(): >>> print 'hello world' >>> >>> >>> Now in the same module, I'd like to take this function and convert it >>> into a string: >>> >>> """def myFunc(): >>> print 'hello world'\n""" >>> >> Try inspect.getsource(myFunc). But why? >> >> Kent >> >> > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at btinternet.com Fri Aug 24 00:04:48 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 23 Aug 2007 23:04:48 +0100 Subject: [Tutor] Converting code to string References: <61d0e2b40708231309h6757d90cy7c76f3279f9d758d@mail.gmail.com><46CDF387.7080406@tds.net> <61d0e2b40708231414m35daefearff7003a3b7d2aed5@mail.gmail.com> Message-ID: "Bernard Lebel" <3dbernard at gmail.com> wrote > Why? Because I'm using an API (the Softimage|XSI scripting API) > where > I have to create a custom GUI (using that API's GUI toolkit). > > I have to attach a logic callback to a number of widgets that can > change from one execution to the next. Can you show us a simple(!) example, I'm not sure I quite understand the parameters of the problem. How does the XSI GUI execute the code you pass to it? If it executes it by itself then it why not just write the callbacks as strings: ## create a foo wrapper ''' def foo(x): myfoo(x) ''' def myfoo(x): real code here Or do you need to call them too? This might be a valid use for exec: foostr = ''' def foo(x); print x ''' exec(foostr) > The only way to do that, in that API, is to define the callback > functions "on-the-fly". But I'm not sure what the restrictions of 'on the fly' are. How close to runtime must the definition be? Could it be parameterised by a format string? > And to define such a callback, the API > requires that the function must be represented as a string. How bizarre! HTH, Alan G. From brunson at brunson.com Fri Aug 24 00:05:41 2007 From: brunson at brunson.com (Eric Brunson) Date: Thu, 23 Aug 2007 16:05:41 -0600 Subject: [Tutor] capturing process's status with python In-Reply-To: References: Message-ID: <46CE04B5.1070302@brunson.com> I'm a bit more of a Linux expert than a Python guru, so I don't know if there's a facility in python to do that. However, if you look in /proc, every running process has a directory corresponding to its PID and in that directory is a pseudo-file called "status" that you can get state information from: foxtrot(~)$ grep State: /proc/*/status | head -10 /proc/10065/status:State: S (sleeping) /proc/10125/status:State: S (sleeping) /proc/10793/status:State: S (sleeping) /proc/10801/status:State: S (sleeping) /proc/10/status:State: S (sleeping) /proc/1125/status:State: S (sleeping) /proc/1126/status:State: S (sleeping) /proc/1128/status:State: S (sleeping) /proc/1129/status:State: S (sleeping) /proc/11/status:State: S (sleeping) Convert that to python and you're in: import glob for file in glob.glob( '/proc/*/status' ): f = open( file ) for line in f: if line.startswith( 'State:' ): junk, state, text = line.split( None, 2 ) print state, text I'm interested to know if there's a portable python interface to the kernel process table, though, because that is very Linux specific. Hope that helps, e. Flaper87 wrote: > Hi everybody! > > i would like to know how can i capture the system process's status > with python, i need to know if they are sleeping, zombie or runing. > > I use Debian lenny, GNU/Linux > > thanks > > -- > Flavio Percoco Premoli, A.K.A. [Flaper87] > http://www.flaper87.com > Usuario Linux registrado #436538 > Geek by nature, Linux by choice, Debian of course. > Key Fingerprint: CFC0 C67D FF73 463B 7E55 CF43 25D1 E75B E2DB 15C7 > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From ricaraoz at gmail.com Thu Aug 23 17:03:36 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Thu, 23 Aug 2007 12:03:36 -0300 Subject: [Tutor] Table Joins In-Reply-To: References: Message-ID: <46CDA1C8.7030400@bigfoot.com> Terry Carroll wrote: > On Wed, 22 Aug 2007, z machinez wrote: > >> Hi All: >> >> I have the following tables selected from a database: >> >> a1 >> >> a2 >> >> each table are of the same column length, same col names. How do I combine >> or concatenate these tables ? So, I would like to have >> >> a3 = a1, a2 # combining all the rows into one formal table > > If a1 and a2 are both lists, my first approach would have been to convert > them to sets and take their union (converting to tuples along the way to > make them hashable): > >>>> a1 = [[1, 'a'], [2, 'b'], [3, 'c'], [4, 'd'], [5, 'e']] >>>> a2 = [[1, 'a'], [5, 'e'], [9, 'i'], [15, 'o'], [21, 'u']] >>>> t1 = [tuple(x) for x in a1] >>>> t2 = [tuple(x) for x in a2] >>>> s1 = set(t1) >>>> s2 = set(t2) >>>> s3 = s1.union(s2) > > You can see the combination is all done now: > >>>> s3 > set([(5, 'e'), (4, 'd'), (9, 'i'), (3, 'c'), (2, 'b'), (21, 'u'), (1, 'a'), (15, 'o')]) > > All that's left is to get them back into a list of lists: > >>>> a3 = [list(x) for x in list(s3)] >>>> a3 > [[5, 'e'], [4, 'd'], [9, 'i'], [3, 'c'], [2, 'b'], [21, 'u'], [1, 'a'], [15, 'o']] > > And you can sort them if you want a more rational order: > >>>> a3.sort() >>>> a3 > [[1, 'a'], [2, 'b'], [3, 'c'], [4, 'd'], [5, 'e'], [9, 'i'], [15, 'o'], [21, 'u']] > > Now, if you want to maintain the origianl two lists' order, interleaving > as you go, this approach won't work, and you're instead going to have to > do it with a couple nested loops (I think). > > If you want to pull them out of the database as a single table.... > I was wondering that myself the other day. I was planning on looking > into whether you could just do a FULL OUTER JOIN (which is essentially a > union operation) on both tables. I haven't checked that out, yet; you > might want to look into it. > In SQL if you want an union operation you must use UNION (if you want no repetitions) or UNION ALL (which will output repetitions), both tables must have the same structure and the names of the output fields will be those of the first table. A join is a pairing of the fields of both tables. a = field1, field2, field3 b = field4, field5, field6 let's say they have 3 records each. Then a join without any condition (WHERE or ON) would be : 1field1, 1field2, 1field3, 1field4, 1field5, 1field6 1field1, 1field2, 1field3, 2field4, 2field5, 2field6 1field1, 1field2, 1field3, 3field4, 3field5, 3field6 2field1, 2field2, 2field3, 1field4, 1field5, 1field6 2field1, 2field2, 2field3, 2field4, 2field5, 2field6 2field1, 2field2, 2field3, 3field4, 3field5, 3field6 3field1, 3field2, 3field3, 1field4, 1field5, 1field6 3field1, 3field2, 3field3, 2field4, 2field5, 2field6 3field1, 3field2, 3field3, 3field4, 3field5, 3field6 It can get very big in no time. Now you usually qualify the join. Let's say u say : select * from a join b on a.field1 = b.field4 Now only the records that fulfill the ON condition will be left, thats an INNER JOIN. If you want to keep all the records from table 'a' even if they don't have a corresponding record in table 'b' (b fields will be NULL) then that's a LEFT JOIN ('b' records that don't have a corresponding 'a' record will be left out). If you want all records of table 'b' and only corresponding records from table 'a' that's a RIGHT JOIN. Finally if you want all records from 'a' and all records from 'b' to be on your output that's a FULL OUTER JOIN. HTH From alan.gauld at btinternet.com Fri Aug 24 01:46:29 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 24 Aug 2007 00:46:29 +0100 Subject: [Tutor] capturing process's status with python References: Message-ID: "Flaper87" wrote > i would like to know how can i capture the system process's status > with > python, i need to know if they are sleeping, zombie or runing. The simplest route on Unix may be just to run ps using the subprocess.Popen object or os.popen. You can then parse the ps output. The OS topic of my tutor gives some examples of running ps using popen and Popen... HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From sebastien at solutions-linux.org Fri Aug 24 02:18:40 2007 From: sebastien at solutions-linux.org (Sebastien) Date: Thu, 23 Aug 2007 19:18:40 -0500 Subject: [Tutor] Problem from complex string messing up Message-ID: <1132d44ba3a95115a493e244315a2f95@localhost> Hi, I have these bunch of html files from which I've stripped presentation with BeautifulSoup (only kept a content div with the bare content). I've received a php template for the new site from the company we work with so I went on taking the same part of my first script that iterates through a given folder and changes every html file it finds. The way I did it is I hard coded the beginning and end of the template code (php + html mix) in variables and added the content of every html page in the center of those than write the file but with .php instead of .html and removing the .html version. I've hard coded the template code because I found it easier this way (and this script had to be done really fast) I used triple quotes """template code""" to avoid problems, but every file touched by the script end up having a problem and not being able the show the supposed drop down menu. Now the code the company did for this drop down is pretty esoteric: I wonder what program creates such unreadable code. Well, anyway, a javascript error pops-up somewhere in that code after I run my script on the files. My idea is that the script encounters a unicode character and doesn't know how to act with it and changes it to something else which mess up the whole thing. Do you people thing this sound like a good explanation. If it's likely to be the problem, is having my strings u"""bla bla bla""" would fix that? Thanks in advance From tim at johnsons-web.com Fri Aug 24 03:17:13 2007 From: tim at johnsons-web.com (Tim Johnson) Date: Thu, 23 Aug 2007 17:17:13 -0800 Subject: [Tutor] HOWTO: adding to sys.path the simplest way. Message-ID: <200708231717.13266.tim@johnsons-web.com> I have a seperate library directory both on my work station on the the remote servers that I write applications for.. I commonly use sys.path.append('/path/to/mylibraries') in my python code. That code has to be placed in any standalone script that I write. I can also place that path in a system file. On my kubuntu workstation, it is /var/lib/python-support/python2.5/.path I believe that path is different on the solaris or redhat servers that I provide scripts to. Furthermore, any update of the python version will necessitate editing of the new .path file. I would welcome some opinions on this matter. Thanks Tim From kent37 at tds.net Fri Aug 24 04:45:23 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 23 Aug 2007 22:45:23 -0400 Subject: [Tutor] Problem from complex string messing up In-Reply-To: <1132d44ba3a95115a493e244315a2f95@localhost> References: <1132d44ba3a95115a493e244315a2f95@localhost> Message-ID: <46CE4643.1040306@tds.net> Sebastien wrote: > I used triple quotes """template code""" to avoid problems, but every file touched by the script end up having a problem and not being able the show the supposed drop down menu. Now the code the company did for this drop down is pretty esoteric: > > > > I wonder what program creates such unreadable code. Well, anyway, a javascript error pops-up somewhere in that code after I run my script on the files. > > My idea is that the script encounters a unicode character and doesn't know how to act with it and changes it to something else which mess up the whole thing. > > Do you people thing this sound like a good explanation. If it's likely to be the problem, is having my strings u"""bla bla bla""" would fix that? No, I doubt it has any unicode chars, it is probably pure ascii. I think the \ chars are the problem. Try using a raw string - start the string with r""" so Python doesn't try to interpret the \ chars as escapes. Kent From kent37 at tds.net Fri Aug 24 04:49:35 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 23 Aug 2007 22:49:35 -0400 Subject: [Tutor] HOWTO: adding to sys.path the simplest way. In-Reply-To: <200708231717.13266.tim@johnsons-web.com> References: <200708231717.13266.tim@johnsons-web.com> Message-ID: <46CE473F.10907@tds.net> Tim Johnson wrote: > I have a seperate library directory both on my work station on > the the remote servers that I write applications for.. > > I commonly use sys.path.append('/path/to/mylibraries') in my > python code. > > That code has to be placed in any standalone script that I write. > I can also place that path in a system file. On my kubuntu > workstation, it is /var/lib/python-support/python2.5/.path > > I believe that path is different on the solaris or redhat servers > that I provide scripts to. Furthermore, any update of the python version > will necessitate editing of the new .path file. > > I would welcome some opinions on this matter. Make a file called mylibraries.pth with contents /path/to/mylibraries Put the file in your site-packages folder (I don't know wherethat is for you). Updating Python will still require copying the .pth file to the new site-packages folder but no editing. Or you could just put the libraries in site-packages directly. Kent From dos.fool at gmail.com Fri Aug 24 07:12:04 2007 From: dos.fool at gmail.com (max baseman) Date: Thu, 23 Aug 2007 23:12:04 -0600 Subject: [Tutor] the and command Message-ID: <8CC3B8AA-E03A-4C7E-874F-BBF9153EECE1@gmail.com> hello im checking if a number is in all 5 of the other lists and when i use the and command it seems to just be checking if it's in a least one of the others, here is the program it's choppy i needed it for a quick calculation so it's not pretty but it's not long: n2=2 n3=3 n4=4 n5=5 n6=6 n7=7 l2=[] l3=[] l4=[] l5=[] l6=[] l7=[] while n2 < 100: l2.append(n2) n2=n2+2 while n3 < 100: l3.append(n3) n3=n3+3 while n4 < 100: l4.append(n4) n4=n4+4 while n5 < 100: l5.append(n5) n5=n5+5 while n6 < 100: l6.append(n6) n6=n6+6 while n7<100: l7.append(n7) n7=n7+7 possible=[] for num in l2 and l3 and l4 and l5 and l6: # here seems to be the problem possible.append(num) for a in possible: if a-1 in l7: print a any help is great thanks From alan.gauld at btinternet.com Fri Aug 24 09:25:33 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 24 Aug 2007 08:25:33 +0100 Subject: [Tutor] the and command References: <8CC3B8AA-E03A-4C7E-874F-BBF9153EECE1@gmail.com> Message-ID: "max baseman" wrote > im checking if a number is in all 5 of the other lists and when > i use the and command it seems to just be checking if it's in a > least > one of the others, > for num in l2 and l3 and l4 and l5 and l6: # here seems to be the Try: if num in I2 and num in I3 and num in I4 and num in I5 and num in I6: In your case you are 'and'ing the lists which is a boolean expression and because of how Python does short circuit evaluation it returns the last list >>> a = [1,2] >>> b = [3,4] >>> a and b [3, 4] so for n in a and b: is the same as for n in b: which iterates over b... HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From dos.fool at gmail.com Fri Aug 24 14:24:40 2007 From: dos.fool at gmail.com (max baseman) Date: Fri, 24 Aug 2007 06:24:40 -0600 Subject: [Tutor] the and command In-Reply-To: References: <8CC3B8AA-E03A-4C7E-874F-BBF9153EECE1@gmail.com> Message-ID: <068F7CE0-320E-49E3-B7A0-C2082E8B8C1B@gmail.com> thanks much you really helped me if anyone wants here is the program: n2=2 n3=3 n4=4 n5=5 n6=6 n7=7 l2=[] l3=[] l4=[] l5=[] l6=[] l7=[] while n2 < 1000: l2.append(n2) n2=n2+2 while n3 < 1000: l3.append(n3) n3=n3+3 while n4 < 1000: l4.append(n4) n4=n4+4 while n5 < 1000: l5.append(n5) n5=n5+5 while n6 < 1000: l6.append(n6) n6=n6+6 while n7<1000: l7.append(n7) n7=n7+7 possible=[] for num in l2: if num in l3 and num in l4 and num in l5 and num in l6: possible.append(num) for a in possible: if a+1 in l7: print a+1 On Aug 24, 2007, at 1:25 AM, Alan Gauld wrote: > > "max baseman" wrote >> im checking if a number is in all 5 of the other lists and when >> i use the and command it seems to just be checking if it's in a >> least >> one of the others, > > >> for num in l2 and l3 and l4 and l5 and l6: # here seems to be the > > Try: > > if num in I2 and num in I3 and num in I4 and num in I5 and num in I6: > > In your case you are 'and'ing the lists which is a boolean expression > and because of how Python does short circuit evaluation it returns > the last list > >>>> a = [1,2] >>>> b = [3,4] >>>> a and b > [3, 4] > > so > > for n in a and b: > > is the same as > > for n in b: > > which iterates over b... > > HTH, > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.freenetpages.co.uk/hp/alan.gauld > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From kent37 at tds.net Fri Aug 24 15:06:26 2007 From: kent37 at tds.net (Kent Johnson) Date: Fri, 24 Aug 2007 09:06:26 -0400 Subject: [Tutor] the and command In-Reply-To: <068F7CE0-320E-49E3-B7A0-C2082E8B8C1B@gmail.com> References: <8CC3B8AA-E03A-4C7E-874F-BBF9153EECE1@gmail.com> <068F7CE0-320E-49E3-B7A0-C2082E8B8C1B@gmail.com> Message-ID: <46CED7D2.7090905@tds.net> max baseman wrote: > thanks much you really helped me if anyone wants here is the program: Hmmm...this is quite wordy. Some suggestions below: > > n2=2 > n3=3 > n4=4 > n5=5 > n6=6 > n7=7 > l2=[] > l3=[] > l4=[] > l5=[] > l6=[] > l7=[] > while n2 < 1000: > l2.append(n2) > n2=n2+2 This can be written l2 = range(2, 1000, 2) > while n3 < 1000: > l3.append(n3) > n3=n3+3 > while n4 < 1000: > l4.append(n4) > n4=n4+4 > while n5 < 1000: > l5.append(n5) > n5=n5+5 > while n6 < 1000: > l6.append(n6) > n6=n6+6 > while n7<1000: > l7.append(n7) > n7=n7+7 > possible=[] > for num in l2: > if num in l3 and num in l4 and num in l5 and num in l6: > possible.append(num) Testing for membership is better done with sets or dicts than lists. In this case you want the intersection of l2,...,l6. Sets support intersection directly. Also l2 and l3 are redundant; any number in l6 will also be in l2 and l3. So possible can be created as a set like this: possible = set(xrange(4, 1000, 4)).intersection(xrange(5, 1000, 5)) \ .intersection(xrange(6, 1000, 6)) > for a in possible: > if a+1 in l7: > print a+1 Here you are checking if a is divisible by 7. You could do it directly instead of creating a helper: for a in possible: if (a+1) % 7 == 0: print a+1 Or you could apply a little more number theory and realize that to be a multiple of 4, 5 and 6 it is necessary and sufficient to be a multiple of 60 and write the whole thing in one loop: for a in xrange(60, 1000, 60): if (a+1) % 7 == 0: print a+1 Kent From alan.gauld at btinternet.com Fri Aug 24 15:32:40 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 24 Aug 2007 14:32:40 +0100 Subject: [Tutor] Off Topic: xrange, WAS: Re: the and command References: <8CC3B8AA-E03A-4C7E-874F-BBF9153EECE1@gmail.com> <068F7CE0-320E-49E3-B7A0-C2082E8B8C1B@gmail.com> <46CED7D2.7090905@tds.net> Message-ID: "Kent Johnson" wrote > possible = set(xrange(4, 1000, 4)).intersection(xrange(5, 1000, 5)) > \ > .intersection(xrange(6, 1000, 6)) > Kent, I've noticed in a few of your replie recemntly you have been using xrange rather than range. I was under the impression that since iterators were introduced that xrange was more or less just an alias for range. Your usage suggests that my understanding is wrong? However, even in its original incarnation I would not have used it here since I thought its main advantage was in loops where it (like a geneator) yielded values one by one to save memory. In this case aren't you generating the full set in each case? Or at least in the first case, the set()? I notice that help() still differentiates between the two, and indeed that xrange purports to be a type rather than a function. I suspect I'm missing something! :-) Alan G From 3dbernard at gmail.com Fri Aug 24 15:40:33 2007 From: 3dbernard at gmail.com (Bernard Lebel) Date: Fri, 24 Aug 2007 09:40:33 -0400 Subject: [Tutor] Converting code to string Message-ID: <61d0e2b40708240640h38a54d32xf5899cbe20d8f853@mail.gmail.com> okay here "simple" examples about why I have to define callbacks as strings instead of code. In XSI, one of the GUI objects that you can create is called a "custom property". A custom property is basically a floating window in which there are widgets. Custom properties can define a layout or not. Custom properties that do not define a layout display a bunch of simple widgets (text fields, sliders for scalar values, checkboxes, etc), vertically on top of each other. Custom properties that define a layout offer a lot more interesting widgets: buttons, tabs, combo boxes, radio buttons, labels, groups, etc. To interactive widgets, callbacks can be attached. So when a button is clicked or a combo box changed, code can be ran. There are two implementations for custom property layouts. 1- property plugins: the entire property is defined in a plugin file. Here the programmer can put any amount of widgets and callbacks he wants. However, the number of such items is constant, one cannot dynamically add or remove elements from a property created in that fashion. (well, perhaps it is possible, but I don't know how). When the XSI application starts, the plugin is loaded. In scripts, the property can be instantiated and inspected. The great benefit of this approach is that the property's layout and logic are persistable. Since those are defined in a plugin, if the plugin is always found, then the property will keep its layout and logic, even if the document is closed and reopen. Here is an example of such a plugin: # Load plugin in XSI def XSILoadPlugin( in_reg ): in_reg.Author = "Bernard Lebel" in_reg.Name = "plugindemo" in_reg.Major = 1 in_reg.Minor = 1 in_reg.RegisterProperty( "propertyplugindemo" ) return True # Define property def propertyplugindemo_Define( io_Context ): """ Add parameters """ oProp = io_Context.source oProp.addparameter3( 'myparameter', 8, '' ) def propertyplugindemo_DefineLayout( io_Context ): """ Skip layout creation. We'll do it at inspection time. """ pass def propertyplugindemo_OnInit(): """ Called when the property is inspected (brought up to the screen for the user to use it) """ oProp = PPG.Inspected(0) # Create property layout oLayout = PPG.PPGLayout oLayout.Clear() oLayout.additem( 'myparameter', 'myparameter' ) # add "myparameter text field" oLayout.addbutton( 'myButton' ) # add "myButton" button PPG.Refresh() # Callbacks for widgets def propertyplugindemo_myButton_OnClicked(): print 'hello world' 2- on-the-fly logic: instead of creating a plugin, the programmer can create a custom property along with layout and logic entirely at execution time. While this prevents the property layout and logic from being persisted, it allows the programmer to define dynamically how many widgets and callback he wants. The problem with this approach is that it I believe it was not designed with Python in mind, but rather JScript. The callbacks defined in "on-the-fly" context, for some reason, must be written as strings and then injected into the property's logic. JScript has the toString() method, which converts easily code blocks into strings. The following Pythoin code works well. Functions are written directly as strings, so no problem. It does exactly the same property as the example above, except that it is being done "on-the-fly" instead of through a plugin. # Instantiate the Applicaiton object, # for running command in the host application xsi = Application # Define callback functions sOnInit = """def OnInit(): pass""" sMyButtonOnClicked = """def myButton_OnClicked(): print 'hello world'""" # Create plain custom property oProperty = xsi.activesceneroot.addproperty( 'CustomProperty', False ) # Add parameters oParameter = oProperty.addparameter3( 'myparameter', 8, '' ) # Get property layout oLayout = oProperty.PPGLayout oLayout.Clear() # Set the layout environment oLayout.Language = 'Python' # Inject logic into the layout. # Join all functions defined in strings. oLayout.Logic = '\n'.join( [sOnInit, sMyButtonOnClicked] ) # Create buttons oLayout.additem( oParameter.scriptname, oParameter.scriptname ) oLayout.addbutton( 'myButton' ) # Inspect the property xsi.inspectobj( oProperty ) Now back to the actual problem. In the task I'm currently having, I have to dynamically create a certain number of layout elements along its logic. The number of elements to create changes from one execution to the next, as it is driven by the user input. Since properpty plugins do not support such dynamic creation, my only solution is with the "on-the-fly" approach. Now what I'd like to do is to create "real" functions, not strings, and convert them into strings for logic injection. Thanks! Bernard From 3dbernard at gmail.com Fri Aug 24 15:44:15 2007 From: 3dbernard at gmail.com (Bernard Lebel) Date: Fri, 24 Aug 2007 09:44:15 -0400 Subject: [Tutor] Converting code to string In-Reply-To: <61d0e2b40708240640h38a54d32xf5899cbe20d8f853@mail.gmail.com> References: <61d0e2b40708240640h38a54d32xf5899cbe20d8f853@mail.gmail.com> Message-ID: <61d0e2b40708240644s1483cbd2rb2040f34f58e6861@mail.gmail.com> Actually, regarding inspect.getsource() that raised IOErrors: Running it from imported module actually works! Thanks Bernard From kent37 at tds.net Fri Aug 24 15:52:16 2007 From: kent37 at tds.net (Kent Johnson) Date: Fri, 24 Aug 2007 09:52:16 -0400 Subject: [Tutor] Off Topic: xrange, WAS: Re: the and command In-Reply-To: References: <8CC3B8AA-E03A-4C7E-874F-BBF9153EECE1@gmail.com> <068F7CE0-320E-49E3-B7A0-C2082E8B8C1B@gmail.com> <46CED7D2.7090905@tds.net> Message-ID: <46CEE290.7090506@tds.net> Alan Gauld wrote: > "Kent Johnson" wrote > >> possible = set(xrange(4, 1000, 4)).intersection(xrange(5, 1000, 5)) >> \ >> .intersection(xrange(6, 1000, 6)) >> > > Kent, > > I've noticed in a few of your replie recemntly you have been using > xrange rather than range. I was under the impression that since > iterators were introduced that xrange was more or less just an > alias for range. Your usage suggests that my understanding is > wrong? Yes, you misunderstand. range() still creates a list, xrange() returns a iterator. In Python 3000 range() will return an iterator and xrange() will go away. In [3]: type(range(1000)) Out[3]: In [4]: type(xrange(1000)) Out[4]: > However, even in its original incarnation I would not have used it > here since I thought its main advantage was in loops where it > (like a geneator) yielded values one by one to save memory. > In this case aren't you generating the full set in each case? > Or at least in the first case, the set()? I generate the full set but using xrange() avoids creating an intermediate list. set() is happy to have an iterable argument, it doesn't need a list. There is an implicit loop; the set constructor must iterate over its argument. There is a modest performance benefit to using xrange(): src $ python -m timeit "set(range(1000))" 10000 loops, best of 3: 99.8 usec per loop src $ python -m timeit "set(xrange(1000))" 10000 loops, best of 3: 86.7 usec per loop Of course in most cases 13 usec is not of any consequence. In fact in my own code I usually use range(). Kent From kent37 at tds.net Fri Aug 24 16:06:49 2007 From: kent37 at tds.net (Kent Johnson) Date: Fri, 24 Aug 2007 10:06:49 -0400 Subject: [Tutor] Converting code to string In-Reply-To: <61d0e2b40708240640h38a54d32xf5899cbe20d8f853@mail.gmail.com> References: <61d0e2b40708240640h38a54d32xf5899cbe20d8f853@mail.gmail.com> Message-ID: <46CEE5F9.1080707@tds.net> Bernard Lebel wrote: > In the task I'm currently having, I have to dynamically create a > certain number of layout elements along its logic. The number of > elements to create changes from one execution to the next, as it is > driven by the user input. Since properpty plugins do not support such > dynamic creation, my only solution is with the "on-the-fly" approach. > > Now what I'd like to do is to create "real" functions, not strings, > and convert them into strings for logic injection. I think the inspect module is as good as you are going to get and it is just looking up the source code for a function and giving it back to you so it won't work with any kind of dynamic function, for example a function created inside a closure would not have a useful string representation in source. Maybe you should look instead at flexible ways of creating the strings you need, some kind of template language. There are some simple ones in the Python Cookbook: http://aspn.activestate.com/ASPN/search?query=template&x=0&y=0§ion=PYTHONCKBK&type=Subsection http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52305 and quite a few more that have been developed for Web server use: http://wiki.python.org/moin/Templating Kent From pwpeterson at yahoo.com Fri Aug 24 16:47:40 2007 From: pwpeterson at yahoo.com (Paul W Peterson) Date: Fri, 24 Aug 2007 08:47:40 -0600 Subject: [Tutor] Help Request: Nested While commands In-Reply-To: <46CEE290.7090506@tds.net> References: <8CC3B8AA-E03A-4C7E-874F-BBF9153EECE1@gmail.com> <068F7CE0-320E-49E3-B7A0-C2082E8B8C1B@gmail.com> <46CED7D2.7090905@tds.net> <46CEE290.7090506@tds.net> Message-ID: <1187966860.5922.18.camel@Africa> Greeting! I'm learning Python through the book "Python Programming, Second Edition for the absolute beginner" by Michael Dawson. In it, he has the program "Guess my number" (code pasted below). His challenge is to modify the code so that there are only a limited number of attempts before the program exits with a chastising message. Try as I may, I cannot seem to get the syntax correct for nested while loops. I was able to do it with two separate if statements, but this seems very unelegant to me. Could you provide a way to achieve this using nested while statements, or suggest a better use of the ifs? Also, while asking for help from this forum: for short pieces of code such as these, is it appropriate to enter them as inline text, or is it preferred to have them as attachments? I presume for long pieces of code the latter applies. Thank you Paul Peterson Ellicott, Colorado The Technological Capital of Mid Central Eastern El Paso County, Colorado. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070824/a5e5088e/attachment-0001.htm -------------- next part -------------- A non-text attachment was scrubbed... Name: modified_guess_my_ number.py Type: text/x-python Size: 993 bytes Desc: Url : http://mail.python.org/pipermail/tutor/attachments/20070824/a5e5088e/attachment-0002.py -------------- next part -------------- A non-text attachment was scrubbed... Name: original_guess_my_ number.py Type: text/x-python Size: 850 bytes Desc: Url : http://mail.python.org/pipermail/tutor/attachments/20070824/a5e5088e/attachment-0003.py From tinoloc at gmail.com Fri Aug 24 17:00:51 2007 From: tinoloc at gmail.com (Tino Dai) Date: Fri, 24 Aug 2007 11:00:51 -0400 Subject: [Tutor] using in over several entities Message-ID: Hi there, I am wondering about a short cut to doing this. Let's say that we have an array: dbs= ['oracle','mysql','postgres','infomix','access'] and we wanted to do this: if 'oracle' in dbs or 'mysql' in dbs or 'bdb' in dbs: <... do something ...> Is there a short way or writing this? Something like ('oracle','mysql','bdb') in dbs I do see that the the conjunction can be problematic, and I do see that can write a short function to get this working. But before I do that, I wanted to see that there was nothing in Python that already did that. Thanks! Tino -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070824/17b325f8/attachment.htm From kent37 at tds.net Fri Aug 24 17:20:02 2007 From: kent37 at tds.net (Kent Johnson) Date: Fri, 24 Aug 2007 11:20:02 -0400 Subject: [Tutor] using in over several entities In-Reply-To: References: Message-ID: <46CEF722.5030802@tds.net> Tino Dai wrote: > Hi there, > > I am wondering about a short cut to doing this. Let's say that we > have an array: > > dbs= ['oracle','mysql','postgres','infomix','access'] > > and we wanted to do this: > > if 'oracle' in dbs or 'mysql' in dbs or 'bdb' in dbs: > <... do something ...> > > Is there a short way or writing this? Something like > ('oracle','mysql','bdb') in dbs I don't think there is a shortcut with lists. You could write any(db in dbs for db in ('oracle','mysql','bdb')) which at least lets you use a list for the targets, or if [ db for db in ('oracle','mysql','bdb') if db in dbs ]: With sets you can write dbs= set(['oracle','mysql','postgres','infomix','access']) if dbs.intersection(('oracle','mysql','bdb')): Kent From tim at johnsons-web.com Fri Aug 24 17:26:57 2007 From: tim at johnsons-web.com (Tim Johnson) Date: Fri, 24 Aug 2007 07:26:57 -0800 Subject: [Tutor] HOWTO: adding to sys.path the simplest way. In-Reply-To: <46CE473F.10907@tds.net> References: <200708231717.13266.tim@johnsons-web.com> <46CE473F.10907@tds.net> Message-ID: <200708240726.57102.tim@johnsons-web.com> On Thursday 23 August 2007, Kent Johnson wrote: > > I would welcome some opinions on this matter. > > Make a file called mylibraries.pth with contents > /path/to/mylibraries Aha! User-defined .pth file is recognized by python > Put the file in your site-packages folder (I don't know wherethat is for > you). On *nix systems, I think it is generally var/lib/python/site-packages > Updating Python will still require copying the .pth file to the new > site-packages folder but no editing. Great! Thanks Kent Tim From tim at johnsons-web.com Fri Aug 24 17:35:46 2007 From: tim at johnsons-web.com (Tim Johnson) Date: Fri, 24 Aug 2007 07:35:46 -0800 Subject: [Tutor] HOWTO: adding to sys.path the simplest way. In-Reply-To: <200708240726.57102.tim@johnsons-web.com> References: <200708231717.13266.tim@johnsons-web.com> <46CE473F.10907@tds.net> <200708240726.57102.tim@johnsons-web.com> Message-ID: <200708240735.46210.tim@johnsons-web.com> On Friday 24 August 2007, Tim Johnson wrote: > On Thursday 23 August 2007, Kent Johnson wrote: > > > I would welcome some opinions on this matter. > > > > Make a file called mylibraries.pth with contents > > /path/to/mylibraries > > Aha! User-defined .pth file is recognized by python > > > Put the file in your site-packages folder (I don't know wherethat is for > > you). > > On *nix systems, I think it is generally > var/lib/python/site-packages Oops! Meant to say /usr/lib/python... sorry. tim From cbc at unc.edu Fri Aug 24 17:40:19 2007 From: cbc at unc.edu (Chris Calloway) Date: Fri, 24 Aug 2007 11:40:19 -0400 Subject: [Tutor] using in over several entities In-Reply-To: References: Message-ID: <46CEFBE3.3000601@unc.edu> Tino Dai wrote: > I am wondering about a short cut to doing this. Let's say that we > have an array: > > dbs= ['oracle','mysql','postgres','infomix','access'] > > and we wanted to do this: > > if 'oracle' in dbs or 'mysql' in dbs or 'bdb' in dbs: > <... do something ...> > > Is there a short way or writing this? Something like > ('oracle','mysql','bdb') in dbs Sets to the rescue. Set intersection specifically: >>> dbs = set(['oracle','mysql','postgres','infomix','access']) >>> mine = set(['oracle','mysql','bdb']) >>> dbs & mine set(['oracle', 'mysql']) >>> if dbs & mine: ... print 'doing something' ... doing something >>> This also has the advantage of returning to you an object of exactly what elements in mine were in dbs. And difference: >>> dbs - mine set(['access', 'infomix', 'postgres']) >>> will show you which elements of mine were not in dbs. -- Sincerely, Chris Calloway http://www.seacoos.org office: 332 Chapman Hall phone: (919) 962-4323 mail: Campus Box #3300, UNC-CH, Chapel Hill, NC 27599 From Mike.Hansen at atmel.com Fri Aug 24 18:45:31 2007 From: Mike.Hansen at atmel.com (Mike Hansen) Date: Fri, 24 Aug 2007 10:45:31 -0600 Subject: [Tutor] the and command In-Reply-To: <46CED7D2.7090905@tds.net> References: <8CC3B8AA-E03A-4C7E-874F-BBF9153EECE1@gmail.com> <068F7CE0-320E-49E3-B7A0-C2082E8B8C1B@gmail.com> <46CED7D2.7090905@tds.net> Message-ID: <57B026980605A64F9B23484C5659E32E9841AA@poccso.US.ad.atmel.com> > -----Original Message----- > ... > > for num in l2: > > if num in l3 and num in l4 and num in l5 and num in l6: > > possible.append(num) Yikes! Glancing at the code, I was reading l3, l4, l5, l6 as the numbers 13, 14, 15, 16..(Thirteen, Fourteen, Fifteen, Sixteen). I'd avoid using variables named like that since the lowercase L looks like a one (l, 1) in many fonts. Mike From alan.gauld at btinternet.com Fri Aug 24 18:50:37 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 24 Aug 2007 17:50:37 +0100 Subject: [Tutor] Help Request: Nested While commands References: <8CC3B8AA-E03A-4C7E-874F-BBF9153EECE1@gmail.com><068F7CE0-320E-49E3-B7A0-C2082E8B8C1B@gmail.com> <46CED7D2.7090905@tds.net> <46CEE290.7090506@tds.net> <1187966860.5922.18.camel@Africa> Message-ID: "Paul W Peterson" wrote > "Guess my number" (code pasted below). His challenge is to modify the > code so that there are only a limited number of attempts before the > program exits with a chastising message. > > Try as I may, I cannot seem to get the syntax correct for nested while > loops. I wouldn't use a nested loop for that but an if/break at the top of the existing loop. But nested loops are easy, its just an extra indentation level: >>> j = 0 >>> while j < 5: ... n = 0 ... while n < 10: ... print n, ... n += 1 ... j += 1 ... > using nested while statements, or suggest a better use of the ifs? Using 'if's I'd do: # guessing loop while (guess != the_number): if tries >= TRY_LIMIT: print "Too many tries" break if (guess > the_number): print "Lower..." else: print "Higher..." guess = int(raw_input("Take a guess: ")) tries += 1 > Also, while asking for help from this forum: for short pieces of code > such as these, is it appropriate to enter them as inline text Yes, if it gets above a screenful(50 lines?) then an attachment (or a url) is usually better. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070824/92a0322f/attachment.htm From rdm at rcblue.com Fri Aug 24 06:15:53 2007 From: rdm at rcblue.com (Dick Moores) Date: Thu, 23 Aug 2007 21:15:53 -0700 Subject: [Tutor] A fun puzzle In-Reply-To: <46CDD6AB.2030207@tds.net> References: <156304361588.20070822204055@columbus.rr.com> <46CCF229.9000802@tds.net> <20070823145247.92A561E400B@bag.python.org> <46CDA5C6.4080705@tds.net> <20070823164730.7EBB41E400B@bag.python.org> <46CDD6AB.2030207@tds.net> Message-ID: <20070824165305.7B5D81E4013@bag.python.org> At 11:49 AM 8/23/2007, Kent Johnson wrote: >Dick Moores wrote: >>>Two reasons. First, looking up a name that is local to a function >>>is faster than looking up a global name. To find the value of >>>'str', the interpreter has to look at the module namespace, then >>>the built-in namespace. These are each dictionary lookups. Local >>>values are stored in an array and accessed by offset so it is much faster. >>Wow, what DON'T you understand? > >Lots, actually :-) There is a whole 'nother tier or two of Python >expert above me that I can't touch. I just parrot back what I hear >them saying. :-) > >>Please explain "accessed by offset". > >IIUC an array is allocated on the call stack to hold references to >the local variables. (Anticipating you next question: >http://en.wikipedia.org/wiki/Stack_frame) To get the value of the >local variable the runtime just has to look up the correct entry in >the array. The bytecode has the offset into the array. This is very >quick - an indexed lookup. > >Normal attribute access such as a module or builtin has to read the >value out of a dict which is much more expensive, even with Python's >optimized dicts. Thank you. Nice parroting. :-) >>This time I added "xrange(10, end, 10)" and did the timing using >>the template in the timeit module: >>template = """ >>def inner(_it, _timer): >> _t0 = _timer() >> from itertools import chain >> end = 1000000 >> for _i in _it: >> for x in chain(xrange(1, end, 10), xrange(2, end, 10), >> xrange(3, end, 10), xrange(4, end, 10), xrange(5, end, 10), >> xrange(6, end, 10), xrange(7, end, 10), xrange(8, end, 10), >> xrange(9, end, 10), xrange(10, end, 10)): >> pass >> _t1 = _timer() >> return _t1 - _t0 >>""" >>This gets always close to 71 msec per loop. >> >>template = """ >>def inner(_it, _timer): >> _t0 = _timer() >> end = 1000000 >> for _i in _it: >> for x in xrange(end): >> pass >> _t1 = _timer() >> return _t1 - _t0 >>""" >>This gets always close to 84 msec per loop. >>So they're not the same! And yours is the faster one! Because >>itertools.chain() is written in C, I suppose. > >That is very strange. I did a simple timer with time.time() and >found that my original (1-9) version was consistently a little >slower than the simple xrange(). And xrange is written in C too, and >the chain version adds a layer over xrange. You should check your >code carefully, that is a very surprising result. Yes, surprising. But the templates pasted above are exactly what I used in 2 copies of timeit.py. I don't know what to check. Can you see what's wrong? I just ran both of those again, with very similar results. Following your lead I've now done some timing using time.time(): ============================================================== from __future__ import division from itertools import chain import time end = 1000000 timeTotal = 0 for c in range(100): timeStart = time.time() for x in chain(xrange(1, end, 10), xrange(2, end, 10), xrange(3, end, 10), xrange(4, end, 10), xrange(5, end, 10), xrange(6, end, 10), xrange(7, end, 10), xrange(8, end, 10), xrange(9, end, 10), xrange(10, end, 10)): pass timeEnd = time.time() timeElapsed = timeEnd - timeStart timeTotal += timeElapsed avgTime = timeTotal/c print "with chain avgTime was %.4g seconds" % avgTime """ results of 5 runs: with chain avgTime was 0.2072 seconds with chain avgTime was 0.1916 seconds with chain avgTime was 0.1913 seconds with chain avgTime was 0.1921 seconds with chain avgTime was 0.1915 seconds (avg is 0.1947 seconds) """ ================================================= ================================================= from __future__ import division import time end = 1000000 timeTotal = 0 for c in range(100): timeStart = time.time() for x in xrange(end): pass timeEnd = time.time() timeElapsed = timeEnd - timeStart timeTotal += timeElapsed avgTime = timeTotal/c print "no chain avgTime was %.4g seconds" % avgTime """ results of 5 runs: no chain avgTime was 0.2104 seconds no chain avgTime was 0.2109 seconds no chain avgTime was 0.1946 seconds no chain avgTime was 0.1948 seconds no chain avgTime was 0.1946 seconds (avg is 0.2011 seconds) """ ===================================================== When I ran the above 2 scripts, I alternated between them. Don't really see that one is decisively faster than the other. Dick ====================================== Bagdad Weather From alan.gauld at btinternet.com Fri Aug 24 19:11:29 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 24 Aug 2007 18:11:29 +0100 Subject: [Tutor] using in over several entities References: Message-ID: "Tino Dai" wrote > dbs= ['oracle','mysql','postgres','infomix','access'] > > and we wanted to do this: > > if 'oracle' in dbs or 'mysql' in dbs or 'bdb' in dbs: > <... do something ...> > > Is there a short way or writing this? Something like > ('oracle','mysql','bdb') in dbs You could use sets and check the intersection: dbs = set(['oracle','mysql','postgres','infomix','access']) test = set(['oracle','mysql','dbd']) if dbs.intersection(test): HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From dkuhlman at rexx.com Fri Aug 24 18:28:41 2007 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Fri, 24 Aug 2007 09:28:41 -0700 Subject: [Tutor] Off Topic: xrange, WAS: Re: the and command In-Reply-To: <46CEE290.7090506@tds.net> References: <8CC3B8AA-E03A-4C7E-874F-BBF9153EECE1@gmail.com> <46CED7D2.7090905@tds.net> <46CEE290.7090506@tds.net> Message-ID: <20070824162841.GA18864@cutter.rexx.com> On Fri, Aug 24, 2007 at 09:52:16AM -0400, Kent Johnson wrote: Kent and Alan - Thanks for encouraging me to do a little reading and experimenting. I thought xrange() returned an iterator. I was wrong. Actually xrange() returns an xrange object which, according to the docs, is "an opaque sequence". Small points I suppose, but ... There are some differences between an xrange object and an iterator: - an xrange object can be used multiple times to produce the sequence. An iterator is exhausted after it has produced its sequence. At least, thats what the docs seem to say, although, I suppose, it depends on the implementation of the individual iterator. See http://docs.python.org/lib/typeiter.html. - an xrange object is index-able; iterators are not. Here is the relavant part from the docs: xrange([start,] stop[, step]) This function is very similar to range(), but returns an `xrange object'' instead of a list. This is an opaque sequence type which yields the same values as the corresponding list, without actually storing them all simultaneously. The advantage of xrange() over range() is minimal (since xrange() still has to create the values when asked for them) except when a very large range is used on a memory-starved machine or when all of the range's elements are never used (such as when the loop is usually terminated with break). http://docs.python.org/lib/built-in-funcs.html#l2h-80 Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman From alan.gauld at btinternet.com Fri Aug 24 19:13:14 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 24 Aug 2007 18:13:14 +0100 Subject: [Tutor] using in over several entities References: <46CEFBE3.3000601@unc.edu> Message-ID: "Chris Calloway" wrote > >>> dbs = set(['oracle','mysql','postgres','infomix','access']) > >>> mine = set(['oracle','mysql','bdb']) > >>> dbs & mine > set(['oracle', 'mysql']) > >>> dbs - mine > set(['access', 'infomix', 'postgres']) Interesting. I didn't know about the & and - set operations. Thanks for the pointer. Alan G From kent37 at tds.net Fri Aug 24 19:22:31 2007 From: kent37 at tds.net (Kent Johnson) Date: Fri, 24 Aug 2007 13:22:31 -0400 Subject: [Tutor] A fun puzzle In-Reply-To: <20070824165305.7B5D81E4013@bag.python.org> References: <156304361588.20070822204055@columbus.rr.com> <46CCF229.9000802@tds.net> <20070823145247.92A561E400B@bag.python.org> <46CDA5C6.4080705@tds.net> <20070823164730.7EBB41E400B@bag.python.org> <46CDD6AB.2030207@tds.net> <20070824165305.7B5D81E4013@bag.python.org> Message-ID: <46CF13D7.9050002@tds.net> Dick Moores wrote: >>> This time I added "xrange(10, end, 10)" and did the timing using >>> the template in the timeit module: >>> template = """ >>> def inner(_it, _timer): >>> _t0 = _timer() >>> from itertools import chain >>> end = 1000000 >>> for _i in _it: >>> for x in chain(xrange(1, end, 10), xrange(2, end, 10), >>> xrange(3, end, 10), xrange(4, end, 10), xrange(5, end, 10), >>> xrange(6, end, 10), xrange(7, end, 10), xrange(8, end, 10), >>> xrange(9, end, 10), xrange(10, end, 10)): >>> pass >>> _t1 = _timer() >>> return _t1 - _t0 >>> """ >>> This gets always close to 71 msec per loop. >>> >>> template = """ >>> def inner(_it, _timer): >>> _t0 = _timer() >>> end = 1000000 >>> for _i in _it: >>> for x in xrange(end): >>> pass >>> _t1 = _timer() >>> return _t1 - _t0 >>> """ >>> This gets always close to 84 msec per loop. >>> So they're not the same! And yours is the faster one! Because >>> itertools.chain() is written in C, I suppose. >> That is very strange. I did a simple timer with time.time() and >> found that my original (1-9) version was consistently a little >> slower than the simple xrange(). And xrange is written in C too, and >> the chain version adds a layer over xrange. You should check your >> code carefully, that is a very surprising result. > > Yes, surprising. But the templates pasted above are exactly what I > used in 2 copies of timeit.py. I don't know what to check. Can you > see what's wrong? I just ran both of those again, with very similar results. So you actually pasted that code into timeit.py? That is a pretty unconventional use of the module! I wonder if there is something strange going on there? Using timeit more conventionally I get unsurprising results. This program: from timeit import Timer setup = 'from itertools import chain' stmt = '''end = 1000000 for x in chain(xrange(1, end, 10), xrange(2, end, 10), xrange(3, end, 10), xrange(4, end, 10), xrange(5, end, 10), xrange(6, end, 10), xrange(7, end, 10), xrange(8, end, 10), xrange(9, end, 10), xrange(10, end, 10)): pass ''' print min(Timer(stmt, setup=setup).repeat(number=10)) stmt = '''end = 1000000 for x in xrange(end): pass ''' print min(Timer(stmt).repeat(number=10)) has output: 0.497083902359 0.359513998032 which is more in line with what I would expect. I can't account for the variations between different timing methods. Kent From kent37 at tds.net Fri Aug 24 19:38:23 2007 From: kent37 at tds.net (Kent Johnson) Date: Fri, 24 Aug 2007 13:38:23 -0400 Subject: [Tutor] Off Topic: xrange, WAS: Re: the and command In-Reply-To: <20070824162841.GA18864@cutter.rexx.com> References: <8CC3B8AA-E03A-4C7E-874F-BBF9153EECE1@gmail.com> <46CED7D2.7090905@tds.net> <46CEE290.7090506@tds.net> <20070824162841.GA18864@cutter.rexx.com> Message-ID: <46CF178F.50200@tds.net> Dave Kuhlman wrote: > I thought xrange() returned an iterator. I was wrong. > > Actually xrange() returns an xrange object which, according to the > docs, is "an opaque sequence". Interesting. So an xrange object is an iterable sequence, not an iterator. Kent From brunson at brunson.com Fri Aug 24 20:06:31 2007 From: brunson at brunson.com (Eric Brunson) Date: Fri, 24 Aug 2007 12:06:31 -0600 Subject: [Tutor] Off Topic: xrange, WAS: Re: the and command In-Reply-To: <46CF178F.50200@tds.net> References: <8CC3B8AA-E03A-4C7E-874F-BBF9153EECE1@gmail.com> <46CED7D2.7090905@tds.net> <46CEE290.7090506@tds.net> <20070824162841.GA18864@cutter.rexx.com> <46CF178F.50200@tds.net> Message-ID: <46CF1E27.6060105@brunson.com> Kent Johnson wrote: > Dave Kuhlman wrote: > >> I thought xrange() returned an iterator. I was wrong. >> >> Actually xrange() returns an xrange object which, according to the >> docs, is "an opaque sequence". >> > > Interesting. So an xrange object is an iterable sequence, not an iterator. > > It's a fine distinction to the language lawyers. Most of the time I see the term "iterator" used, the speaker is referring to an "iterable container", which is a container that defines an "__iter__()" method. That method returns the actual "iterator object", i.e. an object that implements an "__iter__()" and a "next()" method which returns the next item from the container until exhausted, then raises StopIteration. So, xrange doesn't implement the next() method, but the object returned by xrange.__iter__() does, and *that* is the iterator object, though xrange can be referred to as "iterable". Just semantics, but important when trying to be ultra-clear. :-) e. From cbc at unc.edu Fri Aug 24 20:47:56 2007 From: cbc at unc.edu (Chris Calloway) Date: Fri, 24 Aug 2007 14:47:56 -0400 Subject: [Tutor] using in over several entities In-Reply-To: References: <46CEFBE3.3000601@unc.edu> Message-ID: <46CF27DC.3080709@unc.edu> Alan Gauld wrote: > "Chris Calloway" wrote > >>>>> dbs = set(['oracle','mysql','postgres','infomix','access']) >>>>> mine = set(['oracle','mysql','bdb']) >>>>> dbs & mine >> set(['oracle', 'mysql']) >>>>> dbs - mine >> set(['access', 'infomix', 'postgres']) > > Interesting. I didn't know about the & and - set operations. > Thanks for the pointer. They just invoke special methods, of course: s.issubset(t) s <= t __le__ s.issuperset(t) s >= t __ge__ s.union(t) s | t __or__ s.intersection(t) s & t __and__ s.difference(t) s - t __sub__ s.symmetric_difference(t) s ^ t __xor__ s.update(t) s |= t __ior__ s.intersection_update(t) s &= t __iand__ s.difference_update(t) s -= t __isub__ s.symmetric_difference_update(t) s ^= t __ixor__ Good times! The advantage of the s.method(t) versions are, in Python 2.3.1 and after, they will accept any, cough, iterable as argument t, whereas the operator versions require set objects on both side of the operator: >>> set(xrange(10)).issubset(xrange(20)) True >>> -- Sincerely, Chris Calloway http://www.seacoos.org office: 332 Chapman Hall phone: (919) 962-4323 mail: Campus Box #3300, UNC-CH, Chapel Hill, NC 27599 From cbc at unc.edu Fri Aug 24 21:02:47 2007 From: cbc at unc.edu (Chris Calloway) Date: Fri, 24 Aug 2007 15:02:47 -0400 Subject: [Tutor] Help Request: Nested While commands In-Reply-To: <1187966860.5922.18.camel@Africa> References: <8CC3B8AA-E03A-4C7E-874F-BBF9153EECE1@gmail.com> <068F7CE0-320E-49E3-B7A0-C2082E8B8C1B@gmail.com> <46CED7D2.7090905@tds.net> <46CEE290.7090506@tds.net> <1187966860.5922.18.camel@Africa> Message-ID: <46CF2B57.3010606@unc.edu> Paul W Peterson wrote: > Could you provide a way to achieve this > using nested while statements, or suggest a better use of the ifs? You could use one while statement. while guess != the_number and tries < 5: I can't think of a *good* way to use nested whiles for your problem. > Ellicott, Colorado > The Technological Capital of Mid Central Eastern El Paso County, Colorado. Nice. -- Sincerely, Chris Calloway http://www.seacoos.org office: 332 Chapman Hall phone: (919) 962-4323 mail: Campus Box #3300, UNC-CH, Chapel Hill, NC 27599 From rdm at rcblue.com Fri Aug 24 20:59:36 2007 From: rdm at rcblue.com (Dick Moores) Date: Fri, 24 Aug 2007 11:59:36 -0700 Subject: [Tutor] A fun puzzle In-Reply-To: <46CF13D7.9050002@tds.net> References: <156304361588.20070822204055@columbus.rr.com> <46CCF229.9000802@tds.net> <20070823145247.92A561E400B@bag.python.org> <46CDA5C6.4080705@tds.net> <20070823164730.7EBB41E400B@bag.python.org> <46CDD6AB.2030207@tds.net> <20070824165305.7B5D81E4013@bag.python.org> <46CF13D7.9050002@tds.net> Message-ID: <20070824190458.7FA121E4011@bag.python.org> At 10:22 AM 8/24/2007, Kent Johnson wrote: >Dick Moores wrote: >>>>This time I added "xrange(10, end, 10)" and did the timing using >>>>the template in the timeit module: >>>>template = """ >>>>def inner(_it, _timer): >>>> _t0 = _timer() >>>> from itertools import chain >>>> end = 1000000 >>>> for _i in _it: >>>> for x in chain(xrange(1, end, 10), xrange(2, end, 10), >>>> xrange(3, end, 10), xrange(4, end, 10), xrange(5, end, 10), >>>> xrange(6, end, 10), xrange(7, end, 10), xrange(8, end, 10), >>>> xrange(9, end, 10), xrange(10, end, 10)): >>>> pass >>>> _t1 = _timer() >>>> return _t1 - _t0 >>>>""" >>>>This gets always close to 71 msec per loop. >>>> >>>>template = """ >>>>def inner(_it, _timer): >>>> _t0 = _timer() >>>> end = 1000000 >>>> for _i in _it: >>>> for x in xrange(end): >>>> pass >>>> _t1 = _timer() >>>> return _t1 - _t0 >>>>""" >>>>This gets always close to 84 msec per loop. >>>>So they're not the same! And yours is the faster one! Because >>>>itertools.chain() is written in C, I suppose. >>>That is very strange. I did a simple timer with time.time() and >>>found that my original (1-9) version was consistently a little >>>slower than the simple xrange(). And xrange is written in C too, >>>and the chain version adds a layer over xrange. You should check >>>your code carefully, that is a very surprising result. >>Yes, surprising. But the templates pasted above are exactly what I >>used in 2 copies of timeit.py. I don't know what to check. Can you >>see what's wrong? I just ran both of those again, with very similar results. > >So you actually pasted that code into timeit.py? Yeah. :-( I think I learned on the Tutor list to do it that way, but I'm not sure. Thanks for showing me a correct way. >That is a pretty unconventional use of the module! I wonder if there >is something strange going on there? > >Using timeit more conventionally I get unsurprising results. This program: > >from timeit import Timer > >setup = 'from itertools import chain' >stmt = '''end = 1000000 >for x in chain(xrange(1, end, 10), xrange(2, end, 10), > xrange(3, end, 10), xrange(4, end, 10), xrange(5, end, 10), > xrange(6, end, 10), xrange(7, end, 10), xrange(8, end, 10), > xrange(9, end, 10), xrange(10, end, 10)): > pass >''' > >print min(Timer(stmt, setup=setup).repeat(number=10)) > >stmt = '''end = 1000000 >for x in xrange(end): > pass >''' > >print min(Timer(stmt).repeat(number=10)) > > >has output: >0.497083902359 >0.359513998032 > >which is more in line with what I would expect. Using your exact code, I just got 0.737564690484 1.17399585702 Which is the reverse of your result, but on a slower computer. What's up with that?? >I can't account for the variations between different timing methods. Dick From kent37 at tds.net Fri Aug 24 21:12:15 2007 From: kent37 at tds.net (Kent Johnson) Date: Fri, 24 Aug 2007 15:12:15 -0400 Subject: [Tutor] A fun puzzle In-Reply-To: <20070824190457.KTOL5718.inaamta14.mail.tds.net@sccrmhc15.comcast.net> References: <156304361588.20070822204055@columbus.rr.com> <46CCF229.9000802@tds.net> <20070823145247.92A561E400B@bag.python.org> <46CDA5C6.4080705@tds.net> <20070823164730.7EBB41E400B@bag.python.org> <46CDD6AB.2030207@tds.net> <20070824165305.7B5D81E4013@bag.python.org> <46CF13D7.9050002@tds.net> <20070824190457.KTOL5718.inaamta14.mail.tds.net@sccrmhc15.comcast.net> Message-ID: <46CF2D8F.8060102@tds.net> Dick Moores wrote: > At 10:22 AM 8/24/2007, Kent Johnson wrote: >> So you actually pasted that code into timeit.py? > > Yeah. :-( I think I learned on the Tutor list to do it that way, but I'm > not sure. Thanks for showing me a correct way. I hope not! >> Using timeit more conventionally I get unsurprising results. This >> program has output: >> 0.497083902359 >> 0.359513998032 >> >> which is more in line with what I would expect. > > Using your exact code, I just got > 0.737564690484 > 1.17399585702 > > Which is the reverse of your result, but on a slower computer. What's up > with that?? I have no idea. Some strange interaction with the memory cache? I'm running Python 2.5.1 on a MacBook Pro (Intel Core 2 Duo processor). How about you? Time for one of the ?ber-wizards to chime in, maybe :-) or post the code and results on comp.lang.python and see what they say there. Kent From rdm at rcblue.com Fri Aug 24 21:49:06 2007 From: rdm at rcblue.com (Dick Moores) Date: Fri, 24 Aug 2007 12:49:06 -0700 Subject: [Tutor] A fun puzzle In-Reply-To: <46CF2D8F.8060102@tds.net> References: <156304361588.20070822204055@columbus.rr.com> <46CCF229.9000802@tds.net> <20070823145247.92A561E400B@bag.python.org> <46CDA5C6.4080705@tds.net> <20070823164730.7EBB41E400B@bag.python.org> <46CDD6AB.2030207@tds.net> <20070824165305.7B5D81E4013@bag.python.org> <46CF13D7.9050002@tds.net> <20070824190457.KTOL5718.inaamta14.mail.tds.net@sccrmhc15.comcast.net> <46CF2D8F.8060102@tds.net> Message-ID: <20070824194911.DC4601E4011@bag.python.org> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070824/6cce9a9e/attachment.htm From rdm at rcblue.com Fri Aug 24 22:30:19 2007 From: rdm at rcblue.com (Dick Moores) Date: Fri, 24 Aug 2007 13:30:19 -0700 Subject: [Tutor] A fun puzzle Message-ID: <20070824203032.827EA1E4011@bag.python.org> Dick Moores wrote: >At 10:22 AM 8/24/2007, Kent Johnson wrote: >>So you actually pasted that code into timeit.py? >Yeah. :-( I think I learned on the Tutor list to do it that way, but >I'm not sure. Thanks for showing me a correct way. I hope not! >>Using timeit more conventionally I get unsurprising results. This >>program has output: >>0.497083902359 >>0.359513998032 >> >>which is more in line with what I would expect. >Using your exact code, I just got >0.737564690484 >1.17399585702 >Which is the reverse of your result, but on a slower computer. >What's up with that?? Kent, That result was gotten using Ulipad. Thought I'd try it at my command line (several times, of course--I've reported what seemed to be representative data). Using command line: 0.673447044247 0.511676204657 Using IDLE: 0.845213567646 0.685519807685 Using Wing Pro (executing with Alt+F5) 0.940486290855 0.998467123615 Is it possible that the timeit module should be used only at the command line? Dick ====================================== Bagdad Weather From ksterling at mindspring.com Fri Aug 24 22:46:54 2007 From: ksterling at mindspring.com (Ken Oliver) Date: Fri, 24 Aug 2007 16:46:54 -0400 (EDT) Subject: [Tutor] A fun puzzle Message-ID: <20137357.1187988415536.JavaMail.root@mswamui-thinleaf.atl.sa.earthlink.net> -----Original Message----- >From: Dick Moores >Sent: Aug 24, 2007 4:30 PM >To: Python Tutor List >Subject: Re: [Tutor] A fun puzzle > >Dick Moores wrote: >>At 10:22 AM 8/24/2007, Kent Johnson wrote: >>>So you actually pasted that code into timeit.py? >>Yeah. :-( I think I learned on the Tutor list to do it that way, but >>I'm not sure. Thanks for showing me a correct way. > >I hope not! > >>>Using timeit more conventionally I get unsurprising results. This >>>program has output: >>>0.497083902359 >>>0.359513998032 >>> >>>which is more in line with what I would expect. >>Using your exact code, I just got >>0.737564690484 >>1.17399585702 >>Which is the reverse of your result, but on a slower computer. >>What's up with that?? > > >Kent, > >That result was gotten using Ulipad. Thought I'd try it at my command >line (several times, of course--I've reported what seemed to be >representative data). > >Using command line: >0.673447044247 >0.511676204657 > >Using IDLE: >0.845213567646 >0.685519807685 > >Using Wing Pro (executing with Alt+F5) >0.940486290855 >0.998467123615 > >Is it possible that the timeit module should be used only at the command line? > >Dick The IDLE numbers match those on my machine to within 0.001. For what it is worth. From kent37 at tds.net Fri Aug 24 23:06:47 2007 From: kent37 at tds.net (Kent Johnson) Date: Fri, 24 Aug 2007 17:06:47 -0400 Subject: [Tutor] A fun puzzle In-Reply-To: <20070824203032.827EA1E4011@bag.python.org> References: <20070824203032.827EA1E4011@bag.python.org> Message-ID: <46CF4867.50002@tds.net> Dick Moores wrote: >> Using your exact code, I just got >> 0.737564690484 >> 1.17399585702 >> Which is the reverse of your result, but on a slower computer. > > That result was gotten using Ulipad. Thought I'd try it at my command > line (several times, of course--I've reported what seemed to be > representative data). > > Using command line: > 0.673447044247 > 0.511676204657 > > Using IDLE: > 0.845213567646 > 0.685519807685 > > Using Wing Pro (executing with Alt+F5) > 0.940486290855 > 0.998467123615 Curiouser and curiouser... > Is it possible that the timeit module should be used only at the command line? No, you should be able to use it anywhere Python works. I get very similar results running it Terminal and from TextMate... Kent From wormwood_3 at yahoo.com Fri Aug 24 23:27:11 2007 From: wormwood_3 at yahoo.com (wormwood_3) Date: Fri, 24 Aug 2007 14:27:11 -0700 (PDT) Subject: [Tutor] Spawning terminals from Python - A failed question Message-ID: <605324.95222.qm@web32410.mail.mud.yahoo.com> Hello all, I had this question all written up, then found I had the answer:-) So I decided to share anyway in case anyone found it useful ---------------------------------- I am trying to write a script that will open terminal windows for me, based on certain criteria. In this case, gnome-terminals, in Ubuntu, but my question is more general: How do I launch a command from a script and having it continue running? The pertinent part of my script right now: # Spawn the 4 terminals, with needed positions and sizes, then exit quietly: "gnome-terminal --geometry=%dx%d+%d+%d" % (t1width, t1height, t1posx, t1posy) "gnome-terminal --geometry=%dx%d+%d+%d" % (t2width, t2height, t2posx, t2posy) "gnome-terminal --geometry=%dx%d+%d+%d" % (t3width, t3height, t3posx, t3posy) "gnome-terminal --geometry=%dx%d+%d+%d" % (t4width, t4height, t4posx, t4posy) I need something to pass these lines to of course, to actually launch them. I thought first of the commands module (http://docs.python.org/lib/module-commands.html), but I don't:q want to get status or output, I want to basically spawn the process so it keeps running regardless of what the script does next (like running something with " &" after it in linux). ----------------------------------- All I ended up having to do was: >>> import commands >>> commands.getoutput("gnome-terminal") ... >>> And the terminal launched. When I closed the interpreter, the terminal stayed open fine. So getoutput() was the ticket. -Sam From alan.gauld at btinternet.com Sat Aug 25 00:04:28 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 24 Aug 2007 23:04:28 +0100 Subject: [Tutor] Spawning terminals from Python - A failed question References: <605324.95222.qm@web32410.mail.mud.yahoo.com> Message-ID: "wormwood_3" wrote > want to basically spawn the process so it keeps running regardless > of what the script does next (like running something with " &" after > it in linux). Umm, so just put the ampersand at the end of the command string and call os.system() > All I ended up having to do was: >>>> import commands >>>> commands.getoutput("gnome-terminal") However both os.system and the commands module are deprecated in favour of the new(ish) subprocess module where the equivalent incantation would be: p = subprocess.Popen("gnome-terminal", shell=True)HTH,-- Alan GauldAuthor of the Learn to Program web sitehttp://www.freenetpages.co.uk/hp/alan.gauld From trey at opmstech.org Sat Aug 25 00:11:06 2007 From: trey at opmstech.org (Trey Keown) Date: Fri, 24 Aug 2007 17:11:06 -0500 (CDT) Subject: [Tutor] Read dictionary data in a specific order... Message-ID: <62811.208.97.187.133.1187993466.squirrel@webmail.opmstech.org> Hello. I would like to know, how can I read (or sort) a dictionary in a certain order? say this is my dictionary- attrs={u'title': u'example window title', u'name': u'SELF', u'icon': u'e.ico'} how could I get the data so that u'name' is read first, u'title' second, and u'icon' third? thanks so much for any help- Trey From ricaraoz at gmail.com Fri Aug 24 16:06:03 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Fri, 24 Aug 2007 11:06:03 -0300 Subject: [Tutor] HOWTO: adding to sys.path the simplest way. In-Reply-To: <200708231717.13266.tim@johnsons-web.com> References: <200708231717.13266.tim@johnsons-web.com> Message-ID: <46CEE5CB.2050209@bigfoot.com> Tim Johnson wrote: > I have a seperate library directory both on my work station on > the the remote servers that I write applications for.. > > I commonly use sys.path.append('/path/to/mylibraries') in my > python code. > > That code has to be placed in any standalone script that I write. > I can also place that path in a system file. On my kubuntu > workstation, it is /var/lib/python-support/python2.5/.path > > I believe that path is different on the solaris or redhat servers > that I provide scripts to. Furthermore, any update of the python version > will necessitate editing of the new .path file. > > I would welcome some opinions on this matter. > Thanks > Tim > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > You might put your libraries in your development directory : /path/devel /path/devel/mylibraries /path/devel/mylibraries/graphiclibraries /path/devel/mylibraries/databaselibraries /path/devel/myapplications/mynewapplication Then inside /path/devel/myapplications/mynewapplication/myprogram.py when you want to access a module you just write : import mylibraries.mygeneralmodule from mylibraries.mygeneralmodule import x import mylibraries.graphiclibraries.mygraphiclibrary from mylibraries.graphiclibraries.mygraphiclibrary import x import mylibraries.databaselibraries.mygraphiclibrary from mylibraries.databaselibraries.mygraphiclibrary import x Of course /path/devel must be in your path, but as long as the rest of the structure remains unchanged you may place your stuff anywhere. HTH From ricaraoz at gmail.com Fri Aug 24 16:19:35 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Fri, 24 Aug 2007 11:19:35 -0300 Subject: [Tutor] the and command In-Reply-To: References: <8CC3B8AA-E03A-4C7E-874F-BBF9153EECE1@gmail.com> Message-ID: <46CEE8F7.7040607@bigfoot.com> Alan Gauld wrote: > "max baseman" wrote >> im checking if a number is in all 5 of the other lists and when >> i use the and command it seems to just be checking if it's in a >> least >> one of the others, > > >> for num in l2 and l3 and l4 and l5 and l6: # here seems to be the > > Try: > > if num in I2 and num in I3 and num in I4 and num in I5 and num in I6: > or also : if num in l1 + l2 + l3 + l4 + l5 : > In your case you are 'and'ing the lists which is a boolean expression > and because of how Python does short circuit evaluation it returns > the last list > >>>> a = [1,2] >>>> b = [3,4] >>>> a and b > [3, 4] > > so > > for n in a and b: > > is the same as > > for n in b: > > which iterates over b... > > HTH, > From kent37 at tds.net Sat Aug 25 01:13:29 2007 From: kent37 at tds.net (Kent Johnson) Date: Fri, 24 Aug 2007 19:13:29 -0400 Subject: [Tutor] the and command In-Reply-To: <46CEE8F7.7040607@bigfoot.com> References: <8CC3B8AA-E03A-4C7E-874F-BBF9153EECE1@gmail.com> <46CEE8F7.7040607@bigfoot.com> Message-ID: <46CF6619.6040307@tds.net> Ricardo Ar?oz wrote: > Alan Gauld wrote: >> "max baseman" wrote >>> im checking if a number is in all 5 of the other lists and when >>> i use the and command it seems to just be checking if it's in a >>> least >>> one of the others, >> >>> for num in l2 and l3 and l4 and l5 and l6: # here seems to be the >> Try: >> >> if num in I2 and num in I3 and num in I4 and num in I5 and num in I6: >> > > or also : if num in l1 + l2 + l3 + l4 + l5 : No, that has a different meaning, it is true if num is in *any* of the lists; the original version requires num to be in *all* of the lists. Also your version will compute the sum of lists every time through the loop which you don't really want... Kent From alan.gauld at btinternet.com Sat Aug 25 01:41:18 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 25 Aug 2007 00:41:18 +0100 Subject: [Tutor] Read dictionary data in a specific order... References: <62811.208.97.187.133.1187993466.squirrel@webmail.opmstech.org> Message-ID: "Trey Keown" wrote > I would like to know, how can I read (or sort) a dictionary in a > certain > order? Dictionaries are by design unsorted and indeed may even change their order during their lifetime. > attrs={u'title': u'example window title', u'name': u'SELF', u'icon': > u'e.ico'} > how could I get the data so that u'name' is read first, u'title' > second, > and u'icon' third? Normally you would sort the keys of the dictionary but since your order is not a natural sort order then the easiest way is probably to create a list of the keys you want in the order you want them. Thus: keys = ['name','title','icon'] for key in keys: print attrs[key] HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From wormwood_3 at yahoo.com Sat Aug 25 02:52:12 2007 From: wormwood_3 at yahoo.com (wormwood_3) Date: Fri, 24 Aug 2007 17:52:12 -0700 (PDT) Subject: [Tutor] Spawning terminals from Python - A failed question Message-ID: <542743.57840.qm@web32408.mail.mud.yahoo.com> >>Umm, so just put the ampersand at the end of the command string and >>call os.system() Not sure what the point of this variation would be if os is being deprecated along with commands... >>However both os.system and the commands module are deprecated in >>favour >>of the new(ish) subprocess module where the equivalent incantation >>would be: >>p = subprocess.Popen("gnome-terminal", shell=True)HTH,-- Alan Good to know! I will start using this instead. -Sam From trey at opmstech.org Sat Aug 25 03:56:32 2007 From: trey at opmstech.org (Trey Keown) Date: Fri, 24 Aug 2007 20:56:32 -0500 (CDT) Subject: [Tutor] Read dictionary data in a specific order... Message-ID: <63328.208.97.187.133.1188006992.squirrel@webmail.opmstech.org> > "Trey Keown" wrote > >> I would like to know, how can I read (or sort) a dictionary in a >> certain >> order? > > Dictionaries are by design unsorted and indeed may even change > their order during their lifetime. > >> attrs={u'title': u'example window title', u'name': u'SELF', u'icon': >> u'e.ico'} >> how could I get the data so that u'name' is read first, u'title' >> second, >> and u'icon' third? > > Normally you would sort the keys of the dictionary but since > your order is not a natural sort order then the easiest way is > probably to create a list of the keys you want in the order you > want them. Thus: > > keys = ['name','title','icon'] > for key in keys: print attrs[key] > ---------------------------------------------------------------------- Okay, the reason I need to know this is that expat, my xml parsing module, returns the attributes of an xml element as a dictionary. Now that i've done what you recommended above, my xml parsing program returns the dictionary's value as the value and the tag. here's my code- """"""""""""""""""""""""""""""""""""" ... global window_attrs_key_order window_attrs_key_order = ["name", "title", "icon"] def start_element(name, attrs): global window_attrs_key_order if name in acceptedelements: ...... if name == "window": print attrs.iteritems() for (tag,val) in attrs.iteritems(): if tag in window_attrs_key_order: for tag in window_attrs_key_order: if tag == u"name": print "%s%s = Tk()" %(whitespace, val) print "***^^^%s^^^***" %val whatwindow = val if tag == u"title": print "%s%s.title(\"%s\")" % (whitespace, whatwindow, val) if tag == u"icon": if val == "NONE": print "#---->NO ICON" else: print "%s%s.iconbitmap(\"%s\")" %(whitespace, whatwindow, val) else: print "#-----Error, unrecognized attribute in window element...-----" ...... """"""""""""""""""""""""""""""""""""" here's a likely example of what expat would spit out the attributes as- """"""""""""""""""""""""""""""""""""" attrs={u'title': u'example window title', u'name': u'SELF', u'icon': u'e.ico'} """"""""""""""""""""""""""""""""""""" and the program output is this- """"""""""""""""""""""""""""""""""""" ...... Example Window Title = Tk() ***^^^Example Window Title^^^*** Example Window Title.title("Example Window Title") Example Window Title.iconbitmap("Example Window Title") SELF = Tk() ***^^^SELF^^^*** SELF.title("SELF") SELF.iconbitmap("SELF") e.ico = Tk() ***^^^e.ico^^^*** e.ico.title("e.ico") e.ico.iconbitmap("e.ico") """"""""""""""""""""""""""""""""""""" why would you think that the program would do this? Trey From ghashsnaga at gmail.com Sat Aug 25 06:59:02 2007 From: ghashsnaga at gmail.com (Ara Kooser) Date: Fri, 24 Aug 2007 22:59:02 -0600 Subject: [Tutor] Question about classes Message-ID: <2107481c0708242159gbeccf6enad3bf1c5b075eb0e@mail.gmail.com> Hello all, I am working on trying to understand classes by creating a character generator for a rpg. I know I am doing something silly but I am not sure what. When I run the program I and type no when prompted I get the following message: Traceback (most recent call last): File "/Users/ara/Documents/ct_generator.py", line 10, in class Main: File "/Users/ara/Documents/ct_generator.py", line 68, in Main reroll() File "/Users/ara/Documents/ct_generator.py", line 53, in reroll upp() NameError: global name 'upp' is not defined I guess it doesn't recognize that I want to call the function upp() again. I think I might be using the wrong syntax here. My code is below. Thank you any help or guidance. Ara ################################################################################### #Version: not even 0.1 #By: Ara Kooser # #################################################################################### import random class Main: print """Welcome to the Classic Traveller character generator. Written in Python""" print """Press return to generate a character""" raw_input() def upp(): print """Generating your UPP.""" print strength = 0 dexterity = 0 endurance = 0 intelligence = 0 education = 0 social = 0 strength = random.randrange(2,12) dexterity = random.randrange(2,12) endurance = random.randrange(2,12) intelligence = random.randrange(2,12) education = random.randrange(2,12) social = random.randrange(2,12) return strength, dexterity, endurance, intelligence, education, social print upp() def reroll(): a = raw_input("Are you satisfied with your UPP? Choose yes or no.").lower() try: if a == "yes": career() elif a == "no": upp() else: print "Please choose a valid option." print reroll() except ValueError: print "Please choose a valid option." print reroll() return print """You have a chance to reroll if needed.""" reroll() def career(): print """You will now choose are career path for your character.""" -- Quis hic locus, quae regio, quae mundi plaga. Ubi sum. Sub ortu solis an sub cardine glacialis ursae. From noufal at airtelbroadband.in Sat Aug 25 08:23:11 2007 From: noufal at airtelbroadband.in (Noufal Ibrahim) Date: Sat, 25 Aug 2007 11:53:11 +0530 Subject: [Tutor] Question about classes In-Reply-To: <2107481c0708242159gbeccf6enad3bf1c5b075eb0e@mail.gmail.com> References: <2107481c0708242159gbeccf6enad3bf1c5b075eb0e@mail.gmail.com> Message-ID: <46CFCACF.7050601@airtelbroadband.in> Ara Kooser wrote: > Hello all, > > I am working on trying to understand classes by creating a > character generator for a rpg. I know I am doing something silly but I > am not sure what. When I run the program I and type no when prompted I > get the following message: > Traceback (most recent call last): > File "/Users/ara/Documents/ct_generator.py", line 10, in > class Main: > File "/Users/ara/Documents/ct_generator.py", line 68, in Main > reroll() > File "/Users/ara/Documents/ct_generator.py", line 53, in reroll > upp() > NameError: global name 'upp' is not defined > > I guess it doesn't recognize that I want to call the function upp() > again. I think I might be using the wrong syntax here. My code is > below. Thank you any help or guidance. In Python, if you want to call an object method, you have to do so explicitly via the object. Otherwise, it looks for a local/global variable of the same name. For example, def foo(): print "I am foo!" class Foo(object): def __init__(self): pass def foo(self): print "I am Foo.foo" def display(self): self.foo() foo() >>> x=Foo() >>> x.display() I am Foo.foo I am foo! All objects methods are passed the object instance explicitly as their first argument. It's conventionally called "self" (similar to the "this" pointer in C++ if you're familiar with it). Let me know if there's something that's not clear. -- ~noufal From rabidpoobear at gmail.com Sat Aug 25 09:20:03 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sat, 25 Aug 2007 02:20:03 -0500 Subject: [Tutor] Spawning terminals from Python - A failed question In-Reply-To: <542743.57840.qm@web32408.mail.mud.yahoo.com> References: <542743.57840.qm@web32408.mail.mud.yahoo.com> Message-ID: <46CFD823.7030609@gmail.com> wormwood_3 wrote: >>> Umm, so just put the ampersand at the end of the command string and >>> call os.system() >>> > > Not sure what the point of this variation would be if os is being deprecated along with commands... > He was pointing out that you already had a workable solution with os.system but you didn't take the time to think if your current tool set could be used to perform the task, and instead invested the time in searching for the commands module. -Luke > >>> However both os.system and the commands module are deprecated in >>> favour >>> of the new(ish) subprocess module where the equivalent incantation >>> would be: >>> p = subprocess.Popen("gnome-terminal", shell=True)HTH,-- Alan >>> > > Good to know! I will start using this instead. > > -Sam > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From alan.gauld at btinternet.com Sat Aug 25 10:26:54 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 25 Aug 2007 09:26:54 +0100 Subject: [Tutor] Read dictionary data in a specific order... References: <63328.208.97.187.133.1188006992.squirrel@webmail.opmstech.org> Message-ID: "Trey Keown" wrote > window_attrs_key_order = ["name", "title", "icon"] > for (tag,val) in attrs.iteritems(): > for (tag,val) in attrs.iteritems(): > if tag in window_attrs_key_order: > for tag in window_attrs_key_order: > if tag == u"name": > print "%s%s = Tk()" %(whitespace, val) > print "***^^^%s^^^***" %val > whatwindow = val > if tag == u"title": > print "%s%s.title(\"%s\")" % (whitespace, whatwindow, val) > if tag == u"icon": > print "%s%s.iconbitmap(\"%s\")" %(whitespace, whatwindow, > val) > """"""""""""""""""""""""""""""""""""" > attrs={u'title': u'example window title', u'name': u'SELF', u'icon': > u'e.ico'} > """"""""""""""""""""""""""""""""""""" > ...... > Example Window Title = Tk() > ***^^^Example Window Title^^^*** > Example Window Title.title("Example Window Title") > Example Window Title.iconbitmap("Example Window Title") > SELF = Tk() > ***^^^SELF^^^*** > SELF.title("SELF") > SELF.iconbitmap("SELF") > e.ico = Tk() > ***^^^e.ico^^^*** > e.ico.title("e.ico") > e.ico.iconbitmap("e.ico") > """"""""""""""""""""""""""""""""""""" > > why would you think that the program would do this? Odd. I'd try a few things: 1) I'd make the keylist use unicode strings since thats what you use elsewhere. 2) I'd put a debugging print statement in at the top of the for loop to print out the tag values. That will show exactly what tag is set to and prove that the loop is being executed and how often 3) change the name of tag in the inner loop since as it is you are masking the name in the outer loop which is likely to cause strange behaviour. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Sat Aug 25 10:30:10 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 25 Aug 2007 09:30:10 +0100 Subject: [Tutor] Read dictionary data in a specific order... References: <63328.208.97.187.133.1188006992.squirrel@webmail.opmstech.org> Message-ID: "Trey Keown" wrote I just spotted something. > for (tag,val) in attrs.iteritems(): > for tag in window_attrs_key_order: > print "%s%s = Tk()" %(whitespace, val) etc... You set tag and val in the outer loop, then you change tag in the innrter loop but you never change val. Thus for each tag in your list you print the same val. Then you gpo bavk to the outer loop and do the same for the next val. You need to rething your variable naming and how you access the val. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From eric at abrahamsen.com Sat Aug 25 10:21:06 2007 From: eric at abrahamsen.com (Eric Abrahamsen) Date: Sat, 25 Aug 2007 16:21:06 +0800 Subject: [Tutor] Question about classes In-Reply-To: <2107481c0708242159gbeccf6enad3bf1c5b075eb0e@mail.gmail.com> References: <2107481c0708242159gbeccf6enad3bf1c5b075eb0e@mail.gmail.com> Message-ID: On Aug 25, 2007, at 12:59 PM, Ara Kooser wrote: > Hello all, > > I am working on trying to understand classes by creating a > character generator for a rpg. I know I am doing something silly but I > am not sure what. When I run the program I and type no when prompted I > get the following message: > Traceback (most recent call last): > File "/Users/ara/Documents/ct_generator.py", line 10, in > class Main: > File "/Users/ara/Documents/ct_generator.py", line 68, in Main > reroll() > File "/Users/ara/Documents/ct_generator.py", line 53, in reroll > upp() > NameError: global name 'upp' is not defined > > I guess it doesn't recognize that I want to call the function upp() > again. I think I might be using the wrong syntax here. My code is > below. Thank you any help or guidance. This is exactly the level I'm at right now, so I got all excited and tried to solve this properly. Unfortunately I've hit a new snag, which I hope the OP or someone else can help me solve. At least the below should represent progress. Instead of calling general methods inside your class, you'll want to use the __init__ method, and then call the other methods from inside that, so that when a new instance of the class is created, all the methods act on that one new instance. That's what the first response was saying. So under __init__ we create a dictionary of attributes, and run both __upp and __career, all on the one new object. Showstats might as well be a separate function, because you'll want that available to players at any time. The new problem is the while loop inside __upp. Every time I say "no", and it generates a new set of attributes, it seems to add another "layer" of unfinished = True, so that once I've got attributes I like, I need to say "yes" as many times as I said "no" before it will let me break out of the loop and go on my way. I guess this is because it's calling the entire method over again, but I don't really understand this, or how else to get around it. Any solutions (and, obviously, general corrections of the whole thing) would be appreciated. Yrs, Eric ================== import random class Character(object): """Welcome to the Classic Traveller character generator. Written in Python """ def __init__(self): print "Generating statistics for your new character..." self.atts = {} self.__upp() self.__career() def __upp(self): for att in ('strength', 'dexterity', 'endurance', 'intelligence', 'education', 'social'): self.atts[att] = random.randrange(2,12) self.showstats() unhappy = True while unhappy: a = raw_input("Are you satisfied with your UPP? Choose yes or no.").lower() if a == "yes": unhappy = False elif a == "no": print "Rerolling attributes..." self.__upp() else: print "Please choose a valid option." continue return def __career(self): print "This is where the next step would go" def showstats(self): print "Your character's attributes are:" for attribute, value in self.atts.items(): print "%s: %d" % (attribute.title(), value) me = Character() From alan.gauld at btinternet.com Sat Aug 25 10:48:56 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 25 Aug 2007 09:48:56 +0100 Subject: [Tutor] Question about classes References: <2107481c0708242159gbeccf6enad3bf1c5b075eb0e@mail.gmail.com> Message-ID: "Ara Kooser" wrote > I am working on trying to understand classes by creating a > character generator for a rpg. You are so ar off base at the moment that I suggest you go back to basics and try a much simpler class. Your MAIN is not really a class at all, it's a function. Classes represent things(ie Objects). Main is not a thing. Secondly classes should not contain any directly executable code such as print/raw_input etc (they can but it's bad practice) Instead, a class should just be a collection of data attruibutes and methods. In your case it would be more appropriate to create a Character class with methods to do whatever characters do... > import random > > class Main: > > print """Welcome to the Classic Traveller character generator. > Written in Python""" > print """Press return to generate a character""" > raw_input() > > > > def upp(): methods of classes should have a first parameter of 'self' > print """Generating your UPP.""" > print > > strength = 0 > dexterity = 0 > endurance = 0 > intelligence = 0 > education = 0 > social = 0 > > strength = random.randrange(2,12) > dexterity = random.randrange(2,12) > endurance = random.randrange(2,12) > intelligence = random.randrange(2,12) > education = random.randrange(2,12) > social = random.randrange(2,12) There is no point in setting them all to zero then initialising them again via randrange. Just do it once. > return strength, dexterity, endurance, intelligence, > education, social But in a class you wouldn't expect to return these values here you would expect to store them as attributes of an object and return the object. > print upp() > def reroll(): > > a = raw_input("Are you satisfied with your UPP? Choose yes or > no.").lower() > try: > > if a == "yes": > career() > > elif a == "no": > upp() > > else: > print "Please choose a valid option." > print > reroll() > > except ValueError: > print "Please choose a valid option." > print > reroll() > > return > > print """You have a chance to reroll if needed.""" > reroll() > > def career(): > print """You will now choose are career path for your > character.""" Basically you don;t really have a class here at all you have a main function calling other functions but because you've wrapped them in a class its confusing things. Try simplifying your class to just define the attributes, something like this: class Upp: def __init__(self): print "Creating your Upp" self.strength = random.randrange(2,12) self.dexterity = random.randrange(2,12) self.endurance = random.randrange(2,12) self.intelligence = random.randrange(2,12) self.education = random.randrange(2,12) self.social = random.randrange(2,12) def display(self) print """ strength = %s dexterity = %s endurance = %s intelligence = %s education = %s social = %s""" % (self.strength, self.dexterity,self.endurance, self. intelligence,self.education, self.social) Now in your main function you can create Upps like so: #create 3 Upps: players = [] for p in range(3): players.append(Upp()) # show the players we created for p in players: p.display() If that is not clear then you need to go back to the tutorials again and work through the basics of wqhat a class and object are. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From rabidpoobear at gmail.com Sat Aug 25 10:50:26 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sat, 25 Aug 2007 03:50:26 -0500 Subject: [Tutor] A fun puzzle In-Reply-To: <20070824194911.DC4601E4011@bag.python.org> References: <156304361588.20070822204055@columbus.rr.com> <46CCF229.9000802@tds.net> <20070823145247.92A561E400B@bag.python.org> <46CDA5C6.4080705@tds.net> <20070823164730.7EBB41E400B@bag.python.org> <46CDD6AB.2030207@tds.net> <20070824165305.7B5D81E4013@bag.python.org> <46CF13D7.9050002@tds.net> <20070824190457.KTOL5718.inaamta14.mail.tds.net@sccrmhc15.comcast.net> <46CF2D8F.8060102@tds.net> <20070824194911.DC4601E4011@bag.python.org> Message-ID: <46CFED52.5090609@gmail.com> Dick Moores wrote: > At 12:12 PM 8/24/2007, Kent Johnson wrote: >> Dick Moores wrote: >>> At 10:22 AM 8/24/2007, Kent Johnson wrote: >>>> So you actually pasted that code into timeit.py? >>> Yeah. :-( I think I learned on the Tutor list to do it that way, but >>> I'm not sure. Thanks for showing me a correct way. >> >> I hope not! >> >>>> Using timeit more conventionally I get unsurprising results. This >>>> program has output: >>>> 0.497083902359 >>>> 0.359513998032 >>>> >>>> which is more in line with what I would expect. >>> Using your exact code, I just got >>> 0.737564690484 >>> 1.17399585702 >>> Which is the reverse of your result, but on a slower computer. >>> What's up with that?? >> >> I have no idea. Some strange interaction with the memory cache? I'm >> running Python 2.5.1 on a MacBook Pro (Intel Core 2 Duo processor). >> How about you? > > Python 2.5; Dell Dimension 4600i; 2.80 gigahertz Intel Pentium 4. The > other day my computer guy put in a 512K stick of memory, making the > total 1024K. Wow, I don't think I've ever owned a computer with less than 32 Mb of memory! I hope you didn't pay him too much for that 1024K. > However, by doing so he shut off the dual channel memory. I understand > now that he should have put in a pair of 256k sticks to go with the > pair that were already there. Assuming you're meaning to talk about megabytes and not kilobytes, I'm not sure how easy it would be to get dual-channel 256 mb sticks anyway, the minimum I usually see is 512 (512x2 for 1024 total). Ah, never mind, I was wrong. Newegg has some 2x256MB sets for $30. -Luke From rabidpoobear at gmail.com Sat Aug 25 10:57:11 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sat, 25 Aug 2007 03:57:11 -0500 Subject: [Tutor] Help Request: Nested While commands In-Reply-To: <1187966860.5922.18.camel@Africa> References: <8CC3B8AA-E03A-4C7E-874F-BBF9153EECE1@gmail.com> <068F7CE0-320E-49E3-B7A0-C2082E8B8C1B@gmail.com> <46CED7D2.7090905@tds.net> <46CEE290.7090506@tds.net> <1187966860.5922.18.camel@Africa> Message-ID: <46CFEEE7.90501@gmail.com> Paul W Peterson wrote: > > Greeting! Greeting. Can you please make a new message next time you post to the list, instead of replying to an existing message and changing the subject line? There is more to an e-mail than just the subject, and threaded mail clients notice whether an e-mail is completely new or just a modified subject line, and consequently your e-mail was placed in the same thread as the "the and command" so your message got buried under an avalanche of unrelated discussion on my end. Thanks, -Luke From alan.gauld at btinternet.com Sat Aug 25 11:50:14 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 25 Aug 2007 10:50:14 +0100 Subject: [Tutor] Question about classes References: <2107481c0708242159gbeccf6enad3bf1c5b075eb0e@mail.gmail.com> Message-ID: "Eric Abrahamsen" wrote > The new problem is the while loop inside __upp. Every time I say > "no", and it generates a new set of attributes, it seems to add > another "layer" of unfinished = True, so that once I've got > attributes I like, I need to say "yes" as many times as I said "no" Welcome to the wacky world of recursion. You call __upp from inside __upp so you do indeed generate a new layer, in fact you start a new while loop. You need to move the while loop out into init, something like this: class Character(object): def __init__(self): happy = False while not happy: upp = _upp() upp.showstats() ok = raw_input('Happy now?[y/n] ') if ok[0] in 'yY': happy = True def _upp(self): # all the randrange stuff self.career() def career(self): # all the career stuff But actually I'd take the whole happy test stuff outside the class entirely and make it a function: def getCharacter(): happy = False while not happy: upp = Character() upp.showstats() ok = raw_input('Happy now?[y/n] ') if ok[0] in 'yY': happy = True And the init becomes: def __init__(self) self._upp() self._career() That way the class only has to deal with creating an object and is much more reusable. Similarly for the career stuff, I'd put all the user interaction outside the class and then pass some kind of parameter(s) into the init method which passes them along to the career method def __init__(self, info=None) self._upp() if info == None: info = self.getCareerInfo() # does the interaction stuff if necessary self._career(info) HTH, Alan G. From eric at abrahamsen.com Sat Aug 25 12:20:29 2007 From: eric at abrahamsen.com (Eric Abrahamsen) Date: Sat, 25 Aug 2007 18:20:29 +0800 Subject: [Tutor] Question about classes In-Reply-To: References: <2107481c0708242159gbeccf6enad3bf1c5b075eb0e@mail.gmail.com> Message-ID: > Welcome to the wacky world of recursion. > You call __upp from inside __upp so you do indeed generate > a new layer, in fact you start a new while loop. You need to > move the while loop out into init, something like this: So all those "yes"s were actually backing out of multiple while loops... Should have guessed that calling a method from inside itself was a bad idea. Thanks for your help, E From alan.gauld at btinternet.com Sat Aug 25 14:42:15 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 25 Aug 2007 13:42:15 +0100 Subject: [Tutor] Question about classes References: <2107481c0708242159gbeccf6enad3bf1c5b075eb0e@mail.gmail.com> Message-ID: "Eric Abrahamsen" wrote >> Welcome to the wacky world of recursion. >> You call __upp from inside __upp so you do indeed generate >> a new layer, in fact you start a new while loop. You need to > > So all those "yes"s were actually backing out of multiple while > loops... Should have guessed that calling a method from inside > itself > was a bad idea. Actually recursion is a very powerful construction and not at all a bad idea, but it needs to be carefully controlled - as you discovered - but I have a topic on it in my tutorial (in the 'advanced' section) if you want to see some of the things it can be used for. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Sat Aug 25 15:19:00 2007 From: kent37 at tds.net (Kent Johnson) Date: Sat, 25 Aug 2007 09:19:00 -0400 Subject: [Tutor] Question about classes In-Reply-To: <2107481c0708242159gbeccf6enad3bf1c5b075eb0e@mail.gmail.com> References: <2107481c0708242159gbeccf6enad3bf1c5b075eb0e@mail.gmail.com> Message-ID: <46D02C44.6040401@tds.net> Ara Kooser wrote: > Hello all, > > I am working on trying to understand classes by creating a > character generator for a rpg. I know I am doing something silly but I > am not sure what. This is a procedural program wrapped in a class declaration. Just get rid of "class Main:" and outdent everything and it will work better. It is rare to have code other than function definitions (methods) and simple assignment (class attributes) in the body of a class. You might want to gather all the top-level code into a main() function and call that once, rather than intermingling the top-level code with the function definitions. You need to do a bit more reading about classes in Python, you clearly misunderstand. I don't have time to explain now but try the beginner tutorials. Kent > When I run the program I and type no when prompted I > get the following message: > Traceback (most recent call last): > File "/Users/ara/Documents/ct_generator.py", line 10, in > class Main: > File "/Users/ara/Documents/ct_generator.py", line 68, in Main > reroll() > File "/Users/ara/Documents/ct_generator.py", line 53, in reroll > upp() > NameError: global name 'upp' is not defined > > I guess it doesn't recognize that I want to call the function upp() > again. I think I might be using the wrong syntax here. My code is > below. Thank you any help or guidance. > > Ara > > ################################################################################### > #Version: not even 0.1 > #By: Ara Kooser > # > #################################################################################### > > import random > > > class Main: > > > > print """Welcome to the Classic Traveller character generator. > Written in Python""" > print """Press return to generate a character""" > > raw_input() > > > > def upp(): > print """Generating your UPP.""" > print > > strength = 0 > dexterity = 0 > endurance = 0 > intelligence = 0 > education = 0 > social = 0 > > strength = random.randrange(2,12) > dexterity = random.randrange(2,12) > endurance = random.randrange(2,12) > intelligence = random.randrange(2,12) > education = random.randrange(2,12) > social = random.randrange(2,12) > > return strength, dexterity, endurance, intelligence, education, social > > > print upp() > > def reroll(): > > a = raw_input("Are you satisfied with your UPP? Choose yes or > no.").lower() > try: > > if a == "yes": > career() > > elif a == "no": > upp() > > else: > print "Please choose a valid option." > print > reroll() > > except ValueError: > print "Please choose a valid option." > print > reroll() > > return > > print """You have a chance to reroll if needed.""" > reroll() > > def career(): > print """You will now choose are career path for your character.""" > > > > > > > > > > > > > From tinoloc at gmail.com Sat Aug 25 18:31:54 2007 From: tinoloc at gmail.com (Tino Dai) Date: Sat, 25 Aug 2007 12:31:54 -0400 Subject: [Tutor] using in over several entities In-Reply-To: <46CF27DC.3080709@unc.edu> References: <46CEFBE3.3000601@unc.edu> <46CF27DC.3080709@unc.edu> Message-ID: On 8/24/07, Chris Calloway wrote Thanks everybody for their assistance! Makes my code a lot more elegant. -Tino -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070825/4ea6d3e6/attachment.htm From eric at abrahamsen.com Sun Aug 26 10:10:49 2007 From: eric at abrahamsen.com (Eric Abrahamsen) Date: Sun, 26 Aug 2007 16:10:49 +0800 Subject: [Tutor] sorting lists in dictionary values Message-ID: <5CE9A9D8-2CFB-4752-B559-AD5143E502E6@abrahamsen.com> I wrote the stupid little script below for practice; it takes a text file with a list of surnames, and returns a dictionary where the keys are first letters of the names, and the values are lists of names grouped under their appropriate first-letter key, like so: {'A': ['Abercrombie'], 'B': ['Barnaby', 'Black', 'Biggles'], 'D': ['Douglas', 'Dawn', 'Diggle'], 'G': ['Granger', 'Gossen']} This is all well and good, but I want to sort the names in place, so that the names in each list are alphabetical. I tried slapping a sort () onto the dictionary list comprehension in every configuration I could think of. I even replaced the one-line comprehension with a two- step deal, like so: for item in letters: little_list = [name for name in names if name.startswith(item)] phonebook[item] = little_list.sort() That didn't work either, which I thought was very strange. Can anyone help? Another tangential question: why can't I do away with having a separate names = [] list variable, and write the comprehension as: for item in letters: phonebook[item] = [line.strip('\n') for line in x if line.startswith (item)] Many thanks, Eric ================ x = file('/path/to/file.txt', 'r') letters = set() names = [] phonebook = {} for line in x: y = line[0].upper() letters.add(y) names.append(line.strip('\n ')) for item in letters: phonebook[item] = [name for name in names if name.startswith(item)] print phonebook -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070826/30ae9b10/attachment.htm From eric at abrahamsen.com Sun Aug 26 11:43:32 2007 From: eric at abrahamsen.com (Eric Abrahamsen) Date: Sun, 26 Aug 2007 17:43:32 +0800 Subject: [Tutor] sorting lists in dictionary values In-Reply-To: <46D14028.4000105@free.fr> References: <5CE9A9D8-2CFB-4752-B559-AD5143E502E6@abrahamsen.com> <46D14028.4000105@free.fr> Message-ID: <06A38641-2BA7-4C6F-A5C1-6C722AA9E464@abrahamsen.com> > From noob to noob : sort sorts in place. I seem to remember it > returns nothing. > > This works: > > In [12]: directoryOut[12]: > {'A': ['Abercrombie', 'Aalberg'], > 'B': ['Barnaby', 'Black', 'Biggles'], > 'D': ['Douglas', 'Dawn', 'Diggle'], > 'G': ['Granger', 'Gossen']} > > In [13]: for key in directory: > directory[key].sort() > > In [14]: directory > Out[14]: > {'A': ['Aalberg', 'Abercrombie'], > 'B': ['Barnaby', 'Biggles', 'Black'], > 'D': ['Dawn', 'Diggle', 'Douglas'], > 'G': ['Gossen', 'Granger']} > > Please let me know if I'm wrong! > > Best > > Chris Beautiful, that works perfectly. A single line added to the list comprehension: for item in letters: phonebook[item] = [name for name in names if name.startswith(item)] phonebook[item].sort() and all is well. Thanks for the help, Eric From tknierim at mail.ieway.com Sun Aug 26 02:02:42 2007 From: tknierim at mail.ieway.com (Daniel Knierim) Date: Sun, 26 Aug 2007 00:02:42 GMT Subject: [Tutor] How to put an event into the Tcl/Tk event queue? Message-ID: <200708251702125.SM07212@66.193.33.4> Hi All, I'm starting to learn how to use the TkInter module. So far I've got a couple versions of 'hello world' working. I'd like to simulate user input to TkInter applications from another Python script, by inserting events in the Tcl event queue. Tcl/Tk has a couple functions for this (Tk_QueueWindowEvent and Tcl_QueueEvent). Is there a Python interface for either of those? I can't find any... My second choice would be to use Tcl_CreateEventSource, but I don't see a Python interface for that, either. I'd rather not work through the actual GUI interface if I can avoid it. Thanks - Dan K. From paulino1 at sapo.pt Sun Aug 26 13:09:13 2007 From: paulino1 at sapo.pt (paulino1 at sapo.pt) Date: Sun, 26 Aug 2007 12:09:13 +0100 Subject: [Tutor] client server apps In-Reply-To: References: Message-ID: <20070826120913.xcua7w55w08k8kok@w7.mail.sapo.pt> Hi! What's the point in having a server app between the user frontend and a database backend? (As is the case of TinyERP wich is writen in python-GTK) Can't simillar functionality be achieved without that server? What are the main pro's and con's? Thank you! Paulino From ricaraoz at gmail.com Sun Aug 26 14:03:42 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Sun, 26 Aug 2007 09:03:42 -0300 Subject: [Tutor] sorting lists in dictionary values In-Reply-To: <5CE9A9D8-2CFB-4752-B559-AD5143E502E6@abrahamsen.com> References: <5CE9A9D8-2CFB-4752-B559-AD5143E502E6@abrahamsen.com> Message-ID: <46D16C1E.70404@bigfoot.com> Eric Abrahamsen wrote: > I wrote the stupid little script below for practice; it takes a text > file with a list of surnames, and returns a dictionary where the keys > are first letters of the names, and the values are lists of names > grouped under their appropriate first-letter key, like so: > > {'A': ['Abercrombie'], 'B': ['Barnaby', 'Black', 'Biggles'], 'D': > ['Douglas', 'Dawn', 'Diggle'], 'G': ['Granger', 'Gossen']} > > This is all well and good, but I want to sort the names in place, so > that the names in each list are alphabetical. I tried slapping a sort() > onto the dictionary list comprehension in every configuration I could > think of. I even replaced the one-line comprehension with a two-step > deal, like so: > > for item in letters: > little_list = [name for name in names if name.startswith(item)] > phonebook[item] = little_list.sort() > > That didn't work either, which I thought was very strange. Can anyone help? > > Another tangential question: why can't I do away with having a separate > names = [] list variable, and write the comprehension as: > > for item in letters: > phonebook[item] = [line.strip('\n') for line in x if line.startswith(item)] > > > Many thanks, > Eric > > ================ > x = file('/path/to/file.txt', 'r') > letters = set() > names = [] > phonebook = {} > for line in x: > y = line[0].upper() > letters.add(y) > names.append(line.strip('\n ')) > > for item in letters: > phonebook[item] = [name for name in names if name.startswith(item)] > > print phonebook > > ------------------------------------------------------------------------ > Try this : nameFile = open(r'/path/to/file.txt', 'rU') phonebook = {} for line in nameFile : phonebook.setdefault(line[0].upper(), []).append(line.strip('\n')) for item, names in phonebook.iteritems() : names.sort() print phonebook HTH From noufal at airtelbroadband.in Sun Aug 26 16:33:00 2007 From: noufal at airtelbroadband.in (Noufal Ibrahim) Date: Sun, 26 Aug 2007 20:03:00 +0530 Subject: [Tutor] client server apps In-Reply-To: <20070826120913.xcua7w55w08k8kok@w7.mail.sapo.pt> References: <20070826120913.xcua7w55w08k8kok@w7.mail.sapo.pt> Message-ID: <46D18F1C.4090904@airtelbroadband.in> paulino1 at sapo.pt wrote: > Hi! > > > What's the point in having a server app between the user frontend and > a database backend? (As is the case of TinyERP wich is writen in > python-GTK) > > Can't simillar functionality be achieved without that server? What are > the main pro's and con's? > Off the cuff, I think the layer would decouple your store (the db) and the UI. So, you can actually make a GUI, a web based UI etc. for the same application. Also, it would decouple your front end from a specific database. On the negative side, it's one more thing that needs to be written and maintained and is a point of failure especially when large number of clients connect simultaneously. I'd value the opinions of some of the more experienced programmers on this list. -- ~noufal From eric at abrahamsen.com Sun Aug 26 16:50:12 2007 From: eric at abrahamsen.com (Eric Abrahamsen) Date: Sun, 26 Aug 2007 22:50:12 +0800 Subject: [Tutor] sorting lists in dictionary values In-Reply-To: <46D16C1E.70404@bigfoot.com> References: <5CE9A9D8-2CFB-4752-B559-AD5143E502E6@abrahamsen.com> <46D16C1E.70404@bigfoot.com> Message-ID: <6FA92079-6212-42B7-B70D-90CA30E32459@abrahamsen.com> Whoa, this made my brain hurt. And I thought I was being clever using a set... I can't say I really understand this yet, but I'm trying. If anyone's following along at home I found this link kind of helpful: http://python.net/crew/mwh/hacks/setdefault.html Thanks a lot for your help, Eric > Try this : > > nameFile = open(r'/path/to/file.txt', 'rU') > phonebook = {} > > for line in nameFile : > phonebook.setdefault(line[0].upper(), []).append(line.strip('\n')) > > for item, names in phonebook.iteritems() : > names.sort() > > print phonebook > > HTH > From alan.gauld at btinternet.com Sun Aug 26 17:32:39 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 26 Aug 2007 16:32:39 +0100 Subject: [Tutor] client server apps References: <20070826120913.xcua7w55w08k8kok@w7.mail.sapo.pt> <46D18F1C.4090904@airtelbroadband.in> Message-ID: "Noufal Ibrahim" wrote >> What's the point in having a server app between the user frontend >> and >> a database backend? > Off the cuff, I think the layer would decouple your store (the db) > and > the UI. That's part of it but not the main reason. N-Teir was being touted long before web clients had been heard of! > On the negative side, it's one more thing that needs to be written > and > maintained and is a point of failure especially when large number of > clients connect simultaneously. Actually the latter scenario is the main reason for going 3-teir client server. The middle teir can be replicateed and thus a 3 teir (or more generally an N-Teir) application will scale much better. Most 2-teir C/S apps runout of steam with a few hundred concurrent users due to problems with the database locking and other types of contention. With a mid teir doing the business rules andcalculations you can generally wscale 3-teir up to 10's of thousands of concurrent users. Also because you have multiple servers for 10,000 users - say each handles 1000 users - then if one server goes down the rest keep functioning and you only lose service to 10% of your users. Even better if you have a layer of middleware doing the load balancing the users won't even know the server failed because their requests will be bounced to another server instance. The worst that happens is a time-out and an error message for the transaction that was running at the point of failure. Multi-teir also gives you much more flexibility over where to put the processing. Databases are very good at searching and sorting, but not usually very good at high intensity calculations. So by moving the math into the server and keeping the data access in the database you optimise performance. You can also create services that are usable across a range of applications using multiple databases - eg an image processing server. But that takes us into the realms of Service Oriented Architectures(SOA) Further, where an application is dispersed geographically an N-Teir solution can dramatically improve performance by reducing network delays. For example I worked on a customer service app for a global company with offices in Asia, Africa, the Middle East, Europe and North America. The main database was on a mainframe in Europe but we had intermediate app servers in South Africa, Australia (for all Asia) , two in the USA, and two in Europe(UK & Italy). During the trials (with only one server in the UK) we were getting 5 second plus transaction times in the US and Asia but after distributing the servers we got 1-2 seconds everywhere. Of course to make that work you have to design the transaction sequences to maximise caching etc, it's not automatic, but done right it can be a major boost to performance. Finally, by using intelligent caching, intermediate servers can partially protect from a database failure, since many transactions (especially read-only) can be carried out using most recently used data in a cache. This will typically be adequate to cover the downtime between the database going down and a cold standby being booted into life (say 10-20 minutes) and the network reconfigured. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Sun Aug 26 18:04:38 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 26 Aug 2007 17:04:38 +0100 Subject: [Tutor] How to put an event into the Tcl/Tk event queue? References: <200708251702125.SM07212@66.193.33.4> Message-ID: "Daniel Knierim" wrote > I'd like to simulate user input to TkInter applications from > another Python script, by inserting events in the Tcl event queue. There are two scenarios where I'd expect that to be needed: 1) To roboticise an existing app, particularly if you don;t have source code access. 2) testing a GUI. Other than that it's usually easier to go in at the level below the GUI and call the underlying commands directly. Is that a possibility here? > Tcl/Tk has a couple functions for this (Tk_QueueWindowEvent > and Tcl_QueueEvent). These were new to me and indeed don't appear in either of my Tcl refrence books (Ousterhout and O'Reilly Nutshell) Are they recent additions? > Is there a Python interface for either of those? I can't find > any... Neither can I. > My second choice would be to use Tcl_CreateEventSource, > but I don't see a Python interface for that, either. Nope, me neither. No references in my books and no Python/Tkinter equivalents. In fact my Tcl prompt doesn't recognise any of the 3 commands you cite. Are these actuially Tcl/Tk interpreter commands or C interface functions? Only interpreter commands are reproduced in Tkinter. > I'd rather not work through the actual GUI interface if I can avoid > it. Why do you need to work through the GUI events? Normally the GUI is there to connect humans to the back end code. If an app needs access to the back end code it can usually call the functions directly using more conventional IPC mechanisms. Thee are a couple of higher level methods that might be of use? send(app, cmd, *args) event_generate(sequence, option=...) Dunno if they will help. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From ghashsnaga at gmail.com Sun Aug 26 23:41:30 2007 From: ghashsnaga at gmail.com (Ara Kooser) Date: Sun, 26 Aug 2007 15:41:30 -0600 Subject: [Tutor] Question about calling functions Message-ID: <2107481c0708261441i5ea60537o33e33c8585388751@mail.gmail.com> Hello, After taking some suggestions from bhaaluu my program for generating a character works except for one part. You have a choice of excepting a set of numbers. If you choose n then the program dumps you into: def navy() instead of going back to def upp(). I am guessing this has to do with how I am calling the functions at the end of the program: ############################################################################### # start program here ############################################################################### print """Welcome to the Classic Traveller character generator. Written in Python""" print """Press return to generate a character""" raw_input() print upp() print """You have a chance to reroll if needed.""" reroll() navy() I see that after reroll() it goes to navy(). What I don't understand is why when you have a choose n it won't go back to upp(). Thanks. Ara PROGRAM BELOW ############################################################################################## # Version:0.3 # By: Ara Kooser ############################################################################################# import random strength = 0 dexterity = 0 endurance = 0 intelligence = 0 education = 0 social = 0 print """\nGenerating your UPP.""" print def upp(): global strength global dexterity global endurance global intelligence global education global social strength = random.randrange(2,12) dexterity = random.randrange(2,12) endurance = random.randrange(2,12) intelligence = random.randrange(2,12) education = random.randrange(2,12) social = random.randrange(2,12) return strength, dexterity, endurance, intelligence, education, social def reroll(): a = raw_input("Are you satisfied with your UPP? Choose yes or no.").lower() try: if a[0] == "y": career() elif a[0] == "n": upp() else: print "Please choose a valid option." print out = reroll() except: print "Please choose a valid option." print out = reroll() return def career(): print """You will now choose a career path for your character.""" print """Please choose your career path.""" print b = raw_input("Navy, Marines, Army, Scouts, Merchants").lower() try: if b[0] == "navy": out = navy() elif b[0] == "marines": marines() elif b[0] == "army": army() elif b[0] == "scouts": scouts() elif b[0] == "merchants": merchants() except: print "Please choose a valid option." print career() return def navy(): global strength global dexterity global endurance global intelligence global education global social print """You have selected a naval career.""" c = raw_input("How many terms of service do you want? 1,2,3,4,5") enlist = int(c) count = 0 rank = 0 age = 18 benefits = [] cash = [] skills = [] commission = False while count=10: commission = True print "You made commission" else: print "You did not make comission" if commission == True: prom = random.randrange(2,12) if prom>=8: rank=rank+1 print "Your rank is now" print rank else: print "You did not make promotion" pskill = random.randrange(1,6) if pskill == 1: strength=strength+1 elif pskill == 2: dexterity=dexterity+1 elif pskill == 3: endurance=endurance+1 elif pskill == 4: intelligence=intelligence+1 elif pskill == 5: education=education+1 elif pskill == 6: social=social+1 sskill = random.randrange(1,6) if sskill == 1: skills[1:1]=['Ships Boat'] elif sskill == 2: skills[1:1]=['Vacc Suit'] elif sskill == 3: skills[1:1]=['Fwd Obsvr'] elif sskill == 4: skills[1:1]=['Gunnery'] elif sskill == 5: skills[1:1]=['Blade Cbt'] elif sskill == 6: skills[1:1]=['Gun Cbt'] if education<8: aeskill = random.randrange(1,6) if aeskill == 1: skills[1:1]=['Vacc Suit'] elif aeskill == 2: skills[1:1]=['Mechanical'] elif aeskill == 3: skills[1:1]=['Electronic'] elif aeskill == 4: skills[1:1]=['Engineering'] elif aeskill == 5: skills[1:1]=['Gunnery'] elif aeskill == 6: skills[1:1]=['Jack-o-T'] if education>=8: ae8skill = random.randrange(1,6) if ae8skill == 1: skills[1:1]=['Medical'] elif ae8skill == 2: skills[1:1]=['Navigation'] elif ae8skill == 3: skills[1:1]=['Engineering'] elif ae8skill == 4: skills[1:1]=['Computer'] elif ae8skill == 5: skills[1:1]=['Pilot'] elif ae8skill == 6: skills[1:1]=['Admin'] print print"#################################" print "# Your UPP is:",strength, dexterity, endurance, intelligence, education, social print "# Your current rank is now:",rank print "# Your current age is now:",age print "#",skills print"#################################" return ############################################################################### # start program here ############################################################################### print """Welcome to the Classic Traveller character generator. Written in Python""" print """Press return to generate a character""" raw_input() print upp() print """You have a chance to reroll if needed.""" reroll() navy() -- Quis hic locus, quae regio, quae mundi plaga. Ubi sum. Sub ortu solis an sub cardine glacialis ursae. From carroll at tjc.com Mon Aug 27 01:07:01 2007 From: carroll at tjc.com (Terry Carroll) Date: Sun, 26 Aug 2007 16:07:01 -0700 (PDT) Subject: [Tutor] sorting lists in dictionary values In-Reply-To: <5CE9A9D8-2CFB-4752-B559-AD5143E502E6@abrahamsen.com> Message-ID: On Sun, 26 Aug 2007, Eric Abrahamsen wrote: > I wrote the stupid little script below for practice; it takes a text > file with a list of surnames, and returns a dictionary where the keys > are first letters of the names, and the values are lists of names > grouped under their appropriate first-letter key, like so: > > {'A': ['Abercrombie'], 'B': ['Barnaby', 'Black', 'Biggles'], 'D': > ['Douglas', 'Dawn', 'Diggle'], 'G': ['Granger', 'Gossen']} > > This is all well and good, but I want to sort the names in place, so > that the names in each list are alphabetical. I tried slapping a sort > () onto the dictionary list comprehension in every configuration I > could think of. You want sorted(), not sort(): >>> names = ['Abercrombie', 'Barnaby', 'Douglas', 'Granger', 'Black', 'Dawn','Gssen', 'Biggles', 'Diggle'] >>> from string import uppercase as letters >>> mydict={} >>> for letter in letters: ... mydict[letter] = sorted([name for name in names if name.startswith(letter)) ... >>> mydict {'A': ['Abercrombie'], 'C': [], 'B': ['Barnaby', 'Biggles', 'Black'], 'E': [], D': ['Dawn', 'Diggle', 'Douglas'], 'G': ['Gossen', 'Granger'], 'F': [], 'I': [] 'H': [], 'K': [], 'J': [], 'M': [], 'L': [], 'O': [], 'N': [], 'Q': [], 'P': [, 'S': [], 'R': [], 'U': [], 'T': [], 'W': [], 'V': [], 'Y': [], 'X': [], 'Z':]} >>> You can get rid of the empties... >>> for key in mydict.keys(): #Note: not "for key in mydict:" ... if mydict[key] == []: del mydict[key] ... >>> mydict {'A': ['Abercrombie'], 'B': ['Barnaby', 'Biggles', 'Black'], 'D': ['Dawn', 'Diggle', 'Douglas'], 'G': ['Gossen', 'Granger']} From alan.gauld at btinternet.com Mon Aug 27 01:57:46 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 27 Aug 2007 00:57:46 +0100 Subject: [Tutor] Question about calling functions References: <2107481c0708261441i5ea60537o33e33c8585388751@mail.gmail.com> Message-ID: "Ara Kooser" wrote > a character works except for one part. You have a choice of > excepting > a set of numbers. If you choose n then the program dumps you into: > def navy() instead of going back to def upp(). > > print upp() > print """You have a chance to reroll if needed.""" > reroll() > navy() When you exit reroll() you always go into navy() > I see that after reroll() it goes to navy(). What I don't understand > is why when you have a choose n it won't go back to upp(). Thanks. Because you have nothing to stop it going into reroll(). Thee is no if statement, it will always, without fail exit reroll and go into navy. (It may call upp() in between times but it will nonetheless go into navy after reroll finishes.) > strength = 0 > dexterity = 0 > endurance = 0 > intelligence = 0 > education = 0 > social = 0 > > def upp(): > global strength > global dexterity > global endurance > global intelligence > global education > global social > > strength = random.randrange(2,12) > dexterity = random.randrange(2,12) > endurance = random.randrange(2,12) > intelligence = random.randrange(2,12) > education = random.randrange(2,12) > social = random.randrange(2,12) > > return strength, dexterity, endurance, intelligence, education, > social You don't really need to return therse since they are the global values initialised at the top of the code. > def reroll(): > a = raw_input("Are you satisfied with your UPP? Choose yes or > no.").lower() > try: > if a[0] == "y": > career() > elif a[0] == "n": > upp() > else: > print "Please choose a valid option." > print > out = reroll() > > except: > print "Please choose a valid option." > print > out = reroll() You don't need the try/except since the is/elif/else will catch all possible cases. BUT you are assigning out to the return value of reroll() but reroll() never returns a value. So out will always equal None. This isn't much of a problem since you never use out anyway! You don't really need this function you could replace it with a while loop at the top level. Your use of nested calls is what is giving your odd behaviouir. You call upp() Then you call reroll() Inside reroll() you either call career() or call upp() again or call reroll() again If you call career() then, when it exits, you will exit reroll() and then call navy(). If you call upp() then, when it exits, you will exit reroll() and then call navy(). If you call reroll() then, when it exits, you will exit the outer reroll() and then call navy(). So whatever happens in reroll() you eventually wind up calling navy() > return This does nothing. > def career(): > b = raw_input("Navy, Marines, Army, Scouts, Merchants").lower() > try: > if b[0] == "navy": > out = navy() b[0] will be a character. You are comparing a character to a string. It will never equate. > elif b[0] == "marines": > elif b[0] == "army": > elif b[0] == "scouts": > elif b[0] == "merchants": Same for these > except: > print "Please choose a valid option." > print > career() The except will never get called(unl;ess one of the called functions raises an exception, which is fairly unlikely. > return Again, this does nothing > def navy(): > global strength > global dexterity > global endurance > global intelligence > global education > global social > > print """You have selected a naval career.""" > c = raw_input("How many terms of service do you want? 1,2,3,4,5") > > enlist = int(c) > count = 0 > > rank = 0 > age = 18 > benefits = [] > cash = [] > skills = [] > commission = False > > while count age=age+4 > count=count+1 > > if commission == False: > comm = random.randrange(2,12) > if comm>=10: > commission = True > print "You made commission" > else: > print "You did not make comission" > > > if commission == True: > prom = random.randrange(2,12) > if prom>=8: > rank=rank+1 > print "Your rank is now" > print rank You could simplify that to one line with: > print "Your rank is now", rank Or if you really want a separate line: > print "Your rank is now\n", rank > else: > print "You did not make promotion" > > > pskill = random.randrange(1,6) > if pskill == 1: > strength=strength+1 > > elif pskill == 2: > dexterity=dexterity+1 > > elif pskill == 3: > endurance=endurance+1 > > elif pskill == 4: > intelligence=intelligence+1 > > elif pskill == 5: > education=education+1 > > elif pskill == 6: > social=social+1 > > > sskill = random.randrange(1,6) > if sskill == 1: > skills[1:1]=['Ships Boat'] This is an unusual way of inserting entries to a list. It would be more common to use append or insert, as in: skills.append('Ships Boat') > elif sskill == 2: > elif sskill == 3: > elif sskill == 4: > elif sskill == 5: > elif sskill == 6: > if education<8: > aeskill = random.randrange(1,6) > if aeskill == 1: > elif aeskill == 2: > elif aeskill == 3: > elif aeskill == 4: > elif aeskill == 5: > elif aeskill == 6: > > if education>=8: > ae8skill = random.randrange(1,6) > if ae8skill == 1: > elif ae8skill == 2: > elif ae8skill == 3: > elif ae8skill == 4: > elif ae8skill == 5: > elif ae8skill == 6: You can almost certainly tidy this lot up using better data structures then it becomes a case of indexing into the data rather than all the if/elif steps. > print"#################################" > print "# Your UPP is:",strength, dexterity, endurance, > intelligence, education, social > print "# Your current rank is now:",rank > print "# Your current age is now:",age > print "#",skills > print"#################################" > > return > > > ############################################################################### > # start program here > ############################################################################### > print """Welcome to the Classic Traveller character generator. > Written in Python""" > print """Press return to generate a character""" > raw_input() > > > print upp() > print """You have a chance to reroll if needed.""" > > reroll() > navy() In general you will find life easier if you start with a simpler version of your program (only two or three characeristics/skills etc) and get the overall structure right. Its easier to debug and less code to write. Once its basically working adding extra features is easy. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From python at mrfab.info Mon Aug 27 11:04:33 2007 From: python at mrfab.info (Michael) Date: Mon, 27 Aug 2007 17:04:33 +0800 Subject: [Tutor] Need Some Help In-Reply-To: References: Message-ID: <46D293A1.70906@mrfab.info> Hi I have just taught myself some Python and among my resources were... http://www.ibiblio.org/obp/thinkCSpy/ - I worked my way through over half of this online and downloadable manual http://www.livewires.org.uk/python/index.html - This course is good, I am currently working through this but it is a good idea to have a bit of an idea about Python first, hence the previous site. http://www.freenetpages.co.uk/hp/alan.gauld/ - This looks good, I had been meaning to get to it but there are only so many hours... After that there are heaps of sites with tutorials and downloadable programmes for all sorts of specific uses of Python, just do a search. Michael chinni wrote: > Hi All, > > I am new to python.i need some help about python.i want to learn > python so plz guide me from where can i start.so,that i can learn and > under stand quickly. > > -- > Best Regards, > M.Srikanth Kumar, > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From python at mrfab.info Mon Aug 27 10:50:02 2007 From: python at mrfab.info (Michael) Date: Mon, 27 Aug 2007 16:50:02 +0800 Subject: [Tutor] validation Message-ID: <46D2903A.6010304@mrfab.info> Hi I am fairly new to Python and I wish to validate input. Such as wanting to check and make sure that an integer is entered and the program not crashing when a naughty user enters a character instead. I have been trying to use the Type() function but I cannot work out how to check the return value? Caomparing it to 'int' or 'str' isn't working, or should I be using the isinstance property? I want to use raw_input and check that it is a number. Can someone point me in the right direction? Thanks Michael From shantanoo at gmail.com Mon Aug 27 12:12:14 2007 From: shantanoo at gmail.com (Shantanoo Mahajan) Date: Mon, 27 Aug 2007 15:42:14 +0530 Subject: [Tutor] validation In-Reply-To: <46D2903A.6010304@mrfab.info> References: <46D2903A.6010304@mrfab.info> Message-ID: On 27-Aug-07, at 2:20 PM, Michael wrote: > Hi > > I am fairly new to Python and I wish to validate input. Such as > wanting > to check and make sure that an integer is entered and the program not > crashing when a naughty user enters a character instead. I have been > trying to use the Type() function but I cannot work out how to > check the > return value? Caomparing it to 'int' or 'str' isn't working, or > should I > be using the isinstance property? I want to use raw_input and check > that > it is a number. Can someone point me in the right direction? > > Thanks > > Michael http://docs.python.org/tut/node10.html Check section 8.3. 'Exception Handling'. You may use the example without any modifications. regards, shantanoo From john at fouhy.net Mon Aug 27 12:17:18 2007 From: john at fouhy.net (John Fouhy) Date: Mon, 27 Aug 2007 22:17:18 +1200 Subject: [Tutor] validation In-Reply-To: <46D2903A.6010304@mrfab.info> References: <46D2903A.6010304@mrfab.info> Message-ID: <5e58f2e40708270317t5c4d0d68q7abbdb9c8168fea2@mail.gmail.com> On 27/08/07, Michael wrote: > I am fairly new to Python and I wish to validate input. Such as wanting > to check and make sure that an integer is entered and the program not > crashing when a naughty user enters a character instead. I have been > trying to use the Type() function but I cannot work out how to check the > return value? Caomparing it to 'int' or 'str' isn't working, or should I > be using the isinstance property? I want to use raw_input and check that > it is a number. Can someone point me in the right direction? Hi Michael, raw_input() will give you a string. Python does not do automatic type conversions, like some languages do. To convert string to int, you can use int(). e.g.: user_input = raw_input() num = int(user_input) If you call int() on something that is not a valid integer string, this will throw an exception -- TypeError, I think. So the pythonic way to check is to catch the exception: while True: user_input = raw_input() try: num = int(user_input) break except TypeError: print 'Oops, try again!' HTH! -- John. From alan.gauld at btinternet.com Mon Aug 27 12:54:10 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 27 Aug 2007 11:54:10 +0100 Subject: [Tutor] validation References: <46D2903A.6010304@mrfab.info> Message-ID: "Michael" wrote > to check and make sure that an integer is entered and the program > not > crashing when a naughty user enters a character instead. John F has already pointed you to the use of try/except for this, however... > trying to use the Type() function but I cannot work out how to check > the > return value? Caomparing it to 'int' or 'str' isn't working, The easiest way is to compare to another type: x = 42 if type(x) == type(int()): or even if type(x) == type(2): Or you can use the types module: if type(x) == types.IntType But for your purposes the Python idiom of its 'better to ask forgiveness than permission' applies. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From tknierim at ieway.com Mon Aug 27 07:02:04 2007 From: tknierim at ieway.com (Dan Knierim) Date: Sun, 26 Aug 2007 22:02:04 -0700 Subject: [Tutor] How to put an event into the Tcl/Tk event queue? Message-ID: <46D25ACC.1090806@ieway.com> Hello Mr. Gauld, Your second guess about the scenario is right: I want to automate tests of Tcl/Tk GUIs. I know about the GUI test automation tools like WATSUP, PyWinAuto, winGuiAuto etc., and will use one if necessary. But test automation is usually easier at the lowest possible level for the test target (as per your suggestion to test the back-end functions directly). In this case, my test target is the Tcl/Tk GUI itself. The Tcl/Tk functions I mentioned (Tcl_QueueEvent etc.) are listed in my copy of the Tcl/Tk Man pages (downloadable from www.tcl.tk/man). I believe they are C or C++ functions. Thanks for the explanation of what Tkinter does and doesn't cover. Is there another Python module that does include Python wrappers for Tcl/Tk C functions? My first glance at send() and event_generate() gave me the idea they were for other purposes. Your suggestion triggered a second glance; maybe event_generate can do what I need. I'll study it some more. Thanks for the clues - Dan K. "Alan Gauld" wrote: > > I'd like to simulate user input to TkInter applications from > > another Python script, by inserting events in the Tcl event queue. > > There are two scenarios where I'd expect that to be needed: > 1) To roboticise an existing app, particularly if you don;t have > source code access. > 2) testing a GUI. > > Other than that it's usually easier to go in at the level below the > GUI and > call the underlying commands directly. Is that a possibility here? > > > Tcl/Tk has a couple functions for this (Tk_QueueWindowEvent > > and Tcl_QueueEvent). > > These were new to me and indeed don't appear in either of > my Tcl refrence books (Ousterhout and O'Reilly Nutshell) > Are they recent additions? > > > Is there a Python interface for either of those? I can't find > > any... > > Neither can I. > > > My second choice would be to use Tcl_CreateEventSource, > > but I don't see a Python interface for that, either. > > Nope, me neither. No references in my books and no > Python/Tkinter equivalents. In fact my Tcl prompt doesn't > recognise any of the 3 commands you cite. Are these > actuially Tcl/Tk interpreter commands or C interface > functions? Only interpreter commands are reproduced > in Tkinter. > > > I'd rather not work through the actual GUI interface if I can avoid > > it. > > Why do you need to work through the GUI events? > Normally the GUI is there to connect humans to the back end code. > If an app needs access to the back end code it can usually call the > functions directly using more conventional IPC mechanisms. > > There are a couple of higher level methods that might be of use? > > send(app, cmd, *args) > > event_generate(sequence, option=...) > > Dunno if they will help. > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.freenetpages.co.uk/hp/alan.gauld > From kent37 at tds.net Mon Aug 27 13:31:01 2007 From: kent37 at tds.net (Kent Johnson) Date: Mon, 27 Aug 2007 07:31:01 -0400 Subject: [Tutor] validation In-Reply-To: References: <46D2903A.6010304@mrfab.info> Message-ID: <46D2B5F5.3090003@tds.net> Alan Gauld wrote: > "Michael" wrote >> trying to use the Type() function but I cannot work out how to check >> the >> return value? Caomparing it to 'int' or 'str' isn't working, > > The easiest way is to compare to another type: > > x = 42 > if type(x) == type(int()): > > or even > > if type(x) == type(2): For the built-in types, since Python 2.2 the familiar name (int, str, float, list, dict, set) *is* the type and you can compare to that directly, e.g.: In [13]: type(3)==int Out[13]: True In [14]: type([]) == list Out[14]: True Kent From alan.gauld at btinternet.com Mon Aug 27 14:00:44 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 27 Aug 2007 13:00:44 +0100 Subject: [Tutor] validation References: <46D2903A.6010304@mrfab.info> <46D2B5F5.3090003@tds.net> Message-ID: "Kent Johnson" wrote >> if type(x) == type(int()): >> > For the built-in types, since Python 2.2 the familiar name (int, > str, > float, list, dict, set) *is* the type and you can compare to that > directly, e.g.: > > In [13]: type(3)==int > Out[13]: True I knew I should be able to use int but I tried to be too clever and used type(int) which of course returns 'type type'. So I used the default int() constructor which returns zero... For some reason I never thought of simply comparing type() to int... doh! Thanks Kent, Alan g. From alan.gauld at btinternet.com Mon Aug 27 14:04:50 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 27 Aug 2007 13:04:50 +0100 Subject: [Tutor] How to put an event into the Tcl/Tk event queue? References: <46D25ACC.1090806@ieway.com> Message-ID: "Dan Knierim" wrote in > The Tcl/Tk functions I mentioned (Tcl_QueueEvent etc.) are > listed in my copy of the Tcl/Tk Man pages (downloadable > from www.tcl.tk/man). > I believe they are C or C++ functions. That's what I suspected, the names look like the C functions. > Is there another Python module that does include Python > wrappers for Tcl/Tk C functions? Unfortunately I don't know of anything. > Your suggestion triggered a second glance; maybe event_generate can > do what I need. > I'll study it some more. I hope it works, the documentation in the Nutshell book certainly suggested that, under X windows at least, any app could send to any other app within the same X environment... Alan G From tinoloc at gmail.com Mon Aug 27 15:20:53 2007 From: tinoloc at gmail.com (Tino Dai) Date: Mon, 27 Aug 2007 09:20:53 -0400 Subject: [Tutor] Detecting sequences in lists Message-ID: Hi Everybody, Thank you so much for the information on sets. I think that that has certain uses, but in my case I can't find a way. I have been thinking about sequences in a list. Let me give you an example: tset = [ 1,2,4,0,0,1,2,4,4] What I want to do is detect the 1,2,4 sequence and perhaps how many. What I have tried is [1,2,4] in tset and also tset.count([1,2,4]) Is there a method or a function that does this in python, or am I left with DIY? -Thanks, Tino -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070827/462aec29/attachment.htm From lutz.horn at fastmail.fm Mon Aug 27 15:50:10 2007 From: lutz.horn at fastmail.fm (Lutz Horn) Date: Mon, 27 Aug 2007 15:50:10 +0200 Subject: [Tutor] Detecting sequences in lists In-Reply-To: References: Message-ID: <1188222610.32537.1207467163@webmail.messagingengine.com> Hi, DIY is easy. On Mon, 27 Aug 2007 09:20:53 -0400, "Tino Dai" said: > What I want to do is detect the 1,2,4 sequence and perhaps how many. >>> tset = [ 1,2,4,0,0,1,2,4,4] >>> s = [1, 2, 4] >>> c = 0 >>> for i in range(len(tset) - len(s)): ... if tset[i:i+len(s)] == s: ... c = c + 1 ... print "found at %d" % i ... found at 0 found at 5 >>> print c 2 Regards Lutz -- From kent37 at tds.net Mon Aug 27 16:31:36 2007 From: kent37 at tds.net (Kent Johnson) Date: Mon, 27 Aug 2007 10:31:36 -0400 Subject: [Tutor] Detecting sequences in lists In-Reply-To: References: Message-ID: <46D2E048.9070804@tds.net> Tino Dai wrote: > Hi Everybody, > > Thank you so much for the information on sets. I think that that > has certain uses, but in my case I can't find a way. I have been > thinking about sequences in a list. Let me give you an example: > > tset = [ 1,2,4,0,0,1,2,4,4] > > What I want to do is detect the 1,2,4 sequence and perhaps how many. There is nothing built-in for this. Here is a solution that uses index() to quickly find potential starting points. It is based on this post to c.l.py and the followup: http://groups.google.com/group/comp.lang.python/msg/a03abee619ec54ef?hl=en& This is likely to be much faster than Lutz' solution tset is long, though you would have to test to be sure. def subPositions(alist, innerlist): if innerlist == []: return first, start = innerlist[0], 0 while 1: try: p = alist.index(first, start) except ValueError: return if alist[p: p + len(innerlist)] == innerlist: yield p start = p+1 Kent From wormwood_3 at yahoo.com Mon Aug 27 16:54:19 2007 From: wormwood_3 at yahoo.com (wormwood_3) Date: Mon, 27 Aug 2007 07:54:19 -0700 (PDT) Subject: [Tutor] Equivalent of && in Python? Message-ID: <284751.5904.qm@web32401.mail.mud.yahoo.com> I have a script that reads some local system information, performs some calculations, and then launches some terminal windows: # Spawn the 4 terminals, with needed positions and sizes, then exit commands.getoutput("%s --geometry=%dx%d+%d+%d --working-directory=%s" % \ (terminal, t1width, t1height, t1posx, t1posy, workingdir)) commands.getoutput("%s --geometry=%dx%d+%d+%d --working-directory=%s" % \ (terminal, t2width, t2height, t2posx, t2posy, workingdir)) commands.getoutput("%s --geometry=%dx%d+%d+%d --working-directory=%s" % \ (terminal, t3width, t3height, t3posx, t3posy, workingdir)) commands.getoutput("%s --geometry=%dx%d+%d+%d --working-directory=%s" % \ (terminal, t4width, t4height, t4posx, t4posy, workingdir)) The oddity: When I call this script, sometimes all four terminals launch, one right after another, which is the desired behaviour. At other times, one will launch, and ONLY after I close it will the second launch, and so on until the fourth. I do not understand how this is happening. I thought each line in a script which does anything has to be done before the next one is executed, but I may be way off on this. If this were in a bash script, I could add " &&" after each line, but what to do in a Python script? -Sam From brunson at brunson.com Mon Aug 27 17:29:04 2007 From: brunson at brunson.com (Eric Brunson) Date: Mon, 27 Aug 2007 09:29:04 -0600 Subject: [Tutor] Equivalent of && in Python? In-Reply-To: <284751.5904.qm@web32401.mail.mud.yahoo.com> References: <284751.5904.qm@web32401.mail.mud.yahoo.com> Message-ID: <46D2EDC0.3010805@brunson.com> wormwood_3 wrote: > I have a script that reads some local system information, performs some calculations, and then launches some terminal windows: > > # Spawn the 4 terminals, with needed positions and sizes, then exit > commands.getoutput("%s --geometry=%dx%d+%d+%d --working-directory=%s" % \ > (terminal, t1width, t1height, t1posx, t1posy, workingdir)) > commands.getoutput("%s --geometry=%dx%d+%d+%d --working-directory=%s" % \ > (terminal, t2width, t2height, t2posx, t2posy, workingdir)) > commands.getoutput("%s --geometry=%dx%d+%d+%d --working-directory=%s" % \ > (terminal, t3width, t3height, t3posx, t3posy, workingdir)) > commands.getoutput("%s --geometry=%dx%d+%d+%d --working-directory=%s" % \ > (terminal, t4width, t4height, t4posx, t4posy, workingdir)) > > > The oddity: When I call this script, sometimes all four terminals launch, one right after another, which is the desired behaviour. That is what's actually odd. Just reading the script without being well versed in the intricacies of the command module, I would expect them to be run sequentially. > At other times, one will launch, and ONLY after I close it will the second launch, and so on until the fourth. I do not understand how this is happening. I thought each line in a script which does anything has to be done before the next one is executed, but I may be way off on this. > > If this were in a bash script, I could add " &&" after each line, but what to do in a Python script? > Actually, I think you mean a single ampersand. "&&" is condition execution of the next command and is done synchronously. I would say try putting an ampersand after the command in getoutput(), have you tried that? If that doesn't work, then make sure getoutput() is using a shell, since the shell is the mechanism through which the ampersand works, or else read the docs for getoutput() to see if there's some way to get it in the background. If none of those solutions work, you could spawn a thread for each command, or finally, use the subprocess module, which I know can be instructed to use a subshell. > -Sam > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From pacbaby27 at yahoo.com Mon Aug 27 20:02:59 2007 From: pacbaby27 at yahoo.com (Latasha Marks) Date: Mon, 27 Aug 2007 11:02:59 -0700 (PDT) Subject: [Tutor] user in put Message-ID: <868508.80963.qm@web56412.mail.re3.yahoo.com> Need help get a user to in put his or her favortie food the the program should the n print oue the name of the new food by joining the original food names together code: favortie_food= raw_input("What is your favortie food?") What is your favortie food? hot dog >>> print favortie_food hot dog >>> favortie_food= raw_input("What is your favortie food?") What is your favortie food? pizza >>> print favortie_food.replace("hot dog", "pizza) SyntaxError: EOL while scanning single-quoted string >>> print favortie_food.replace("hot dog", "pizza") pizza --------------------------------- Yahoo! oneSearch: Finally, mobile search that gives answers, not web links. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070827/00769b36/attachment.htm From carroll at tjc.com Mon Aug 27 21:07:37 2007 From: carroll at tjc.com (Terry Carroll) Date: Mon, 27 Aug 2007 12:07:37 -0700 (PDT) Subject: [Tutor] validation In-Reply-To: <46D2B5F5.3090003@tds.net> Message-ID: On Mon, 27 Aug 2007, Kent Johnson wrote: > For the built-in types, since Python 2.2 the familiar name (int, str, > float, list, dict, set) *is* the type and you can compare to that > directly, e.g.: > > In [13]: type(3)==int > Out[13]: True > In [14]: type([]) == list > Out[14]: True That is so cool. I never knew that. Last night, I coded a routine that could accept either 1) a string, or 2) a list or tuple of such strings or 3) a list or tuple of lists or tuples of such strings. I ended up writing a short isListOrTuple function that went something like this: def isListOrTuple(thing): result = False if isinstance(thing, list): result = True if isinstance(thing, tuple): result = True return result Then I used if isListOrTuple(param): stuff else: other stuff How much cleanar it would have been to just write: if type(param) in [list, tuple]: stuff else: other stuff Thanks, Kent. From kent37 at tds.net Mon Aug 27 21:18:39 2007 From: kent37 at tds.net (Kent Johnson) Date: Mon, 27 Aug 2007 15:18:39 -0400 Subject: [Tutor] validation In-Reply-To: References: Message-ID: <46D3238F.7090109@tds.net> Terry Carroll wrote: > I ended up writing a short isListOrTuple function that went something > like this: > > def isListOrTuple(thing): > result = False > if isinstance(thing, list): result = True > if isinstance(thing, tuple): result = True > return result isinstance can take a tuple of types as its second argument so this could be written def isListOrTuple(thing): return isinstance(thing, (list, tuple)) > How much cleanar it would have been to just write: > > if type(param) in [list, tuple]: > stuff > else: > other stuff Note that isinstance(thing, (list, tuple)) and type(thing) in [list, tuple] are not equivalent. The first will be true for objects whose type is a subclass of list and tuple while the second will not. In [2]: class Foo(list): pass ...: In [3]: f=Foo() In [4]: type(f) Out[4]: In [5]: type(f) in [list, tuple] Out[5]: False In [6]: isinstance(f, list) Out[6]: True Kent From rdm at rcblue.com Mon Aug 27 21:32:57 2007 From: rdm at rcblue.com (Dick Moores) Date: Mon, 27 Aug 2007 12:32:57 -0700 Subject: [Tutor] Question about installing 2.51 Message-ID: <20070827193315.922451E401B@bag.python.org> XP, Python 2.5 I just downloaded python-2.5.1.msi from python.org. During the installation process (which I aborted), I was told, "This Update will replace your existing Python25 installation". What exactly does this mean? What will happen, for example, to all my scripts that are in E:\Python25\dev? Or to the packages I've put into E:\Python25\Lib\site-packages? Thanks, Dick Moores From kent37 at tds.net Mon Aug 27 21:50:14 2007 From: kent37 at tds.net (Kent Johnson) Date: Mon, 27 Aug 2007 15:50:14 -0400 Subject: [Tutor] Question about installing 2.51 In-Reply-To: <20070827193315.922451E401B@bag.python.org> References: <20070827193315.922451E401B@bag.python.org> Message-ID: <46D32AF6.8010809@tds.net> Dick Moores wrote: > XP, Python 2.5 > > I just downloaded python-2.5.1.msi from python.org. During the > installation process (which I aborted), I was told, "This Update will > replace your existing Python25 installation". > > What exactly does this mean? What will happen, for example, to all my > scripts that are in E:\Python25\dev? Or to the packages I've put into > E:\Python25\Lib\site-packages? In general minor releases (x.y.z) install over any existing x.y.w release preserving stuff you have installed into x.y.z. In particular site-packages will be preserved. Not sure about \dev since AFAIK that is not part of the standard distribution. You could just copy E:\Python25 to be safe before you do the install. Kent From dkuhlman at rexx.com Mon Aug 27 22:32:24 2007 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Mon, 27 Aug 2007 13:32:24 -0700 Subject: [Tutor] user in put In-Reply-To: <868508.80963.qm@web56412.mail.re3.yahoo.com> References: <868508.80963.qm@web56412.mail.re3.yahoo.com> Message-ID: <20070827203224.GA99460@cutter.rexx.com> On Mon, Aug 27, 2007 at 11:02:59AM -0700, Latasha Marks wrote: > Need help get a user to in put his or her favortie food the the > program should the n print oue the name of the new food by > joining the original food names together If what you want is to enable your user to enter several foods (strings), then concatenate them together, try something like the following: In [33]: foods = [] In [34]: food = raw_input('What is your favorite food?') What is your favorite food?peaches In [35]: foods.append(food) In [36]: food = raw_input('What is your favorite food?') What is your favorite food?nectarines In [37]: foods.append(food) In [38]: food = raw_input('What is your favorite food?') What is your favorite food?cantaloupe In [39]: foods.append(food) In [40]: ', '.join(foods) Out[40]: 'peaches, nectarines, cantaloupe' Note that we append each food to a list, then do string.join(). That's faster than doing multiple string concatenations. In this case there are not enough strings to make a difference. But, it's a good habit to get into. Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman From alan.gauld at btinternet.com Mon Aug 27 23:00:21 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 27 Aug 2007 22:00:21 +0100 Subject: [Tutor] Question about installing 2.51 References: <20070827193315.922451E401B@bag.python.org> Message-ID: "Dick Moores" wrote > installation process (which I aborted), I was told, "This Update > will > replace your existing Python25 installation". > > What exactly does this mean? What will happen, for example, to all > my > scripts that are in E:\Python25\dev? Or to the packages I've put > into > E:\Python25\Lib\site-packages? Probably all will be well. However I generally think its a bad idea to keep your scripts inside the Python folder structure since it makes it harder to share them over multiple Python versions and of course there is the small risk that an upgrade like this might destroy them (if for example Python acquired a dev sub folder structure!) I always create a separate folder structure for my python code and point python at it using the PYTHONPATH env variable (or sys.path). But that may not be a generally held view... Alan G. From carroll at tjc.com Mon Aug 27 23:48:28 2007 From: carroll at tjc.com (Terry Carroll) Date: Mon, 27 Aug 2007 14:48:28 -0700 (PDT) Subject: [Tutor] validation In-Reply-To: <46D3238F.7090109@tds.net> Message-ID: On Mon, 27 Aug 2007, Kent Johnson wrote: > isinstance can take a tuple of types as its second argument.... > > Note that > isinstance(thing, (list, tuple)) > > and > type(thing) in [list, tuple] > > are not equivalent. The first will be true for objects whose type is a > subclass of list and tuple while the second will not. Thanks. I totally missed that isinstance's second parameter can be a tuple. That's a much better approach. Wow, that makes two things I've learned today. My brain is now full. From rdm at rcblue.com Tue Aug 28 03:26:58 2007 From: rdm at rcblue.com (Dick Moores) Date: Mon, 27 Aug 2007 18:26:58 -0700 Subject: [Tutor] Question about installing 2.51 In-Reply-To: References: <20070827193315.922451E401B@bag.python.org> Message-ID: <20070828012709.B4FE51E4007@bag.python.org> At 02:00 PM 8/27/2007, Alan Gauld wrote: >"Dick Moores" wrote > > > installation process (which I aborted), I was told, "This Update > > will > > replace your existing Python25 installation". > > > > What exactly does this mean? What will happen, for example, to all > > my > > scripts that are in E:\Python25\dev? Or to the packages I've put > > into > > E:\Python25\Lib\site-packages? > >Probably all will be well. However I generally think its a bad idea to >keep >your scripts inside the Python folder structure since it makes it >harder >to share them over multiple Python versions and of course there is the >small risk that an upgrade like this might destroy them (if for >example >Python acquired a dev sub folder structure!) > >I always create a separate folder structure for my python code and >point >python at it using the PYTHONPATH env variable (or sys.path). > >But that may not be a generally held view... Thanks very much, Alan and Kent. I took your advice. Backed up Python25, and created a PythonWork folder outside of Python25, for my stuff. Don't know why I didn't do the latter long before! The installation went fine. Dick From pine508 at hotmail.com Tue Aug 28 05:07:40 2007 From: pine508 at hotmail.com (Che M) Date: Mon, 27 Aug 2007 23:07:40 -0400 Subject: [Tutor] tagging pieces of information Message-ID: Hi, I am curious about ways in Python to approach the idea of "tagging" pieces of information much in the way that one can tag favorite websites like on the site Del.icio.us. I'm not sure if tagging is the best term for this (due to confusion with HTML tags), but the idea would be a way to assign one or more words to stored data such that later one might search by those words in order to retrieve the data. That data might be a chunk of text, a graph, image, whatever...the point would be to be able to search later by tags name. I know the prorgram GyrFalcon uses tags and is written in Python. And of course Flickr and many other things. I don't know if there are any preexisting Python structures which would help with this or if it has to be done by scratch, or if it is easy or difficult. I also don't know what are good ideas for ways to save the tags, whether in a text file, in a database (if so, comma separated in one cell?), or some other means, and how to associate them with the data chunk they refer to, and lastly how to search for them. Some starting points in the right direction, jargon words to search for, etc., would be very helpful. Thanks. _________________________________________________________________ Learn.Laugh.Share. Reallivemoms is right place! http://www.reallivemoms.com?ocid=TXT_TAGHM&loc=us From eric at abrahamsen.com Tue Aug 28 05:31:45 2007 From: eric at abrahamsen.com (Eric Abrahamsen) Date: Tue, 28 Aug 2007 11:31:45 +0800 Subject: [Tutor] tagging pieces of information In-Reply-To: References: Message-ID: <78C17467-D73F-4C71-B40D-8D3ED6C59298@abrahamsen.com> On Aug 28, 2007, at 11:07 AM, Che M wrote: > I don't know if there are any preexisting Python structures which > would help > with this or if it has to be done by scratch, or if it is easy or > difficult. > I also don't know what are good ideas for ways to save the tags, > whether > in a text file, in a database (if so, comma separated in one > cell?), or some > other means, and how to associate them with the data chunk they > refer to, > and lastly how to search for them. My first thought would be to create a class for your 'data chunks', and then make 'tags' a class attribute that is created empty on initialization. The basic code would look like: class Data_chunk(object): def __init__(self): self.tags = set() Then every time you create a new data chunk like so: my_data = Data_chunk() You can add, remove and search for tags using the set methods (I made it a set because that seemed appropriate to a tagging feature, you could use a list or something else): my_data.tags.add('dogs') my_data.tags.add('cats') if 'dogs' in my_data.tags: print "It's about dogs" my_data.tags.remove('dogs') print my_data.tags The pickle module is usually simplest and most convenient for long- term data storage. Enjoy! E From john at fouhy.net Tue Aug 28 05:36:11 2007 From: john at fouhy.net (John Fouhy) Date: Tue, 28 Aug 2007 15:36:11 +1200 Subject: [Tutor] tagging pieces of information In-Reply-To: References: Message-ID: <5e58f2e40708272036i10877fc2h39219c2c6c2917bb@mail.gmail.com> On 28/08/07, Che M wrote: > Hi, I am curious about ways in Python to approach the idea of "tagging" > pieces of information much in the way that one can tag favorite websites > like on the site Del.icio.us. I'm not sure if tagging is the best term for > this (due to confusion with HTML tags), but the idea would be a way to > assign one or more words to stored data such that later one might search by > those words in order to retrieve the data. That data might be a chunk of > text, a graph, image, whatever...the point would be to be able to search > later by tags name. I know the prorgram GyrFalcon uses tags and is written > in Python. And of course Flickr and many other things. A simple way to do this in-memory would be to use a dict: keys are tags and values are sets (or lists) of objects. You might need to maintain an inverse structure too, mapping object to list/set of tags. You could use a database (sqlite comes with python 2.5). I'm not sure what the "best practice" strucutre would be, but maybe you could have a table with two columns: "object ID" and "tag". "object ID" would be some kind of identifier for your tagged objects. You could then: Find tags for an object: select tag from tagTable where objectID = ? Find objects matching a tag: select objectID from tagTable where tag = ? -- John. From witham.ian at gmail.com Tue Aug 28 05:44:44 2007 From: witham.ian at gmail.com (Ian Witham) Date: Tue, 28 Aug 2007 15:44:44 +1200 Subject: [Tutor] tagging pieces of information In-Reply-To: References: Message-ID: You may be able to use a dictionary to store your data chunks. eg: >>> tagged_items = {('spam, swordfights'): 'ITEM A', ... ('swordfights', 'custard'): 'ITEM B'} >>> [tagged_items[tags] for tags in tagged_items if 'spam' in tags] ['ITEM A'] >>> [tagged_items[tags] for tags in tagged_items if 'swordfights' in tags] ['ITEM A', 'ITEM B'] or.. >>> for tags in tagged_items: ... if 'custard' in tags: ... print tagged_items[tags] ... ITEM B Ian. On 8/28/07, Che M wrote: > > Hi, I am curious about ways in Python to approach the idea of "tagging" > pieces of information much in the way that one can tag favorite websites > like on the site Del.icio.us. I'm not sure if tagging is the best term > for > this (due to confusion with HTML tags), but the idea would be a way to > assign one or more words to stored data such that later one might search > by > those words in order to retrieve the data. That data might be a chunk of > text, a graph, image, whatever...the point would be to be able to search > later by tags name. I know the prorgram GyrFalcon uses tags and is > written > in Python. And of course Flickr and many other things. > > I don't know if there are any preexisting Python structures which would > help > with this or if it has to be done by scratch, or if it is easy or > difficult. > I also don't know what are good ideas for ways to save the tags, whether > in a text file, in a database (if so, comma separated in one cell?), or > some > other means, and how to associate them with the data chunk they refer to, > and lastly how to search for them. > > Some starting points in the right direction, jargon words to search for, > etc., would be very helpful. Thanks. > > _________________________________________________________________ > Learn.Laugh.Share. Reallivemoms is right place! > http://www.reallivemoms.com?ocid=TXT_TAGHM&loc=us > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070828/fd6a2c19/attachment.htm From python at mrfab.info Tue Aug 28 15:35:57 2007 From: python at mrfab.info (Michael) Date: Tue, 28 Aug 2007 21:35:57 +0800 Subject: [Tutor] validation In-Reply-To: References: <46D2903A.6010304@mrfab.info> Message-ID: <46D424BD.4090808@mrfab.info> Thanks Everybody I now have several methods in my arsenal and they all look quite simple, now that I know. Just wondering, when would you use isInstance()? Thanks Alan Gauld wrote: > "Michael" wrote > > >> to check and make sure that an integer is entered and the program >> not >> crashing when a naughty user enters a character instead. >> > > John F has already pointed you to the use of try/except for this, > however... > > >> trying to use the Type() function but I cannot work out how to check >> the >> return value? Caomparing it to 'int' or 'str' isn't working, >> > > The easiest way is to compare to another type: > > x = 42 > if type(x) == type(int()): > > or even > > if type(x) == type(2): > > Or you can use the types module: > > if type(x) == types.IntType > > But for your purposes the Python idiom of its 'better to ask > forgiveness than permission' applies. > > > From witham.ian at gmail.com Tue Aug 28 23:36:54 2007 From: witham.ian at gmail.com (Ian Witham) Date: Wed, 29 Aug 2007 09:36:54 +1200 Subject: [Tutor] Filemaker interactions In-Reply-To: <46D092AF.80800@egenix.com> References: <1186004514.108975.119380@e9g2000prf.googlegroups.com> <46D092AF.80800@egenix.com> Message-ID: Hello, I thought I'd update on my Filemaker Pro 6 situation. The PyFileMaker module (CGI based access) is meeting my requirements at present, although record searches with a large number of results are a little slow. If my project grows much larger in scope I will certainly look into the mxODBC extension. Thanks for the suggestions. On 8/26/07, M.-A. Lemburg wrote: > > On 2007-08-01 23:41, Ian Witham wrote: > > Hello, > > > > I'm hoping someone here can put me on the right track with some broad > > concepts here. > > > > What I am hoping to achieve is a simple HTML page to be served over > > our company LAN, into which the users (Real Estate Agents) can enter a > > property address or reference number. > > > > My next thought was to have a Python CGI script query our filemaker > > database of property listings, construct a PDF from the relevant > > information, and finally return this PDF to the user. > > > > At no stage do I want the user to have unfettered access to the > > database or the ability to alter/delete records. > > > > My question is: what is the most appropriate way for my script to > > interact with Filemaker? Can this be done with Filemaker Pro 6? > > > > According to the Filemaker Help, the "Local Data Access Companion" > > shares the FileMaker Pro database with ODBC-compliant applications on > > the same computer. Is this the right option? > > > > Can my CGI script be an ODBC client? How? Would it need to be > > Filemaker specific code or does ODBC have a standardised format? > > > > I'm grateful for any advice and a nudge in the right direction. > > You could try our mxODBC extension for Python which will > likely just work out of the box: > > https://www.egenix.com/products/python/mxODBC/ > > with the Filemaker ODBC driver. > > Or give this module a try (if you have more time at hand > and can do without a DB-API interface): > > http://www.lfd.uci.edu/~gohlke/code/filemaker.py.html > > It uses Filemaker's XML interface. > > -- > Marc-Andre Lemburg > eGenix.com > > Professional Python Services directly from the Source (#1, Aug 25 2007) > >>> Python/Zope Consulting and Support ... http://www.egenix.com/ > >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ > >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ > ________________________________________________________________________ > > :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: > > > eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 > D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg > Registered at Amtsgericht Duesseldorf: HRB 46611 > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070829/dc98f14f/attachment.htm From ricaraoz at gmail.com Wed Aug 29 00:04:04 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Tue, 28 Aug 2007 19:04:04 -0300 Subject: [Tutor] Shared Class Attribute In-Reply-To: <46C4A6D4.9060404@tds.net> References: <46C4A6D4.9060404@tds.net> Message-ID: <46D49BD4.10109@bigfoot.com> Hi, if I have this class : class myClass : ClassCount = 0 def __init__(self) : (here I want to increment ClassCount for the whole class) self.InstanceAttr = 1 How would I increment the shared class attribute (ClassCount) from INSIDE the class? I can do it from the outside by stating myClass.ClassCount = 22 and it will change for all instances. But haven't found a way to do it from inside. From brunson at brunson.com Wed Aug 29 00:18:15 2007 From: brunson at brunson.com (Eric Brunson) Date: Tue, 28 Aug 2007 16:18:15 -0600 Subject: [Tutor] Shared Class Attribute In-Reply-To: <46D49BD4.10109@bigfoot.com> References: <46C4A6D4.9060404@tds.net> <46D49BD4.10109@bigfoot.com> Message-ID: <46D49F27.9020903@brunson.com> Ricardo Ar?oz wrote: > Hi, > Hi Ricardo, In the future, please start a new thread with a new email and not a reply to an existing thread. Compliant mail clients thread based on headers you may or may not see in your client, and this email is part of the thread you replied to called "[Tutor] PyCon 2008 - Call for Tutorial Ideas". In addition, you send a copy of your message to pycon-tutorials at python.org and many who reply using a "Reply All" function in their mailer will spam that list, too. > if I have this class : > > class myClass : > ClassCount = 0 > def __init__(self) : > (here I want to increment ClassCount for the whole class) > self.InstanceAttr = 1 > You always reference a class variable by the class name: >>> class myclass: ... count = 0 ... def __init__( self ): ... myclass.count += 1 ... >>> c = myclass() >>> print c.count 1 >>> d = myclass() >>> print d.count 2 >>> print c.count 2 >>> e = myclass() >>> print e.count, myclass.count 3 3 Hope that helps. Sincerely, e. > How would I increment the shared class attribute (ClassCount) from > INSIDE the class? > I can do it from the outside by stating myClass.ClassCount = 22 and it > will change for all instances. But haven't found a way to do it from inside. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From carroll at tjc.com Wed Aug 29 00:56:21 2007 From: carroll at tjc.com (Terry Carroll) Date: Tue, 28 Aug 2007 15:56:21 -0700 (PDT) Subject: [Tutor] validation In-Reply-To: <46D424BD.4090808@mrfab.info> Message-ID: On Tue, 28 Aug 2007, Michael wrote: > I now have several methods in my arsenal and they all look quite simple, > now that I know. Just wondering, when would you use isInstance()? Well, as this thread has shown, I'm no expert, but let me take a stab on it. If nothing else, we'll all learn something as the experts come in to correct me! We have three (or four, depending on how you count) possible approaches: 1) Use duck-typing. Don't worry about the type of operand you're being fed. You don't really care, for example, whether it is actually a file, or an int, or a float, or a string, or whatever, as long as it acts like one for the purpose for which you're using it. For example, if you're writing an increment function: def incr(n): "returns an incremented value of n" return n + 1 It will work whether you get an int or a float. It won't work with a file or a string, but rather than spend your time checking that, just let Python generate the exception. In the mean time, you code will work with ints, floats, complex numbers, or anything that subclassed from them, with no special work from you. This is called "duck-typing" from the phrase, "if it looks like a duck, walks like a duck and quacks like a duck, it's a duck." If it looks enough like a number that it lets itself have one added to it, I'm calling it a number. 1A) a variation of option 1 (which is why I said "depending on how you count" above): duck-typing with error recovery. def incr(n): "returns an incremented value of n, or None if n is not incrementable" try: return n + 1 except: return None This will try to return a value equal to N + 1, but if n does not quack like a duck, it just returns None (and it's up to the caller to deal with it). Options 2 & 3 are non-duck-typing approaches, usually called Look-Before-You-Leap (LBYL), where the code is checking to see if it was passed the right type, and behaving accordingly. These are: 2) Using type() to obtain the type of the operand, and making a decision based on the type; 3) using isinstance() to see if the operand is an instance of a particular type, and then making a decision based on whether or not it is. These are subtly different, because of subclassing. An object has only one type -- the type of its class. But it is an instance, not only of its class, but of that class's superclass(es), if any; and the superclass(es)'s superclass(s), if any, etc. all the way back to the "object" class. Here's an example. I'm going to create a mutant list class that subclasses list. It produces objects that are the same as an ordinary list with one difference: if the list is sorted, the contents are sorted without regard to case; that is, both "B" and "b" sort after both "A" and "a", and before "C" and "c". Here's the class definition: >>> class caseindependentlist(list): ... def __init__(self, *args): ... list.__init__(self, *args) ... def sort(self): ... return list.sort(self, key=str.upper) It subclasses list, and overrides the usual sort method with a replacement method that sorts based on what the value would be if converted to all upper-case (which means the sort is case-independent). Let's create a plain old ordinary list and a mutant caseindependentlist to see how they compare. (I'm using a long form of the list(0 constructor just to be consistent here) >>> ordinary_list = list(["Zebra", "alligator", "Duck", "penguin"]) >>> mutant_list = caseindependentlist(["Zebra", "alligator", "Duck", "penguin"]) Let's look at each before and after sorting to show how they work... >>> ordinary_list ['Zebra', 'alligator', 'Duck', 'penguin'] >>> ordinary_list.sort() >>> ordinary_list ['Duck', 'Zebra', 'alligator', 'penguin'] That worked as expected, but the upper-case ones are sorted first. But... >>> mutant_list ['Zebra', 'alligator', 'Duck', 'penguin'] >>> mutant_list.sort() >>> mutant_list ['alligator', 'Duck', 'penguin', 'Zebra'] Okay, that works as expected. Now here's the thing: mutant_list, for almost every purpose, is just a list. You can do anything with it that you can do with a plain old list. the only thing different about it is that it sorts without regard to case. But mutant_list and ordinary_list have differing types: >>> type(ordinary_list) >>> type(mutant_list) >>> If you were to write a program that checked "to make sure" it was being passed a list, and were checking with type(), it would wrongly reject mutant_list. isinstance does a better job here. isinstance doesn't care whether the object in question is a list directly (as in the case of ordinary_list) or indirectly (as in the case of mutant_list): >>> isinstance(ordinary_list, list) True >>> isinstance(mutant_list, list) True So, when to use what? I would say: 1) where possible, use duck-typing, either of the type 1 or type 1A variety. That's the easiest way to have your program just work if it's possible to work. 2) if you must expressly check type, use isinstance(). It doesn't care whether the object is directly or indirectly the instance you're looking for. 3) I only use type() interactively or experimentally, when trying to learn about what I'm getting passed at any particular time. In a program I'm writing now, I would like to use duck-typing, but I don't think it works well. In my particular case, to simplify it a bit, I'm writing a method that can either take a string that contains SQL statements; or a list or tuple that contains strings of SQL statements. Duck-typing doesn't work too well here, because a string of characters looks an awful lot like a list or tuple of one-character strings for most duck-typing tests. I'd have to put together a weird duck-typing approach that would ultimately be a type-checking approach disguised as duck-typing; so I opted to just be up-front about it and check the type (using isinstance, of course). From ricaraoz at gmail.com Wed Aug 29 01:48:31 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Tue, 28 Aug 2007 20:48:31 -0300 Subject: [Tutor] Shared Class Attribute In-Reply-To: <46D49F27.9020903@brunson.com> References: <46C4A6D4.9060404@tds.net> <46D49BD4.10109@bigfoot.com> <46D49F27.9020903@brunson.com> Message-ID: <46D4B44F.2070701@bigfoot.com> Eric Brunson wrote: > Ricardo Ar?oz wrote: >> Hi, >> > > Hi Ricardo, > > In the future, please start a new thread with a new email and not a > reply to an existing thread. Compliant mail clients thread based on > headers you may or may not see in your client, and this email is part of > the thread you replied to called "[Tutor] PyCon 2008 - Call for Tutorial > Ideas". In addition, you send a copy of your message to > pycon-tutorials at python.org and many who reply using a "Reply All" > function in their mailer will spam that list, too. Hi Eric. Sorry, thought that by changing the subject I was changing the thread, won't happen again. BTW, I did a 'reply all', is that bad? Thanks for the info on the class attribute. From brunson at brunson.com Wed Aug 29 01:51:19 2007 From: brunson at brunson.com (Eric Brunson) Date: Tue, 28 Aug 2007 17:51:19 -0600 Subject: [Tutor] Shared Class Attribute In-Reply-To: <46D4B44F.2070701@bigfoot.com> References: <46C4A6D4.9060404@tds.net> <46D49BD4.10109@bigfoot.com> <46D49F27.9020903@brunson.com> <46D4B44F.2070701@bigfoot.com> Message-ID: <46D4B4F7.9060308@brunson.com> Ricardo Ar?oz wrote: > Eric Brunson wrote: > >> Ricardo Ar?oz wrote: >> >>> Hi, >>> >>> >> Hi Ricardo, >> >> In the future, please start a new thread with a new email and not a >> reply to an existing thread. Compliant mail clients thread based on >> headers you may or may not see in your client, and this email is part of >> the thread you replied to called "[Tutor] PyCon 2008 - Call for Tutorial >> Ideas". In addition, you send a copy of your message to >> pycon-tutorials at python.org and many who reply using a "Reply All" >> function in their mailer will spam that list, too. >> > > Hi Eric. > > Sorry, thought that by changing the subject I was changing the thread, > won't happen again. > No worries, everyone has to learn sometime. > BTW, I did a 'reply all', is that bad? > No, that's preferred. :-) > Thanks for the info on the class attribute. > > No problem, good luck. e. From kent37 at tds.net Wed Aug 29 02:24:21 2007 From: kent37 at tds.net (Kent Johnson) Date: Tue, 28 Aug 2007 20:24:21 -0400 Subject: [Tutor] validation In-Reply-To: References: Message-ID: <46D4BCB5.7090607@tds.net> Terry Carroll wrote: > 1A) a variation of option 1 (which is why I said "depending on how you > count" above): duck-typing with error recovery. > > def incr(n): > "returns an incremented value of n, or None if n is not incrementable" > try: > return n + 1 > except: > return None > > This will try to return a value equal to N + 1, but if n does not quack > like a duck, it just returns None (and it's up to the caller to deal with > it). This is generally a bad idea. The problem is that you depend on the caller checking the return value for None. If it doesn't, it will probably get some other exception later which will be hard to track down because the source will not be clear. Depending on the caller to check for errors is unreliable. Raising an exception forces the issue - the caller has to catch the exception or propagate it, it can't just ignore it. IIRC exceptions were introduced in C++ to give an alternative to checking for errors. On the other hand, if the caller *does* check for errors, the code can quickly get very cluttered with error checking. Long ago and far away I wrote a lot of MacOS code. At that time, almost every system call returned an error code that had to be checked. Functions tended to look like err = DoSomethingWithX(x); if (err != noErr) return err; err = DoSomethingElse(y); if (err != noErr) return err; etc. With exceptions this can be written much more simply, compactly and readably as DoSomethingWithX(x); DoSomethingElse(y); > In a program I'm writing now, I would like to use duck-typing, but I don't > think it works well. In my particular case, to simplify it a bit, I'm > writing a method that can either take a string that contains SQL > statements; or a list or tuple that contains strings of SQL statements. > Duck-typing doesn't work too well here, because a string of characters > looks an awful lot like a list or tuple of one-character strings for most > duck-typing tests. I'd have to put together a weird duck-typing approach > that would ultimately be a type-checking approach disguised as > duck-typing; so I opted to just be up-front about it and check the type > (using isinstance, of course). This is one of the common cases where there is no simple alternative to LBYL - a function that can take a string or a list of strings as a parameter. Kent From carroll at tjc.com Wed Aug 29 03:34:39 2007 From: carroll at tjc.com (Terry Carroll) Date: Tue, 28 Aug 2007 18:34:39 -0700 (PDT) Subject: [Tutor] validation In-Reply-To: <46D4BCB5.7090607@tds.net> Message-ID: On Tue, 28 Aug 2007, Kent Johnson wrote: > Terry Carroll wrote: > > > 1A) a variation of option 1 (which is why I said "depending on how you > > count" above): duck-typing with error recovery. > > > > def incr(n): > > "returns an incremented value of n, or None if n is not incrementable" > > try: > > return n + 1 > > except: > > return None > > > > This will try to return a value equal to N + 1, but if n does not quack > > like a duck, it just returns None (and it's up to the caller to deal with > > it). > > This is generally a bad idea. The problem is that you depend on the > caller checking the return value for None. Agreed. I was just trying to come up with a short example of catching the exception and doing something different because of it. Admittedly, returning None is not much of an "error recovery." From trey at opmstech.org Wed Aug 29 03:56:26 2007 From: trey at opmstech.org (Trey Keown) Date: Tue, 28 Aug 2007 20:56:26 -0500 (CDT) Subject: [Tutor] A replacement for a "for" loop Message-ID: <63990.68.191.136.241.1188352586.squirrel@webmail.opmstech.org> Hello everybody. I'm using a couple of "for" loops to help me in xml parsing using expat. Unfortunately, though, I've found that using more than one of these in a row, at least in my case, causes a redundancy error. a snippet of my code (note that this is not the way I set the dictionaries)- attrs={u'title': u'example window title', u'name': u'SELF', u'icon': u'e.ico'} keys = ['name','title','icon'] for (tag, val) in attrs.iteritems(): for key in keys: print val the first "for" tag causes the dictionary (attrs) to have its keys called "tag" and its value called "val". The second "for" loop causes the dictionary keys to be read in a certain order. How could I take away the first "for" loop and replace it with something else to do the same general function? thanks for any help. Trey From john at fouhy.net Wed Aug 29 04:12:35 2007 From: john at fouhy.net (John Fouhy) Date: Wed, 29 Aug 2007 14:12:35 +1200 Subject: [Tutor] A replacement for a "for" loop In-Reply-To: <63990.68.191.136.241.1188352586.squirrel@webmail.opmstech.org> References: <63990.68.191.136.241.1188352586.squirrel@webmail.opmstech.org> Message-ID: <5e58f2e40708281912w3834d32blcb6f5db6d9afbe28@mail.gmail.com> On 29/08/07, Trey Keown wrote: > attrs={u'title': u'example window title', u'name': u'SELF', u'icon': > u'e.ico'} > keys = ['name','title','icon'] > for (tag, val) in attrs.iteritems(): > for key in keys: > print val > > the first "for" tag causes the dictionary (attrs) to have its keys called > "tag" and its value called "val". The second "for" loop causes the > dictionary keys to be read in a certain order. How could I take away the > first "for" loop and replace it with something else to do the same general > function? for key in keys: print 'Attribute %s has value %s' % (key, attrs[key]) -- John. From the.tobmeister at gmail.com Wed Aug 29 04:25:11 2007 From: the.tobmeister at gmail.com (Toby Holland) Date: Tue, 28 Aug 2007 22:25:11 -0400 Subject: [Tutor] Newbie Message-ID: HI all, I was wondering if any of you had any advice as to where I should start in regards to learning using and programing with Python. I have wanted to learn a program language for some time and just felt that now was good and I have heard some great things about Python so any suggestions would be great. Thank you all in advance! Toby -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070828/b0fc2df2/attachment.htm From slewin at rogers.com Wed Aug 29 05:35:20 2007 From: slewin at rogers.com (Scott) Date: Tue, 28 Aug 2007 23:35:20 -0400 Subject: [Tutor] Newbie In-Reply-To: References: Message-ID: <46D4E978.4030305@rogers.com> Toby Holland wrote: > I was wondering if any of you had any advice as to where I should start > in regards to learning using and programing with Python. I have wanted > to learn a program language for some time and just felt that now was > good and I have heard some great things about Python so any suggestions > would be great. I myself am a newbie and I found starting with "How to Think Like a Computer Scientist Learning with Python" as a great starter. You can find it at http://ibiblio.org/obp/thinkCS/python.php. It was very easy to read, the writer is great, I believe a high school teacher. The writer does not expect you to know any prior programming. also, best of all, it is completely free. -- Your friend, Scott Sent to you from a Linux computer using Ubuntu Version 7.04 (Feisty Fawn) From lutz.horn at fastmail.fm Wed Aug 29 08:04:30 2007 From: lutz.horn at fastmail.fm (Lutz Horn) Date: Wed, 29 Aug 2007 08:04:30 +0200 Subject: [Tutor] Newbie In-Reply-To: References: Message-ID: <1188367470.27095.1207810229@webmail.messagingengine.com> Hi, On Tue, 28 Aug 2007 22:25:11 -0400, "Toby Holland" said: > I was wondering if any of you had any advice as to where I should > start in regards to learning using and programing with Python. Take a look at: * "Byte of Python" * The "Python Tutorial" by GvR * "Dive into Python" (advanced) Lutz -- From bhaaluu at gmail.com Wed Aug 29 10:00:25 2007 From: bhaaluu at gmail.com (bhaaluu) Date: Wed, 29 Aug 2007 04:00:25 -0400 Subject: [Tutor] Newbie In-Reply-To: References: Message-ID: On 8/28/07, Toby Holland wrote: > HI all, > I was wondering if any of you had any advice as to where I should start in > regards to learning using and programing with Python. I have wanted to > learn a program language for some time and just felt that now was good and I > have heard some great things about Python so any suggestions would be great. > Thank you all in advance! > Toby Greetings, The Python Books I have are the ones that are freely available for download from the Internet. Here is the list: Learning to Program (by Alan Gauld - a Tutor on this list.) http://www.freenetpages.co.uk/hp/alan.gauld/index.htm This book is also available for purchase in dead-tree form. How To Think Like a Computer Scientist: Learning with Python http://ibiblio.org/obp/thinkCS/python/english2e/html/index.html Dive Into Python http://www.diveintopython.org/ A Byte of Python http://swaroopch.info/text/Byte_of_Python:Main_Page Python Documentation http://docs.python.org/index.html Thinking in Python http://mindview.net/Books/TIPython Text Processing in Python http://gnosis.cx/TPiP/ Your best bet may be the "Learning to Program" book by Alan Gauld. Also there are a ton of tutorials on the Internet, many of which will get you up to speed with the basic stuff in a hurry. Your best bet is to find a book that has a writing style that "clicks" with you, and work through it, sitting in front of your computer, with Python installed and working. It is important to read and DO if you want to learn how to program a computer. Happy Programming! -- bhaaluu at gmail dot com From freebsd at scottevil.com Wed Aug 29 18:34:27 2007 From: freebsd at scottevil.com (Scott Oertel) Date: Wed, 29 Aug 2007 11:34:27 -0500 Subject: [Tutor] A replacement for a "for" loop In-Reply-To: <5e58f2e40708281912w3834d32blcb6f5db6d9afbe28@mail.gmail.com> References: <63990.68.191.136.241.1188352586.squirrel@webmail.opmstech.org> <5e58f2e40708281912w3834d32blcb6f5db6d9afbe28@mail.gmail.com> Message-ID: <46D5A013.5030602@scottevil.com> John Fouhy wrote: > On 29/08/07, Trey Keown wrote: > >> attrs={u'title': u'example window title', u'name': u'SELF', u'icon': >> u'e.ico'} >> keys = ['name','title','icon'] >> for (tag, val) in attrs.iteritems(): >> for key in keys: >> print val >> >> the first "for" tag causes the dictionary (attrs) to have its keys called >> "tag" and its value called "val". The second "for" loop causes the >> dictionary keys to be read in a certain order. How could I take away the >> first "for" loop and replace it with something else to do the same general >> function? >> > > for key in keys: > print 'Attribute %s has value %s' % (key, attrs[key]) > > Why even have the keys variable at all.. for key in attrs: print 'Attribute %s has value %s' % (key, attrs[key]) -Scott Oertel From carroll at tjc.com Wed Aug 29 19:49:22 2007 From: carroll at tjc.com (Terry Carroll) Date: Wed, 29 Aug 2007 10:49:22 -0700 (PDT) Subject: [Tutor] A replacement for a "for" loop In-Reply-To: <46D5A013.5030602@scottevil.com> Message-ID: On Wed, 29 Aug 2007, Scott Oertel wrote: > John Fouhy wrote: > > On 29/08/07, Trey Keown wrote: > > > >> attrs={u'title': u'example window title', u'name': u'SELF', u'icon': > >> u'e.ico'} > >> keys = ['name','title','icon'] > >> for (tag, val) in attrs.iteritems(): > >> for key in keys: > >> print val > >> > >> the first "for" tag causes the dictionary (attrs) to have its keys called > >> "tag" and its value called "val". The second "for" loop causes the > >> dictionary keys to be read in a certain order. How could I take away the > >> first "for" loop and replace it with something else to do the same general > >> function? > >> > > > > for key in keys: > > print 'Attribute %s has value %s' % (key, attrs[key]) > > > > > Why even have the keys variable at all.. > > for key in attrs: > print 'Attribute %s has value %s' % (key, attrs[key]) In a prior email thread, the OP indicated that he needed to process the keys in that particular order; and it's not really amenable to any sort. From pine508 at hotmail.com Wed Aug 29 21:55:49 2007 From: pine508 at hotmail.com (Che M) Date: Wed, 29 Aug 2007 15:55:49 -0400 Subject: [Tutor] tagging pieces of information In-Reply-To: Message-ID: > > Hi, I am curious about ways in Python to approach the idea of "tagging" > > pieces of information much in the way that one can tag favorite websites > > like on the site Del.icio.us. I'm not sure if tagging is the best term >for > > this (due to confusion with HTML tags), but the idea would be a way to > > assign one or more words to stored data such that later one might search >by > > those words in order to retrieve the data. That data might be a chunk >of > > text, a graph, image, whatever...the point would be to be able to search > > later by tags name. I know the prorgram GyrFalcon uses tags and is >written > > in Python. And of course Flickr and many other things. > >A simple way to do this in-memory would be to use a dict: keys are >tags and values are sets (or lists) of objects. You might need to >maintain an inverse structure too, mapping object to list/set of tags. > >You could use a database (sqlite comes with python 2.5). I'm not sure >what the "best practice" strucutre would be, but maybe you could have >a table with two columns: "object ID" and "tag". "object ID" would be >some kind of identifier for your tagged objects. You could then: > >Find tags for an object: > select tag from tagTable where objectID = ? > >Find objects matching a tag: > select objectID from tagTable where tag = ? > >-- >John. Thanks, John, I've fooled around with the database way to do it and it fits in nicely with other things I'm trying to do and should work well for me. Thanks to the others for their suggestions as well. -Che _________________________________________________________________ Puzzles, trivia teasers, word scrambles and more. Play for your chance to win! http://club.live.com/home.aspx?icid=CLUB_hotmailtextlink From dos.fool at gmail.com Thu Aug 30 00:19:21 2007 From: dos.fool at gmail.com (max baseman) Date: Wed, 29 Aug 2007 16:19:21 -0600 Subject: [Tutor] clearing a text document Message-ID: <46338834-B334-4266-885A-3CC4CD6DAD54@gmail.com> quick question how would i clear a text document? From gonzillaaa at gmail.com Thu Aug 30 00:13:05 2007 From: gonzillaaa at gmail.com (Gonzillaaa) Date: Wed, 29 Aug 2007 23:13:05 +0100 Subject: [Tutor] tagging pieces of information In-Reply-To: References: Message-ID: <6b6a049d0708291513k68885853tc97d6a8a1a3d8603@mail.gmail.com> Have a look at Tasty last time I checked it was postgres centric, it might have changed now. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070829/a1c3889b/attachment.htm From alessandrofd at yahoo.com.br Thu Aug 30 01:09:42 2007 From: alessandrofd at yahoo.com.br (Alessandro Dantas) Date: Wed, 29 Aug 2007 16:09:42 -0700 (PDT) Subject: [Tutor] Code reading for learning Python Message-ID: <86105.56732.qm@web56412.mail.re3.yahoo.com> Hello Everyone, I'm learning Python and my preferred method for learning a new language is to read code written by experts. I guess it makes even more sense in Python since I've been hearing so much about how your code should be pythonic to benefit from all the language can offer. Can anyone suggest some good pieces of (pythonic???) code? Alessandro Dantas Flickr agora em portugu?s. Voc? clica, todo mundo v?. http://www.flickr.com.br/ -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070829/b97cb440/attachment.htm From alan.gauld at btinternet.com Thu Aug 30 01:43:16 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 30 Aug 2007 00:43:16 +0100 Subject: [Tutor] Code reading for learning Python References: <86105.56732.qm@web56412.mail.re3.yahoo.com> Message-ID: "Alessandro Dantas" wrote > Can anyone suggest some good pieces of (pythonic???) code? The samples that come with python? The standard library modules? The IDLE IDE? Most of the sourceforge Python projects... Should be enough reading there... :-) Alan G From alan.gauld at btinternet.com Thu Aug 30 01:45:08 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 30 Aug 2007 00:45:08 +0100 Subject: [Tutor] clearing a text document References: <46338834-B334-4266-885A-3CC4CD6DAD54@gmail.com> Message-ID: "max baseman" wrote > quick question how would i clear a text document? A bit of context? If its a file you just open the file for writing. If its a list of strings in memory text = [] will clear it... If its a GUI text widget it will depend on which framework you are using. Alan G From gofinner at gmail.com Thu Aug 30 00:46:02 2007 From: gofinner at gmail.com (Tim Finley) Date: Wed, 29 Aug 2007 16:46:02 -0600 Subject: [Tutor] Trouble with script not parsing out text Message-ID: <46D5A2CA.B971.005E.3@gmail.com> I get the following when running a script. TypeError: argument 1 must be string or read-only character buffer, not _sre.SRE_Pattern Here is the script I am trying to run. I am trying to verify that my search is returning what I am trying to search for, but due to the error I can verify it. import re log = open('audit.log') # Opens audit log log2 = open('timaudit.log','w') for line in log: line =re.compile(r""" \w #match any alphanumeric character \Audit report for user+ \User reported as inactive+ """, re.VERBOSE) line.search('Audit report for user () User reported as inactive') log2.write(line) log.close() log2.close() Thank you, Tim Finley Novell IT Services Engineer Novell Technical Services Novell -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070829/23eeea19/attachment.htm -------------- next part -------------- A non-text attachment was scrubbed... Name: timaudit.log Type: application/octet-stream Size: 0 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20070829/23eeea19/attachment.obj From kent37 at tds.net Thu Aug 30 03:23:22 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 29 Aug 2007 21:23:22 -0400 Subject: [Tutor] Code reading for learning Python In-Reply-To: <86105.56732.qm@web56412.mail.re3.yahoo.com> References: <86105.56732.qm@web56412.mail.re3.yahoo.com> Message-ID: <46D61C0A.9090204@tds.net> Alessandro Dantas wrote: > Hello Everyone, > > I'm learning Python and my preferred method for learning a new language > is to read code written by experts. I guess it makes even more sense in > Python since I've been hearing so much about how your code should be > pythonic to benefit from all the language can offer. Can anyone suggest > some good pieces of (pythonic???) code? I found the printed Python Cookbook very helpful after I had learned the basics. Django seems to be well written and fairly easy to read. Kent From kent37 at tds.net Thu Aug 30 03:27:59 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 29 Aug 2007 21:27:59 -0400 Subject: [Tutor] Trouble with script not parsing out text In-Reply-To: <46D5A2CA.B971.005E.3@gmail.com> References: <46D5A2CA.B971.005E.3@gmail.com> Message-ID: <46D61D1F.4030308@tds.net> Tim Finley wrote: > I get the following when running a script. > > TypeError: argument 1 must be string or read-only character buffer, not > _sre.SRE_Pattern > > Here is the script I am trying to run. I am trying to verify that my > search is returning what I am trying to search for, but due to the error > I can verify it. > > import re > > log = open('audit.log') # Opens audit log > log2 = open('timaudit.log','w') > for line in log: > line =re.compile(r""" Here you are replacing 'line' the data from one line of the log with 'line' a compiled regular expression. 'line' the data is no longer available. > \w #match any alphanumeric character > \Audit report for user+ > \User reported as inactive+ > """, re.VERBOSE) > line.search('Audit report for user () User reported as inactive') Now you use 'line' the regex to search some fixed text. > log2.write(line) This writes the regex to the file, which is the cause of the error. > > log.close() > log2.close() I'm not really sure what you are trying to do. I think you want to write every line from log that matches the regex to log2. Code to do that would look like this: log = open('audit.log') # Opens audit log log2 = open('timaudit.log','w') audit_re =re.compile(r""" \w #match any alphanumeric character \Audit report for user+ \User reported as inactive+ """, re.VERBOSE) for line in log: if audit_re.search(line): log2.write(line) log.close() log2.close() Kent From brunson at brunson.com Thu Aug 30 03:29:11 2007 From: brunson at brunson.com (Eric Brunson) Date: Wed, 29 Aug 2007 19:29:11 -0600 Subject: [Tutor] Trouble with script not parsing out text In-Reply-To: <46D5A2CA.B971.005E.3@gmail.com> References: <46D5A2CA.B971.005E.3@gmail.com> Message-ID: <46D61D67.6060102@brunson.com> Tim Finley wrote: > I get the following when running a script. > > TypeError: argument 1 must be string or read-only character buffer, > not _sre.SRE_Pattern First, please post the entire error report when asking for help. In this case I can tell you what the problem is, but in others the context of the error may not be so apparent. > > Here is the script I am trying to run. I am trying to verify that my > search is returning what I am trying to search for, but due to the > error I can verify it. > > import re > > log = open('audit.log') # Opens audit log > log2 = open('timaudit.log','w') > for line in log: > line =re.compile(r""" I think you want to use a different variable name than "line". You're using it for the current line, then setting it to the compiled regular expression. > \w #match any alphanumeric character > \Audit report for user+ > \User reported as inactive+ > """, re.VERBOSE) > line.search('Audit report for user () User reported as inactive') > log2.write(line) Hence the error. Write expects a line of text, but it doesn't point to the line of text you read any more. Hope that helps, e. > > log.close() > log2.close() > > Thank you, > > Tim Finley > Novell IT Services Engineer > Novell Technical Services > Novell > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From dos.fool at gmail.com Thu Aug 30 06:33:00 2007 From: dos.fool at gmail.com (max baseman) Date: Wed, 29 Aug 2007 22:33:00 -0600 Subject: [Tutor] clearing a text document In-Reply-To: References: <46338834-B334-4266-885A-3CC4CD6DAD54@gmail.com> Message-ID: <90373A8E-94A6-4C22-8469-03886E14068E@gmail.com> right it's for a quick math "game" the rules are simple you start with any number to get the next number you, a. if it's odd multiply by 3 than add 1 or b. if it's even divide by two, the point of this is to see how long it takes to get to one are it starts to repeat 4,2,1,4,2,1... now im looking for a a number with a very high amount of numbers till you get to 1 so every time it's finds a new one i would like it to write that to a file and clear the last entry, On Aug 29, 2007, at 5:45 PM, Alan Gauld wrote: > > "max baseman" wrote > >> quick question how would i clear a text document? > > A bit of context? If its a file you just open the file for writing. > > If its a list of strings in memory > > text = [] > > will clear it... > > If its a GUI text widget it will depend on which framework you are > using. > > Alan G > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From rabidpoobear at gmail.com Thu Aug 30 07:02:59 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Thu, 30 Aug 2007 00:02:59 -0500 Subject: [Tutor] clearing a text document In-Reply-To: <90373A8E-94A6-4C22-8469-03886E14068E@gmail.com> References: <46338834-B334-4266-885A-3CC4CD6DAD54@gmail.com> <90373A8E-94A6-4C22-8469-03886E14068E@gmail.com> Message-ID: <46D64F83.7060403@gmail.com> max baseman wrote: > right it's for a quick math "game" the rules are simple you start > with any number to get the next number you, a. if it's odd multiply > by 3 than add 1 or b. if it's even divide by two, the point of this > is to see how long it takes to get to one are it starts to repeat > 4,2,1,4,2,1... > now im looking for a a number with a very high amount of numbers > till you get to 1 so every time it's finds a new one i would like it > to write that to a file and clear the last entry, Just open the file for writing and it will erase all previous contents and create the file if it doesn't already exist. -Luke From kent37 at tds.net Thu Aug 30 12:53:59 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 30 Aug 2007 06:53:59 -0400 Subject: [Tutor] clearing a text document In-Reply-To: <90373A8E-94A6-4C22-8469-03886E14068E@gmail.com> References: <46338834-B334-4266-885A-3CC4CD6DAD54@gmail.com> <90373A8E-94A6-4C22-8469-03886E14068E@gmail.com> Message-ID: <46D6A1C7.8000703@tds.net> max baseman wrote: > right it's for a quick math "game" the rules are simple you start > with any number to get the next number you, a. if it's odd multiply > by 3 than add 1 or b. if it's even divide by two, the point of this > is to see how long it takes to get to one are it starts to repeat > 4,2,1,4,2,1... > now im looking for a a number with a very high amount of numbers > till you get to 1 so every time it's finds a new one i would like it > to write that to a file and clear the last entry, If your goal is to find long sequences why not write your program to try every number up to some limit and find the longest? It's a nice use of generators, for those who know what they are... These sequences are known as hailstone numbers. The (unproven) conjecture that the sequence will always terminate is called Collatz' Conjecture. Some interesting info and pictures here: http://sprott.physics.wisc.edu/pickover/hailstone.html http://mathworld.wolfram.com/CollatzProblem.html Kent From dos.fool at gmail.com Thu Aug 30 14:11:10 2007 From: dos.fool at gmail.com (max baseman) Date: Thu, 30 Aug 2007 06:11:10 -0600 Subject: [Tutor] clearing a text document In-Reply-To: <46D6A1C7.8000703@tds.net> References: <46338834-B334-4266-885A-3CC4CD6DAD54@gmail.com> <90373A8E-94A6-4C22-8469-03886E14068E@gmail.com> <46D6A1C7.8000703@tds.net> Message-ID: thats what it does but in order to just be able to let it sit and work for as long as it can i made it a endless loop of just trying every number, for now it just displays the highest on the screen but it would be nice to get it in a text document thanks On Aug 30, 2007, at 4:53 AM, Kent Johnson wrote: > max baseman wrote: >> right it's for a quick math "game" the rules are simple you start >> with any number to get the next number you, a. if it's odd >> multiply by 3 than add 1 or b. if it's even divide by two, the >> point of this is to see how long it takes to get to one are it >> starts to repeat 4,2,1,4,2,1... >> now im looking for a a number with a very high amount of numbers >> till you get to 1 so every time it's finds a new one i would like >> it to write that to a file and clear the last entry, > > If your goal is to find long sequences why not write your program > to try every number up to some limit and find the longest? > > It's a nice use of generators, for those who know what they are... > > These sequences are known as hailstone numbers. The (unproven) > conjecture that the sequence will always terminate is called > Collatz' Conjecture. Some interesting info and pictures here: > http://sprott.physics.wisc.edu/pickover/hailstone.html > http://mathworld.wolfram.com/CollatzProblem.html > > Kent From dos.fool at gmail.com Thu Aug 30 14:11:42 2007 From: dos.fool at gmail.com (max baseman) Date: Thu, 30 Aug 2007 06:11:42 -0600 Subject: [Tutor] clearing a text document In-Reply-To: <46D64F83.7060403@gmail.com> References: <46338834-B334-4266-885A-3CC4CD6DAD54@gmail.com> <90373A8E-94A6-4C22-8469-03886E14068E@gmail.com> <46D64F83.7060403@gmail.com> Message-ID: <1DECECE1-424C-425F-8D72-303F3B5B5C8F@gmail.com> cool thank you :) On Aug 29, 2007, at 11:02 PM, Luke Paireepinart wrote: > max baseman wrote: >> right it's for a quick math "game" the rules are simple you start >> with any number to get the next number you, a. if it's odd >> multiply by 3 than add 1 or b. if it's even divide by two, the >> point of this is to see how long it takes to get to one are it >> starts to repeat 4,2,1,4,2,1... >> now im looking for a a number with a very high amount of numbers >> till you get to 1 so every time it's finds a new one i would like >> it to write that to a file and clear the last entry, > Just open the file for writing and it will erase all previous > contents and create the file if it doesn't already exist. > -Luke From janos.juhasz at VELUX.com Thu Aug 30 15:13:39 2007 From: janos.juhasz at VELUX.com (=?ISO-8859-1?Q?J=E1nos_Juh=E1sz?=) Date: Thu, 30 Aug 2007 15:13:39 +0200 Subject: [Tutor] Triangle structure for triangulation Message-ID: Dear All, I have written a Delaunay triangulation 10 years ago in C based on triangle structure. It was 400 lines, so it seems to be a fine task to turn into python. My problem is the translation of the C structure and the OO thinking. I tried to draft it so. /* The triangle, its neighbours, sides and rotations. 0 VTOP / \ / t r \ LEFT/ o o \RIGHT 1 / r t \ / act \ 1 VLEFT--------VRIGHT 2 BOTTOM 0 */ typedef struct{ TRIINDEX neighbour[3]; // triangles: bottom, right, left POINTINDEX vertex[3]; // vertex: top, left, right float height; // elevation } TRIANGLE; Each triangle has three vertices and three neighbours. To calculate the elvation on the triangulation at a given point, it is important to find the coresponding triangle as fast as possible, so the triangles had directions. But it was important in the update process too. So I had an array with the triangles, but the neighbours were directed triangles not simple triangle (TRIINDEX). There were C macros to get the neighbours of the triangles. To get the left triangle tleft = LEFT(t), tright = RIGHT(t), tbottom = BOTTOM(t) ROT(t) was the same triangle as t, but rotated ccw. so t = ROT(ROT(ROT(t))) TOR(t) was the same triangle as t, but rotated cw. t = TOR(TOR(TOR(t))) In C, I have used typedef unsigned int TRIINDEX; to identify a triangle, where the last two bites were used to handle the directions. ## I can translate it into python in this way class Triangle: def __init__(self, points, neighbours): self.points = points self.neighbours = neighbours def TOR(self, direction): return (self, (direction+1)%3) def ROT(self, direction): return (self, (direction+2)%3) def RIGHT(self, direction): return (self.neighbours[(direction+2)%3]) I would ask your opinions to encapsulate a triangle into a directed triangle. I made my first trial on the way to keep a directed triangle as a tuple (triangle, direction) and register it in that way. I would like to use directed triangles, but wouldn't like to use too much memory. Yours sincerely, Janos Juhasz From alan.gauld at btinternet.com Thu Aug 30 17:33:34 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 30 Aug 2007 16:33:34 +0100 Subject: [Tutor] Triangle structure for triangulation References: Message-ID: "J?nos Juh?sz" wrote > ## I can translate it into python in this way > class Triangle: > def __init__(self, points, neighbours): > self.points = points > self.neighbours = neighbours > > def TOR(self, direction): > return (self, (direction+1)%3) > > def ROT(self, direction): > return (self, (direction+2)%3) > > def RIGHT(self, direction): > return (self.neighbours[(direction+2)%3]) > > I would ask your opinions to encapsulate a triangle into a directed > triangle. I'm not totally sure what you are looking for but my first guess would be to add a direction argument to the init and store it as an attribute. But it sounds like you need to add some methods too. What do you do with these triangles? From your descriptionI'd expect to see some methods taking other triangles as arguments? For example you store the points but never use them. Attributes in a class shjould be thee to support the metjods. If the atrributes are not used by any method that implies that they are not needed or that you are accessing them from some function outside the class, which is probably an indication of bad OO design. > I made my first trial on the way to keep a directed triangle as a > tuple > (triangle, direction) and register it in that way. > I would like to use directed triangles, but wouldn't like to use too > much > memory. How much memory would be too much? If you don't know, then go with the best design and optimise the memory only when you know that there is a need. Prematurely optimising memory is just as bad as prematurely optimising speed. It usually leads to bad code when there is no need. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From freebsd at scottevil.com Thu Aug 30 21:10:56 2007 From: freebsd at scottevil.com (Scott Oertel) Date: Thu, 30 Aug 2007 14:10:56 -0500 Subject: [Tutor] A replacement for a "for" loop In-Reply-To: References: Message-ID: <46D71640.5010800@scottevil.com> Terry Carroll wrote: > On Wed, 29 Aug 2007, Scott Oertel wrote: > > >> Why even have the keys variable at all.. >> >> for key in attrs: >> print 'Attribute %s has value %s' % (key, attrs[key]) >> > > In a prior email thread, the OP indicated that he needed to process the > keys in that particular order; and it's not really amenable to any sort. > > Yup, I didn't see that the first time, sorry. -Scott Oertel From freebsd at scottevil.com Thu Aug 30 21:18:15 2007 From: freebsd at scottevil.com (Scott Oertel) Date: Thu, 30 Aug 2007 14:18:15 -0500 Subject: [Tutor] Formatting output into columns Message-ID: <46D717F7.8030000@scottevil.com> Someone asked me this question the other day, and I couldn't think of any easy way of printing the output besides what I came up with pasted below. So what you have is a file with words in it as such: apple john bean joke ample python nice and you want to sort and output the text into columns as such: a p j b n apple python john bean nice ample joke and this is what works, but I would also like to know how to wrap the columns, plus any ideas on a better way to accomplish this. #!/usr/bin/env python data = {} lrgColumn = 0 for line in open("test.txt","r").read().splitlines(): char = line[0].lower() if not char in data: data[char] = [line] else: data[char].append(line) for item in data: print item.ljust(10), if len(data[item]) > lrgColumn: lrgColumn = len(data[item]) print for item in range(lrgColumn): for i in data.iteritems(): try: print i[1][item].ljust(10), except IndexError: print "".ljust(10), print From janos.juhasz at VELUX.com Thu Aug 30 22:18:36 2007 From: janos.juhasz at VELUX.com (=?ISO-8859-1?Q?J=E1nos_Juh=E1sz?=) Date: Thu, 30 Aug 2007 22:18:36 +0200 Subject: [Tutor] Triangle structure for triangulation Message-ID: Dear Allan, thanks for your coments. > > ## I can translate it into python in this way > > class Triangle: > > def __init__(self, points, neighbours): > > self.points = points > > self.neighbours = neighbours > > > > def TOR(self, direction): > > return (self, (direction+1)%3) > > > > def ROT(self, direction): > > return (self, (direction+2)%3) > > > > def RIGHT(self, direction): > > return (self.neighbours[(direction+2)%3]) > > > > I would ask your opinions to encapsulate a triangle into a directed > > triangle. > > I'm not totally sure what you are looking for but my first > guess would be to add a direction argument to the init > and store it as an attribute. But it sounds like you need > to add some methods too. What do you do with these > triangles? From your descriptionI'd expect to see some > methods taking other triangles as arguments? The triangulation would be used for surface modelling. The most important function is CalcZ(point(x, y)), that interpolates the elevation on the surface of a triangle. For this interpolation I have to find the corresponding triangle of the point, that can be made the fastest by walking from triangle to triangle. This is the first reason I need the neighbours. I also need to extend and update the triangulation, when a new point inserted into it. > For example you store the points but never use them. > Attributes in a class shjould be thee to support the metjods. > If the atrributes are not used by any method that implies > that they are not needed or that you are accessing them > from some function outside the class, which is probably > an indication of bad OO design. I feel that, the best would be to strore 3 separate triangles for A,B,C points, Triangulation.Append(Triangle(A,B,C)) Triangulation.Append(Triangle(B,C,A)) Triangulation.Append(Triangle(C,A,B)) And register the topological relations after it. It could be OO, and simple. As I wrote, I made it in C with structures, so it wasn't OO, but fast. I can translate a C iteration over C structures into python, to iterate over class objects, and usually I don't miss the pointers. Except now, when the algorithm based strongly on pointers and indeces :( Yours sincerely, Janos Juhasz From alan.gauld at btinternet.com Thu Aug 30 22:58:44 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 30 Aug 2007 21:58:44 +0100 Subject: [Tutor] Formatting output into columns References: <46D717F7.8030000@scottevil.com> Message-ID: "Scott Oertel" wrote > and you want to sort and output the text into columns as such: > > a p j b n > apple python john bean nice > ample joke > > and this is what works, but I would also like to know how to wrap > the > columns, plus any ideas on a better way to accomplish this. Use format strings. You can calculate the column widths by analyzing the data then create a format string for the required number of columns. Finally insert the data on each row from a tuple. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From freebsd at scottevil.com Thu Aug 30 23:20:03 2007 From: freebsd at scottevil.com (Scott Oertel) Date: Thu, 30 Aug 2007 16:20:03 -0500 Subject: [Tutor] Formatting output into columns In-Reply-To: References: <46D717F7.8030000@scottevil.com> Message-ID: <46D73483.8080502@scottevil.com> Alan Gauld wrote: > "Scott Oertel" wrote > > >> and you want to sort and output the text into columns as such: >> >> a p j b n >> apple python john bean nice >> ample joke >> >> and this is what works, but I would also like to know how to wrap >> the >> columns, plus any ideas on a better way to accomplish this. >> > > Use format strings. You can calculate the column widths by analyzing > the data then create a format string for the required number of > columns. > Finally insert the data on each row from a tuple. > > > HTH, > > > Do you have any good documentation that could shed some more light on exactly how to use format strings in such a way? -Scott Oertel From kent37 at tds.net Thu Aug 30 23:25:55 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 30 Aug 2007 17:25:55 -0400 Subject: [Tutor] Formatting output into columns In-Reply-To: <46D717F7.8030000@scottevil.com> References: <46D717F7.8030000@scottevil.com> Message-ID: <46D735E3.40909@tds.net> Scott Oertel wrote: > #!/usr/bin/env python > > data = {} > lrgColumn = 0 > > for line in open("test.txt","r").read().splitlines(): > char = line[0].lower() > if not char in data: > data[char] = [line] > else: > data[char].append(line) I like data.setdefault(char, []).append(line) instead of the four lines above. > > for item in data: > print item.ljust(10), > if len(data[item]) > lrgColumn: > lrgColumn = len(data[item]) > print > > for item in range(lrgColumn): > for i in data.iteritems(): > try: > print i[1][item].ljust(10), If you used data.itervalues() then it would be just print i[item].ljust(10), > except IndexError: > print "".ljust(10), > print To get the data in row order you can use map(None, *data.values()) This will give a list of rows with None in the blank spots. You might like one of these recipes for the actual table output: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/267662 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/519618 Kent From alan.gauld at btinternet.com Thu Aug 30 23:26:59 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 30 Aug 2007 22:26:59 +0100 Subject: [Tutor] Triangle structure for triangulation References: Message-ID: "J?nos Juh?sz" wrote >> > ## I can translate it into python in this way >> > class Triangle: >> > def __init__(self, points, neighbours): >> > def TOR(self, direction): >> > def ROT(self, direction): >> > def RIGHT(self, direction): >> and store it as an attribute. But it sounds like you need >> to add some methods too. What do you do with these >> triangles? > The most important function is CalcZ(point(x, y)), that interpolates > the > elevation on the surface of a triangle. > For this interpolation I have to find the corresponding triangle of > the > point, that can be made the fastest by walking from triangle to > triangle. > This is the first reason I need the neighbours. OK, That suggests to me that your triangle should have a predicate method contains(aPoint) where aPoint is a tuple of x,y coords and it returns a boolean. The iteration could then become a list comprehension: candidates = [t for t in triangles if t.contains(myPoint)] candidates will be a list of all triangles containing the point (hopefully a very short list!!) And the calcZ function could be a method of the collection of triangles if the collection were made into a class - a TriangualtedSurface maybe? > I also need to extend and update the triangulation, when a new point > inserted into it. OK That sounds like a job for the Surface class too, but with a fairt bit of help from, the triangles within it. A lot of the adoption of OOP is about rethinking how procedural style functionscan be split up with the various responsibilities parceled out between the various objects. The end result tends to be a lot of small methods within the various classes. And the top level method either simply orchestrates the execution of the helper methods in the component classes or starts a cascade of method calls as each component does something then delegates to its components (this is usually how GUIs work). I suspect your surface model would be a candidate for the orchestration technique. > I feel that, the best would be to strore 3 separate triangles for > A,B,C > points, > > Triangulation.Append(Triangle(A,B,C)) > Triangulation.Append(Triangle(B,C,A)) > Triangulation.Append(Triangle(C,A,B)) > And register the topological relations after it. It could be OO, and > simple. OO is usually simpler that traditiona;l procedural once you get the knack. Its because you delegate the functions to where the data is so all processing tends to be simplified. The big down side is that you can end up with very deep call stacks, but in practice this is rarely as big a problem as traditionalists expected when OOP was introduced. > As I wrote, I made it in C with structures, so it wasn't OO, but > fast. OO doesn't need to be slow, especially in C++ where some OOP programs have been shown to be faster than their non OOP equiva;lents. But in Python speed of execution is almost never the primary aim, "fast enough" and easy to build and maintain are the usual goals. > Except now, when the algorithm based strongly on pointers and > indeces :( Real low level pointer arithmetic can be tricky to convert pythonically but normal array indexing is nt usually an issue. Either a while loop or a for loop will do the job. But an OOP approach can often render both unnecessary, or at least greatly simplify things. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Thu Aug 30 23:44:03 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 30 Aug 2007 22:44:03 +0100 Subject: [Tutor] Formatting output into columns References: <46D717F7.8030000@scottevil.com> <46D73483.8080502@scottevil.com> Message-ID: "Scott Oertel" wrote >> Use format strings. You can calculate the column widths by >> analyzing >> the data then create a format string for the required number of >> columns. >> Finally insert the data on each row from a tuple. >> > Do you have any good documentation that could shed some more light > on > exactly how to use format strings in such a way? The docs contain the basic documentation, here is a short example: data = ['one','fifteen',''four'] max_width = max([len(w) for w in data)]) # there's a slightly better way to do this which I can't recall right now! # %% -> literal %, # %s = insert string # so %%%ss -> %Xs where X is the inserted data fmtStr = "%%%ss\t%%%ss%%%ss" % (max_width, max_width, max_width) print fmtStr % tuple(data) That should produce a format string where each column is the max width of any of the data items You can use the string center() method to pad the headings if required. You can either put left/right justification into the format string (using +/-) or use the string methods (rjust,ljust) to do it for you. If its not clear how to extend that to a multi dimensional set of data then feel free to ask for more detail with some sample data and the specific requirements HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From orest.kozyar at gmail.com Fri Aug 31 00:02:12 2007 From: orest.kozyar at gmail.com (Orest Kozyar) Date: Thu, 30 Aug 2007 18:02:12 -0400 Subject: [Tutor] Variable scope for class? Message-ID: <003901c7eb51$6bd99b50$bd32000a@issphoenix> I'm trying to follow the example listed in the wiki at http://www.sqlalchemy.org/trac/wiki/UsageRecipes/UniqueObject regarding the use of a metaclass. What I don't understand is how the metaclass (EntitySingleton) has access to the variable ctx which is instantinated outside the scope of the class definition. Could anyone point me in the right direction please? Thanks, Orest From kent37 at tds.net Fri Aug 31 00:21:47 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 30 Aug 2007 18:21:47 -0400 Subject: [Tutor] Formatting output into columns In-Reply-To: References: <46D717F7.8030000@scottevil.com> <46D73483.8080502@scottevil.com> Message-ID: <46D742FB.5010307@tds.net> Alan Gauld wrote: > "Scott Oertel" wrote >> Do you have any good documentation that could shed some more light >> on >> exactly how to use format strings in such a way? > > The docs contain the basic documentation http://docs.python.org/lib/typesseq-strings.html > # there's a slightly better way to do this which I can't recall right > now! > # %% -> literal %, > # %s = insert string > # so %%%ss -> %Xs where X is the inserted data > fmtStr = "%%%ss\t%%%ss%%%ss" % (max_width, max_width, max_width) > > print fmtStr % tuple(data) I think you are looking for * as a width specifier which takes the width from the argument list though it might be a bit awkward in this case where the length of the argument list varies. Kent From kent37 at tds.net Fri Aug 31 00:33:20 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 30 Aug 2007 18:33:20 -0400 Subject: [Tutor] Variable scope for class? In-Reply-To: <003901c7eb51$6bd99b50$bd32000a@issphoenix> References: <003901c7eb51$6bd99b50$bd32000a@issphoenix> Message-ID: <46D745B0.1060107@tds.net> Orest Kozyar wrote: > I'm trying to follow the example listed in the wiki at > http://www.sqlalchemy.org/trac/wiki/UsageRecipes/UniqueObject regarding the > use of a metaclass. > > What I don't understand is how the metaclass (EntitySingleton) has access to > the variable ctx which is instantinated outside the scope of the class > definition. Could anyone point me in the right direction please? This is just basic name lookup rules. Names are looked up, in order, - in the scope of the current function - in the scope of any lexically enclosing functions - in the scope of the module containing the function (the 'global' scope) - in the built-in scope. ctx is defined at module level so the third step of the name lookup finds it. Not finding any great references but here are a few that might help: http://diveintopython.org/html_processing/locals_and_globals.html http://swaroopch.info/text/Special:Search?search=namespace&go=Go http://docs.python.org/ref/naming.html Kent From dkuhlman at rexx.com Fri Aug 31 00:53:47 2007 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Thu, 30 Aug 2007 15:53:47 -0700 Subject: [Tutor] Variable scope for class? In-Reply-To: <003901c7eb51$6bd99b50$bd32000a@issphoenix> References: <003901c7eb51$6bd99b50$bd32000a@issphoenix> Message-ID: <20070830225347.GA35364@cutter.rexx.com> On Thu, Aug 30, 2007 at 06:02:12PM -0400, Orest Kozyar wrote: > I'm trying to follow the example listed in the wiki at > http://www.sqlalchemy.org/trac/wiki/UsageRecipes/UniqueObject regarding the > use of a metaclass. > > What I don't understand is how the metaclass (EntitySingleton) has access to > the variable ctx which is instantinated outside the scope of the class > definition. Could anyone point me in the right direction please? Alan's book has a chapter on this (chapter 16 "Namespaces", in "Learn to Program using Python"). And, "Learning Python", by Mark Lutz also covers it. You will need to pay attention to the LEGB rule, which basically says that Python searches for a name in namespaces in the following order: 1. Local 2. Enclosing (specifically enclosing functions if this is a nested function) 3. Global 4. Built-ins So, in your specific example, Python looks: 1. In the Local namespace, but can't find ctx. 2. The enclosing namespace, but there is none, since this function/method is not nested in another one. 3. The Global namespace, where it finds "ctx" and quits. One thing to keep in mind, is that Python looks for names (variables) in the namespaces where a class or method or function is defined, *not* in the namespaces where those objects are used or called. So far so good. But, here is the one I do not understand. G1 = 111 class A(object): G1 = 222 def show(self): print G1 def test(): a = A() a.show() test() But, when I run this I see "111", not "222". Why is that? "G1 = 222" is in the enclosing scope, right? Well, I guess that is wrong. Apparently in Python, a class does not create an enclosing scope. Actually, the particular edition of Alan's book that I have is old enough so that it does not discuss the Enclosing namespace, which came later to Python. The enclosing namespace not make a difference in your example, but does in mine. Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman From kent37 at tds.net Fri Aug 31 01:52:11 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 30 Aug 2007 19:52:11 -0400 Subject: [Tutor] Variable scope for class? In-Reply-To: <20070830225347.GA35364@cutter.rexx.com> References: <003901c7eb51$6bd99b50$bd32000a@issphoenix> <20070830225347.GA35364@cutter.rexx.com> Message-ID: <46D7582B.7060007@tds.net> Dave Kuhlman wrote: > So far so good. But, here is the one I do not understand. > > G1 = 111 > class A(object): > G1 = 222 > def show(self): > print G1 > > def test(): > a = A() > a.show() > > test() > > But, when I run this I see "111", not "222". > > Why is that? "G1 = 222" is in the enclosing scope, right? > > Well, I guess that is wrong. Apparently in Python, a class does > not create an enclosing scope. Right. The class statement creates a temporary local namespace that is used to initialize the __dict__ of the class. Names in this namespace can be accessed directly while the class statement is executing; after that they have to be accessed as attributes of the class or an instance. Kent From alan.gauld at btinternet.com Fri Aug 31 01:54:30 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 31 Aug 2007 00:54:30 +0100 Subject: [Tutor] Variable scope for class? References: <003901c7eb51$6bd99b50$bd32000a@issphoenix> <20070830225347.GA35364@cutter.rexx.com> Message-ID: "Dave Kuhlman" wrote > Actually, the particular edition of Alan's book that I have is old > enough so that it does not discuss the Enclosing namespace, which > came later to Python. The enclosing namespace not make a > difference in your example, but does in mine. The paper book is based on Python 1.5.1 The web page is based on Python 2.2 and mentions enclosing scope (although I call it "nested" and avoid discussing it in detail! :-) I intended adding sections in the functional programming and OOP topics but it doesn't look like I ever really got round to it! oops! :-( Alan G. From rabidpoobear at gmail.com Fri Aug 31 05:03:48 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Thu, 30 Aug 2007 22:03:48 -0500 Subject: [Tutor] Formatting output into columns In-Reply-To: <46D717F7.8030000@scottevil.com> References: <46D717F7.8030000@scottevil.com> Message-ID: <46D78514.8040403@gmail.com> Scott Oertel wrote: > Someone asked me this question the other day, and I couldn't think of > any easy way of printing the output besides what I came up with pasted > below. > > So what you have is a file with words in it as such: > > apple > john > bean > joke > ample > python > nice > > and you want to sort and output the text into columns as such: > > a p j b n > apple python john bean nice > ample joke > > and this is what works, but I would also like to know how to wrap the > columns, plus any ideas on a better way to accomplish this. > > #!/usr/bin/env python > > data = {} > lrgColumn = 0 > > for line in open("test.txt","r").read().splitlines(): > you can just directly do for line in open('test.txt'): depending on your Python version. I believe it's 2.3+. I have 2.4 and it works there, at least. If using an older version of Python, you can use .readlines() instead of .read().splitlines() I believe Kent and Alan already helped you with your original question. -Luke From freebsd at scottevil.com Fri Aug 31 15:35:59 2007 From: freebsd at scottevil.com (Scott Oertel) Date: Fri, 31 Aug 2007 08:35:59 -0500 Subject: [Tutor] Formatting output into columns In-Reply-To: <46D78514.8040403@gmail.com> References: <46D717F7.8030000@scottevil.com> <46D78514.8040403@gmail.com> Message-ID: <46D8193F.60501@scottevil.com> Luke Paireepinart wrote: > Scott Oertel wrote: >> Someone asked me this question the other day, and I couldn't think of >> any easy way of printing the output besides what I came up with pasted >> below. >> >> So what you have is a file with words in it as such: >> >> apple >> john >> bean >> joke >> ample >> python >> nice >> >> and you want to sort and output the text into columns as such: >> >> a p j b n >> apple python john bean nice >> ample joke >> >> and this is what works, but I would also like to know how to wrap the >> columns, plus any ideas on a better way to accomplish this. >> >> #!/usr/bin/env python >> >> data = {} >> lrgColumn = 0 >> >> for line in open("test.txt","r").read().splitlines(): >> > you can just directly do > for line in open('test.txt'): > > depending on your Python version. I believe it's 2.3+. > I have 2.4 and it works there, at least. > If using an older version of Python, you can use .readlines() instead > of .read().splitlines() > > I believe Kent and Alan already helped you with your original question. > -Luke The reason I use read().splitlines, is because if you do .readlines() it adds the carriage return to the end of each line where in i have to .rstrip() to remove it. If you use .read() it doesn't split the lines in the file into a tuple, there for you it is not an iteration. -Scott Oertel From ghashsnaga at gmail.com Fri Aug 31 21:06:01 2007 From: ghashsnaga at gmail.com (Ara Kooser) Date: Fri, 31 Aug 2007 13:06:01 -0600 Subject: [Tutor] Starting classes Message-ID: <2107481c0708311206h6f7179c9j44ef62a470d4e249@mail.gmail.com> Hello, I read Alan Gauld's and How to Think Like a Computer Scientist section on classes. So I tried to write a simple room class. My goal is to write a short text adventure using classes. Here is the code: class Area: def _init_(self, name, description): self.name = name def look(here): "Look around the place you are in" print here.description outside1 = Area("Outside") outside1.description = "You are standing outside with the town gate to your back" self.contents.append("dirt") look(bedroom) I get the following error. Traceback (most recent call last): File "/Users/ara/Documents/text_advent.py", line 11, in outside1 = Area("Outside") TypeError: this constructor takes no arguments Do the outside1 = Area("Outside) need to be nested in the class or can they be outside of it? Thank you. Ara -- Quis hic locus, quae regio, quae mundi plaga. Ubi sum. Sub ortu solis an sub cardine glacialis ursae. From brunson at brunson.com Fri Aug 31 21:48:37 2007 From: brunson at brunson.com (Eric Brunson) Date: Fri, 31 Aug 2007 13:48:37 -0600 Subject: [Tutor] Starting classes In-Reply-To: <2107481c0708311206h6f7179c9j44ef62a470d4e249@mail.gmail.com> References: <2107481c0708311206h6f7179c9j44ef62a470d4e249@mail.gmail.com> Message-ID: <46D87095.9000407@brunson.com> Ara Kooser wrote: > Hello, > I read Alan Gauld's and How to Think Like a Computer Scientist > section on classes. So I tried to write a simple room class. My goal > is to write a short text adventure using classes. Here is the code: > > class Area: > def _init_(self, name, description): > Not enough underscores, you need two before and after the word "init". > self.name = name > > > def look(here): > "Look around the place you are in" > print here.description > > > outside1 = Area("Outside") > outside1.description = "You are standing outside with the town gate to > your back" > Why not: outside1 = Area( "Outside", "You are standing outside..." ) and store self.description in the constructor? > self.contents.append("dirt") > What is self? You've only defined self in the class methods and you're outside the class definition. Was that just a cut and paste error? > > look(bedroom) > You'll get another error here, I think you want: outside1.look( bedroom ) > I get the following error. > Traceback (most recent call last): > File "/Users/ara/Documents/text_advent.py", line 11, in > outside1 = Area("Outside") > TypeError: this constructor takes no arguments > > Do the outside1 = Area("Outside) need to be nested in the class or can > they be outside of it? > No, that's correct, because you are instantiating the class and naming that instance "outside1". > Thank you. > > Ara > > > > Hope that all helps, e. From david.bear at asu.edu Fri Aug 31 21:40:04 2007 From: david.bear at asu.edu (David Bear) Date: Fri, 31 Aug 2007 12:40:04 -0700 Subject: [Tutor] or synxtax in if statement Message-ID: <1209729.3dhOnFbX70@teancum> I think I want to be lazy and express this if a == b | a = c (if a equal b or a equals c) using if a == b | c it seems to work.. but I'm not sure if it is correct -- and I haven't seen any documentation on using this type of syntax. -- -- David Bear College of Public Programs at Arizona State University From jsmith at medplus.com Fri Aug 31 22:20:05 2007 From: jsmith at medplus.com (Smith, Jeff) Date: Fri, 31 Aug 2007 16:20:05 -0400 Subject: [Tutor] or synxtax in if statement In-Reply-To: <1209729.3dhOnFbX70@teancum> References: <1209729.3dhOnFbX70@teancum> Message-ID: <288A3B43F7B2224D9C8441C9FC5D6A02023A35F8@EXCHMAIL01.corp.medplus.com> That definitely won't work. How could the language possibly determine if you meant a == b | a == c as opposed to the literal a == b | c What this becomes is a == (b | c) Also be aware that | is a "bitwise or" and not a logical "or" which may not be what you want. So your original expression may not be what you want since it will get evaluated as a == (b | a) == c Consider the following result: >>> a=0 >>> b=0 >>> c=1 >>> print a == b | a == c False >>> print a == (b | a) == c False >>> print (a == b) | (a == c) True >>> print a == b | c False Although what I suspect you really want is >>> print a == b or a == c True >>> print (a == b) or (a == c) True But this means that your shortcut becomes (a == b) or c So consider >>> a=0 >>> b=1 >>> c=0 >>> print a == b or c 0 Which is the same as false. Jeff -----Original Message----- From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of David Bear Sent: Friday, August 31, 2007 3:40 PM To: tutor at python.org Subject: [Tutor] or synxtax in if statement I think I want to be lazy and express this if a == b | a = c (if a equal b or a equals c) using if a == b | c it seems to work.. but I'm not sure if it is correct -- and I haven't seen any documentation on using this type of syntax. -- -- David Bear College of Public Programs at Arizona State University _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From brunson at brunson.com Fri Aug 31 22:24:34 2007 From: brunson at brunson.com (Eric Brunson) Date: Fri, 31 Aug 2007 14:24:34 -0600 Subject: [Tutor] or synxtax in if statement In-Reply-To: <1209729.3dhOnFbX70@teancum> References: <1209729.3dhOnFbX70@teancum> Message-ID: <46D87902.1060408@brunson.com> David Bear wrote: > I think I want to be lazy and express this > > if a == b | a = c > (if a equal b or a equals c) > using > > if a == b | c > > it seems to work.. but I'm not sure if it is correct -- and I haven't seen > any documentation on using this type of syntax. > > > The pipe is the "bitwise or" operator. I think you're looking for "or". And... "if a==b or c" won't work. e. From rdm at rcblue.com Fri Aug 31 22:38:16 2007 From: rdm at rcblue.com (Dick Moores) Date: Fri, 31 Aug 2007 13:38:16 -0700 Subject: [Tutor] problem resulting from installing 3.0 Message-ID: <20070831203855.35FF31E4006@bag.python.org> XP, Python 2.5.1 I installed 3.0 alpha out of curiosity in a separate folder from 2.5.1. Then I found that both 2.5.1's IDLE and my main Python editor Ulipad would no longer open. My first idea was that the installation of 3.0 somehow changed my path. But it didn't. After uninstalling 3.0, and fiddling with the path and PYTHONPATH, IDLE and Ulipad now open, but the console opens first. The files executed are idle.pyw and ulipad.pyw. How can I get back to where I was before, without that annoying console opening? path: %SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;C:\Program Files\Microsoft SQL Server\90\Tools\binn\;E:\Program Files\IDM Computer Solutions\UltraEdit-32;E:\Program Files\QuickTime\QTSystem\;E:\Program Files\Subversion\bin PYTHONPATH: E:\Python25\;E:\PythonWork\;E:\Programs\Ulipad3.7\ And another question is, exactly what should go into PYTHONPATH? I've never been clear about that. Thanks, Dick Moores From christopher.henk at allisontransmission.com Fri Aug 31 22:58:13 2007 From: christopher.henk at allisontransmission.com (christopher.henk at allisontransmission.com) Date: Fri, 31 Aug 2007 16:58:13 -0400 Subject: [Tutor] Fw: Starting classes Message-ID: Oops, forgot to reply all. Chris Henk ----- Forwarded by Christopher Henk/US/ATD/GMC on 08/31/2007 04:55 PM ----- Christopher Henk/US/ATD/GMC 08/31/2007 04:13 PM To "Ara Kooser" cc Subject Re: [Tutor] Starting classes The class definition will only have the methods and/or the variables in its definition. So these two functions make up your class class Area: def _init_(self, name, description): self.name = name def look(here): "Look around the place you are in" print here.description looking at the class code: your init function only has one underscore before and after init, you want two, that is why you are getting the error. def __init__(self, name, description): Also you are requiring two arguments to make an Area class, the name and the description. If you try to create an instance using only the name (as you do below) the interpreter will again raise an error. def look(here): "Look around the place you are in" print here.description Not sure if this works as is, I believe it depends on the interpreter, but it is customary to use the word self as the first parameter, and then also change here in the function body def look(self): "Look around the place you are in" print self.description Getting into the code below the class definition: >outside1 = Area("Outside") This will raise an error since you required two parameters to create an Area class and you only provide one. You can either add the description here or leave it off in the __init__ function. Since most likely every area will have a description , I would add it here. outside1 = Area("Outside","You are standing outside with the town gate to your back") outside1.description = "You are standing outside with the town gate to your back" (see above, and below) self.contents.append("dirt") Here we have two problems. The first is the class doesn't have the "contents" attribute yet That's only a problem since you are trying to call a function with it. When you assign to an attribute (like with "description" in the line above), you are adding the attribute to you class instance ("outside1"), however you need to add it before you can use it. Second, you only use self from within the function definition. In this case you would want to use outside1.contents. look(bedroom) Since look was defined in the class definition, you would want to call it like this. bedroom.look() But as of right now there is no bedroom created, so this will give an error. however you can instead look outside. outside1.look() Looking at your code I would have a class something like this: class Area: #what does an area have that makes it an area? contents=None name=None description=None paths=None #where you can go def __init__(self, name, description): #define what everything will start as self.name = name self.discription=None self.contents=[] self.paths={} #Methods: #what can you do to an Area? def look(self): "Look around the place you are in" print self.description def addSomething(self,thing): "adds something to the contents" def removeSomething(self,thing) "remove from contents" def addPath(self,direction,area) "Adds a connection to area" #... #more as needed Chris Henk "Ara Kooser" Sent by: tutor-bounces at python.org 08/31/2007 03:06 PM To tutor at python.org cc Subject [Tutor] Starting classes Hello, I read Alan Gauld's and How to Think Like a Computer Scientist section on classes. So I tried to write a simple room class. My goal is to write a short text adventure using classes. Here is the code: class Area: def _init_(self, name, description): self.name = name def look(here): "Look around the place you are in" print here.description outside1 = Area("Outside") outside1.description = "You are standing outside with the town gate to your back" self.contents.append("dirt") look(bedroom) I get the following error. Traceback (most recent call last): File "/Users/ara/Documents/text_advent.py", line 11, in outside1 = Area("Outside") TypeError: this constructor takes no arguments Do the outside1 = Area("Outside) need to be nested in the class or can they be outside of it? Thank you. Ara -- Quis hic locus, quae regio, quae mundi plaga. Ubi sum. Sub ortu solis an sub cardine glacialis ursae. _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070831/9352fc12/attachment-0001.htm From brian.wisti at gmail.com Fri Aug 31 23:19:48 2007 From: brian.wisti at gmail.com (Brian Wisti) Date: Fri, 31 Aug 2007 14:19:48 -0700 Subject: [Tutor] or synxtax in if statement In-Reply-To: <1209729.3dhOnFbX70@teancum> References: <1209729.3dhOnFbX70@teancum> Message-ID: On 8/31/07, David Bear wrote: > > I think I want to be lazy and express this > > if a == b | a = c > (if a equal b or a equals c) > using > > if a == b | c > > it seems to work.. but I'm not sure if it is correct -- and I haven't seen > any documentation on using this type of syntax. You could put b and c in a tuple or array and check for membership >>> a, b, c = 1, 0, 1 >>> a in (b, c) True Is that lazy enough? Kind Regards, Brian Wisti http://coolnamehere.com/ -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070831/bf66388f/attachment.htm From kent37 at tds.net Fri Aug 31 12:37:08 2007 From: kent37 at tds.net (Kent Johnson) Date: Fri, 31 Aug 2007 06:37:08 -0400 Subject: [Tutor] [OT] Py3k news Message-ID: <46D7EF54.8090203@tds.net> I don't usually post general announcements and news items here but we did recently have a discussion about whether Python 3000 is real or fictional. It's very real... Last week over twenty developers came together for a successful Py3k sprint. As a result the first alpha release is expected in 'a few days'. http://google-code-updates.blogspot.com/2007/08/updates-from-latest-python-sprint.html Kent