From ricaraoz at gmail.com Sat Sep 1 00:50:35 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Fri, 31 Aug 2007 19:50:35 -0300 Subject: [Tutor] Starting classes In-Reply-To: <46D87095.9000407@brunson.com> References: <2107481c0708311206h6f7179c9j44ef62a470d4e249@mail.gmail.com> <46D87095.9000407@brunson.com> Message-ID: <46D89B3B.1020107@bigfoot.com> Eric Brunson wrote: > 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? To do that you'll need the line : self.description = description right after the line assigning name to self.name. > > > >> 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 ) But bedroom MUST be created before that. > >> I get the following error. >> Traceback (most recent call last): >> File "/Users/ara/Documents/text_advent.py", line 11, in <module> >> 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 alan.gauld at btinternet.com Sat Sep 1 01:14:48 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 1 Sep 2007 00:14:48 +0100 Subject: [Tutor] Starting classes References: <OFD92203B3.D8A02CB4-ON85257348.0072FAEA-85257348.0073319F@gm.com> Message-ID: <fba7df$co7$1@sea.gmane.org> <christopher.henk at allisontransmission.com> wrote > 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, It is just a custom and 'here' is as good a name as any since its refering to the place object - ie here... But self is more conventional and using here might confuse some readers. The interpreters should all be happy enough with either name. Alan G From alan.gauld at btinternet.com Sat Sep 1 01:20:58 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 1 Sep 2007 00:20:58 +0100 Subject: [Tutor] problem resulting from installing 3.0 References: <20070831203855.35FF31E4006@bag.python.org> Message-ID: <fba7p1$dlh$1@sea.gmane.org> "Dick Moores" <rdm at rcblue.com> wrote > and ulipad.pyw. How can I get back to where I was before, without > that annoying console opening? Sorry, no idea - thats why I never install alpha software! :-) > 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. Its what goes into sys.path. In other words its where your local modules are stored. Using an environment variable rather than a path file, as is often suggested, allows each user to have their own module library, and even multiple libraries by using a script to launch Python that redefines PYTHONPATH before starting Python. Or you can do it manually. Much more flexible. I'm a big fan of environment variables! Alan G From carroll at tjc.com Sat Sep 1 02:17:55 2007 From: carroll at tjc.com (Terry Carroll) Date: Fri, 31 Aug 2007 17:17:55 -0700 (PDT) Subject: [Tutor] Python 3000 has just become less mythical Message-ID: <Pine.LNX.4.44.0708311715260.17259-100000@violet.rahul.net> The first Alpha release of Python 3000 was released today: http://python.org/download/releases/3.0/ Guido's post: http://www.artima.com/weblogs/viewpost.jsp?thread=213583 From kent37 at tds.net Sat Sep 1 02:22:27 2007 From: kent37 at tds.net (Kent Johnson) Date: Fri, 31 Aug 2007 20:22:27 -0400 Subject: [Tutor] Starting classes In-Reply-To: <2107481c0708311206h6f7179c9j44ef62a470d4e249@mail.gmail.com> References: <2107481c0708311206h6f7179c9j44ef62a470d4e249@mail.gmail.com> Message-ID: <46D8B0C3.4010709@tds.net> Ara Kooser wrote: > def look(here): > "Look around the place you are in" > print here.description This is technicaly OK but conventionally the first argument to a method is 'self'. Since you are learning it would be good to keep to the convention. > outside1 = Area("Outside") > outside1.description = "You are standing outside with the town gate to > your back" > self.contents.append("dirt") > > > look(bedroom) Maybe you mean bedroom.look() or outside1.look() Kent From kent37 at tds.net Sat Sep 1 02:25:58 2007 From: kent37 at tds.net (Kent Johnson) Date: Fri, 31 Aug 2007 20:25:58 -0400 Subject: [Tutor] problem resulting from installing 3.0 In-Reply-To: <20070831203855.35FF31E4006@bag.python.org> References: <20070831203855.35FF31E4006@bag.python.org> Message-ID: <46D8B196.5010307@tds.net> Dick Moores wrote: > 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? A guess - check the file association for .pyw files. Make sure they are associated with pythonw, not python. Kent From rdm at rcblue.com Sat Sep 1 02:54:45 2007 From: rdm at rcblue.com (Dick Moores) Date: Fri, 31 Aug 2007 17:54:45 -0700 Subject: [Tutor] problem resulting from installing 3.0 In-Reply-To: <fba7p1$dlh$1@sea.gmane.org> References: <20070831203855.35FF31E4006@bag.python.org> <fba7p1$dlh$1@sea.gmane.org> Message-ID: <20070901005453.64CA21E4006@bag.python.org> At 04:20 PM 8/31/2007, you wrote: >"Dick Moores" <rdm at rcblue.com> wrote > > > and ulipad.pyw. How can I get back to where I was before, without > > that annoying console opening? > >Sorry, no idea - thats why I never install alpha software! :-) > > > 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. > >Its what goes into sys.path. > >In other words its where your local modules are stored. Using an >environment variable rather than a path file, as is often suggested, >allows each user to have their own module library, and even >multiple libraries by using a script to launch Python that redefines >PYTHONPATH before starting Python. Or you can do it manually. >Much more flexible. I'm a big fan of environment variables! I don't think I follow you, Alan. I thought I was using environment variables. In XP, System Properties | Advanced | Environment Variables | System Variables. That's where path and PYTHONPATH are. There are subfolders with local modules in E:\PythonWork\. Do I have to list them too? And modules such as datetime.py, and random.py?are not local? I'm guessing not. Here what the sys.path doc says: ===================================== path A list of strings that specifies the search path for modules. Initialized from the environment variable PYTHONPATH, plus an installation-dependent default. As initialized upon program startup, the first item of this list, path[0], is the directory containing the script that was used to invoke the Python interpreter. If the script directory is not available (e.g. if the interpreter is invoked interactively or if the script is read from standard input), path[0] is the empty string, which directs Python to search modules in the current directory first. Notice that the script directory is inserted before the entries inserted as a result of PYTHONPATH. A program is free to modify this list for its own purposes. Changed in version 2.3: Unicode strings are no longer ignored. ======================================= And my PYTHONPATH again: E:\Python25\;E:\PythonWork\;E:\Programs\Ulipad3.7\. It seems that all subfolders of Python25/ would be initialized by default. I'm thinking that maybe if I uninstall and then reinstall 2.5.1. The problem I asked about would clear up. Thoughts about this, anyone? Thanks, Dick >Alan G > > >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor From rdm at rcblue.com Sat Sep 1 03:03:04 2007 From: rdm at rcblue.com (Dick Moores) Date: Fri, 31 Aug 2007 18:03:04 -0700 Subject: [Tutor] problem resulting from installing 3.0 In-Reply-To: <46D8B196.5010307@tds.net> References: <20070831203855.35FF31E4006@bag.python.org> <46D8B196.5010307@tds.net> Message-ID: <20070901010314.C16271E4006@bag.python.org> At 05:25 PM 8/31/2007, Kent Johnson wrote: >Dick Moores wrote: >>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? > >A guess - check the file association for .pyw files. Make sure they >are associated with pythonw, not python. Yes! Thanks, Kent. Dick From pine508 at hotmail.com Sat Sep 1 07:55:34 2007 From: pine508 at hotmail.com (Che M) Date: Sat, 01 Sep 2007 01:55:34 -0400 Subject: [Tutor] date matching with python and sqlite3 Message-ID: <BAY105-F36B091F291B3EB1FB8C930E0CF0@phx.gbl> I'm trying to allow users to select data from an sqlite database using Python by choosing either a date or a range of dates. I'm stuck at just allowing the to select data that entered the database "today" and return values from a column called duration. I have this mess at the moment: #assume they have already chosen this self.datechoice to be today if self.datechoice == "today": todaystring = str(datetime.datetime.today()) today = todaystring[0:10] cur.execute('SELECT duration FROM datatable WHERE date =' + '"' + today + '"') The 3rd line is a way to take just the first part 10 chars of the datetime.today string, so instead of "2007-09-01 12:00:03" it would be just "2007-09-01", since I just want to match it to today, not a particular time during today. But this only works if the dates have been saved that way--typically they are saved with the time as well, so this method is not good and obviously not the right way to do it. I can tell I am going about this totally wrongly and that I should be able to use either the Python datetime functions or SQLite's date functions much better, so any insight would be appreciated. Thank you. _________________________________________________________________ A place for moms to take a break! http://www.reallivemoms.com?ocid=TXT_TAGHM&loc=us From alan.gauld at btinternet.com Sat Sep 1 10:08:53 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 1 Sep 2007 09:08:53 +0100 Subject: [Tutor] problem resulting from installing 3.0 References: <20070831203855.35FF31E4006@bag.python.org><fba7p1$dlh$1@sea.gmane.org> <20070901005453.64CA21E4006@bag.python.org> Message-ID: <fbb6ms$b83$1@sea.gmane.org> "Dick Moores" <rdm at rcblue.com> wrote > > > And another question is, exactly what should go into PYTHONPATH? > > >Its what goes into sys.path. > > >In other words its where your local modules are stored. > >Much more flexible. I'm a big fan of environment variables! > > I don't think I follow you, Alan. I thought I was > using environment variables. You are, but you asked about what should go in PYTHONPATH I was pointing out the advantages of using PYHONPATH over just putting a path file into your installation, which is another way of telling Python where too look. I wasn't suggesting that you weren't doing it, merely affirming that its a good idea. > There are subfolders with local modules in > E:\PythonWork\. Do I have to list them too? Thats exactly what should be in there. > modules such as datetime.py, and random.py-are not local? These would more typically be installed in the site-packages folder within your installation since they are not your own scripts. But if you chodse to store them outside the Python folders then yes you could point to their folders too. HTH, Alan G From pluijzer at gmail.com Sat Sep 1 13:46:38 2007 From: pluijzer at gmail.com (Righard/Riku van Roy) Date: Sat, 01 Sep 2007 11:46:38 +0000 Subject: [Tutor] date matching with python and sqlite3 In-Reply-To: <BAY105-F36B091F291B3EB1FB8C930E0CF0@phx.gbl> References: <BAY105-F36B091F291B3EB1FB8C930E0CF0@phx.gbl> Message-ID: <1188647198.3315.9.camel@iisjmii.TeleWell.gateway> I sorry, maybe I am stupid at the moment but I cannot follow your question,.... 1) User can select a date, or a range of dates. 2) At the moment you are only able to let the user select a date that has entered the database today. 3) A value from a table called duratation will be returned for the selected date? 4) It will only work if the date is saved in this? "2007-09-01", way., What other way can the date be saved? 5) You want to now how you can improve your program? Can you give some more info please, again sorry if others understeand it perfectly, Righard Op za, 01-09-2007 te 01:55 -0400, schreef Che M: > I'm trying to allow users to select data from an sqlite database using > Python by choosing either a date or a range of dates. I'm stuck at just > allowing the to select data that entered the database "today" and return > values from a column called duration. I have this mess at the moment: > > #assume they have already chosen this self.datechoice to be today > > if self.datechoice == "today": > todaystring = str(datetime.datetime.today()) > today = todaystring[0:10] > cur.execute('SELECT duration FROM datatable WHERE date =' + '"' + today > + '"') > > The 3rd line is a way to take just the first part 10 chars of the > datetime.today string, so > instead of 2007-09-01it would be just "2007-09-01", since I just > want > to match it to today, not a particular time during today. But this only > works if the > dates have been saved that way--typically they are saved with the time as > well, so > this method is not good and obviously not the right way to do it. > > I can tell I am going about this totally wrongly and that I should be able > to use either > the Python datetime functions or SQLite's date functions much better, so any > insight > would be appreciated. Thank you. > > _________________________________________________________________ > A place for moms to take a break! > http://www.reallivemoms.com?ocid=TXT_TAGHM&loc=us > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From seancron at gmail.com Sat Sep 1 00:54:02 2007 From: seancron at gmail.com (Sean Cronin) Date: Fri, 31 Aug 2007 18:54:02 -0400 Subject: [Tutor] parsing response from SOAPpy request Message-ID: <cdb9f2be0708311554g4d18e98cp65e35310ad6df667@mail.gmail.com> I'm using SOAPpy to access weather data from the NOAA National Digital Forecast Database XML Web Service [1] and I've been having trouble figuring out how to parse the data. The response comes back as XML document but when I check it with type(result) it shows the the response is a string. Does anyone have any suggestions on getting relevant data? I've attached a sample SOAP response to this post. Thanks, -Sean -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070831/69697610/attachment.htm -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: response.txt Url: http://mail.python.org/pipermail/tutor/attachments/20070831/69697610/attachment.txt From pluijzer at gmail.com Sat Sep 1 15:29:32 2007 From: pluijzer at gmail.com (Righard/Riku van Roy) Date: Sat, 01 Sep 2007 13:29:32 +0000 Subject: [Tutor] Is there any logic in this? Message-ID: <1188653372.3315.17.camel@iisjmii.TeleWell.gateway> If you copy a list into another variable, and then change the second one, the first gets changed aswell, for example: >>> a = [10, 40, 30, 20] >>> b = a >>> b.sort() >>> a [10, 20, 30, 40] >>> b [10, 20, 30, 40] or: >>> a = [10, 40, 30, 20] >>> b = a >>> b[0] = 99 >>> a [99, 40, 30, 20] >>> b [99, 40, 30, 20] this happens with dictionary's too, but not with intergers, it is not that this is a problem because I can just use... >>> b = a[:] ...but I wonder if there is any logic behind this, I cannot find a practical use for it, just problems. thx, Righard From jim at well.com Sat Sep 1 16:50:53 2007 From: jim at well.com (jim stockford) Date: Sat, 1 Sep 2007 07:50:53 -0700 Subject: [Tutor] Is there any logic in this? In-Reply-To: <1188653372.3315.17.camel@iisjmii.TeleWell.gateway> References: <1188653372.3315.17.camel@iisjmii.TeleWell.gateway> Message-ID: <682433d724bbd619b0559f2aa2e4795d@well.com> seems to me this is an artifact of the language. reading right to left: "make a list that contains 10,40,30,20, then create a name 'a' to be used as a label to identify that list, then (next line) create a label 'b' to attach to whatever is the thing 'a' refers to, then (next line) modify the thing via 'b' (e.g. b.sort)." the essence is to allow multiple names for things without clogging up memory with a lot of copies and to have a uniform mechanism of referencing anything (i.e. any "object", for everything in Python is an object, hence the utility of a uniform mechanism. the effect is programmers have to know this is the case. those who have the old style "C head" using the model of a variable name representing an area in memory where assignment copies data to a new area in memory with the other variable name will get caught on this until they catch on. I'll be very grateful for any criticism of the above. On Sep 1, 2007, at 6:29 AM, Righard/Riku van Roy wrote: > If you copy a list into another variable, and then change the second > one, the first gets changed aswell, for example: > >>>> a = [10, 40, 30, 20] >>>> b = a >>>> b.sort() >>>> a > [10, 20, 30, 40] >>>> b > [10, 20, 30, 40] > > or: > >>>> a = [10, 40, 30, 20] >>>> b = a >>>> b[0] = 99 >>>> a > [99, 40, 30, 20] >>>> b > [99, 40, 30, 20] > > this happens with dictionary's too, but not with intergers, it is not > that this is a problem because I can just use... > >>>> b = a[:] > > ...but I wonder if there is any logic behind this, I cannot find a > practical use for it, just problems. > > thx, Righard > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From pluijzer at gmail.com Sat Sep 1 17:02:01 2007 From: pluijzer at gmail.com (Righard/Riku van Roy) Date: Sat, 01 Sep 2007 15:02:01 +0000 Subject: [Tutor] Is there any logic in this? In-Reply-To: <682433d724bbd619b0559f2aa2e4795d@well.com> References: <1188653372.3315.17.camel@iisjmii.TeleWell.gateway> <682433d724bbd619b0559f2aa2e4795d@well.com> Message-ID: <1188658921.3315.27.camel@iisjmii.TeleWell.gateway> Thanks for your explenation, so essentialy a = b, copys the pointer of a to b rather than the actual content. This explains why a[:] does work. Do you have an explenation why this is not the case with integers ie. >>> a, b = 10, a >>> b = b + 10 >>> a, b (10, 20) thx Op za, 01-09-2007 te 07:50 -0700, schreef jim stockford: > seems to me this is an artifact of the language. > reading right to left: > "make a list that contains 10,40,30,20, then create a > name 'a' to be used as a label to identify that list, then > (next line) create a label 'b' to attach to whatever is > the thing 'a' refers to, then (next line) modify the thing > via 'b' (e.g. b.sort)." > the essence is to allow multiple names for things > without clogging up memory with a lot of copies and > to have a uniform mechanism of referencing anything > (i.e. any "object", for everything in Python is an object, > hence the utility of a uniform mechanism. > the effect is programmers have to know this is the > case. those who have the old style "C head" using the > model of a variable name representing an area in > memory where assignment copies data to a new area > in memory with the other variable name will get caught > on this until they catch on. > > I'll be very grateful for any criticism of the above. > > > > On Sep 1, 2007, at 6:29 AM, Righard/Riku van Roy wrote: > > > If you copy a list into another variable, and then change the second > > one, the first gets changed aswell, for example: > > > >>>> a = [10, 40, 30, 20] > >>>> b = a > >>>> b.sort() > >>>> a > > [10, 20, 30, 40] > >>>> b > > [10, 20, 30, 40] > > > > or: > > > >>>> a = [10, 40, 30, 20] > >>>> b = a > >>>> b[0] = 99 > >>>> a > > [99, 40, 30, 20] > >>>> b > > [99, 40, 30, 20] > > > > this happens with dictionary's too, but not with intergers, it is not > > that this is a problem because I can just use... > > > >>>> b = a[:] > > > > ...but I wonder if there is any logic behind this, I cannot find a > > practical use for it, just problems. > > > > thx, Righard > > > > > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > From kent37 at tds.net Sat Sep 1 17:36:16 2007 From: kent37 at tds.net (Kent Johnson) Date: Sat, 01 Sep 2007 11:36:16 -0400 Subject: [Tutor] Is there any logic in this? In-Reply-To: <682433d724bbd619b0559f2aa2e4795d@well.com> References: <1188653372.3315.17.camel@iisjmii.TeleWell.gateway> <682433d724bbd619b0559f2aa2e4795d@well.com> Message-ID: <46D986F0.3060505@tds.net> jim stockford wrote: > seems to me this is an artifact of the language. 'artifact of the language' to me implies some sort of unintended consequence. In fact it is fundamental to the way assignment works in Python. This is good reading: http://tinyurl.com/ysz8sr > reading right to left: > "make a list that contains 10,40,30,20, then create a > name 'a' to be used as a label to identify that list, then > (next line) create a label 'b' to attach to whatever is > the thing 'a' refers to, then (next line) modify the thing > via 'b' (e.g. b.sort)." Yes > the effect is programmers have to know this is the > case. those who have the old style "C head" using the > model of a variable name representing an area in > memory where assignment copies data to a new area > in memory with the other variable name will get caught > on this until they catch on. Yes. If you think of variables as containers for values in Python you will be sorry, it is not a model that works. We had a really good discussion of this not too long ago but I can't find it in the archives. Does anyone have a link? Kent From bhaaluu at gmail.com Sat Sep 1 17:38:44 2007 From: bhaaluu at gmail.com (bhaaluu) Date: Sat, 1 Sep 2007 11:38:44 -0400 Subject: [Tutor] game programming python Message-ID: <ea979d70709010838u1b27c22fxee8cc0ecce3e9964@mail.gmail.com> Greetings, I recently found a rather obscure book that looks pretty good. The Reader Level is Beginner to Advanced, so I thought I'd share it with the list (something for everyone). Game Programming, The L Line, The Express Line To Learning. Andy Harris. Published by Wiley in February 1995. ISBN: 978-0-470-06822-9 http://www.wiley.com/WileyCDA/WileyTitle/productCd-0470068221.html The above site has downloadable source code, PowerPoint slides (viewable with Open Office Impress), as well as excerpts and supplementary materials: (Appendix D is a tutorial on how to create your own game graphics and sounds using free software: the Gimp and Audacity). This book focuses on Game Programming with Python and the pyGame module. I found a copy online for about USD$15, so look around. This book seems to be well written, and it covers a lot of ground. If you're interested in learning Python game programming, take a look at this one! Happy Programming! -- bhaaluu at gmail dot com From alan.gauld at btinternet.com Sat Sep 1 18:05:07 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 1 Sep 2007 17:05:07 +0100 Subject: [Tutor] Is there any logic in this? References: <1188653372.3315.17.camel@iisjmii.TeleWell.gateway> Message-ID: <fbc2jq$lrm$1@sea.gmane.org> "Righard/Riku van Roy" <pluijzer at gmail.com> wrote > If you copy a list into another variable, and then change the second > one, the first gets changed as well, for example: > >>>> a = [10, 40, 30, 20] >>>> b = a This is not a copy its a name assignment. You have created a list object and assigned the name 'a' to it. Then you created a new name 'b' and told it to refer to the same object as 'a'. You did not create any new objects, you did not copy any objects. To copy a list in Python you must use the copy function or use a slice [:] (as you do below). You can check this with the id() function in Python: >>> a = [1,2,3] >>> b = a >>> id(a) 24474288 >>> id(b) 24474288 So they have the same id, they are the same object. > this happens with dictionary's too, but not with intergers, It does happen with integers (and strings etc) too. But integers and strings are immutable, you cannot change the object you can only create new objects. >>> x = 42 >>> y = x >>> id(x) 10835268 >>> id(y) 10835268 Notice the same id, the same object b.sort() changes the data ordering inside the list object. It does not change the list object itself. >>> b.sort() >>> id(b) 24474288 Still the same id as above, the same object. Only the data contained by the list has changed. You can do that because lists are mutable, they can be changed. But integers are not mutable, you can only create new integers: >>> y = 2*x >>> id(y) 10836748 A different id, we have created a new integer object >>>> b = a[:] Thats correct, here you really do create a copy of a. > ...but I wonder if there is any logic behind this, I cannot find a > practical use for it, just problems. There are a few situations where it is useful, but mainly it saves memory. However I don't think the memory saving is the main reason its built that way, its a model of thinking about names that moves us away from thinking about variable names as being aliaes for memory locations. It makes the computing machine more abstract and therefore more portable and keeps p[rogrammes focused on solving core problems rather than directing the computers mechanism. PS. For an entirely different explanation of Python's naming concept try reading the section on variables in my raw materials tutor topic... 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 Sep 1 18:09:21 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 1 Sep 2007 17:09:21 +0100 Subject: [Tutor] parsing response from SOAPpy request References: <cdb9f2be0708311554g4d18e98cp65e35310ad6df667@mail.gmail.com> Message-ID: <fbc2ro$mjp$1@sea.gmane.org> "Sean Cronin" <seancron at gmail.com> wrote > The response comes back as XML document but when I check it with > type(result) it shows the the response is a string. Thats right the string is the XML document, just as if you had read it from a file with the read() method. > Does anyone have any suggestions on getting relevant data? You need to parse the xml. The classic way to do that is using DOM or sax parsing, but Python now has the ElementTree parser which is usually much easier to use. Look at the module docs and for a lot more detail visit the ElementTree homepage: http://effbot.org/zone/element-index.htm HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From pine508 at hotmail.com Sat Sep 1 18:51:13 2007 From: pine508 at hotmail.com (Che M) Date: Sat, 01 Sep 2007 12:51:13 -0400 Subject: [Tutor] date matching with python and sqlite3 In-Reply-To: <mailman.1352.1188658073.28952.tutor@python.org> Message-ID: <BAY105-F2046566AD9CECC41315A30E0CF0@phx.gbl> Re: date matching with python and sqlite3 >I sorry, maybe I am stupid at the moment but I cannot follow your >question,.... I'm sorry, I didn't describe that too clearly...have coffee now, let's try that again. The user will have a choicebox that has options of "today", "this week", "this month", etc., as well as a way to just provide a range of dates, e.g. "Jan 1 2007--Apr 15 2007". The point is I want them to be able to get data from the database for whatever time period they want. Let's say the data is type of fruit they ate on various dates. So they would put in "this month" and it would return all the fruit that was eaten that month. And every time they indicate they ate a fruit, they enter it into the database and Python will save it as a datetime object, which has the format 2007-09-01 12:00:00. My trouble is in how to write the SQL statements to match the date(s) they need while ignoring the time part of the datetime. For example, the code I have for matching to "today" doesn't work because it will match a date saved as "2007-09-01" but not "2007-09-01 12:03:03", and it is this 2nd format that the datetime object takes. I also prefer that format, actually, in case I later want to sort by time of day. Again, this is the non-working and inelegant code: if self.datechoice == "today": todaystring = str(datetime.datetime.today()) today = todaystring[0:10] cur.execute('SELECT duration FROM datatable WHERE date =' + '"' + today + '"') I'm sure there is an easy way to do this since both Python and SQLite have date functions, but I have just had trouble understanding the SQlite documentation. Sorry if this is more an SQLite concern than a Python concern, but it is sort of on the border. If this is still unclear I will try again. Thanks! _________________________________________________________________ Get a FREE small business Web site and more from Microsoft? Office Live! http://clk.atdmt.com/MRT/go/aub0930003811mrt/direct/01/ From brunson at brunson.com Sat Sep 1 18:24:24 2007 From: brunson at brunson.com (Eric Brunson) Date: Sat, 01 Sep 2007 10:24:24 -0600 Subject: [Tutor] parsing response from SOAPpy request In-Reply-To: <fbc2ro$mjp$1@sea.gmane.org> References: <cdb9f2be0708311554g4d18e98cp65e35310ad6df667@mail.gmail.com> <fbc2ro$mjp$1@sea.gmane.org> Message-ID: <46D99238.6090505@brunson.com> Alan Gauld wrote: > "Sean Cronin" <seancron at gmail.com> wrote > > >> The response comes back as XML document but when I check it with >> type(result) it shows the the response is a string. >> > > Thats right the string is the XML document, just as if you had read it > from a file with the read() method. > > >> Does anyone have any suggestions on getting relevant data? >> > > You need to parse the xml. > > The classic way to do that is using DOM or sax parsing, Bleah. ;-) > but > Python now has the ElementTree parser which is usually > much easier to use. Look at the module docs and for a lot > more detail visit the ElementTree homepage: > > http://effbot.org/zone/element-index.htm > I've used ElementTree a tiny bit, but preferred BeautifulSoup as it seemed more "pythonic" to me. You should look at both and pick the one that suits you. BeautifulSoup has the advantage of not choking on choking on XML that is not well formed. e. From jim at well.com Sat Sep 1 20:43:51 2007 From: jim at well.com (jim stockford) Date: Sat, 1 Sep 2007 11:43:51 -0700 Subject: [Tutor] Is there any logic in this? In-Reply-To: <1188658921.3315.27.camel@iisjmii.TeleWell.gateway> References: <1188653372.3315.17.camel@iisjmii.TeleWell.gateway> <682433d724bbd619b0559f2aa2e4795d@well.com> <1188658921.3315.27.camel@iisjmii.TeleWell.gateway> Message-ID: <7d5a55d1c9c6b8623472b195f7168d64@well.com> essentially right reinterpretation. I believe Pythonists use the term "bind" to describe the action of what we're used to thinking of as the assignment operator = the name 'a' is bound to the list, in your former example. Everything is an object in Python, including integers. Every object persists until there are no names bound to it, in which case the object is permanently out of scope and eligible for garbage collection. but... Objects for the small integers remain in scope always. your example is interesting, but reading right to left doesn't work well, which bothers me. I read your first line as "make 'a' reference the integer object 10, then make 'b' reference whatever 'a' references, then (next line) add 10 to whatever 'b' references, but oops: under the hood the Python interpreting system must as its first principle keep common sense--the human wants to add 10 to 'b' so 'b' will now reference the integer object that matches 10 + 10. I totally made the above explanation up, so it's a good target for skepticism. I hate not being able to read from right to left in a procrustean manner. The compromise is read the right side of the "assignment" operator and then the left side and do what common sense expects. I hope one of the p-t gurus will explain better. On Sep 1, 2007, at 8:02 AM, Righard/Riku van Roy wrote: > Thanks for your explenation, so essentialy a = b, copys the pointer of > a > to b rather than the actual content. This explains why a[:] does work. > > Do you have an explenation why this is not the case with integers ie. > >>>> a, b = 10, a >>>> b = b + 10 >>>> a, b > (10, 20) > > thx > > > Op za, 01-09-2007 te 07:50 -0700, schreef jim stockford: >> seems to me this is an artifact of the language. >> reading right to left: >> "make a list that contains 10,40,30,20, then create a >> name 'a' to be used as a label to identify that list, then >> (next line) create a label 'b' to attach to whatever is >> the thing 'a' refers to, then (next line) modify the thing >> via 'b' (e.g. b.sort)." >> the essence is to allow multiple names for things >> without clogging up memory with a lot of copies and >> to have a uniform mechanism of referencing anything >> (i.e. any "object", for everything in Python is an object, >> hence the utility of a uniform mechanism. >> the effect is programmers have to know this is the >> case. those who have the old style "C head" using the >> model of a variable name representing an area in >> memory where assignment copies data to a new area >> in memory with the other variable name will get caught >> on this until they catch on. >> >> I'll be very grateful for any criticism of the above. >> >> >> >> On Sep 1, 2007, at 6:29 AM, Righard/Riku van Roy wrote: >> >>> If you copy a list into another variable, and then change the second >>> one, the first gets changed aswell, for example: >>> >>>>>> a = [10, 40, 30, 20] >>>>>> b = a >>>>>> b.sort() >>>>>> a >>> [10, 20, 30, 40] >>>>>> b >>> [10, 20, 30, 40] >>> >>> or: >>> >>>>>> a = [10, 40, 30, 20] >>>>>> b = a >>>>>> b[0] = 99 >>>>>> a >>> [99, 40, 30, 20] >>>>>> b >>> [99, 40, 30, 20] >>> >>> this happens with dictionary's too, but not with intergers, it is not >>> that this is a problem because I can just use... >>> >>>>>> b = a[:] >>> >>> ...but I wonder if there is any logic behind this, I cannot find a >>> practical use for it, just problems. >>> >>> thx, Righard >>> >>> >>> >>> _______________________________________________ >>> 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 dkuhlman at rexx.com Sat Sep 1 20:09:51 2007 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Sat, 1 Sep 2007 11:09:51 -0700 Subject: [Tutor] parsing response from SOAPpy request In-Reply-To: <46D99238.6090505@brunson.com> References: <cdb9f2be0708311554g4d18e98cp65e35310ad6df667@mail.gmail.com> <fbc2ro$mjp$1@sea.gmane.org> <46D99238.6090505@brunson.com> Message-ID: <20070901180951.GA76332@cutter.rexx.com> On Sat, Sep 01, 2007 at 10:24:24AM -0600, Eric Brunson wrote: > Alan Gauld wrote: > > "Sean Cronin" <seancron at gmail.com> wrote > > > > > >> The response comes back as XML document but when I check it with > >> type(result) it shows the the response is a string. > >> > > > > Thats right the string is the XML document, just as if you had read it > > from a file with the read() method. > > > > > >> Does anyone have any suggestions on getting relevant data? > >> > > > > You need to parse the xml. > > > > The classic way to do that is using DOM or sax parsing, > > Bleah. ;-) I don't understand this. The response comes back as the value of a function/method call. You should not have to look at XML (text) at all, unless something goes wrong and you need to do debugging. This is the point of using SOAPpy. XML is the underlying (and mostly hidden) data representation that is sent "across the wire". But, you deal with Python and SOAPpy. It translates your function calls into XML, sends it to a SOAP server, receives an (XML) response, and translates that XML response back into Python objects. Currently, I do not have SOAPpy installed. But last time I used it, I did not parse XML. For an example, in the SOAPpy distribution, look at tests/cardClient.py. It makes SOAP requests, and receives the responses to those requests, but it does not (directly) generate or parse XML. SOAPpy does that for you. You have most likely already looked at those examples. So, maybe there is something that I don't understand about your question? Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman From alan.gauld at btinternet.com Sun Sep 2 00:13:09 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 1 Sep 2007 23:13:09 +0100 Subject: [Tutor] parsing response from SOAPpy request References: <cdb9f2be0708311554g4d18e98cp65e35310ad6df667@mail.gmail.com><fbc2ro$mjp$1@sea.gmane.org> <46D99238.6090505@brunson.com> <20070901180951.GA76332@cutter.rexx.com> Message-ID: <fbco5t$eu3$1@sea.gmane.org> "Dave Kuhlman" <dkuhlman at rexx.com> wrote >> >> The response comes back as XML document but when I check it with >> >> type(result) it shows the the response is a string. > This is the point of using SOAPpy. XML is the underlying (and > mostly hidden) data representation that is sent "across the wire". > But, you deal with Python and SOAPpy. It translates your function > calls into XML, sends it to a SOAP server, receives an (XML) > response, and translates that XML response back into Python > objects. That's how it usually works where the return values are simple objects like strings, integers, dates, even lists of things. But Web Services are sometimes defined to return an XML document as the return object. This is usually because the exact content is undefined or there is a lot of it in complex structures. When that happens Python hands you a string, which happens to be an XML document. The XML envelope that surrounds the SOAP message is correctly stripped away by SOAPpy but the string thats left is itself an XML document. Its nothing to do with SOAPpy per se, any SOAP implementation will do the same, it's what the web service returns. 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 Sep 2 00:17:10 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 1 Sep 2007 23:17:10 +0100 Subject: [Tutor] Is there any logic in this? References: <1188653372.3315.17.camel@iisjmii.TeleWell.gateway><682433d724bbd619b0559f2aa2e4795d@well.com><1188658921.3315.27.camel@iisjmii.TeleWell.gateway> <7d5a55d1c9c6b8623472b195f7168d64@well.com> Message-ID: <fbcodd$fgh$1@sea.gmane.org> "jim stockford" <jim at well.com> wrote > your example is interesting, but reading right to left > doesn't work well, which bothers me. It works OK if you treat the entire right hand side as an expression that evaluates to a value which is bound to the name on the left. In the list cae the sort method works in-place so the list object never changes. In the integer case two integers get added together to make a new integer. The new value is bound to the name. > I hate not being able to read from right to left in a > procrustean manner. The compromise is read the > right side of the "assignment" operator and then > the left side and do what common sense expects. You can read from right to left but you just have to do it under the rules of Python :-) Alan G. From ghashsnaga at gmail.com Sun Sep 2 00:23:56 2007 From: ghashsnaga at gmail.com (Ara Kooser) Date: Sat, 1 Sep 2007 16:23:56 -0600 Subject: [Tutor] Further into classes Message-ID: <2107481c0709011523i497f57f0y3ae34f885fa0f132@mail.gmail.com> Thank you for the help on getting started on classes. I have a basic understanding of how they are used and I reread the tutorials again. So I have a class set up and running. My question is how you append a list (such as self.contents = [ ]) using a method like def AddObject? The code I am trying is below but it is not working. I am really sure I am not going about this the right way. Thank you. Ara ##################################################################### #Text Advenuture #By Ara Kooser #Thanks to Chris, e., and Steven at python tutor #################################################################### class Area: #What makes it an area? def __init__(self, name, description): #Number of arguements in the _init_ must be defined self.name = name self.description = description self.contents = [] #Methods. What you can do. def AddObject(self,thing): #pass self.contents.append() def look(self): print "Look around the place you are in" print "You are in the",self.name print self.description def search(self): print "You search the area and find..." print self.contents first_instance = Area("Outside", "You are standing outside") first_instance.AddObject("Stick") first_instance.look() first_instance.search() second_instance = Area("Inside", "You are standing inside") second_instance.AddObject("Iron pot") second_instance.look() second_instance.search() -- Quis hic locus, quae regio, quae mundi plaga. Ubi sum. Sub ortu solis an sub cardine glacialis ursae. From ricaraoz at gmail.com Sun Sep 2 00:41:48 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Sat, 01 Sep 2007 19:41:48 -0300 Subject: [Tutor] files Message-ID: <46D9EAAC.1030209@bigfoot.com> Hi, I am in doubt : >>> In = open(r'E:\MyDir\MyDoc.txt', 'rb') >>> Out = open(r'E:\MyDir\MyUpperDoc.txt', 'wb') >>> Out.write(In.read().upper()) >>> In.close() >>> Out.close() Pretty simple program. The question is : If 'In' is a HUGE file, how does Python process it? Does it treat it as a stream and passes bytes to 'Out' as soon as they are coming in, or does it read the whole file into memory and then passes the whole file to 'Out'? If the answer is the first choice I would like to know how to instruct Python to do the second choice. TIA From alan.gauld at btinternet.com Sun Sep 2 01:46:54 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 2 Sep 2007 00:46:54 +0100 Subject: [Tutor] Further into classes References: <2107481c0709011523i497f57f0y3ae34f885fa0f132@mail.gmail.com> Message-ID: <fbctlm$r3a$1@sea.gmane.org> "Ara Kooser" <ghashsnaga at gmail.com> wrote > So I have a class set up and running. My question is how you append > a > list (such as self.contents = [ ]) using a method like def > AddObject? > class Area: > #Methods. What you can do. > def AddObject(self,thing): > #pass > self.contents.append() > You are almost there but you need to pass 'thing' to the append: self.contents.append(thing) 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 Sep 2 01:51:45 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 2 Sep 2007 00:51:45 +0100 Subject: [Tutor] files References: <46D9EAAC.1030209@bigfoot.com> Message-ID: <fbctuo$rnm$1@sea.gmane.org> "Ricardo Ar?oz" <ricaraoz at gmail.com> wrote >>>> In = open(r'E:\MyDir\MyDoc.txt', 'rb') >>>> Out = open(r'E:\MyDir\MyUpperDoc.txt', 'wb') >>>> Out.write(In.read().upper()) >>>> In.close() >>>> Out.close() > > Pretty simple program. The question is : If 'In' is a HUGE file, how > does Python process it? Exactly as it does for a small file... :-) > Does it treat it as a stream and passes bytes to > 'Out' as soon as they are coming in, or does it read the whole file > into > memory and then passes the whole file to 'Out'? You have told it to do the latter. read() reads the whole file into a string so Out.write(In.read().upper()) Is exactly the same as temp = In.read() temp = temp.upper() Out.write(temp) Just because you put it in one line doesn't chanhge how Python interprets it. > If the answer is the first choice I would like to know how to > instruct > Python to do the second choice. I'm guessing you mean this the other way around? You can read the file line by line for line in In: Out.write(line.upper()) HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From gslindstrom at gmail.com Sun Sep 2 02:52:51 2007 From: gslindstrom at gmail.com (Greg Lindstrom) Date: Sat, 1 Sep 2007 19:52:51 -0500 Subject: [Tutor] PyCon 2008 - Call for Tutorial Topics Message-ID: <a9f39a410709011752n7c5b60aej96be56f346a13cf2@mail.gmail.com> Hello All, We are still soliciting ideas for tutorials to put on at PyCon in Chicago next spring. PyCon is all about our community; under the direction of the PSF, planned, organized and run by volunteers just like you. We are asking for topics that you want to see covered on the tutorial day (the day preceding the "official" conference). There is an additional charge for these classes but they are taught by instructors who really know their topics. The following ideas have been requested (nothing has been scheduled, yet): - Testing strategies - Intermediate Python - Database - How to "think" in Python 3000 - Using Cheeseshop - SOAP/.Net (Iron Python?) - Programming Contest We need more ideas before we start putting things together. What do *you* want to see? This is your chance to learn from the experts (or, maybe, *you* would like to present a class). Let me know what class would entice you to attend the tutorials. Greg Lindstrom Tutorial Coordinator, PyCon 2008 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070901/63370c8c/attachment.htm From ricaraoz at gmail.com Sun Sep 2 02:53:16 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Sat, 01 Sep 2007 21:53:16 -0300 Subject: [Tutor] files In-Reply-To: <fbctuo$rnm$1@sea.gmane.org> References: <46D9EAAC.1030209@bigfoot.com> <fbctuo$rnm$1@sea.gmane.org> Message-ID: <46DA097C.4010601@bigfoot.com> Alan Gauld wrote: > "Ricardo Ar?oz" <ricaraoz at gmail.com> wrote > >>>>> In = open(r'E:\MyDir\MyDoc.txt', 'rb') >>>>> Out = open(r'E:\MyDir\MyUpperDoc.txt', 'wb') >>>>> Out.write(In.read().upper()) >>>>> In.close() >>>>> Out.close() >> Pretty simple program. The question is : If 'In' is a HUGE file, how >> does Python process it? > > Exactly as it does for a small file... :-) > >> Does it treat it as a stream and passes bytes to >> 'Out' as soon as they are coming in, or does it read the whole file >> into >> memory and then passes the whole file to 'Out'? > > You have told it to do the latter. > read() reads the whole file into a string so > > Out.write(In.read().upper()) > > Is exactly the same as > > temp = In.read() > temp = temp.upper() > Out.write(temp) > > Just because you put it in one line doesn't chanhge how > Python interprets it. > >> If the answer is the first choice I would like to know how to >> instruct >> Python to do the second choice. > > I'm guessing you mean this the other way around? > > You can read the file line by line > > for line in In: > Out.write(line.upper()) > > HTH, Thanks a lot. From seancron+pythontutor at gmail.com Sun Sep 2 05:32:11 2007 From: seancron+pythontutor at gmail.com (Sean Cronin[tutor]) Date: Sat, 1 Sep 2007 23:32:11 -0400 Subject: [Tutor] Best way to construct this Message-ID: <cdb9f2be0709012032s12e674e8w45974f05fc9b9d57@mail.gmail.com> Hi, I'm trying to create a desktop weather program using the weather.gov SOAP XML feed[1] and (after I get the insides all sorted out) Tkinter. However, this is my first major program and I was wondering if anyone could offer me some guidance in the construction of it. I have settled on using SOAPpy for the SOAP interface and pyXML to parse the resulting XML, but I am having trouble figuring out what the most efficient way of parsing the XML and arranging my program. Right now I have two modules named libndfdsoap and weatherpy. Module libndfdsoap contains one function that gets the XML and saves it to a file named weather.xml. Module weatherpy contains some constants and a class for parsing the XML with different functions for find different data types. I am using xml.dom.minidom and using childNodes to narrow down to the values that I need and then storing that in a dictionary. Here's a snippet of the code: class ByDayXMLParse: """Contains functions for parsing the NDFD XML""" def __init__(self, path_to_xml_file): global data, maxtempdata, maxtempnode data = minidom.parse(path_to_xml_file) #Dictionary in which the max temps are going to be stored in the format #{1: day1temp, 2: day2temp, ...} maxtempdata = {} #Less typing for me :) maxtempnode = data.childNodes[0].childNodes[3].childNodes[9 ].childNodes[1] def maxTemp(self, path_to_xml_file): x = 3 y = 1 while x < 16: maxtempdata[y] = maxtempnode.childNodes[x].childNodes[0].data x, y = x + 2, y + 1 I've tried putting the XML parsing code in libndfdsoap but by doing so I couldn't access the resulting data. I can't help but feel like I'm missing something that will make my life a whole lot easier. Any help would be greatly appreciated. -Sean [1] http://www.weather.gov/forecasts/xml/ -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070901/377b6f56/attachment.htm From alan.gauld at btinternet.com Sun Sep 2 10:12:40 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 2 Sep 2007 09:12:40 +0100 Subject: [Tutor] Best way to construct this References: <cdb9f2be0709012032s12e674e8w45974f05fc9b9d57@mail.gmail.com> Message-ID: <fbdra0$hrb$1@sea.gmane.org> "Sean Cronin[tutor]" <seancron+pythontutor at gmail.com> wrote > Right now I have two modules named libndfdsoap and weatherpy. > Module > libndfdsoap contains one function that gets the XML and saves it to > a file > named weather.xml. Seems fair enough. > Module weatherpy contains some constants and a class for > parsing the XML with different functions for find different data > types. The idea of a class is that it hoolds the data plus the functions that operate *on that data*. Thus it would be more normal to put your global data into the class itself. > > class ByDayXMLParse: The name is a verb, which does not suggest an Object. Normally classes are nouns since nouns epresent things. What kind of thing is this class representing? It could be an XML Weather document maybe? In which case I'd expect it to have a parse() method and the constructor would just open the related file. > """Contains functions for parsing the NDFD XML""" > def __init__(self, path_to_xml_file): > global data, maxtempdata, maxtempnode Its very unusual to have a lot of global variables in a class. These could all be internal attributes. That would give the advantage of allowing you to have multiple instances and parse them concurrently whereas here the instances would be sharing data. > data = minidom.parse(path_to_xml_file) > #Dictionary in which the max temps are going to be stored in the > format > #{1: day1temp, 2: day2temp, ...} > maxtempdata = {} > #Less typing for me :) > maxtempnode = data.childNodes[0].childNodes[3].childNodes[9 > ].childNodes[1] > Personally I'd probably make the parse method separate from init. I'd just get init to open the file. It could then call parse as a last line, but by taking parse outside init it gives the option of reparsing the file later, if for example you suspect the data has become corrupted somehow. In pseudo code: class Weather: def init(self, fname): self.filename = fname self.data = None self.maxtemp = None self.maxnode = None self.parse() def parse(self): self.data = minidom.parse(self.filename) etc as before def maxTemp(self): # no path needed since its stored in the object > I've tried putting the XML parsing code in libndfdsoap but by doing > so I > couldn't access the resulting data. You could put the functions there and use module cvariables to hold the result, but more usually you would just return the values and the importing module (weather in this case would store them) ## in weather code import libndfdsoap as soap mylocalvar = soap.myparsingfunc() However I actually think that would be a mistake since you are then taking a potentially reusable module which simply calls a web service and stores the result and putting a lot of application specific parsing functions into it. I prefer your approach of building a weather module that reads the file and keeps the weather specific parsing functions separate from fetching the data. > I can't help but feel like I'm missing > something that will make my life a whole lot easier. I think you are on the right track but you probably want to think a bit more about your class as representing an object and what kind of things you you want to do to that object. You can then put the code that instantiates the object and calls its methods outside in your modules driver code - and eventually into your Tkinter GUI module. HTH, Alan G. From varsha.purohit at gmail.com Sun Sep 2 11:12:52 2007 From: varsha.purohit at gmail.com (Varsha Purohit) Date: Sun, 2 Sep 2007 02:12:52 -0700 Subject: [Tutor] Accessing Values of specific column in a 2D list or array Message-ID: <c2157c790709020212v2d7b6991w286a5bc8d0a9f649@mail.gmail.com> Hello, Suppose i have a 2D list(grid) like grid = [[1,1,2,7,6,9],\ [,9,1,1,1,9,1],\ [8,1,2,0,0,4],\ [1,4,1,1,8,5]] how can i access to all the elements of the list from column no. 5. output should be like [6,9,0,8]... thanks,- Varsha Purohit, -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070902/e8945213/attachment.htm From varsha.purohit at gmail.com Sun Sep 2 11:13:59 2007 From: varsha.purohit at gmail.com (Varsha Purohit) Date: Sun, 2 Sep 2007 02:13:59 -0700 Subject: [Tutor] Accessing Values of specific column in a 2D list or array In-Reply-To: <c2157c790709020212v2d7b6991w286a5bc8d0a9f649@mail.gmail.com> References: <c2157c790709020212v2d7b6991w286a5bc8d0a9f649@mail.gmail.com> Message-ID: <c2157c790709020213m494bdd32vcef5e3b2c19bd4f1@mail.gmail.com> Hello, Suppose i have a 2D list(grid) like grid = [[1,1,2,7,6,9],\ [,9,1,1,1,9,1],\ [8,1,2,0,0,4],\ [1,4,1,1,8,5]] how can i access to all the elements of the list from column no. 5. output should be like [6,9,0,8]... thanks,- Varsha Purohit, -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070902/dc8e68ec/attachment.htm From rdm at rcblue.com Sun Sep 2 11:48:19 2007 From: rdm at rcblue.com (Dick Moores) Date: Sun, 02 Sep 2007 02:48:19 -0700 Subject: [Tutor] problem resulting from installing 3.0 In-Reply-To: <fbb6ms$b83$1@sea.gmane.org> References: <20070831203855.35FF31E4006@bag.python.org> <fba7p1$dlh$1@sea.gmane.org> <20070901005453.64CA21E4006@bag.python.org> <fbb6ms$b83$1@sea.gmane.org> Message-ID: <20070902094848.80E021E4006@bag.python.org> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070902/625bc948/attachment.htm From eric at abrahamsen.com Sun Sep 2 12:37:43 2007 From: eric at abrahamsen.com (Eric Abrahamsen) Date: Sun, 2 Sep 2007 18:37:43 +0800 Subject: [Tutor] Accessing Values of specific column in a 2D list or array In-Reply-To: <c2157c790709020213m494bdd32vcef5e3b2c19bd4f1@mail.gmail.com> References: <c2157c790709020212v2d7b6991w286a5bc8d0a9f649@mail.gmail.com> <c2157c790709020213m494bdd32vcef5e3b2c19bd4f1@mail.gmail.com> Message-ID: <3610DA67-FBC9-4A8E-9E87-ECFF24017BD0@abrahamsen.com> > grid = [[1,1,2,7,6,9],\ > [,9,1,1,1,9,1],\ > [8,1,2,0,0,4],\ > [1,4,1,1,8,5]] > > how can i access to all the elements of the list from column no. 5. > > output should be like [6,9,0,8]... Your basic tool is sub-indexing: you can reach items in the sub-lists by using grid[x][x]. So use a 'for' loop to get sub-index four of every item in grid. The most compact way is with a list comprehension: grid = [[1,1,2,7,6,9],[9,1,1,1,9,1],[8,1,2,0,0,4],[1,4,1,1,8,5]] fifth_col = [grid[x][4] for x in range(len(grid))] print fifth_col There might be a more graceful replacement for the range(len(grid)) part. Yrs, Eric From ricaraoz at gmail.com Sun Sep 2 12:45:32 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Sun, 02 Sep 2007 07:45:32 -0300 Subject: [Tutor] Accessing Values of specific column in a 2D list or array In-Reply-To: <c2157c790709020213m494bdd32vcef5e3b2c19bd4f1@mail.gmail.com> References: <c2157c790709020212v2d7b6991w286a5bc8d0a9f649@mail.gmail.com> <c2157c790709020213m494bdd32vcef5e3b2c19bd4f1@mail.gmail.com> Message-ID: <46DA944C.4020201@bigfoot.com> Varsha Purohit wrote: > > > Hello, > Suppose i have a 2D list(grid) like > > grid = [[1,1,2,7,6,9],\ > [,9,1,1,1,9,1],\ > [8,1,2,0,0,4],\ > [1,4,1,1,8,5]] > > how can i access to all the elements of the list from column no. 5. > > output should be like [6,9,0,8]... > COL = 5 [i[COL-1] for i in grid] From eric at abrahamsen.com Sun Sep 2 12:50:50 2007 From: eric at abrahamsen.com (Eric Abrahamsen) Date: Sun, 2 Sep 2007 18:50:50 +0800 Subject: [Tutor] Accessing Values of specific column in a 2D list or array In-Reply-To: <46DA944C.4020201@bigfoot.com> References: <c2157c790709020212v2d7b6991w286a5bc8d0a9f649@mail.gmail.com> <c2157c790709020213m494bdd32vcef5e3b2c19bd4f1@mail.gmail.com> <46DA944C.4020201@bigfoot.com> Message-ID: <8ECDE71C-DF89-4C8C-A2A1-CBBD44C2D52A@abrahamsen.com> > > COL = 5 > [i[COL-1] for i in grid] Should have guessed... From kent37 at tds.net Sun Sep 2 14:40:53 2007 From: kent37 at tds.net (Kent Johnson) Date: Sun, 02 Sep 2007 08:40:53 -0400 Subject: [Tutor] problem resulting from installing 3.0 In-Reply-To: <20070902094848.80E021E4006@bag.python.org> References: <20070831203855.35FF31E4006@bag.python.org> <fba7p1$dlh$1@sea.gmane.org> <20070901005453.64CA21E4006@bag.python.org> <fbb6ms$b83$1@sea.gmane.org> <20070902094848.80E021E4006@bag.python.org> Message-ID: <46DAAF55.7000200@tds.net> Dick Moores wrote: > At 01:08 AM 9/1/2007, Alan Gauld wrote: > >> "Dick Moores" <rdm at rcblue.com> wrote >> >> > > > And another question is, exactly what should go into PYTHONPATH? >> > >> > >Its what goes into sys.path. PYTHONPATH is for your own customizations of sys.path, it is not the entirety of sys.path. AFAIK you don't have to define it at all if you don't want to use it. If you have a dir containing modules that you want to be able to import directly, e.g. mine/ util.py foo.py and in code you want to say import util, foo then put /path/to/mine/ in PYTHONPATH. If you have a package - a dir of modules that go together, that you want to import as a package, e.g. my-packages/ mine/ __init__.py util.py foo.py then you import them as from mine import util you still put /path/to/mine/ in PYTHONPATH but now it is the dir containing the package rather than the dir containing the module. __init__.py signals to Python that the containing dir should be treated as a package. It is independent of PYTHONPATH. There are quite a few ways to get a module into the search path, modifying PYTHONPATH is just one way. Some others: - create a site-packages/ dir in the Python lib dir. Put your modules and packages there and they will be found by Python. - add a .pth file to site-packages/ that contains the path to the dir you want to add to sys.path - modify sys.path directly in code. You can do this in a specific application or you can create site-packages/sitecustomize.py and do site-wide customizations there. Kent From alan.gauld at btinternet.com Sun Sep 2 16:10:54 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 2 Sep 2007 15:10:54 +0100 Subject: [Tutor] Accessing Values of specific column in a 2D list or array References: <c2157c790709020212v2d7b6991w286a5bc8d0a9f649@mail.gmail.com> <c2157c790709020213m494bdd32vcef5e3b2c19bd4f1@mail.gmail.com> Message-ID: <fbeg9m$5ja$1@sea.gmane.org> "Varsha Purohit" <varsha.purohit at gmail.com> wrote > grid = [[1,1,2,7,6,9],\ > [,9,1,1,1,9,1],\ > [8,1,2,0,0,4],\ > [1,4,1,1,8,5]] You don't need the '\' characters, the fact that the closing bracket has not been reached means Python will ignore the newline characters. > how can i access to all the elements of the list from column no. 5. > > output should be like [6,9,0,8]... Others have already shown but the easiest way to build a list from another list is via a list comprehension so: col5 = [row[4] for row in grid] 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 Sep 2 16:15:48 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 2 Sep 2007 15:15:48 +0100 Subject: [Tutor] problem resulting from installing 3.0 References: <20070831203855.35FF31E4006@bag.python.org> <fba7p1$dlh$1@sea.gmane.org> <20070901005453.64CA21E4006@bag.python.org> <fbb6ms$b83$1@sea.gmane.org><20070902094848.80E021E4006@bag.python.org> <46DAAF55.7000200@tds.net> Message-ID: <fbegis$6da$1@sea.gmane.org> "Kent Johnson" <kent37 at tds.net> wrote > PYTHONPATH is for your own customizations of sys.path, it is not the > entirety of sys.path. AFAIK you don't have to define it at all if > you > don't want to use it. All true. The point of PYTHONPATH is that you could have several users all running python on the same box (either concurrently on a server or different users ion the same PC at different times) PYTHONPATH allows each user to have their own custom additions to sys.path. > There are quite a few ways to get a module into the search path, > modifying PYTHONPATH is just one way. Some others: > - create a site-packages/ dir in the Python lib dir. Put your > modules > and packages there and they will be found by Python. Usually used for non standard packages like wxPython, pyGame etc that all users will want to have available > - add a .pth file to site-packages/ that contains the path to the > dir > you want to add to sys.path Similar to above but allows different Python installs on the same machine to share the same library. > - modify sys.path directly in code. This is best if only one (or a very few) application needs access to the modules. Especially if they are intended to mask standard modules like os. So use PYTHONPATH for individual tailoring and sitepackages etc for site wide changes. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From rdm at rcblue.com Sun Sep 2 16:54:20 2007 From: rdm at rcblue.com (Dick Moores) Date: Sun, 02 Sep 2007 07:54:20 -0700 Subject: [Tutor] problem resulting from installing 3.0 In-Reply-To: <46DAAF55.7000200@tds.net> References: <20070831203855.35FF31E4006@bag.python.org> <fba7p1$dlh$1@sea.gmane.org> <20070901005453.64CA21E4006@bag.python.org> <fbb6ms$b83$1@sea.gmane.org> <20070902094848.80E021E4006@bag.python.org> <46DAAF55.7000200@tds.net> Message-ID: <20070902145457.8825B1E4006@bag.python.org> Thanks, Kent. At 05:40 AM 9/2/2007, Kent Johnson wrote: >There are quite a few ways to get a module into the search path, >modifying PYTHONPATH is just one way. Some others: >- create a site-packages/ dir in the Python lib dir. Put your >modules and packages there and they will be found by Python. You mean such as site-packages\mine? That was working until I tried blanking PYTHONPATH, which previously contained E:\Python25\lib\site-packages\mine\ >- add a .pth file to site-packages/ that contains the path to the >dir you want to add to sys.path I tried this with no PYTHONPATH. I put pointers.pth in site-packages\ with the single line, E:\PythonWork\Functions\ . Functions\ contains functions.py . However, >>> import functions Traceback (most recent call last): File "<input>", line 1, in ? ImportError: No module named functions I also tried putting an __init__.py in Functions\ >>> from Functions import functions Traceback (most recent call last): File "<input>", line 1, in ? ImportError: No module named Functions >>> Please tell me where I went wrong. >- modify sys.path directly in code. You can do this in a specific >application or you can create site-packages/sitecustomize.py and do >site-wide customizations there. And also, please, show me what site-packages\sitecustomize.py should contain to make E:\PythonWork\Functions\functions.py importable (with no .pth file and no PYTHONPATH) Dick From kent37 at tds.net Sun Sep 2 17:17:49 2007 From: kent37 at tds.net (Kent Johnson) Date: Sun, 02 Sep 2007 11:17:49 -0400 Subject: [Tutor] problem resulting from installing 3.0 In-Reply-To: <20070902145457.8825B1E4006@bag.python.org> References: <20070831203855.35FF31E4006@bag.python.org> <fba7p1$dlh$1@sea.gmane.org> <20070901005453.64CA21E4006@bag.python.org> <fbb6ms$b83$1@sea.gmane.org> <20070902094848.80E021E4006@bag.python.org> <46DAAF55.7000200@tds.net> <20070902145457.8825B1E4006@bag.python.org> Message-ID: <46DAD41D.9010508@tds.net> Dick Moores wrote: > Thanks, Kent. > > At 05:40 AM 9/2/2007, Kent Johnson wrote: >> There are quite a few ways to get a module into the search path, >> modifying PYTHONPATH is just one way. Some others: >> - create a site-packages/ dir in the Python lib dir. Put your >> modules and packages there and they will be found by Python. > > You mean such as site-packages\mine? That was working until I tried > blanking PYTHONPATH, which previously contained > E:\Python25\lib\site-packages\mine\ You need to be clear on the difference between a module and a package. A module is a single python file, imported by its name. A package is a directory containing python files. The package dir must contain a file named __init__.py, which signals to Python that the dir is a package. Modules within a package are imported by packagename.modulename. This might help: http://docs.python.org/tut/node8.html If you put site-packages\mine\ in PYTHONPATH, you are telling Python to look inside mine\ for modules and modules are imported by their simple name. If you just put mine\ in site-packages, you are saying that mine is a *package* so it must contain __init__.py and modules within it will be imported by compound name mine.mymodule. > >> - add a .pth file to site-packages/ that contains the path to the >> dir you want to add to sys.path > > I tried this with no PYTHONPATH. I put pointers.pth in site-packages\ > with the single line, E:\PythonWork\Functions\ . Functions\ contains > functions.py . However, > >>> import functions > Traceback (most recent call last): > File "<input>", line 1, in ? > ImportError: No module named functions Don't know why this didn't work. Does the Functions dir appear on sys.path? > I also tried putting an __init__.py in Functions\ > >>> from Functions import functions > Traceback (most recent call last): > File "<input>", line 1, in ? > ImportError: No module named Functions In this case E:\PythonWork\ should be in sys.path so the *package* Functions will be found. Kent From rdm at rcblue.com Sun Sep 2 18:01:33 2007 From: rdm at rcblue.com (Dick Moores) Date: Sun, 02 Sep 2007 09:01:33 -0700 Subject: [Tutor] problem resulting from installing 3.0 In-Reply-To: <46DAD41D.9010508@tds.net> References: <20070831203855.35FF31E4006@bag.python.org> <fba7p1$dlh$1@sea.gmane.org> <20070901005453.64CA21E4006@bag.python.org> <fbb6ms$b83$1@sea.gmane.org> <20070902094848.80E021E4006@bag.python.org> <46DAAF55.7000200@tds.net> <20070902145457.8825B1E4006@bag.python.org> <46DAD41D.9010508@tds.net> Message-ID: <20070902160141.D0CDD1E4006@bag.python.org> At 08:17 AM 9/2/2007, Kent Johnson wrote: >Dick Moores wrote: >> >>>- add a .pth file to site-packages/ that contains the path to the >>>dir you want to add to sys.path >>I tried this with no PYTHONPATH. I put pointers.pth in >>site-packages\ with the single line, E:\PythonWork\Functions\ . >>Functions\ contains functions.py . However, >> >>> import functions >>Traceback (most recent call last): >> File "<input>", line 1, in ? >>ImportError: No module named functions > >Don't know why this didn't work. Does the Functions dir appear on sys.path? It does now with Command Prompt (still with no PYTHONPATH): E:\Python25\lib\site-packages\setuptools-0.6c5-py2.5.egg E:\Python25\lib\site-packages\dmath-0.9-py2.5.egg C:\WINDOWS\system32\python25.zip E:\Python25\DLLs E:\Python25\lib E:\Python25\lib\plat-win E:\Python25\lib\lib-tk E:\Python25 E:\Python25\lib\site-packages E:\Python25\lib\site-packages\PIL E:\PythonWork\Functions E:\Python25\lib\site-packages\win32 E:\Python25\lib\site-packages\win32\lib E:\Python25\lib\site-packages\Pythonwin E:\Python25\lib\site-packages\wx-2.8-msw-unicode >>> But not with IDLE, nor with Ulipad. Here's Ulipad's sys.path E:\Programs\Ulipad3.7\packages E:\Programs\Ulipad3.7\plugins E:\Programs\Ulipad3.7\modules E:\Programs\Ulipad3.7 E:\Programs\Ulipad3.7 E:\Python24\lib\site-packages\setuptools-0.6c5-py2.4.egg C:\WINDOWS\system32\python24.zip E:\Programs\Ulipad3.7 E:\Python24\DLLs E:\Python24\lib E:\Python24\lib\plat-win E:\Python24\lib\lib-tk E:\Python24 E:\Python24\lib\site-packages E:\Python24\lib\site-packages\wx-2.6-msw-ansi And import functions fails with both IDLE and Ulipad: >>> import functions Traceback (most recent call last): File "<input>", line 1, in ? ImportError: No module named functions >>> but works in Command Prompt. I put a file, tester.py, in E:\PythonWork\TestA with the only lines: from functions import cube print cube(123) testor.py runs OK in Ulipad and Command Prompt, but not with IDLE. Well, I've learned a lot. Seems I'd better go back to using just PYTHONPATH. And this time I'll know what I'm doing, thanks to Kent and Alan. Dick From seancron+pythontutor at gmail.com Sun Sep 2 18:37:04 2007 From: seancron+pythontutor at gmail.com (Sean Cronin[tutor]) Date: Sun, 2 Sep 2007 12:37:04 -0400 Subject: [Tutor] Best way to construct this Message-ID: <cdb9f2be0709020937q476ab21bq9f35ffb01a72f7c7@mail.gmail.com> Hey, Thanks Alan for the help on the classes. This is my first time using them (in case you couldn't tell :) ). However, I can't understand why you want to make a separate function called parse. What I am trying to do by having different functions in the class like maxtemp, and mintemp, is to allow my self to be able to parse only for certain data, instead of having one giant function that parses for everything. That way I have the option of being able to selectively parse the data. It also gives me the option as you said of being able to reparse the data later if it became corrupted somehow. Also, where should I put the value for the maxtempnode since you set them equal to none in the pseudo code you sent. >class Weather: > def init(self, fname): > self.filename = fname > self.data = None > self.maxtemp = None > self.maxnode = None Should I change the None to what their values should be, or should I do that at some point later in the code? Thanks, -Sean -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070902/fc37cd6c/attachment.htm From varsha.purohit at gmail.com Sun Sep 2 19:12:18 2007 From: varsha.purohit at gmail.com (Varsha Purohit) Date: Sun, 2 Sep 2007 10:12:18 -0700 Subject: [Tutor] Accessing Values of specific column in a 2D list or array In-Reply-To: <fbeg9m$5ja$1@sea.gmane.org> References: <c2157c790709020212v2d7b6991w286a5bc8d0a9f649@mail.gmail.com> <c2157c790709020213m494bdd32vcef5e3b2c19bd4f1@mail.gmail.com> <fbeg9m$5ja$1@sea.gmane.org> Message-ID: <c2157c790709021012j7ce039crdc4f9b4e26f0d991@mail.gmail.com> Thanks Eric and Alan i did that with while loop. I donno i was getting an error while using a for loop for subindexing. Here is what i did i=0 selectCols=0 arr2=[] while i<rows: selectCols=grid[i][colID] i+=1 arr2.append(selectCols) print "col",colID,"values :",arr2 ----->colID is the value of the requested column to print. which remains the same throughout the iteration of while. On 9/2/07, Alan Gauld <alan.gauld at btinternet.com> wrote: > > > "Varsha Purohit" <varsha.purohit at gmail.com> wrote > > > grid = [[1,1,2,7,6,9],\ > > [,9,1,1,1,9,1],\ > > [8,1,2,0,0,4],\ > > [1,4,1,1,8,5]] > > You don't need the '\' characters, the fact that the closing > bracket has not been reached means Python will ignore > the newline characters. > > > how can i access to all the elements of the list from column no. 5. > > > > output should be like [6,9,0,8]... > > Others have already shown but the easiest way to build a list > from another list is via a list comprehension so: > > col5 = [row[4] for row in grid] > > 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 > -- Varsha Purohit, Graduate Student, San Diego State University -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070902/e5be1f7c/attachment.htm From ricaraoz at gmail.com Sun Sep 2 19:52:50 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Sun, 02 Sep 2007 14:52:50 -0300 Subject: [Tutor] Accessing Values of specific column in a 2D list or array In-Reply-To: <c2157c790709021012j7ce039crdc4f9b4e26f0d991@mail.gmail.com> References: <c2157c790709020212v2d7b6991w286a5bc8d0a9f649@mail.gmail.com> <c2157c790709020213m494bdd32vcef5e3b2c19bd4f1@mail.gmail.com> <fbeg9m$5ja$1@sea.gmane.org> <c2157c790709021012j7ce039crdc4f9b4e26f0d991@mail.gmail.com> Message-ID: <46DAF872.1080604@bigfoot.com> Varsha Purohit wrote: > Thanks Eric and Alan i did that with while loop. I donno i was getting > an error while using a for loop for subindexing. Here is what i did > > i=0 > selectCols=0 > arr2=[] > while i<rows: > selectCols=grid[i][colID] > i+=1 > arr2.append(selectCols) > > print "col",colID,"values :",arr2 > How about : print 'Col', colID, 'values :', ', '.join([str(i[colID]) for i in grid]) From simong1080 at gmail.com Sun Sep 2 19:10:17 2007 From: simong1080 at gmail.com (shimon gurman) Date: Sun, 2 Sep 2007 19:10:17 +0200 Subject: [Tutor] Backupfile program. Help. Thanks. Message-ID: <6f4832f90709021010j2a9708e0rce1f79f6a42e1f95@mail.gmail.com> Can someone explain to me why this program isnt working? i.e. I always get 'backup failed'? This is a program from byte of python tutorial and im using windows xp. import os, time source = ['d:\\python'] target_directory = 'd:\\python1' target = target_directory + time.strftime('%Y%m%d_%H%M%S') + '.zip' zip_command = "zip -qr '%s' %s" % (target, ' '.join(source)) print zip_command if os.system(zip_command) == 0: print 'Successful backup to', target else: print 'Backup FAILED' -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070902/3419ec32/attachment.htm From ricaraoz at gmail.com Sun Sep 2 21:01:02 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Sun, 02 Sep 2007 16:01:02 -0300 Subject: [Tutor] Backupfile program. Help. Thanks. In-Reply-To: <6f4832f90709021010j2a9708e0rce1f79f6a42e1f95@mail.gmail.com> References: <6f4832f90709021010j2a9708e0rce1f79f6a42e1f95@mail.gmail.com> Message-ID: <46DB086E.8010700@bigfoot.com> shimon gurman wrote: > Can someone explain to me why this program isnt working? i.e. I always get 'backup failed'? > This is a program from byte of python tutorial and im using windows xp. > > > > > import os, time > > > > source = ['d:\\python'] > > > target_directory = 'd:\\python1' > > target = target_directory + time.strftime('%Y%m%d_%H%M%S') + '.zip' > > zip_command = "zip -qr '%s' %s" % (target, ' '.join(source)) > > print zip_command > > > if os.system(zip_command) == 0: > print 'Successful backup to', target > else: > print 'Backup FAILED' > try (I'm guessing) : target_directory = 'd:\\python1\\' and / or zip_command = 'zip -qr "%s" "%s"' % (target, ' '.join(source)) (your second %s was not enclosed in ", besides it's probably better to use " than ', can't remember right now) Are you sure that is a '-qr' or should it be '-pr'? I can not check it because I use 7-zip (here p would set password and r recurse directories). From alan.gauld at btinternet.com Sun Sep 2 21:11:54 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 2 Sep 2007 20:11:54 +0100 Subject: [Tutor] Best way to construct this References: <cdb9f2be0709020937q476ab21bq9f35ffb01a72f7c7@mail.gmail.com> Message-ID: <fbf1u2$pu0$1@sea.gmane.org> "Sean Cronin[tutor]" <seancron+pythontutor at gmail.com> wrote > (in case you couldn't tell :) ). However, I can't understand why > you want > to make a separate function called parse. OK, I want to make a separate *method* called parse, not a function. Methods are what you have inside classes. You send messages to instances and those messages cause methods to be executed. That's an important concept to get your head around. It's not the same as simply functions. Why have a separate parse method? Three reasons: 1) It keeps the init method simple. init methods are for initialising the state of the object, they should not normally contain any complex code. 2) If, after creating an instance of your class and working with it the data gets corrupted for any reason you can reinstate the original data by calling the parse method. 3) If you should ever have reason to subclass this class having the parse method available as a method allws you to have a new parse algorithm (maybe using a different parser) without having to change the rest of the code. OTOH is the parsing is the same but the other methods change you can leave it as is. If the parsing is in the init then you can almost guarantee that the init will change and you will have to rewrite the parse code in each suib class. > different functions in the class like maxtemp, and mintemp, is to > allow my > self to be able to parse only for certain data, Thats fine, although maxtemp is an attribute not a function/method. > instead of having one giant function that parses for everything. > That > way I have the option of being able to selectively parse the data. > It also gives me the option as you said of being able to reparse the > data later if it became corrupted somehow. I'm not sure how. Your original function did the parsing in the init method and set the values of maxtemp nodede etc from the resultant parse tree. > Also, where should I put the value for the maxtempnode since > you set them equal to none in the pseudo code you sent. I initialised tem to None because you can't set their values till after parsing the file. Thus you would have to set up the max etc in the parse method. >>class Weather: >> def init(self, fname): >> self.filename = fname >> self.data = None >> self.maxtemp = None >> self.maxnode = None > > Should I change the None to what their values should be, or should I > do that > at some point later in the code? Reading your code it looked like the values were dependent on the parsed file. If you know before parsing what they are then I'd make them parameters of init with defaults: def __Iinit__(self, fname, max=42, min=0, node=???): self.filename = fname self.data = None self.maxtemp = max self.mintemp = min self.maxnode = node I'm not sure enough of how your class will be used to know which solution fits best. However the main point is that classes are not just collections of functions - thats what modules are for - they are supposed to be representations of whole entities within your program - objects. The objects have behaviours - their methods and they manage data for you (via the methods). Thus you should think carefully about what objects your class represents and what purpose those objects serve (what are their responsibilities?). HTH -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From jim at well.com Sun Sep 2 21:46:57 2007 From: jim at well.com (jim stockford) Date: Sun, 2 Sep 2007 12:46:57 -0700 Subject: [Tutor] about modules, classes, methods, functions Message-ID: <830f90023849591ba15846a08e0d316c@well.com> I've gotten red-eyed looking through google pages to find answers. I've read the python.org docs and tutorials entirely (some parts very quickly). If I write a little .py file, its name is __main__ assuming no big nit-picks in the claim above, is __main__ a class? What exactly does it mean "module" and how is that different from a class. Is it sufficient to define a class as some executable code that gets run when it's loaded? Someone has so defined, but I don't think it's sufficient. classic definition of a function is some code that takes arguments and returns a single value. What's the definition of a function in python? how is a method different from a function? Is it just that a method is a member of a class, i.e. can a class have both methods and functions? thanks in advance. jim From davmillar at gmail.com Sun Sep 2 19:24:33 2007 From: davmillar at gmail.com (David Millar) Date: Sun, 2 Sep 2007 13:24:33 -0400 Subject: [Tutor] Condensing Some Massive Code Message-ID: <c070fc970709021024t67aed76ai2b3a1fd75b728886@mail.gmail.com> Hello. I'm working on a text adventure game right now, and I seem to be kind of stuck. There's a huge chunk of code called moreaction() that pulls scripted events for certain locations. It's ever-changing so I'm not looking for specifics, but can anyone suggest good ways to clean up or condense the code without sacrificing clarity? The latest version of the source is found at http://thegriddle.net/python/v006.txt Any help is much appreciated :) - Dave M. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070902/c9c20904/attachment-0001.htm From kent37 at tds.net Sun Sep 2 23:45:52 2007 From: kent37 at tds.net (Kent Johnson) Date: Sun, 02 Sep 2007 17:45:52 -0400 Subject: [Tutor] about modules, classes, methods, functions In-Reply-To: <830f90023849591ba15846a08e0d316c@well.com> References: <830f90023849591ba15846a08e0d316c@well.com> Message-ID: <46DB2F10.1070309@tds.net> jim stockford wrote: > I've gotten red-eyed looking through google pages > to find answers. I've read the python.org docs and > tutorials entirely (some parts very quickly). > > If I write a little .py file, its name is __main__ > > assuming no big nit-picks in the claim above, > is __main__ a class? No, it is a module. > What exactly does it mean "module" and how > is that different from a class. A module corresponds to a single file of source code. A class is...well, the object created when you execute a 'class' statement. Classes are defined in modules. I'm struggling with this one. How do you see them as the same? They both contain and organize functions but the way they are used is very different. > Is it sufficient to define a class as some executable > code that gets run when it's loaded? Someone has > so defined, but I don't think it's sufficient. Any executable code? No. A class is a particular kind of object, created (usually) by a class statement. > classic definition of a function is some code that > takes arguments and returns a single value. What's > the definition of a function in python? That sounds OK. > > how is a method different from a function? Is it > just that a method is a member of a class, Yes. > i.e. can > a class have both methods and functions? A class can have static methods and class methods which are functions but not the same as normal methods. Kent From varsha.purohit at gmail.com Mon Sep 3 00:21:17 2007 From: varsha.purohit at gmail.com (Varsha Purohit) Date: Sun, 2 Sep 2007 15:21:17 -0700 Subject: [Tutor] [tutor] Difference between index and find in manipulating strings Message-ID: <c2157c790709021521p1ec3e760rf0ce6df0d3460aba@mail.gmail.com> Hello, i have again very basic question in python string management. I am not able to understand how find and index works and what do they actually return. >>> line = "this is varsha" >>> print line.find("is") 2 >>> print line.rfind("is") 5 >>> print line.rfind("varsha") 8 >>> print line.index("varsha") 8 what does 2 in first line signifies... and why rfind gave 5 as an output... can anybody pls explain me what exactly is interpreter tryin to return..... -- Varsha Purohit, -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070902/9c8726bc/attachment.htm From alan.gauld at btinternet.com Mon Sep 3 00:20:52 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 2 Sep 2007 23:20:52 +0100 Subject: [Tutor] about modules, classes, methods, functions References: <830f90023849591ba15846a08e0d316c@well.com> Message-ID: <fbfd0d$o23$1@sea.gmane.org> "jim stockford" <jim at well.com> wrote > If I write a little .py file, its name is __main__ > > assuming no big nit-picks in the claim above, > is __main__ a class? No, its the name of your module when its run as a script rather than imported. Its assigned by the interpreter. (At least i assumev you haven't literally called your file __main__.py, that might cause Python some confusion!) > What exactly does it mean "module" and how > is that different from a class. A module is a file which contains code. That code could define functions and/or classes It could also define variables as well as contain executable code (loops etc) > Is it sufficient to define a class as some executable > code that gets run when it's loaded? Someone has > so defined, but I don't think it's sufficient. A class definition is executable just like a function definition. But the execution of the code produces a class object. By calling that class object you create an instance of the class (also, somewhat confusingly called an Object) > classic definition of a function is some code that > takes arguments and returns a single value. What's > the definition of a function in python? Pretty much the same. But in the event that the function does not explicitly return a value Python provides a default return of None. Also python return values can include tuples which appear like multiple return values: def maxmin(aSequence): mx = max(aSequence) mn = min(aSequence) return mx,mn x,n = maxmin([1,2,3,4,5,6,7]) > how is a method different from a function? Is it > just that a method is a member of a class, i.e. can > a class have both methods and functions? It differs in several ways. The primary one is that it is defined inside a class. Also the first parameter is the instance to which the method applies at run time and is not explicitly given at execution time. class C: def meth(self,x): print x c = C() c.meth(42) So meth is defined with two parameters but called with one. In pure OOP terms there is another important difference between a method and a function. A function is always called by name but a method is called by sending a "message" to an object. There is nothing in OOP theory (and in some languages in practice) that says the method must have the same name as the message Thus: class C: def _aMethod(self): print 'aMethod is running' foo = _aMethod c = C() c._aMethod() c.foo() Here we send two messages to c but both execute the same method. Other languages (eg. Lisp, Objective C, Eiffel) allow us to explicitly name the method invoked by a message and have the two take different names. Python doesn't support that. Note: The concept of sending a message as distinct from calling a method is quite fundamental to thinking about objects as dynamic emntities within a program. In a theoretically pure OOP environment each object would be a separate process and the messages would be literal inter-process messages. But such a pure approach would be utterly impractical on todays technology - far too slow. However the concept is extremely important in computer science terms since such a machine can be represented mathematically and simulations can be created in much the same way as electronic engineers can build and execute models of circuits. Many software engineering academics believe that this may be the key to building truly reliable and predictable large scale software systems. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From ricaraoz at gmail.com Mon Sep 3 01:03:42 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Sun, 02 Sep 2007 20:03:42 -0300 Subject: [Tutor] [tutor] Difference between index and find in manipulating strings In-Reply-To: <c2157c790709021521p1ec3e760rf0ce6df0d3460aba@mail.gmail.com> References: <c2157c790709021521p1ec3e760rf0ce6df0d3460aba@mail.gmail.com> Message-ID: <46DB414E.4010509@bigfoot.com> Varsha Purohit wrote: > Hello, > i have again very basic question in python string management. > > I am not able to understand how find and index works and what do they > actually return. > >>>> line = "this is varsha" >>>> print line.find("is") > 2 >>>> print line.rfind("is") > 5 >>>> print line.rfind("varsha") > 8 >>>> print line.index("varsha") > 8 > > what does 2 in first line signifies... and why rfind gave 5 as an output... > > can anybody pls explain me what exactly is interpreter tryin to return..... > Sure. The 2 in first line means the string 'is' begins in line[2] that would be the 'is' in 'this' (remember line's first character 't' is line[0]). OTOH rfind looks for the first appearance of 'is' in line but starting from the right, that would be the word 'is' which starts at line[5]. As there is only one occurrence of 'varsha' in line both methods, find and rfind will give the same answer : 8. >From Python 2.5 documentation : index( sub[, start[, end]]) Like find(), but raise ValueError when the substring is not found. HTH From varsha.purohit at gmail.com Mon Sep 3 01:48:56 2007 From: varsha.purohit at gmail.com (Varsha Purohit) Date: Sun, 2 Sep 2007 16:48:56 -0700 Subject: [Tutor] [tutor] Difference between index and find in manipulating strings In-Reply-To: <46DB414E.4010509@bigfoot.com> References: <c2157c790709021521p1ec3e760rf0ce6df0d3460aba@mail.gmail.com> <46DB414E.4010509@bigfoot.com> Message-ID: <c2157c790709021648h6cea49c0k616385af56b9ff16@mail.gmail.com> Thanks guys it was really helpful.... i m just a beginner in python start to program since two days back. So finding little difficulty with some concepts. On 9/2/07, Ricardo Ar?oz <ricaraoz at gmail.com> wrote: > > Varsha Purohit wrote: > > Hello, > > i have again very basic question in python string management. > > > > I am not able to understand how find and index works and what do they > > actually return. > > > >>>> line = "this is varsha" > >>>> print line.find("is") > > 2 > >>>> print line.rfind("is") > > 5 > >>>> print line.rfind("varsha") > > 8 > >>>> print line.index("varsha") > > 8 > > > > what does 2 in first line signifies... and why rfind gave 5 as an > output... > > > > can anybody pls explain me what exactly is interpreter tryin to > return..... > > > Sure. > The 2 in first line means the string 'is' begins in line[2] that would > be the 'is' in 'this' (remember line's first character 't' is line[0]). > OTOH rfind looks for the first appearance of 'is' in line but starting > from the right, that would be the word 'is' which starts at line[5]. > As there is only one occurrence of 'varsha' in line both methods, find > and rfind will give the same answer : 8. > > From Python 2.5 documentation : > > index( sub[, start[, end]]) > Like find(), but raise ValueError when the substring is not found. > > > > HTH > > -- Varsha Purohit, Graduate Student, San Diego State University -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070902/4ab34417/attachment.htm From alan.gauld at btinternet.com Mon Sep 3 01:48:49 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 3 Sep 2007 00:48:49 +0100 Subject: [Tutor] [tutor] Difference between index and find in manipulating strings References: <c2157c790709021521p1ec3e760rf0ce6df0d3460aba@mail.gmail.com> <46DB414E.4010509@bigfoot.com> Message-ID: <fbfi5a$3tm$1@sea.gmane.org> "Ricardo Ar?oz" <ricaraoz at gmail.com> wrote >>From Python 2.5 documentation : > > index( sub[, start[, end]]) > Like find(), but raise ValueError when the substring is not found. As opposed to find() which returns -1 when the string is not found. That means you can use try/except with index but must check for -1 with find: if 'foo'.find('q') == -1: print 'oops!' as opposed to try: 'foo'.index('q') except ValueErrror: print 'oops!' Which style is best will depend on what you are doing. HTH, Alan g From ricaraoz at gmail.com Mon Sep 3 02:00:30 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Sun, 02 Sep 2007 21:00:30 -0300 Subject: [Tutor] [tutor] Difference between index and find in manipulating strings In-Reply-To: <c2157c790709021648h6cea49c0k616385af56b9ff16@mail.gmail.com> References: <c2157c790709021521p1ec3e760rf0ce6df0d3460aba@mail.gmail.com> <46DB414E.4010509@bigfoot.com> <c2157c790709021648h6cea49c0k616385af56b9ff16@mail.gmail.com> Message-ID: <46DB4E9E.4010008@bigfoot.com> Varsha Purohit wrote: > > Thanks guys it was really helpful.... i m just a beginner in python > start to program since two days back. So finding little difficulty with > some concepts. > Don't worry, I'm a 20 days "old timer". ;c) From alan.gauld at btinternet.com Mon Sep 3 02:28:03 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 3 Sep 2007 01:28:03 +0100 Subject: [Tutor] [tutor] Difference between index and find in manipulating strings References: <c2157c790709021521p1ec3e760rf0ce6df0d3460aba@mail.gmail.com> <46DB414E.4010509@bigfoot.com><c2157c790709021648h6cea49c0k616385af56b9ff16@mail.gmail.com> <46DB4E9E.4010008@bigfoot.com> Message-ID: <fbfkes$8hm$1@sea.gmane.org> "Ricardo Ar?oz" <ricaraoz at gmail.com> wrote >> Thanks guys it was really helpful.... i m just a beginner in >> python >> start to program since two days back. So finding little difficulty >> with >> some concepts. >> > > Don't worry, I'm a 20 days "old timer". ;c) And I've been using Python for over 10 years now and still manage to pick up at least one new idea every week on this list! :-) -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From trey at opmstech.org Mon Sep 3 02:31:42 2007 From: trey at opmstech.org (Trey Keown) Date: Sun, 2 Sep 2007 19:31:42 -0500 (CDT) Subject: [Tutor] replacement for .mainloop() in Tk Message-ID: <61153.68.191.136.241.1188779502.squirrel@webmail.opmstech.org> Okay, I'm making a program that turns xml code into python code. Here's the an example of input- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ <element> <section name="MAIN"> <window name="self" icon="e.ico" title="Example Window Title"> <button text="click me." command="doButtonClick" /> </window> </section> </element> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ And here would be the corresponding output (well, what I've got so far...) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ from Tkinter import * import tkFileDialog #<<<<<Main stuff>>>>># self = Tk() self.title("Example Window Title") self.iconbitmap("e.ico") #<<<<<Get to work on button function!!!>>>>># #<<<<<End window self>>>>># #<<<<<End section>>>>># #<<<<<End program>>>>># ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Now, as you probably see, there isn't a "self.mainloop()" function in the output. My question is- *Is there any other thing I could use instead of ".mainloop()" to make a window come up? Because I noticed that only one window can be up at a time that has a ".mainloop()" attribute. From rdm at rcblue.com Mon Sep 3 03:36:29 2007 From: rdm at rcblue.com (Dick Moores) Date: Sun, 02 Sep 2007 18:36:29 -0700 Subject: [Tutor] What's up with Python 2.5.1's IDLE? Message-ID: <20070903013638.687341E4006@bag.python.org> Under Kent's tutelage, I've been experimenting with having no PYTHONDOC, and instead putting a .pth file in E:\Python25\lib\site-packages\ I named pointers.pth. The contents of pointers.pth is: E:\Python25\ E:\PythonWork\ E:\PythonWork\Functions\ E:\Python25\lib\site-packages\ E:\Python25\lib\site-packages\mine Here's what the Command Prompt shell shows for sys.path: E:\Python25>python Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> from sys import path >>> for x in path: ... print x ... E:\Python25\lib\site-packages\setuptools-0.6c5-py2.5.egg E:\Python25\lib\site-packages\dmath-0.9-py2.5.egg C:\WINDOWS\system32\python25.zip E:\Python25\DLLs E:\Python25\lib E:\Python25\lib\plat-win E:\Python25\lib\lib-tk E:\Python25 E:\Python25\lib\site-packages E:\Python25\lib\site-packages\PIL E:\PythonWork E:\PythonWork\Functions E:\Python25\lib\site-packages E:\Python25\lib\site-packages\mine E:\Python25\lib\site-packages\win32 E:\Python25\lib\site-packages\win32\lib E:\Python25\lib\site-packages\Pythonwin E:\Python25\lib\site-packages\wx-2.8-msw-unicode >>> All good. However, this is what IDLE's shell shows for sys.path: >>> from sys import path >>> for x in path: print x E:\Python25\Lib\idlelib E:\Python24\lib\site-packages\setuptools-0.6c5-py2.4.egg C:\WINDOWS\system32\python24.zip E:\Python25\Lib\idlelib E:\Python24\DLLs E:\Python24\lib E:\Python24\lib\plat-win E:\Python24\lib\lib-tk E:\Python24 E:\Python24\lib\site-packages E:\Python24\lib\site-packages\wx-2.6-msw-ansi I do still have Python 2.4, but why does Python 2.5.1's IDLE's shell show all those things from 2.4, and only shows the path to itself in 2.5.1? I like the editing ease of having a .pth file rather than a troublesome-to-edit PYTHONDOC, but I need to first clear up the problem with IDLE (which works fine with a PYTHONDOC). Thanks, Dick Moores XP, Python 2.5.1 From alan.gauld at btinternet.com Mon Sep 3 09:25:11 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 3 Sep 2007 08:25:11 +0100 Subject: [Tutor] replacement for .mainloop() in Tk References: <61153.68.191.136.241.1188779502.squirrel@webmail.opmstech.org> Message-ID: <fbgct0$q5l$1@sea.gmane.org> "Trey Keown" <trey at opmstech.org> wrote > ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ > from Tkinter import * > import tkFileDialog > #<<<<<Main stuff>>>>># > self = Tk() Using self here is a little bit unconventional sinmce its not in a class. That could confuse some readers. > self.title("Example Window Title") > self.iconbitmap("e.ico") > #<<<<<Get to work on button function!!!>>>>># > #<<<<<End window self>>>>># > #<<<<<End section>>>>># > #<<<<<End program>>>>># > ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ > Now, as you probably see, there isn't a "self.mainloop()" > function in the output. My question is- > *Is there any other thing I could use instead of ".mainloop()" to > make a > window come up? Because I noticed that only one window can be up at > a time > that has a ".mainloop()" attribute. I'm not sure what you mean by that. You can have as many windows as you like but there can only be one mainloop call, usually on the top level tk object not on a window at all. The mainloop is the event loop of the program. Without that Tk cannot capture any events and hence can't do anything. But why would having a mainloop be a problem? You can call it at the end of your code. (In fact you can call it at the beginning if you like! The end is just convention - and it does make inserting new controls etc less problematic) I'm slightly confused by what you are asking. What is the problem that you think you have? -- 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 Sep 3 09:39:16 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 3 Sep 2007 08:39:16 +0100 Subject: [Tutor] What's up with Python 2.5.1's IDLE? References: <20070903013638.687341E4006@bag.python.org> Message-ID: <fbgdnd$sce$1@sea.gmane.org> "Dick Moores" <rdm at rcblue.com> wrote > Under Kent's tutelage, I've been experimenting with having no > PYTHONDOC, I assume you mean PYTHONPATH? > and instead putting a .pth file in > E:\Python25\lib\site-packages\ I named pointers.pth. I obviously failed to convince you of the superior flexibility of using PYTHONPATH for your personal libs :-) If your PC is only usd by you and you only have one user account then that probably isn't a problem, except you lose the flexibility of changing PYTHONPATH dynamically during a session using SET. > The contents of > pointers.pth is: > E:\Python25\ > E:\PythonWork\ > E:\PythonWork\Functions\ > E:\Python25\lib\site-packages\ > E:\Python25\lib\site-packages\mine I would have expected Python to load the Python25 stuff itself. You should only need the pointers file to contain the pointers to the non standard directories (just as you would in PYTHONPATH) > Here's what the Command Prompt shell shows for sys.path: > E:\Python25\lib\site-packages\setuptools-0.6c5-py2.5.egg > E:\Python25\lib\site-packages\dmath-0.9-py2.5.egg > C:\WINDOWS\system32\python25.zip > E:\Python25\DLLs > E:\Python25\lib > E:\Python25\lib\plat-win > E:\Python25\lib\lib-tk > E:\Python25 > E:\Python25\lib\site-packages > E:\Python25\lib\site-packages\PIL > E:\PythonWork > E:\PythonWork\Functions > E:\Python25\lib\site-packages > E:\Python25\lib\site-packages\mine > E:\Python25\lib\site-packages\win32 > E:\Python25\lib\site-packages\win32\lib > E:\Python25\lib\site-packages\Pythonwin > E:\Python25\lib\site-packages\wx-2.8-msw-unicode > >>> > All good. Not quite all good - you have multiple entries for site-packages... > However, this is what IDLE's shell shows for sys.path: > > E:\Python25\Lib\idlelib > E:\Python24\lib\site-packages\setuptools-0.6c5-py2.4.egg > C:\WINDOWS\system32\python24.zip > E:\Python25\Lib\idlelib > E:\Python24\DLLs > E:\Python24\lib > E:\Python24\lib\plat-win > E:\Python24\lib\lib-tk > E:\Python24 > E:\Python24\lib\site-packages > E:\Python24\lib\site-packages\wx-2.6-msw-ansi > > I do still have Python 2.4, but why does Python 2.5.1's IDLE's shell > show all those things from 2.4, and only shows the path to itself in > 2.5.1? It looks like IDLE has its own mechanism for populating sys.path and it may be reading something in the Registry. This might be a question to ask on the IDLE mailing list? > I like the editing ease of having a .pth file rather than a > troublesome-to-edit PYTHONDOC, but I need to first clear up the > problem with IDLE (which works fine with a PYTHONDOC). I'm not sure I understand what you mean by the editing ease? You can change PYTHONPATH with a simple SET command (albeit temporarily) and 3 mouse clicks takes you to the dialog editor. HTH, Alan G From kent37 at tds.net Mon Sep 3 12:31:35 2007 From: kent37 at tds.net (Kent Johnson) Date: Mon, 03 Sep 2007 06:31:35 -0400 Subject: [Tutor] replacement for .mainloop() in Tk In-Reply-To: <61153.68.191.136.241.1188779502.squirrel@webmail.opmstech.org> References: <61153.68.191.136.241.1188779502.squirrel@webmail.opmstech.org> Message-ID: <46DBE287.6080006@tds.net> Trey Keown wrote: > Okay, I'm making a program that turns xml code into python code. > > And here would be the corresponding output (well, what I've got so far...) > > ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ > from Tkinter import * > import tkFileDialog > #<<<<<Main stuff>>>>># > self = Tk() > self.title("Example Window Title") > self.iconbitmap("e.ico") > #<<<<<Get to work on button function!!!>>>>># > #<<<<<End window self>>>>># > #<<<<<End section>>>>># > #<<<<<End program>>>>># > ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ > > Now, as you probably see, there isn't a "self.mainloop()" function in the > output. Why not just out put the mainloop() before <<End program>> ? You might be interested in http://www.bitflipper.ca/rapyd/ though it seems to store its data in pickles, not xml. Kent From kent37 at tds.net Mon Sep 3 12:34:19 2007 From: kent37 at tds.net (Kent Johnson) Date: Mon, 03 Sep 2007 06:34:19 -0400 Subject: [Tutor] What's up with Python 2.5.1's IDLE? In-Reply-To: <20070903013638.687341E4006@bag.python.org> References: <20070903013638.687341E4006@bag.python.org> Message-ID: <46DBE32B.3070809@tds.net> Dick Moores wrote: > However, this is what IDLE's shell shows for sys.path: > >>> from sys import path > >>> for x in path: > print x > > > E:\Python25\Lib\idlelib > E:\Python24\lib\site-packages\setuptools-0.6c5-py2.4.egg > C:\WINDOWS\system32\python24.zip > E:\Python25\Lib\idlelib > E:\Python24\DLLs > E:\Python24\lib > E:\Python24\lib\plat-win > E:\Python24\lib\lib-tk > E:\Python24 > E:\Python24\lib\site-packages > E:\Python24\lib\site-packages\wx-2.6-msw-ansi > > I do still have Python 2.4, but why does Python 2.5.1's IDLE's shell > show all those things from 2.4, and only shows the path to itself in 2.5.1? It looks to me like IDLE is running under 2.4 but using the IDLE package from 2.5. Kent From srikanth007m at gmail.com Mon Sep 3 15:40:27 2007 From: srikanth007m at gmail.com (chinni) Date: Mon, 3 Sep 2007 06:40:27 -0700 Subject: [Tutor] indexing elements Message-ID: <b5300ea90709030640i88cb14k3349876e55eaa467@mail.gmail.com> Hi all, i had some doubt about this line can any body clarify this plz....... endings = ['st', 'nd', 'rd'] + 17 * ['th'] + ['st', 'nd', 'rd'] + 7 * ['th'] + ['st'] -- Best Regards, M.Srikanth Kumar, Jr.Software Developer, Google India Pvt Ltd.., HYDERABAD. Phone no: +91-9866774007 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070903/18dbcce8/attachment.html From ghashsnaga at gmail.com Mon Sep 3 19:47:09 2007 From: ghashsnaga at gmail.com (Ara Kooser) Date: Mon, 3 Sep 2007 11:47:09 -0600 Subject: [Tutor] More class questions Message-ID: <2107481c0709031047t53332fb8q185fe92c396d6c8@mail.gmail.com> Hello again, Thank you again for your help. I have classes somewhat figured out and I am beginning to understand the syntax involved in using them. What I have so far is a very simple text adventure with two rooms, two items, and some exits. Two question which relates directly to classes: Do you create all your instances at the end of the program or just as needed? Can you call functions from other classes within a class (So I create an Object class for items and I want then instances to appear in the Room class as they are called). Third question. Using function I understand how to move a player around in different rooms using raw_input and if statements but how do you do that with classes. I created a player class and I want one of the methods to be moving from room to room. Or should movement be a separate class? I am looking at the code that Paul McGuire wrote for using pyparsing and I don't quite understand how it all works. I have to book Game Programming: The L line coming in two weeks. I am just trying to get a head start. Thank you. Ara CODE BELOW ##################################################################### #Text Advenuture - Roguelike #By Ara Kooser #Thanks to Chris, e.,Tino and Steven at python tutor #################################################################### class Player: #What makes this a player. pass #def Move(self): class Area: #What makes it an area? def __init__(self, name, description): #Number of arguements in the _init_ there must be defined self.name = name self.description = description self.contents = [] self.paths = [None,None,None,None] #Methods. What you can do. def AddObject(self,thing): self.contents.append(thing) def AddPaths(self,direction): self.paths.append(direction) def look(self): print "Look around the place you are in" print "You are in the",self.name print self.description print "Your exits are:" print self.paths def search(self): print "You search the area and find..." print self.contents ############################################################################### # MAIN # Start of program ############################################################################### first_instance = Area("Outside", "You are standing outside") first_instance.AddObject("Stick") first_instance.AddPaths("North") first_instance.look() first_instance.search() print print second_instance = Area("Inside", "You are standing inside") second_instance.AddObject("Iron pot") second_instance.AddPaths("South") second_instance.look() second_instance.search() -- Quis hic locus, quae regio, quae mundi plaga. Ubi sum. Sub ortu solis an sub cardine glacialis ursae. From dos.fool at gmail.com Mon Sep 3 22:06:48 2007 From: dos.fool at gmail.com (max baseman) Date: Mon, 3 Sep 2007 14:06:48 -0600 Subject: [Tutor] checking if a number is evan or odd Message-ID: <F57661B9-6EE3-4C97-8C77-1862E74E8D10@gmail.com> hello just a quick check in, it's about the same program i was asking about before ive let it sit for a few days now and i reached a number to high to convert to a decimal by adding 0.0 here's the program: count=1 numstart=268549802 number=0 high=0 a=0 while 1==1: numstart=numstart+1 number=numstart count=1 while number !=1: if number/2 == (number+0.0)/2: number=number/2 else: number=(number*3)+1 count=count+1 if count > a: a=count print numstart,":",count after a few days i got this error: Traceback (most recent call last): File "homework6high.py", line 11, in <module> if number/2 == (number+0.0)/2: OverflowError: long int too large to convert to float just wondering if theirs a way to check if a larger number is even or odd thanks From orest.kozyar at gmail.com Mon Sep 3 22:08:20 2007 From: orest.kozyar at gmail.com (Orest Kozyar) Date: Mon, 3 Sep 2007 16:08:20 -0400 Subject: [Tutor] Metaclass programming Message-ID: <006f01c7ee66$2ec66fa0$bd32000a@issphoenix> I have the following code: class meta(type): def __call__(cls, *args, **kwargs): argnames = inspect.getargspec(cls.__init__)[0] for i, value in enumerate(args): kwargs[argnames[i]] = value return type.__call__(cls, kwargs) class test(object): __metaclass__ = meta def __init__(self, x, y, **kwargs): pass However, inspect.getargspec(cls.__init__) appears to return only the arguments of the meta __init__ rather than the test __init__. Is there any way I can get access to the test __init__ function from the metaclass? Orest From jdoege at da-test.com Tue Sep 4 00:15:52 2007 From: jdoege at da-test.com (Jason Doege) Date: Mon, 3 Sep 2007 18:15:52 -0400 Subject: [Tutor] Dynamically changing a class Message-ID: <0B363C44ED4B4945A08E20094B57144A18EBAD@venus-san> Hi All, I'd like to change the behavior of a class' member function dynamically such that, once changed, all objects of the type would see the new behavior. For instance: >>> class MyClass (object) : def mfunc(self, data): print 'pre change behavior' >>> aMyClassObj = MyClass() >>> aMyClassObj.mfunc(data) pre change behavior >>> def MyClass.mfunc(self, data): #this does not work :-( print 'post change behavior' >>> aMyClassObj.mfunc(data) post change behavior Does anyone have any guidance on how to accomplish this? I'd also like to be able to add and delete attributes, similarly. Best regards, Jason Doege From washakie at gmail.com Tue Sep 4 01:37:57 2007 From: washakie at gmail.com (John) Date: Mon, 3 Sep 2007 16:37:57 -0700 Subject: [Tutor] binary data struct module Message-ID: <aaf235960709031637i2b1423edl1c4f9c928c8ffd14@mail.gmail.com> Hello, I have an unformatted mixed type binary file I'm trying to read into Python. So far, I've gotten as far as: f2=file(infile,'rb') Dfmt=['3i','13s','7i','2f','2i','2f','2i','i'] #format for binary reading first bits if f2: print infile + ' has been opened' #for ft in Dfmt: # print ft a=(struct.unpack(ft,f2.read(struct.calcsize(ft))) for ft in Dfmt) for ln in a: print ln Which gives me: /cygdrive/c/washakie/binfile has been opened (21, 20060612, 0) ('Version 4.3',) (21, 12, -86400, -86400, -900, 12, 24) (-179.0, -90.0) (360, 180) (1.0, 1.0) (24, 16) (3,) however, how can I now assign variables based on the 'generator object' a? What exactly is this? When I try to do something like: print a[0] or print a(0) I get the error: Traceback (most recent call last): File "readheader.py", line 20, in <module> print a[0] TypeError: 'generator' object is unsubscriptable My question is, how can I now work with 'a' so that i can use the values? Thanks! -- Configuration `````````````````````````` Plone 2.5.3-final, CMF-1.6.4, Zope (Zope 2.9.7-final, python 2.4.4, linux2), Five 1.4.1, Python 2.4.4 (#1, Jul 3 2007, 22:58:17) [GCC 4.1.1 20070105 (Red Hat 4.1.1-51)], PIL 1.1.6 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070903/be71470e/attachment.htm From kent37 at tds.net Tue Sep 4 03:38:38 2007 From: kent37 at tds.net (Kent Johnson) Date: Mon, 03 Sep 2007 21:38:38 -0400 Subject: [Tutor] indexing elements In-Reply-To: <b5300ea90709030640i88cb14k3349876e55eaa467@mail.gmail.com> References: <b5300ea90709030640i88cb14k3349876e55eaa467@mail.gmail.com> Message-ID: <46DCB71E.3020604@tds.net> chinni wrote: > Hi all, > > i had some doubt about this line can any body clarify this plz....... > endings = ['st', 'nd', 'rd'] + 17 * ['th'] + ['st', 'nd', 'rd'] + 7 * > ['th'] + ['st'] You can try it in the interactive interpreter: In [8]: endings = ['st', 'nd', 'rd'] + 17 * ['th'] + ['st', 'nd', 'rd'] + 7 * ['th'] + ['st'] In [10]: print endings ['st', 'nd', 'rd', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'st', 'nd', 'rd', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'st'] Kent From witham.ian at gmail.com Tue Sep 4 04:41:57 2007 From: witham.ian at gmail.com (Ian Witham) Date: Tue, 4 Sep 2007 14:41:57 +1200 Subject: [Tutor] checking if a number is evan or odd In-Reply-To: <F57661B9-6EE3-4C97-8C77-1862E74E8D10@gmail.com> References: <F57661B9-6EE3-4C97-8C77-1862E74E8D10@gmail.com> Message-ID: <a04dbf4b0709031941k2d5f1d6ckd52d009c4ed00333@mail.gmail.com> Hi Max, A better way to check if a number is odd or even would be to find the remainder after it is divided by two. for instance: 4 divided by 2 = 2 with 0 remainder 5 divided by 2 = 2 with 1 remainder 6 divided by 2 = 3 with 0 remainder 7 divided by 2 = 3 with 1 remainder As well as the floor division operator '/', Python has another operator for finding the remainder (or 'modulus') On 9/4/07, max baseman <dos.fool at gmail.com> wrote: > > hello just a quick check in, it's about the same program i was asking > about before ive let it sit for a few days now and i reached a number > to high to convert to a decimal by adding 0.0 > here's the program: > > count=1 > numstart=268549802 > number=0 > high=0 > a=0 > while 1==1: > numstart=numstart+1 > number=numstart > count=1 > while number !=1: > if number/2 == (number+0.0)/2: > number=number/2 > else: > number=(number*3)+1 > count=count+1 > if count > a: > a=count > print numstart,":",count > > > after a few days i got this error: > > Traceback (most recent call last): > File "homework6high.py", line 11, in <module> > if number/2 == (number+0.0)/2: > OverflowError: long int too large to convert to float > > just wondering if theirs a way to check if a larger number is even or > odd > > 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/20070904/d1c8c3bc/attachment.htm From witham.ian at gmail.com Tue Sep 4 04:53:36 2007 From: witham.ian at gmail.com (Ian Witham) Date: Tue, 4 Sep 2007 14:53:36 +1200 Subject: [Tutor] indexing elements In-Reply-To: <b5300ea90709030640i88cb14k3349876e55eaa467@mail.gmail.com> References: <b5300ea90709030640i88cb14k3349876e55eaa467@mail.gmail.com> Message-ID: <a04dbf4b0709031953k7e03be01h21762ee77b05ebed@mail.gmail.com> Hi, I'm not too sure what your asking here, your code assigns the following to endings: ['st', 'nd', 'rd', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'st', 'nd', 'rd', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'st'] This is what we would expect.. 17 * ['th'] causes 17 repetitions of 'th' in the list. certain operators, like the multiplication operator in your example, have additional behavior depending on what kind of data they are applied to. The repetition operator binds closer than the '+' as the following brackets show. endings = ['st', 'nd', 'rd'] + (17 * ['th']) + ['st', 'nd', 'rd'] + (7 * ['th']) + ['st'] Ian. On 9/4/07, chinni <srikanth007m at gmail.com> wrote: > > Hi all, > > i had some doubt about this line can any body clarify this plz....... > endings = ['st', 'nd', 'rd'] + 17 * ['th'] + ['st', 'nd', 'rd'] + 7 * > ['th'] + ['st'] > > -- > Best Regards, > M.Srikanth Kumar, > Jr.Software Developer, > Google India Pvt Ltd.., > HYDERABAD. > Phone no: +91-9866774007 > _______________________________________________ > 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/20070904/01920139/attachment.htm From dos.fool at gmail.com Tue Sep 4 05:58:43 2007 From: dos.fool at gmail.com (max baseman) Date: Mon, 3 Sep 2007 21:58:43 -0600 Subject: [Tutor] checking if a number is evan or odd In-Reply-To: <46DCC1BE.4030900@exemail.com.au> References: <F57661B9-6EE3-4C97-8C77-1862E74E8D10@gmail.com> <46DCC1BE.4030900@exemail.com.au> Message-ID: <A91DEF2E-919C-4A28-BAEC-6CEB38526F53@gmail.com> cool thanks the problem was from a math book imp 1 but i already did the work i was just interested in what number had the most steps i could fin wanted to get to 1000 imagine how dismayed i was when it crashed at 965 On Sep 3, 2007, at 8:23 PM, Andrew James wrote: > I'd just go with > > if number%2 == 0: > number = number/2 > > Why do you need to convert it to a float? > > Off topic: > Is this a PE problem? I remember doing the same thing. > > max baseman wrote: >> hello just a quick check in, it's about the same program i was >> asking about before ive let it sit for a few days now and i >> reached a number to high to convert to a decimal by adding 0.0 >> here's the program: >> >> count=1 >> numstart=268549802 >> number=0 >> high=0 >> a=0 >> while 1==1: >> numstart=numstart+1 >> number=numstart >> count=1 >> while number !=1: >> if number/2 == (number+0.0)/2: >> number=number/2 >> else: >> number=(number*3)+1 >> count=count+1 >> if count > a: >> a=count >> print numstart,":",count >> >> >> after a few days i got this error: >> >> Traceback (most recent call last): >> File "homework6high.py", line 11, in <module> >> if number/2 == (number+0.0)/2: >> OverflowError: long int too large to convert to float >> >> just wondering if theirs a way to check if a larger number is even >> or odd >> >> thanks >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> >> >> From trey at opmstech.org Tue Sep 4 07:16:57 2007 From: trey at opmstech.org (Trey Keown) Date: Tue, 4 Sep 2007 00:16:57 -0500 (CDT) Subject: [Tutor] Need some help with wxPython... Message-ID: <60287.68.191.136.241.1188883017.squirrel@webmail.opmstech.org> Hey all, I'm starting to drift away from Tkinter and enter the realm of wxPython. I've recently written a simple text editor in Tkinter, and I would like to know if anyone knows of a good example of a simple wxPython text editor (with the lines properly indented!!!), because all the examples I can find are improperly indented, or just don't work. Or perhaps a tutorial that covers all I need to know for making a text editor would work. Thanks for any help, Trey K. aka thetechgeek From alan.gauld at btinternet.com Tue Sep 4 10:23:01 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 4 Sep 2007 09:23:01 +0100 Subject: [Tutor] More class questions References: <2107481c0709031047t53332fb8q185fe92c396d6c8@mail.gmail.com> Message-ID: <fbj4lg$kf3$1@sea.gmane.org> "Ara Kooser" <ghashsnaga at gmail.com> wrote > What I have so far is a very simple text adventure with two rooms, > two > items, and some exits. So presumably you have a Room class, an Item class and maybe an Exit class? > Two question which relates directly to classes: Do you create all > your instances at the end of the program or just as needed? You create objects as needed. There is no mystery you have been using objects almost since you started using Python. Strings are objects and you create them as you need them. Same with Files. Your own classes are no different except that the instantiation mechanism is a little bit different. > call functions from other classes within a class Yes, If your Room class contains a list of Items you can send messages to thoise items from your Room methods.: class Item: def __innit__(self,n): self.n = n def say(self): print 'item', n class Room: def __init__(self,id) self.items = [Item(42),Item(26)] self.id = id def describe(self): print 'Room:',self.id,'has:' for item in items: item.say() r = R('hall') r.describe() Notice that Room.describe calls the Item.say method... Also note that the Room constructor creates two instances of Item. > Third question. Using function I understand how to move a player > around in different rooms using raw_input and if statements but how > do > you do that with classes. You have a Player class and it has a move method. You create instances of players and ask them to move. If they are in a Room you move within the room - perhaps you move to an exit which will in turn return a new room which you assign to the player. Something like: class Exit: def __init__(self, toRroom) self.room = toRoom def pass(self): return self.room class Player: def __init__(self,location=None): self.location = location def move(self, direction): exit = self.location.exitAt(direction) self.location = exit.pass() Now when you call move('N') the player goes tonthe North exit and passes throough to the room on the other side. > I created a player class and I want one of > the methods to be moving from room to room. > Or should movement be a separate class? I doubt it, movement is an action not an object (usually), its a behaviour of other objects. If more than players can move you may create a Movableobject superclass and inherit the movement methods from that. > I am looking at the code that Paul McGuire wrote for using > pyparsing and I don't quite understand how it all works. I have to > book Game Programming: The L line coming in two weeks. I am just > trying to get a head start. Sorry, cant help there. Alan G. From alan.gauld at btinternet.com Tue Sep 4 10:37:30 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 4 Sep 2007 09:37:30 +0100 Subject: [Tutor] Need some help with wxPython... References: <60287.68.191.136.241.1188883017.squirrel@webmail.opmstech.org> Message-ID: <fbj5gl$n8o$1@sea.gmane.org> "Trey Keown" <trey at opmstech.org> wrote > know if anyone knows of a good example of a simple wxPython text > editor wxPython comes with examples of text editors etc. It uses the amazing Scinitill widget upon which Pythonwin and Scite are both based. But look at the Py package which includes PyCrust, PyAlaMode and their widgets: ...Python24\Lib\site-packages\wx-2.8-msw-ansi\wx\py Also if you get serious about using wxPython get the book! It is invaluable. Alan G From alan.gauld at btinternet.com Tue Sep 4 10:43:12 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 4 Sep 2007 09:43:12 +0100 Subject: [Tutor] binary data struct module References: <aaf235960709031637i2b1423edl1c4f9c928c8ffd14@mail.gmail.com> Message-ID: <fbj5ra$obq$1@sea.gmane.org> "John" <washakie at gmail.com> wrote > a=(struct.unpack(ft,f2.read(struct.calcsize(ft))) for ft in Dfmt) > for ln in a: print ln > > Which gives me: > > /cygdrive/c/washakie/binfile has been opened > (21, 20060612, 0) > ('Version 4.3',) > (21, 12, -86400, -86400, -900, 12, 24) > > however, how can I now assign variables based on the 'generator > object' a? > What exactly is this? When I try to do something like: > > My question is, how can I now work with 'a' so that i can use the > values? You akready have in your for loop. You printed the values. There is nothing to stop you assigning them to variables. You will need to figure out what each line contains (which line you are on) and unpack the values from the tuples. Alternatively put them into a list: values = [ln for ln in a] Now you can use indexing: theDate = values[1][1] 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 Sep 4 10:50:45 2007 From: rdm at rcblue.com (Dick Moores) Date: Tue, 04 Sep 2007 01:50:45 -0700 Subject: [Tutor] What's up with Python 2.5.1's IDLE? In-Reply-To: <fbgdnd$sce$1@sea.gmane.org> References: <20070903013638.687341E4006@bag.python.org> <fbgdnd$sce$1@sea.gmane.org> Message-ID: <20070904085057.548141E400B@bag.python.org> At 12:39 AM 9/3/2007, Alan Gauld wrote: >"Dick Moores" <rdm at rcblue.com> wrote > > > Under Kent's tutelage, I've been experimenting with having no > > PYTHONDOC, > >I assume you mean PYTHONPATH? Yes. Careless of me. > > and instead putting a .pth file in > > E:\Python25\lib\site-packages\ I named pointers.pth. > >I obviously failed to convince you of the superior flexibility >of using PYTHONPATH for your personal libs :-) >If your PC is only usd by you and you only have one >user account then that probably isn't a problem, I'm the only user. >except you lose the flexibility of changing PYTHONPATH >dynamically during a session using SET. Could you show me how to use SET? And an example where it would be useful? > > The contents of > > pointers.pth is: > > E:\Python25\ > > E:\PythonWork\ > > E:\PythonWork\Functions\ > > E:\Python25\lib\site-packages\ > > E:\Python25\lib\site-packages\mine > >I would have expected Python to load the Python25 stuff itself. >You should only need the pointers file to contain the pointers >to the non standard directories (just as you would in PYTHONPATH) > > > this is what IDLE's shell shows for sys.path: > > > > E:\Python25\Lib\idlelib > > E:\Python24\lib\site-packages\setuptools-0.6c5-py2.4.egg > > C:\WINDOWS\system32\python24.zip > > E:\Python25\Lib\idlelib > > E:\Python24\DLLs > > E:\Python24\lib > > E:\Python24\lib\plat-win > > E:\Python24\lib\lib-tk > > E:\Python24 > > E:\Python24\lib\site-packages > > E:\Python24\lib\site-packages\wx-2.6-msw-ansi > > > > I do still have Python 2.4, but why does Python 2.5.1's IDLE's shell > > show all those things from 2.4, and only shows the path to itself in > > 2.5.1? > >It looks like IDLE has its own mechanism for populating sys.path >and it may be reading something in the Registry. This might be >a question to ask on the IDLE mailing list? I couldn't find an IDLE list other than the one for IDLE developers (could I, as a lowly user, ask a question there?). But yours and Kent's hints and a lot of help from the developer of Ulipad (Ulipad was showing similar problems with what its shell showed for sys.path--lots if 2.4 stuff) led me to reinstalling 2.5.1 and uninstalling 2.4, plus doing some registry editing. I think I've finally succeeded. Here's what I have for my .pth file (I cut out some of what I had before, thanks to your comment): E:\PythonWork\Functions\ E:\Python25\lib\site-packages\mine And IDLE's shell now shows me this for sys.path: IDLE 1.2.1 >>> import functions >>> from sys import path >>> for x in path: print x E:\Python25\Lib\idlelib E:\Python25\lib\site-packages\setuptools-0.6c5-py2.5.egg E:\Python25\lib\site-packages\dmath-0.9-py2.5.egg C:\WINDOWS\system32\python25.zip E:\Python25\DLLs E:\Python25\lib E:\Python25\lib\plat-win E:\Python25\lib\lib-tk E:\Python25 E:\Python25\lib\site-packages E:\Python25\lib\site-packages\PIL E:\PythonWork\Functions E:\Python25\lib\site-packages\mine E:\Python25\lib\site-packages\win32 E:\Python25\lib\site-packages\win32\lib E:\Python25\lib\site-packages\Pythonwin E:\Python25\lib\site-packages\wx-2.8-msw-unicode >>> And a similar good result with Ulipad. > > I like the editing ease of having a .pth file rather than a > > troublesome-to-edit PYTHONDOC > >I'm not sure I understand what you mean by the editing ease? >You can change PYTHONPATH with a simple SET command >(albeit temporarily) and 3 mouse clicks takes you to the dialog >editor. Yes, I guess you're right. Still, with no clicks and a shortcut key I can get directly to pointer.pth in Textpad . From alan.gauld at btinternet.com Tue Sep 4 10:52:42 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 4 Sep 2007 09:52:42 +0100 Subject: [Tutor] Dynamically changing a class References: <0B363C44ED4B4945A08E20094B57144A18EBAD@venus-san> Message-ID: <fbj6d4$q5s$1@sea.gmane.org> "Jason Doege" <jdoege at da-test.com> wrote > I'd like to change the behavior of a class' member function > dynamically > such that, once changed, all objects of the type would see the new > behavior. >>>> class MyClass (object) : > def mfunc(self, data): > print 'pre change behavior' > >>>> aMyClassObj = MyClass() >>>> aMyClassObj.mfunc(data) > pre change behavior >>>> def MyClass.mfunc(self, data): #this does not work :-( > print 'post change behavior' You need to do it thusly: def newfunc(self, data): print 'post change' MyClass.mfunc = newfunc That seems to work. I'm slightly surprised since I didn't know if it would, but it seems to! Alan G From alan.gauld at btinternet.com Tue Sep 4 10:54:27 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 4 Sep 2007 09:54:27 +0100 Subject: [Tutor] indexing elements References: <b5300ea90709030640i88cb14k3349876e55eaa467@mail.gmail.com> Message-ID: <fbj6gd$qff$1@sea.gmane.org> "chinni" <srikanth007m at gmail.com> wrote > > i had some doubt about this line can any body clarify this > plz....... > endings = ['st', 'nd', 'rd'] + 17 * ['th'] + ['st', 'nd', 'rd'] + 7 > * ['th'] > + ['st'] Using the interpreter: >>> endings = ['st', 'nd', 'rd'] + 17 * ['th'] + ['st', 'nd', 'rd'] + >>> 7 * ['th'] + ['st'] >>> endings ['st', 'nd', 'rd', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'st', 'nd', 'rd', 'th', 'th', 'th', 'th', 'th', 'th', 'th'] What are your doubts? Alan G. From alan.gauld at btinternet.com Tue Sep 4 11:00:53 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 4 Sep 2007 10:00:53 +0100 Subject: [Tutor] checking if a number is evan or odd References: <F57661B9-6EE3-4C97-8C77-1862E74E8D10@gmail.com> Message-ID: <fbj6sg$rsg$1@sea.gmane.org> Max, > just wondering if theirs a way to check if a larger number is even > or > odd I notice this is homework so I won't give a direct answer. But look at the mod operator '%' - It returns the remainder of an integer division. An even number is exactly divisible by 2. HTH, Alan G. "max baseman" <dos.fool at gmail.com> wrote > about before ive let it sit for a few days now and i reached a > number > to high to convert to a decimal by adding 0.0 Thats a terrible way to convert to a float. Just use the float function (actually a type): f = float(anInt) But to determine if its odd/even you don't need to use floats at all. > here's the program: > > count=1 > numstart=268549802 > number=0 > high=0 > a=0 > while 1==1: > numstart=numstart+1 > number=numstart > count=1 > while number !=1: > if number/2 == (number+0.0)/2: > number=number/2 > else: > number=(number*3)+1 > count=count+1 > if count > a: > a=count > print numstart,":",count Hmm, I have no idea what this is doing... > > thanks > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From dianahawks at optusnet.com.au Tue Sep 4 11:14:54 2007 From: dianahawks at optusnet.com.au (Diana Hawksworth) Date: Tue, 4 Sep 2007 19:14:54 +1000 Subject: [Tutor] searching a text file Message-ID: <003101c7eed4$166f7870$5595693a@SNNECCM> Dear list, I have been teaching Python with minimal knowledege myself!! I need to be able to search a text file that perhaps contains names and scores. How do I find a particular name, change the score and then save the changes back to the text file again?? Thanks for any help. Diana -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070904/43c9ffef/attachment.htm From alan.gauld at btinternet.com Tue Sep 4 11:35:24 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 4 Sep 2007 10:35:24 +0100 Subject: [Tutor] What's up with Python 2.5.1's IDLE? References: <20070903013638.687341E4006@bag.python.org><fbgdnd$sce$1@sea.gmane.org> <20070904085057.548141E400B@bag.python.org> Message-ID: <fbj8t6$2p1$1@sea.gmane.org> "Dick Moores" <rdm at rcblue.com> wrote >>except you lose the flexibility of changing PYTHONPATH >>dynamically during a session using SET. > > Could you show me how to use SET? And an example where it would be > useful? Imagine you are in a DOS command session C:> SET PYTHONPATH=C:\MYNEWFOLDER;%PYTHONPATH% prepends a folder to PYTHONPATH Now next time you run Python it will pick up the extra folder C:> SET PYTHONPATH displays the current value finally C:>SET PYTHONPATH=%PYTHONPATH:Python25=Python24% edits the existing path to substitute Python24 for each occurence of python25 SET /P allows multi line entry. SET is quite surprisingly powerful. Try HELP SET for more info The big downside is that these changes only apply to the current environment. (Which is the point of an *environment* variable after all :-) You still need to edit the variable if you want a permanant change Alan G From alan.gauld at btinternet.com Tue Sep 4 11:39:22 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 4 Sep 2007 10:39:22 +0100 Subject: [Tutor] searching a text file References: <003101c7eed4$166f7870$5595693a@SNNECCM> Message-ID: <fbj94l$3e6$1@sea.gmane.org> "Diana Hawksworth" <dianahawks at optusnet.com.au> wrote > How do I find a particular name, change the score and then save > the changes back to the text file again?? iterate over the file checking (and modifying) each line write the line back out: Pseudo code Out = open('foo.txt','w') for line in file('foo.txt'): if 'somestring' in line: line = 'I changed it\n' Out.write(line) Out.close() You will find much more on this in my file handling topic in my tutorial. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From rdm at rcblue.com Tue Sep 4 11:53:05 2007 From: rdm at rcblue.com (Dick Moores) Date: Tue, 04 Sep 2007 02:53:05 -0700 Subject: [Tutor] What's up with Python 2.5.1's IDLE? In-Reply-To: <fbj8t6$2p1$1@sea.gmane.org> References: <20070903013638.687341E4006@bag.python.org> <fbgdnd$sce$1@sea.gmane.org> <20070904085057.548141E400B@bag.python.org> <fbj8t6$2p1$1@sea.gmane.org> Message-ID: <20070904095315.1D3F01E400B@bag.python.org> At 02:35 AM 9/4/2007, Alan Gauld wrote: >"Dick Moores" <rdm at rcblue.com> wrote > > >>except you lose the flexibility of changing PYTHONPATH > >>dynamically during a session using SET. > > > > Could you show me how to use SET? And an example where it would be > > useful? > >Imagine you are in a DOS command session > >C:> SET PYTHONPATH=C:\MYNEWFOLDER;%PYTHONPATH% > >prepends a folder to PYTHONPATH >Now next time you run Python it will pick up the extra folder > >C:> SET PYTHONPATH > >displays the current value > >finally > >C:>SET PYTHONPATH=%PYTHONPATH:Python25=Python24% > >edits the existing path to substitute Python24 for each occurence of >python25 > >SET /P > >allows multi line entry. > >SET is quite surprisingly powerful. You've given me a new toy! Thanks. >Try HELP SET for more info That's a LOT of info! >The big downside is that these changes only apply to the current >environment. (Which is the point of an *environment* variable after >all :-) >You still need to edit the variable if you want a permanant change Just to make sure I understand, do you mean that the effects of using SET do not last between rebootings? Thanks, Alan. Dick From kent37 at tds.net Tue Sep 4 13:46:20 2007 From: kent37 at tds.net (Kent Johnson) Date: Tue, 04 Sep 2007 07:46:20 -0400 Subject: [Tutor] binary data struct module In-Reply-To: <aaf235960709031637i2b1423edl1c4f9c928c8ffd14@mail.gmail.com> References: <aaf235960709031637i2b1423edl1c4f9c928c8ffd14@mail.gmail.com> Message-ID: <46DD458C.404@tds.net> John wrote: > f2=file(infile,'rb') > > Dfmt=['3i','13s','7i','2f','2i','2f','2i','i'] #format for binary > reading first bits > > if f2: > print infile + ' has been opened' > #for ft in Dfmt: > # print ft > a=(struct.unpack(ft,f2.read(struct.calcsize(ft))) for ft in Dfmt) > for ln in a: print ln however, how can I now assign variables based on the 'generator object' > a? What exactly is this? a is a generator which is an iterable object. Access to its values is through the iterator protocol such as the for loop you use. > My question is, how can I now work with 'a' so that i can use the values? Use a list comprehension instead of a generator expression: a=[struct.unpack(ft,f2.read(struct.calcsize(ft))) for ft in Dfmt] This creates a list instead of a generator object. Kent From kent37 at tds.net Tue Sep 4 14:02:59 2007 From: kent37 at tds.net (Kent Johnson) Date: Tue, 04 Sep 2007 08:02:59 -0400 Subject: [Tutor] Metaclass programming In-Reply-To: <006f01c7ee66$2ec66fa0$bd32000a@issphoenix> References: <006f01c7ee66$2ec66fa0$bd32000a@issphoenix> Message-ID: <46DD4973.9090409@tds.net> Orest Kozyar wrote: > I have the following code: > > class meta(type): > > def __call__(cls, *args, **kwargs): > argnames = inspect.getargspec(cls.__init__)[0] > for i, value in enumerate(args): > kwargs[argnames[i]] = value This could be written kwargs.update(zip(argnames, args)) > return type.__call__(cls, kwargs) You are passing kwargs as a positional argument to __call__(); i.e. passing the dict as an ordinary parameter. To use kwargs as the keyword dict for the call, use the syntax type.__call__(cls, **kwargs) > class test(object): > > __metaclass__ = meta > > def __init__(self, x, y, **kwargs): > pass > > However, inspect.getargspec(cls.__init__) appears to return only the > arguments of the meta __init__ rather than the test __init__. Is there any > way I can get access to the test __init__ function from the metaclass? It works for me: import inspect class meta(type): def __call__(cls, *args, **kwargs): print inspect.getargspec(cls.__init__) return type.__call__(cls, *args, **kwargs) class test(object): __metaclass__ = meta def __init__(self, x, y, **kwargs): pass test(1, 2) prints (['self', 'x', 'y'], None, 'kwargs', None) I think the problem is elsewhere in your code. When I use return type.__call__(cls, kwargs) I get TypeError: __init__() takes exactly 3 arguments (2 given) because test.__init__() is still expecting the two required positional arguments. Why are you doing this? Kent From wormwood_3 at yahoo.com Tue Sep 4 15:06:49 2007 From: wormwood_3 at yahoo.com (wormwood_3) Date: Tue, 4 Sep 2007 06:06:49 -0700 (PDT) Subject: [Tutor] Integer ID Caching Message-ID: <833966.63555.qm@web32415.mail.mud.yahoo.com> I came across the topic of internal Python IDs recently, and learned that the internal numeric ids of small integers are cached to increase speed. I had read that as of 2.5, this applied to integers between -1 and 100. However, doing some quick tests, this seems not to be accurate: 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. >>> a = 10 >>> b = 10 >>> print id(a), id(b) 135716556 135716556 >>> c = 250 >>> d = 250 >>> print id(c), id(d) 135719604 135719604 >>> e = 300 >>> f = 300 >>> print id(e), id(f) 135718812 135718824 So the upper end of the interning range appears to be between 250 and 300, not 100. Does anyone know the exact number, when it changed, and if a decision has been made for future changes? I was unable to find anything specific to this in the documentation. Thanks as always, Sam From kent37 at tds.net Tue Sep 4 15:25:17 2007 From: kent37 at tds.net (Kent Johnson) Date: Tue, 04 Sep 2007 09:25:17 -0400 Subject: [Tutor] Integer ID Caching In-Reply-To: <833966.63555.qm@web32415.mail.mud.yahoo.com> References: <833966.63555.qm@web32415.mail.mud.yahoo.com> Message-ID: <46DD5CBD.6060003@tds.net> wormwood_3 wrote: > I came across the topic of internal Python IDs recently, and learned that the internal numeric ids of small integers are cached to increase speed. I had read that as of 2.5, this applied to integers between -1 and 100. However, doing some quick tests, this seems not to be accurate: > > 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. >>>> a = 10 >>>> b = 10 >>>> print id(a), id(b) > 135716556 135716556 >>>> c = 250 >>>> d = 250 >>>> print id(c), id(d) > 135719604 135719604 >>>> e = 300 >>>> f = 300 >>>> print id(e), id(f) > 135718812 135718824 > > So the upper end of the interning range appears to be between 250 and 300, not 100. > > Does anyone know the exact number, From Python-2.5.1/Objects/intobject.c: #ifndef NSMALLPOSINTS #define NSMALLPOSINTS 257 #endif #ifndef NSMALLNEGINTS #define NSMALLNEGINTS 5 #endif #if NSMALLNEGINTS + NSMALLPOSINTS > 0 /* References to small integers are saved in this array so that they can be shared. The integers that are saved are those in the range -NSMALLNEGINTS (inclusive) to NSMALLPOSINTS (not inclusive). */ > when it changed, Python 2.4.1 has #ifndef NSMALLPOSINTS #define NSMALLPOSINTS 100 Here is the actual changeset: http://svn.python.org/view?rev=42552&view=rev which references this RFE which includes the reason for the change: http://bugs.python.org/issue1436243 and if a decision has been made for future changes? I doubt it, it will change in response to some unanticipated future requirement, just as it did in this case. Kent From orest.kozyar at gmail.com Tue Sep 4 15:41:51 2007 From: orest.kozyar at gmail.com (Orest Kozyar) Date: Tue, 4 Sep 2007 09:41:51 -0400 Subject: [Tutor] Metaclass programming In-Reply-To: <46DD4973.9090409@tds.net> References: <006f01c7ee66$2ec66fa0$bd32000a@issphoenix> <46DD4973.9090409@tds.net> Message-ID: <003701c7eef9$5ac277f0$bd32000a@issphoenix> > This could be written > kwargs.update(zip(argnames, args)) Nice trick! Thanks for the pointer. > > return type.__call__(cls, kwargs) > > You are passing kwargs as a positional argument to __call__(); i.e. > passing the dict as an ordinary parameter. To use kwargs as > the keyword dict for the call, use the syntax > type.__call__(cls, **kwargs) Great, I did not realize that ** was part of the syntax so couldn't figure out what the issue was. It works smoothly now. > I think the problem is elsewhere in your code. You're right. I just figured out that for some reason, when I use the SQLAlchemy mapper() function to map my classes to the corresponding table object, it seems to affect inspect.getargspec(). For example: from sqlalchemy.orm import mapper from sqlalchemy import Table, MetaData import inspect class Foo: def __init__(self, x, y): pass print inspect.getargspec(Foo.__init__) >> (['self', 'x', 'y'], None, None, None) metadata = MetaData() foo_table = Table('foo', metadata) mapper(Foo, foo_table) print inspect.getargspec(Foo.__init__) >> (['instance'], 'args', 'kwargs', None) I'm not sure why this would be the case, but is a bit frustrating since I do need the names of the positional arguments sometimes. > Why are you doing this? Partially as an exercise to help me better understand Python inspection as well as metaclass programming. I also am using it in a EntitySingleton metaclass that I adapted from the SQLAlchemy wiki (http://www.sqlalchemy.org/trac/wiki/UsageRecipes/UniqueObject). Some of my classes have unique constraints, and I want the metaclass to check these unique constraints and return an object from the database if an object meeting these constraints already exists. For example: class User: __unique__ = ['firstname', 'lastname'] __metaclass__ = EntitySingleton def __init__(self, firstname, lastname, password): pass The metaclass knows what the "unique" constraints are based on the __unique__ list, but needs to use inspect.getargspec() to get the variable names and match them up with the *args list that EntitySingleton.__call__ recieves. At least, that's how I'm trying to do it, but I expect this might not be the best way to do it? Either case, when the class is mapped to a database table, I lose all this information, so will need to figure out a different way of approaching this. Orest From srikanth007m at gmail.com Tue Sep 4 15:57:04 2007 From: srikanth007m at gmail.com (chinni) Date: Tue, 4 Sep 2007 06:57:04 -0700 Subject: [Tutor] advanced sorting Message-ID: <b5300ea90709040657x26856eeetf5dc1c1020cdc5fd@mail.gmail.com> In Advance Sorting by giving the keywords to sort the list.But, iam getting the fallowing errors >>> x = ['srikanth', 'kumar', 'muppandam', 'will', 'be', 'a'] >>> x.sort(key=len) Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: sort() takes no keyword arguments >>> x.sort(reverse=True) Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: sort() takes no keyword arguments -Best Regards, M.srikanth. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070904/09c67891/attachment.htm From kent37 at tds.net Tue Sep 4 16:12:10 2007 From: kent37 at tds.net (Kent Johnson) Date: Tue, 04 Sep 2007 10:12:10 -0400 Subject: [Tutor] advanced sorting In-Reply-To: <b5300ea90709040657x26856eeetf5dc1c1020cdc5fd@mail.gmail.com> References: <b5300ea90709040657x26856eeetf5dc1c1020cdc5fd@mail.gmail.com> Message-ID: <46DD67BA.5010308@tds.net> chinni wrote: > > > In Advance Sorting by giving the keywords to sort the list.But, iam > getting the fallowing errors > > >>> x = ['srikanth', 'kumar', 'muppandam', 'will', 'be', 'a'] > >>> x.sort(key=len) > Traceback (most recent call last): > File "<stdin>", line 1, in ? > TypeError: sort() takes no keyword arguments > >>> x.sort(reverse=True) > Traceback (most recent call last): > File "<stdin>", line 1, in ? > TypeError: sort() takes no keyword arguments Are you using an old version of Python? Support for sort(key=fn) was added in Python 2.4. Kent From alan.gauld at btinternet.com Tue Sep 4 17:16:28 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 4 Sep 2007 16:16:28 +0100 Subject: [Tutor] What's up with Python 2.5.1's IDLE? References: <20070903013638.687341E4006@bag.python.org><fbgdnd$sce$1@sea.gmane.org><20070904085057.548141E400B@bag.python.org><fbj8t6$2p1$1@sea.gmane.org> <20070904095315.1D3F01E400B@bag.python.org> Message-ID: <fbjssn$7v0$1@sea.gmane.org> "Dick Moores" <rdm at rcblue.com> wrote > Just to make sure I understand, do you mean that the effects of > using > SET do not last between rebootings? Correct, they only work on the current environment. Very useful if you have two environments such as development and test. You can just swap environment values etc to toggle between them. But any permanaent changes must be added to the Env variables via the dialog box. Alan G From brunson at brunson.com Tue Sep 4 21:39:06 2007 From: brunson at brunson.com (Eric Brunson) Date: Tue, 04 Sep 2007 13:39:06 -0600 Subject: [Tutor] advanced sorting In-Reply-To: <b5300ea90709040657x26856eeetf5dc1c1020cdc5fd@mail.gmail.com> References: <b5300ea90709040657x26856eeetf5dc1c1020cdc5fd@mail.gmail.com> Message-ID: <46DDB45A.4060502@brunson.com> What version of python are you using? chinni wrote: > > > In Advance Sorting by giving the keywords to sort the list.But, iam > getting the fallowing errors > > >>> x = ['srikanth', 'kumar', 'muppandam', 'will', 'be', 'a'] > >>> x.sort(key=len) > Traceback (most recent call last): > File "<stdin>", line 1, in ? > TypeError: sort() takes no keyword arguments > >>> x.sort(reverse=True) > Traceback (most recent call last): > File "<stdin>", line 1, in ? > TypeError: sort() takes no keyword arguments > > > -Best Regards, > M.srikanth. > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From noufal at airtelbroadband.in Tue Sep 4 21:30:44 2007 From: noufal at airtelbroadband.in (Noufal Ibrahim) Date: Wed, 05 Sep 2007 01:00:44 +0530 Subject: [Tutor] advanced sorting In-Reply-To: <b5300ea90709040657x26856eeetf5dc1c1020cdc5fd@mail.gmail.com> References: <b5300ea90709040657x26856eeetf5dc1c1020cdc5fd@mail.gmail.com> Message-ID: <46DDB264.7010006@airtelbroadband.in> chinni wrote: > > > In Advance Sorting by giving the keywords to sort the list.But, iam > getting the fallowing errors > > >>> x = ['srikanth', 'kumar', 'muppandam', 'will', 'be', 'a'] > >>> x.sort(key=len) > Traceback (most recent call last): > File "<stdin>", line 1, in ? > TypeError: sort() takes no keyword arguments > >>> x.sort(reverse=True) > Traceback (most recent call last): > File "<stdin>", line 1, in ? > TypeError: sort() takes no keyword arguments > > Seems to work fine for me. What version of Python are you using? >>> x=['srikanth', 'kumar', 'muppandam', 'will', 'be', 'a'] >>> x.sort(reverse=True) >>> x ['will', 'srikanth', 'muppandam', 'kumar', 'be', 'a'] >>> -- ~noufal From dos.fool at gmail.com Wed Sep 5 00:19:30 2007 From: dos.fool at gmail.com (max baseman) Date: Tue, 4 Sep 2007 16:19:30 -0600 Subject: [Tutor] checking if a number is evan or odd In-Reply-To: <fbj6sg$rsg$1@sea.gmane.org> References: <F57661B9-6EE3-4C97-8C77-1862E74E8D10@gmail.com> <fbj6sg$rsg$1@sea.gmane.org> Message-ID: <9DE3FA2B-90AB-4F44-9B0C-590C63E5482F@gmail.com> cool thanks thats what i changed it to than just now i changed to do something else and instead of leaving the program running for 4 or 5 days as i had been i got my answer in less than a second ^_^" i realized that i was wasting way to much time checking every possible answer because the number is jumping around so much so instead i wrote a real quick program infact i wrote it in interactive that just starts at 1 and works the problem backwards for how ever long i tell it to :)) thanks for considering the homework, but this time you did'nt have to worry i did the homework last week i was just doing this for fun, it randomly asked something like "what about a number that takes 100 steps to get to 1" and i thought what about 1000 :)) now i have one running looking for a number that takes 1000000 steps unfortunately i dont think ill get any extra credit for doing any of this lol here is the program sorry copying it from interactive: >>> number=1 >>> count=1000 >>> count=0 >>> while count < 1000: ... if (number*2)%2 == 0: ... number=number*2 ... else: ... number=(number-1)/3.0 ... count=count+1 ... print number On Sep 4, 2007, at 3:00 AM, Alan Gauld wrote: > Max, > >> just wondering if theirs a way to check if a larger number is even >> or >> odd > > I notice this is homework so I won't give a direct answer. > But look at the mod operator '%' - It returns the remainder > of an integer division. An even number is exactly divisible > by 2. > > HTH, > > Alan G. > > "max baseman" <dos.fool at gmail.com> wrote > >> about before ive let it sit for a few days now and i reached a >> number >> to high to convert to a decimal by adding 0.0 > > Thats a terrible way to convert to a float. Just use the float > function > (actually a type): > > f = float(anInt) > > But to determine if its odd/even you don't need to use floats at all. > > >> here's the program: >> >> count=1 >> numstart=268549802 >> number=0 >> high=0 >> a=0 >> while 1==1: >> numstart=numstart+1 >> number=numstart >> count=1 >> while number !=1: >> if number/2 == (number+0.0)/2: >> number=number/2 >> else: >> number=(number*3)+1 >> count=count+1 >> if count > a: >> a=count >> print numstart,":",count > > > Hmm, I have no idea what this is doing... > >> >> 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 From ricaraoz at gmail.com Tue Sep 4 15:59:37 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Tue, 04 Sep 2007 10:59:37 -0300 Subject: [Tutor] Dynamically changing a class In-Reply-To: <fbj6d4$q5s$1@sea.gmane.org> References: <0B363C44ED4B4945A08E20094B57144A18EBAD@venus-san> <fbj6d4$q5s$1@sea.gmane.org> Message-ID: <46DD64C9.605@bigfoot.com> Alan Gauld wrote: > "Jason Doege" <jdoege at da-test.com> wrote > >> I'd like to change the behavior of a class' member function >> dynamically >> such that, once changed, all objects of the type would see the new >> behavior. > >>>>> class MyClass (object) : >> def mfunc(self, data): >> print 'pre change behavior' >> >>>>> aMyClassObj = MyClass() >>>>> aMyClassObj.mfunc(data) >> pre change behavior >>>>> def MyClass.mfunc(self, data): #this does not work :-( >> print 'post change behavior' > > You need to do it thusly: > > def newfunc(self, data): > print 'post change' > MyClass.mfunc = newfunc > > That seems to work. > I'm slightly surprised since I didn't know if it would, but it seems > to! > So lets take it a notch up. Wanted to change the mfunc method but ONLY for an instance, not a class: >>> MyObj = MyClass() >>> MyObj.mfunc(data) pre change behavior >>> MyObj.mfunc = newfunc >>> MyObj.mfunc(data) Traceback (most recent call last): File "<input>", line 1, in <module> TypeError: newfunc() takes exactly 2 arguments (1 given) and this did not work (mfunc will ask for 2 parameters). So I tried : >>> MyObj.mfunc = newfunc(MyObj) Traceback (most recent call last): File "<input>", line 1, in <module> NameError: name 'Myobj' is not defined this didn't work either. Any ideas? From ricaraoz at gmail.com Tue Sep 4 16:02:36 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Tue, 04 Sep 2007 11:02:36 -0300 Subject: [Tutor] What's up with Python 2.5.1's IDLE? In-Reply-To: <fbj8t6$2p1$1@sea.gmane.org> References: <20070903013638.687341E4006@bag.python.org><fbgdnd$sce$1@sea.gmane.org> <20070904085057.548141E400B@bag.python.org> <fbj8t6$2p1$1@sea.gmane.org> Message-ID: <46DD657C.6030409@bigfoot.com> Alan Gauld wrote: > "Dick Moores" <rdm at rcblue.com> wrote > >>> except you lose the flexibility of changing PYTHONPATH >>> dynamically during a session using SET. >> Could you show me how to use SET? And an example where it would be >> useful? > > Imagine you are in a DOS command session > > C:> SET PYTHONPATH=C:\MYNEWFOLDER;%PYTHONPATH% > > prepends a folder to PYTHONPATH > Now next time you run Python it will pick up the extra folder > > C:> SET PYTHONPATH > > displays the current value > > finally > > C:>SET PYTHONPATH=%PYTHONPATH:Python25=Python24% > > edits the existing path to substitute Python24 for each occurence of > python25 > > SET /P > > allows multi line entry. > > SET is quite surprisingly powerful. > Try HELP SET for more info > > The big downside is that these changes only apply to the current > environment. (Which is the point of an *environment* variable after > all :-) > You still need to edit the variable if you want a permanant change > > Alan G > > I seem to remember there was a way (in the wds console) to set it permanent. Wasn't it 'EXPORT' or something? From alan.gauld at btinternet.com Wed Sep 5 01:35:34 2007 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Tue, 4 Sep 2007 23:35:34 +0000 (GMT) Subject: [Tutor] What's up with Python 2.5.1's IDLE? Message-ID: <202134.80506.qm@web86113.mail.ird.yahoo.com> >> The big downside is that these changes only apply to the current >> environment. (Which is the point of an *environment* variable after >> all :-) > >I seem to remember there was a way (in the wds console) to set it > permanent. Wasn't it 'EXPORT' or something? I think you might be thinking about the Linux/Unix Bourne/Bash/Korn shell where export can be used to export an environment variable to the parent environment? I'm not aware of any such command in anty version of DOS. But then I'm hardly a DOS Guru either! Alan G. From kent37 at tds.net Wed Sep 5 02:12:39 2007 From: kent37 at tds.net (Kent Johnson) Date: Tue, 04 Sep 2007 20:12:39 -0400 Subject: [Tutor] checking if a number is evan or odd In-Reply-To: <9DE3FA2B-90AB-4F44-9B0C-590C63E5482F@gmail.com> References: <F57661B9-6EE3-4C97-8C77-1862E74E8D10@gmail.com> <fbj6sg$rsg$1@sea.gmane.org> <9DE3FA2B-90AB-4F44-9B0C-590C63E5482F@gmail.com> Message-ID: <46DDF477.5050708@tds.net> max baseman wrote: > here is the program sorry copying it from interactive: > > >>> number=1 > >>> count=1000 > >>> count=0 > >>> while count < 1000: > ... if (number*2)%2 == 0: This will always be true, you multiply by two then check if the result is divisible by two. Kent > ... number=number*2 > ... else: > ... number=(number-1)/3.0 > ... count=count+1 > ... print number From kent37 at tds.net Wed Sep 5 02:21:05 2007 From: kent37 at tds.net (Kent Johnson) Date: Tue, 04 Sep 2007 20:21:05 -0400 Subject: [Tutor] Dynamically changing a class In-Reply-To: <46DD64C9.605@bigfoot.com> References: <0B363C44ED4B4945A08E20094B57144A18EBAD@venus-san> <fbj6d4$q5s$1@sea.gmane.org> <46DD64C9.605@bigfoot.com> Message-ID: <46DDF671.9090607@tds.net> Ricardo Ar?oz wrote: > So lets take it a notch up. > Wanted to change the mfunc method but ONLY for an instance, not a class: > >>>> MyObj = MyClass() >>>> MyObj.mfunc(data) > pre change behavior >>>> MyObj.mfunc = newfunc >>>> MyObj.mfunc(data) > Traceback (most recent call last): > File "<input>", line 1, in <module> > TypeError: newfunc() takes exactly 2 arguments (1 given) I believe the correct way to do this is to use the __get__() method of the function object to create a bound method and assign that to the instance attribute: In [13]: class MyClass(object): pass ....: In [14]: myObj = MyClass() In [15]: def newfunc(self): ....: print 'post change behavior' ....: ....: All functions are descriptors. The __get__() method returns a bound method: In [16]: newfunc.__get__? Type: method-wrapper Base Class: <type 'method-wrapper'> String Form: <method-wrapper '__get__' of function object at 0x20a6cb0> Namespace: Interactive Docstring: descr.__get__(obj[, type]) -> value In [17]: newfunc.__get__(myObj, MyClass) Out[17]: <bound method MyClass.newfunc of <__main__.MyClass object at 0x20ba950>> Assigning the bound method to myObj.mfunc has the desired behaviour: In [18]: myObj.mfunc = newfunc.__get__(myObj, MyClass) In [19]: myObj.mfunc() post change behavior I have a writeup of descriptors here: http://personalpages.tds.net/~kent37/kk/00008.html You can also use types.MethodType to do the same thing: In [20]: from types import MethodType In [21]: MethodType(newfunc, myObj, MyClass) Out[21]: <bound method MyClass.newfunc of <__main__.MyClass object at 0x20ba950>> Kent From trey at opmstech.org Wed Sep 5 02:49:49 2007 From: trey at opmstech.org (Trey Keown) Date: Tue, 4 Sep 2007 19:49:49 -0500 (CDT) Subject: [Tutor] Problems with wx in Vista... Message-ID: <61395.68.191.136.241.1188953389.squirrel@webmail.opmstech.org> Although I should have expected at least a few problems, I have a question about a glitch in vista using a wx-implemented script. Here's the example script- =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= #!/usr/bin/python # togglebuttons.py import wx class ToggleButtons(wx.Dialog): def __init__(self, parent, id, title): wx.Dialog.__init__(self, parent, id, title, size=(300, 200)) self.colour = wx.Colour(0, 0, 0) wx.ToggleButton(self, 1, 'red', (20, 25)) wx.ToggleButton(self, 2, 'green', (20, 60)) wx.ToggleButton(self, 3, 'blue', (20, 100)) self.panel = wx.Panel(self, -1, (150, 20), (110, 110), style=wx.SUNKEN_BORDER) self.panel.SetBackgroundColour(self.colour) self.Bind(wx.EVT_TOGGLEBUTTON, self.ToggleRed, id=1) self.Bind(wx.EVT_TOGGLEBUTTON, self.ToggleGreen, id=2) self.Bind(wx.EVT_TOGGLEBUTTON, self.ToggleBlue, id=3) self.Centre() self.ShowModal() self.Destroy() def ToggleRed(self, event): green = self.colour.Green() blue = self.colour.Blue() if self.colour.Red(): self.colour.Set(0, green, blue) else: self.colour.Set(255, green, blue) self.panel.SetBackgroundColour(self.colour) def ToggleGreen(self, event): red = self.colour.Red() blue = self.colour.Blue() if self.colour.Green(): self.colour.Set(red, 0, blue) else: self.colour.Set(red, 255, blue) self.panel.SetBackgroundColour(self.colour) def ToggleBlue(self, event): red = self.colour.Red() green = self.colour.Green() if self.colour.Blue(): self.colour.Set(red, green, 0) else: self.colour.Set(red, green, 255) self.panel.SetBackgroundColour(self.colour) app = wx.App(0) ToggleButtons(None, -1, 'togglebuttons.py') app.MainLoop() =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= This makes a window pop up with 3 buttons that changes the color of a box. Now, my question is, is this a vista-specific problem, am I just doing something wrong, or is the example messed up. Note- the name I saved the program as is testwx.py Thanks for any help From srikanth007m at gmail.com Wed Sep 5 06:12:37 2007 From: srikanth007m at gmail.com (chinni) Date: Tue, 4 Sep 2007 21:12:37 -0700 Subject: [Tutor] advanced sorting Message-ID: <b5300ea90709042112mae3e758u5100880f1fb5ac9f@mail.gmail.com> Hi, i am using a macpro version(10.4.11) and python version is "2.3.5" Message: 10 Date: Wed, 05 Sep 2007 01:00:44 +0530 From: Noufal Ibrahim <noufal at airtelbroadband.in> Subject: Re: [Tutor] advanced sorting To: srikanthkumar007m at rediffmail.com Cc: tutor at python.org Message-ID: <46DDB264.7010006 at airtelbroadband.in> Content-Type: text/plain; charset=ISO-8859-1; format=flowed chinni wrote: > > > In Advance Sorting by giving the keywords to sort the list.But, iam > getting the fallowing errors > > >>> x = ['srikanth', 'kumar', 'muppandam', 'will', 'be', 'a'] > >>> x.sort(key=len) > Traceback (most recent call last): > File "<stdin>", line 1, in ? > TypeError: sort() takes no keyword arguments > >>> x.sort(reverse=True) > Traceback (most recent call last): > File "<stdin>", line 1, in ? > TypeError: sort() takes no keyword arguments > > Seems to work fine for me. What version of Python are you using? >>> x=['srikanth', 'kumar', 'muppandam', 'will', 'be', 'a'] >>> x.sort(reverse=True) >>> x ['will', 'srikanth', 'muppandam', 'kumar', 'be', 'a'] >>> -- ~noufal -- Best Regards, M.Srikanth Kumar, -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070904/02125a2a/attachment.htm From srikanth007m at gmail.com Wed Sep 5 06:43:34 2007 From: srikanth007m at gmail.com (chinni) Date: Tue, 4 Sep 2007 21:43:34 -0700 Subject: [Tutor] Plz help me from this Message-ID: <b5300ea90709042143t2ce4dc6bs12ef615f7129ec9@mail.gmail.com> Hi All, I Want to write a python script to change the permissions(chmod) and owner(chown) and group(chgrp) of a file on unix, script as to read from the /etc/passwd for displaying available users on the machine and from /etc/groups it as to display the available groups and user has to give the mode and owner name and group name from the list. Can i implement this in python or in shell scripting Can any one please suggest me from doing this...:) -- Best Regards, M.Srikanth Kumar, -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070904/3355c174/attachment-0001.htm From clsdaniel at gmail.com Wed Sep 5 08:26:06 2007 From: clsdaniel at gmail.com (Carlos Daniel Ruvalcaba Valenzuela) Date: Tue, 4 Sep 2007 23:26:06 -0700 Subject: [Tutor] Plz help me from this In-Reply-To: <b5300ea90709042143t2ce4dc6bs12ef615f7129ec9@mail.gmail.com> References: <b5300ea90709042143t2ce4dc6bs12ef615f7129ec9@mail.gmail.com> Message-ID: <4fae7dfa0709042326s45995722ia581ea8a64fc4602@mail.gmail.com> Yes is very possible to do this with python. Checkout the os.system and os.popen functions to run external commands (chmod, chown). Reading the list of users and groups should be easy, just open the file and read line by line and parse, you can do it as simple as splitting the line on colon character (:) and parsing the resulting list. It seems you will also need some form of UI, simple print and raw_input may do the trick. On 9/4/07, chinni <srikanth007m at gmail.com> wrote: > Hi All, > > > I Want to write a python script to change the permissions(chmod) and > owner(chown) and group(chgrp) of a file on unix, > script as to read from the /etc/passwd for displaying available users on the > machine and from /etc/groups it as to display the available groups and user > has to give the mode and owner name and group name from the list. > > Can i implement this in python or in shell scripting > Can any one please suggest me from doing this...:) > > -- > Best Regards, > M.Srikanth Kumar, > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From steve at alchemy.com Wed Sep 5 08:27:54 2007 From: steve at alchemy.com (Steve Willoughby) Date: Tue, 04 Sep 2007 23:27:54 -0700 Subject: [Tutor] Plz help me from this In-Reply-To: <b5300ea90709042143t2ce4dc6bs12ef615f7129ec9@mail.gmail.com> References: <b5300ea90709042143t2ce4dc6bs12ef615f7129ec9@mail.gmail.com> Message-ID: <46DE4C6A.1080301@alchemy.com> chinni wrote: > Hi All, > > > I Want to write a python script to change the permissions(chmod) and > owner(chown) and group(chgrp) of a file on unix, > script as to read from the /etc/passwd for displaying available users on > the machine and from /etc/groups it as to display the available groups > and user has to give the mode and owner name and group name from the list. > > Can i implement this in python or in shell scripting > Can any one please suggest me from doing this...:) This would be a lot easier to do with Python than shell, although it's certainly possible to do in either. For a start, check out the "nis" module in the standard library. nis.cat('passwd') and nis.cat('group') should be useful in getting the list of valid inputs. From there, you can create some sort of GUI or text-based selection code, or at least let the user type in the names they want and validate it against what's in NIS. If your system doesn't use NIS, you can see the 'pwd', 'spwd' and 'grp' modules instead. They'll get you what you need directly from the /etc files, but a little less conveniently. Then once you have your input from the user, it's just a simple matter of calling os.chmod() and os.chown() to make the changes. (Note that os.chown() changes the owner and/or group in one call.) HTH --steve From steve at alchemy.com Wed Sep 5 08:29:37 2007 From: steve at alchemy.com (Steve Willoughby) Date: Tue, 04 Sep 2007 23:29:37 -0700 Subject: [Tutor] Plz help me from this In-Reply-To: <4fae7dfa0709042326s45995722ia581ea8a64fc4602@mail.gmail.com> References: <b5300ea90709042143t2ce4dc6bs12ef615f7129ec9@mail.gmail.com> <4fae7dfa0709042326s45995722ia581ea8a64fc4602@mail.gmail.com> Message-ID: <46DE4CD1.8020907@alchemy.com> Carlos Daniel Ruvalcaba Valenzuela wrote: > Yes is very possible to do this with python. > > Checkout the os.system and os.popen functions to run external commands > (chmod, chown). While those are ways of calling external commands, it is best to use built-in language features like os.chmod() and os.chown() whenver possible. They will be much faster and less prone to errors and security issues. From alan.gauld at btinternet.com Wed Sep 5 09:21:56 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 5 Sep 2007 08:21:56 +0100 Subject: [Tutor] Problems with wx in Vista... References: <61395.68.191.136.241.1188953389.squirrel@webmail.opmstech.org> Message-ID: <fbllev$cia$1@sea.gmane.org> "Trey Keown" <trey at opmstech.org> wrote > Although I should have expected at least a few problems, I have a > question > about a glitch in vista using a wx-implemented script. So give us a clue, what is the glitch? > Here's the example script- > =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= snipped > =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= > This makes a window pop up with 3 buttons that changes the color of > a box. > Now, my question is, is this a vista-specific problem It sounds like its doing the right thing? What did you expect it to do? Alan G From alan.gauld at btinternet.com Wed Sep 5 09:28:55 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 5 Sep 2007 08:28:55 +0100 Subject: [Tutor] advanced sorting References: <b5300ea90709042112mae3e758u5100880f1fb5ac9f@mail.gmail.com> Message-ID: <fblls2$dk0$1@sea.gmane.org> "chinni" <srikanth007m at gmail.com> wrote > i am using a macpro version(10.4.11) and python version is "2.3.5" Thats the problem, you need Python v2.4 to use the key= feature of sort. There is a way to modify sort behaviour in older versions of Python The docs say: ------------------------------ The sort() method takes an optional argument specifying a comparison function of two arguments (list items) which should return a negative, zero or positive number depending on whether the first argument is considered smaller than, equal to, or larger than the second argument. Note that this slows the sorting process down considerably;..... As an example of using the cmpfunc argument to the sort() method, consider sorting a list of sequences by the second element of that list: def mycmp(a, b): return cmp(a[1], b[1]) mylist.sort(mycmp) ----------------------------------- Check your v2.3.5 Library Reference docs for more details. http://www.python.org/doc/2.3.5/lib/typesseq-mutable.html#l2h-220 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 Sep 5 09:40:58 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 5 Sep 2007 08:40:58 +0100 Subject: [Tutor] Dynamically changing a class References: <0B363C44ED4B4945A08E20094B57144A18EBAD@venus-san> <fbj6d4$q5s$1@sea.gmane.org><46DD64C9.605@bigfoot.com> <46DDF671.9090607@tds.net> Message-ID: <fblmim$fkl$1@sea.gmane.org> "Kent Johnson" <kent37 at tds.net> wrote >> Wanted to change the mfunc method but ONLY for an instance, not a >> class: > > I believe the correct way to do this is to use the __get__() method > of > the function object to create a bound method and assign that to the > instance attribute: Wow! Another new trick. I've never noticed __get__ before. Time for some playing I think. Thanks Kent, Alan G From ndoe_jtk_05 at yahoo.co.id Wed Sep 5 10:22:14 2007 From: ndoe_jtk_05 at yahoo.co.id (Ndoe jtki) Date: Wed, 5 Sep 2007 15:22:14 +0700 (ICT) Subject: [Tutor] Drag image Message-ID: <121.18941.qm@web45404.mail.sp1.yahoo.com> i want to drag image for my tasks in my college,but i can't understand following example in wx.python 2.6 Docs demo and tool. Have you another simple example for drag image? Thanks --------------------------------- Bergabunglah dengan orang-orang yang berwawasan, di bidang Anda di Yahoo! Answers -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070905/7ee079f0/attachment.htm From ricaraoz at gmail.com Wed Sep 5 11:58:12 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Wed, 05 Sep 2007 06:58:12 -0300 Subject: [Tutor] Dynamically changing a class In-Reply-To: <fblmim$fkl$1@sea.gmane.org> References: <0B363C44ED4B4945A08E20094B57144A18EBAD@venus-san> <fbj6d4$q5s$1@sea.gmane.org><46DD64C9.605@bigfoot.com> <46DDF671.9090607@tds.net> <fblmim$fkl$1@sea.gmane.org> Message-ID: <46DE7DB4.8030307@bigfoot.com> Alan Gauld wrote: > "Kent Johnson" <kent37 at tds.net> wrote > >>> Wanted to change the mfunc method but ONLY for an instance, not a >>> class: >> I believe the correct way to do this is to use the __get__() method >> of >> the function object to create a bound method and assign that to the >> instance attribute: > > Wow! Another new trick. I've never noticed __get__ before. That'd be two this week ;-) > Time for some playing I think. Yep. And once you've got it pls explain it too me, too lazy today to pick the manual. :) Any easier way? > > Thanks Kent, > > Alan G > From kent37 at tds.net Wed Sep 5 12:36:40 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 05 Sep 2007 06:36:40 -0400 Subject: [Tutor] advanced sorting In-Reply-To: <fblls2$dk0$1@sea.gmane.org> References: <b5300ea90709042112mae3e758u5100880f1fb5ac9f@mail.gmail.com> <fblls2$dk0$1@sea.gmane.org> Message-ID: <46DE86B8.2020602@tds.net> Alan Gauld wrote: > There is a way to modify sort behaviour in older versions of Python > The docs say: > ------------------------------ > The sort() method takes an optional argument specifying a > comparison function of two arguments Another way to do this is with the 'Decorate-Sort-Undecorate' idiom. I talk about it here: http://personalpages.tds.net/~kent37/kk/00007.html Kent From =?UTF-8?B?2LLZitin2K8g2KjZhiDYudio2K/Yp9mE2LnYstmK2LIg2KfZhNio2KfYqg==?= Wed Sep 5 12:55:10 2007 From: =?UTF-8?B?2LLZitin2K8g2KjZhiDYudio2K/Yp9mE2LnYstmK2LIg2KfZhNio2KfYqg==?= (=?UTF-8?B?2LLZitin2K8g2KjZhiDYudio2K/Yp9mE2LnYstmK2LIg2KfZhNio2KfYqg==?=) Date: Wed, 05 Sep 2007 13:55:10 +0300 Subject: [Tutor] searching a text file In-Reply-To: <fbj94l$3e6$1@sea.gmane.org> References: <003101c7eed4$166f7870$5595693a@SNNECCM> <fbj94l$3e6$1@sea.gmane.org> Message-ID: <46DE8B0E.7050408@saudi.net.sa> Alan Gauld wrote: > "Diana Hawksworth" <dianahawks at optusnet.com.au> wrote > >> How do I find a particular name, change the score and then save >> the changes back to the text file again?? > > iterate over the file checking (and modifying) each line > write the line back out: > > Pseudo code > > Out = open('foo.txt','w') BEWARE: this will truncate the file immediately, erasing all the data in it!!! Use a temporary file and after you finish processing the data in the original file, move (or rename) the temporary file to the original name. > for line in file('foo.txt'): > if 'somestring' in line: > line = 'I changed it\n' > Out.write(line) > > Out.close() > > You will find much more on this in my file handling topic in my > tutorial. > > Ziyad. From kent37 at tds.net Wed Sep 5 13:22:23 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 05 Sep 2007 07:22:23 -0400 Subject: [Tutor] Dynamically changing a class In-Reply-To: <46DE7DB4.8030307@bigfoot.com> References: <0B363C44ED4B4945A08E20094B57144A18EBAD@venus-san> <fbj6d4$q5s$1@sea.gmane.org><46DD64C9.605@bigfoot.com> <46DDF671.9090607@tds.net> <fblmim$fkl$1@sea.gmane.org> <46DE7DB4.8030307@bigfoot.com> Message-ID: <46DE916F.509@tds.net> Ricardo Ar?oz wrote: > Yep. And once you've got it pls explain it too me, too lazy today to > pick the manual. :) I included a link to my explanation previously. I'm too lazy to try to do better. > Any easier way? Easier how? I don't know what could be easier to implement than a single function call. What did you have in mind? These are all equivalent, take your pick: myObj.mfunc = newfunc.__get__(myObj, MyClass) myObj.mfunc = types.MethodType(newfunc, myObj, MyClass) myObj.mfunc = new.instancemethod(newfunc, myObj, MyClass) For my own interest I looked into how these are actually implemented with an eye to which one might be preferred. new.instancemethod has the advantage of being documented in the library reference but the source says it is deprecated and it is a synonym for types.MethodType (in new.py). types.MethodType is defined in types.py as MethodType = type(_x._m) where _x is a class and _m is a method; i.e. types.MethodType is literally 'the type of a bound method'. It is fairly explicit at the point of use - 'give me a method'. newfunc.__get__ is defined by func_descr_get() in Objects/funcobject.c. It delegates to PyMethod_New() so it is essentially calling MethodType. It's a bit obscure at the point of use. So I guess I prefer MethodType(newfunc, myObj, MyClass) Kent From kent37 at tds.net Wed Sep 5 13:33:37 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 05 Sep 2007 07:33:37 -0400 Subject: [Tutor] searching a text file In-Reply-To: <46DE8B0E.7050408@saudi.net.sa> References: <003101c7eed4$166f7870$5595693a@SNNECCM> <fbj94l$3e6$1@sea.gmane.org> <46DE8B0E.7050408@saudi.net.sa> Message-ID: <46DE9411.4080301@tds.net> ???? ?? ????????? ??????? wrote: > Alan Gauld wrote: >> "Diana Hawksworth" <dianahawks at optusnet.com.au> wrote >> >>> How do I find a particular name, change the score and then save >>> the changes back to the text file again?? >> iterate over the file checking (and modifying) each line >> write the line back out: >> >> Pseudo code >> >> Out = open('foo.txt','w') > BEWARE: this will truncate the file immediately, erasing all the data in > it!!! > > Use a temporary file and after you finish processing the data in the > original file, move (or rename) the temporary file to the original name. The fileinput module can help with this. It lets you edit a file line-by-line, in place, with a backup: import fileinput for line in fileinput.input('test.txt', inplace=1, backup='.bak'): if 'somestring' in line: line = 'I changed it\n' print line, Kent From jdoege at da-test.com Wed Sep 5 16:59:47 2007 From: jdoege at da-test.com (Jason Doege) Date: Wed, 5 Sep 2007 10:59:47 -0400 Subject: [Tutor] Dynamically changing a class Message-ID: <0B363C44ED4B4945A08E20094B57144A18ECC4@venus-san> Thanks for the good and useful information on this. Now for the why... I am building an API and for various reasons I have chosen Python to implement it. I'd like to separate the implementation from the interface as, for instance, C++ does with separate .hpp and .cpp files. Apart from defining a class with a bunch of empty methods and then redefining them, I have not seen a good way to do this in Python. Can you recommend the Pythonic way to do this? Best regards, Jason Doege From kent37 at tds.net Wed Sep 5 17:33:26 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 05 Sep 2007 11:33:26 -0400 Subject: [Tutor] Dynamically changing a class In-Reply-To: <0B363C44ED4B4945A08E20094B57144A18ECC4@venus-san> References: <0B363C44ED4B4945A08E20094B57144A18ECC4@venus-san> Message-ID: <46DECC46.7060209@tds.net> Jason Doege wrote: > Thanks for the good and useful information on this. Now for the why... > > I am building an API and for various reasons I have chosen Python to > implement it. I'd like to separate the implementation from the interface > as, for instance, C++ does with separate .hpp and .cpp files. Apart from > defining a class with a bunch of empty methods and then redefining them, > I have not seen a good way to do this in Python. Can you recommend the > Pythonic way to do this? For smaller projects don't bother. For large projects Zope Interface seems to be popular: http://wiki.zope.org/Interfaces/FrontPage PyProtocols is similar but no longer actively developed: http://peak.telecommunity.com/PyProtocols.html A different approach, perhaps more Pythonic, is for consumers to check what kind of thing they are given. One way to do this is here: http://oakwinter.com/code/typecheck/ You might also be interested in http://www.python.org/dev/peps/pep-0246/ http://www.python.org/dev/peps/pep-3107/ Kent From washakie at gmail.com Wed Sep 5 22:56:33 2007 From: washakie at gmail.com (John) Date: Wed, 5 Sep 2007 13:56:33 -0700 Subject: [Tutor] more on reading binary... a better way? Message-ID: <aaf235960709051356i1b09bc89ifdaf234c6a4e0e90@mail.gmail.com> Hello everyone, Here's my solution for reading binary data (unformatted mixed types) and packing it into a dictionary. It works, but somehow doesn't seem so 'pythonic'. Just seeking comments on how I might make it more efficient. Thanks! def readheader(filename): import struct I={0:'rl',1:'ibdate',2:'ibtime',3:'version',4:'void1',5:'void2',6:'loutstep',7:'loutaver',8:'loutsample',9:'void3',10:'void4',11:'outlon0',12:'oulat0',13:'numxgrid',14:'numygrid',15:'dxout',16:'dyout',17:'void5',18:'void6',19:'numzgrid'} B={} f2=file(filename,'rb') #Define Header format Dfmt=['i','i','i','13s','i','i','i','i','i','i','i','f','f','i','i','f','f','i','i','i'] #format for binary reading first bits if f2: print filename + ' has been opened' #create a dictionary from header file a=[struct.unpack(ft,f2.read(struct.calcsize(ft))) for ft in Dfmt] for i in range(len(a)): B[I[i]]=a[i][0] -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070905/4bdfaca9/attachment.htm From the.tobmeister at gmail.com Wed Sep 5 23:28:10 2007 From: the.tobmeister at gmail.com (Toby Holland) Date: Wed, 5 Sep 2007 17:28:10 -0400 Subject: [Tutor] The IF statement Message-ID: <f42618130709051428s69069c63h563417742996405f@mail.gmail.com> Hi gang, Just doing what I can to understand as I study I have been reading about testing modules this is the statement that I have been given if __name__ == "__main__": I understand that all modules have a built in attribute __name__, but what does the __main__ have to do with this attribute. Is it saying that __name__ is the same as __main__? I know that if the module is imported then __name__is the moules file name, but is this just for the script that your writing while using that module or is it just to show that the module was imported? correct me if I'm wrong please, the modules file name is __main__ when its being used as a stand alone program? If this is the case the difference is whether or not the module is a program by itself or intigrated with a script that is what determines its name (i.e. __name__ and __main__) I hope this question makes senses thanks for the help!! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070905/f3a8e0b2/attachment-0001.htm From tinoloc at gmail.com Wed Sep 5 23:28:09 2007 From: tinoloc at gmail.com (Tino Dai) Date: Wed, 5 Sep 2007 17:28:09 -0400 Subject: [Tutor] Condensing Some Massive Code In-Reply-To: <c070fc970709021024t67aed76ai2b3a1fd75b728886@mail.gmail.com> References: <c070fc970709021024t67aed76ai2b3a1fd75b728886@mail.gmail.com> Message-ID: <e033edfb0709051428m3b76a9ffvdf74c2c01e82a7f5@mail.gmail.com> On 9/2/07, David Millar <davmillar at gmail.com> wrote: > > Hello. I'm working on a text adventure game right now, and I seem to be > kind of stuck. There's a huge chunk of code called moreaction() that pulls > scripted events for certain locations. It's ever-changing so I'm not looking > for specifics, but can anyone suggest good ways to clean up or condense the > code without sacrificing clarity? The latest version of the source is found > at http://thegriddle.net/python/v006.txt Any help is much appreciated :) - > Dave M. I just took a look at the code, it seems that you are in if-then hell. I think that I have a solution for you that improve the readability of the code. It's using multiple dictionaries to get you out of if-then hell. Let's say we have: sceneDict = {} # We populate these with the difference scene numbers. In the sceneDict, we have eventDict if there are any events. Lets say we take your first piece of code: if thescene == 3: if event[1] == 0: global choins choins = choins - 10 add_item("BEAN",1) map[2].add_opt("NORTH",4) map[2].set_desc("You are just outside a nasty looking movie theatre. Shady Latin gang members have a shell game set up nearby, and from previous experiences you know to avoid gambling like the plague.") event[1] = 1 elif event[1] == 1: map[3].set_desc("You walk up to the gangsters and the boss guy says 'Get lost, fool!'") event[1] = 2 elif event[1] == 3: map[3].set_desc("You walk up to the gangsters but they tell you to get lost.") if (inventory.has_key("ARMONDO'S NOTE") == 0): print "\nYou walk up to the gangsters and flash a picture of Candy in front of them. 'Woah, is that Candy?' the boss guy asks. I ain't seen her since high school!' He scribbles something on the back of a receipt for frozen wonton burrito meals, and you do the math and realize that he wants you to give candy the number." add_item("ARMONDO'S NOTE",1) elif event[1] == 4: print "\nYou see Candy with Armondo, and they wave you over. 'Hey, thanks for hooking us up again! And sorry Armondo took your choins in his little game, teehee!' She hands you 5 choins. 'Uhh, he took 10 choins from me, not fi-' 'SHUT UP RUBE!' Candy laughs at Armondo and kisses him on the cheek. 'We're going to the back seat of Armondo's car for coffee. See ya! They walk away and get into Armondo's car, which starts bucking around a bit. Then it suddenly starts up and leaves, opening the street to the south." choins += 5 map[2].rem_opt("TALK") map[2].add_opt("SOUTH",15) map[1].add_opt("ORDER",16) elif thescene == 6: map[5].rem_opt("EAST") add_item('MAIN MAP',1) add_recipe('ICED COFFEE','COFFEE','ICE',1) add_recipe('ESPRESSO','COFFEE','BEAN',2) add_recipe('CAPPUCCINO','ESPRESSO','MILK',2) add_recipe('CREAMY COFFEE','COFFEE','MILK',1) elif thescene == 8: if event[1] >= 3 and (book.has_key("SYRUP") == 0): print "\n'PROTIP!' 'Huh?' you respond. 'PROTIP! CANDY and WATER make various sugary SYRUPS to add to your drinks!' Wow. Interesting." add_recipe('SYRUP','CANDY','WATER',1) disp_menu(0) sceneDict = { 3:"" , 6:"",8:""} sceneDict[3] = { 0:"",1:"",2:"",4:""} # The key 3 points to a dictionary of event dictionary. I have to research how to get the values of these dictionary to be executeable code :). Tell me what you think (by the way, you will need one or two if statements and perhaps an try-except block to make this code work). More tonight or if Kent, Alan or Bob want to step in. :) -Tino -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070905/577cfd95/attachment-0001.htm From kent37 at tds.net Thu Sep 6 00:03:36 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 05 Sep 2007 18:03:36 -0400 Subject: [Tutor] The IF statement In-Reply-To: <f42618130709051428s69069c63h563417742996405f@mail.gmail.com> References: <f42618130709051428s69069c63h563417742996405f@mail.gmail.com> Message-ID: <46DF27B8.5040609@tds.net> Toby Holland wrote: > Hi gang, > > Just doing what I can to understand as I study > > > I have been reading about testing modules this is the statement that I > have been given > > if __name__ == "__main__": > > > I understand that all modules have a built in attribute __name__, but > what does the __main__ have to do with this attribute. Is it saying > that __name__ is the same as __main__? Yes. Note that __name__ is a variable and "__main__" is a string. So this says that the value of the variable __name__ is the string "__main__". > I know that if the module is imported then __name__is the moules file > name, It is the module name which is not quite the same as the file name. __file__ has the file name. > but is this just for the script that your writing while using that > module or is it just to show that the module was imported? It is a way to tell if the module was imported or run directly as a script. > correct me if I'm wrong please, the modules file name is __main__ when > its being used as a stand alone program? The modules name, not the file name; otherwise yes. > If this is the case the difference is whether or not the module is a > program by itself or intigrated with a script that is what determines > its name (i.e. __name__ and __main__) Yes. It is handy to be able to write a module so it can be used by being imported into another module, or by being run on its own. When run on its own it might provide a simple command line interface or run unit tests or whatever the developer finds useful. When imported as a library for another module then this behaviour is not wanted so it is hidden by the if __name__ == '__main__': condition. Kent From ricaraoz at gmail.com Thu Sep 6 00:41:09 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Wed, 05 Sep 2007 19:41:09 -0300 Subject: [Tutor] Dynamically changing a class In-Reply-To: <46DE916F.509@tds.net> References: <0B363C44ED4B4945A08E20094B57144A18EBAD@venus-san> <fbj6d4$q5s$1@sea.gmane.org><46DD64C9.605@bigfoot.com> <46DDF671.9090607@tds.net> <fblmim$fkl$1@sea.gmane.org> <46DE7DB4.8030307@bigfoot.com> <46DE916F.509@tds.net> Message-ID: <46DF3085.1060501@bigfoot.com> Kent Johnson wrote: > Ricardo Ar?oz wrote: > >> Yep. And once you've got it pls explain it too me, too lazy today to >> pick the manual. :) > > I included a link to my explanation previously. I'm too lazy to try to > do better. > LOL, too tired yesterday to even think straight. Thanks for your answer. From alan.gauld at btinternet.com Thu Sep 6 01:29:53 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 6 Sep 2007 00:29:53 +0100 Subject: [Tutor] more on reading binary... a better way? References: <aaf235960709051356i1b09bc89ifdaf234c6a4e0e90@mail.gmail.com> Message-ID: <fbne5t$glg$1@sea.gmane.org> "John" <washakie at gmail.com> wrote > packing it into a dictionary. It works, but somehow doesn't seem so > 'pythonic'. Just seeking comments on how I might make it more > efficient. I don't think its too bad but I'd probably try reading all the data in one go. > #Define Header format > Dfmt=['i','i','i','13s','i','i','i','i','i','i','i','f','f','i','i','f','f','i','i','i'] Dfmt = "iii13siiiiiiiiiiiiiiii" ln = 19 * struct.calcsize('i') + struct.calcsize('13s') a = struct.unpack(Dfmt,f2.read(ln)) Which should return a tuple of all your values in one go. Now you can go straight to the last for loop below... All untested of course! :-) > #format for binary reading first bits > if f2: > print filename + ' has been opened' > #create a dictionary from header file > a=[struct.unpack(ft,f2.read(struct.calcsize(ft))) for ft in Dfmt] > for i in range(len(a)): > B[I[i]]=a[i][0] -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Thu Sep 6 02:26:53 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 05 Sep 2007 20:26:53 -0400 Subject: [Tutor] Dynamically changing a class In-Reply-To: <46DECC46.7060209@tds.net> References: <0B363C44ED4B4945A08E20094B57144A18ECC4@venus-san> <46DECC46.7060209@tds.net> Message-ID: <46DF494D.7020507@tds.net> Kent Johnson wrote: > Jason Doege wrote: >> I am building an API and for various reasons I have chosen Python to >> implement it. I'd like to separate the implementation from the interface >> as, for instance, C++ does with separate .hpp and .cpp files. Apart from >> defining a class with a bunch of empty methods and then redefining them, >> I have not seen a good way to do this in Python. Can you recommend the >> Pythonic way to do this? > > For smaller projects don't bother. A bit more on this...it is common for Python APIs to be defined by convention, documentation and example rather than by code artifacts such as formal interfaces. In Python itself, examples are file-like objects, sequences, mappings, iterators, decorators, descriptors and context managers, to name the ones that come to immediately mind. All of these are defined more-or-less clearly by documentation and usage. A more extensive example is Python DB-API which defines a way to interface to a database. This is defined entirely by the spec: http://www.python.org/dev/peps/pep-0249/ Kent From kent37 at tds.net Thu Sep 6 02:44:07 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 05 Sep 2007 20:44:07 -0400 Subject: [Tutor] Metaclass programming In-Reply-To: <003701c7eef9$5ac277f0$bd32000a@issphoenix> References: <006f01c7ee66$2ec66fa0$bd32000a@issphoenix> <46DD4973.9090409@tds.net> <003701c7eef9$5ac277f0$bd32000a@issphoenix> Message-ID: <46DF4D57.3040207@tds.net> Orest Kozyar wrote: > You're right. I just figured out that for some reason, when I use the > SQLAlchemy mapper() function to map my classes to the corresponding table > object, it seems to affect inspect.getargspec(). > > For example: > > from sqlalchemy.orm import mapper > from sqlalchemy import Table, MetaData > import inspect > > class Foo: > def __init__(self, x, y): > pass > > print inspect.getargspec(Foo.__init__) > >>> (['self', 'x', 'y'], None, None, None) > > metadata = MetaData() > foo_table = Table('foo', metadata) > mapper(Foo, foo_table) > > print inspect.getargspec(Foo.__init__) > >>> (['instance'], 'args', 'kwargs', None) > > I'm not sure why this would be the case, but is a bit frustrating since I do > need the names of the positional arguments sometimes. I can't be sure without looking at the code but it looks like SA is decorating the class methods; this usually loses the signature of the method. The problem is described here: http://www.phyast.pitt.edu/~micheles/python/documentation.html#statement-of-the-problem >> Why are you doing this? > > Partially as an exercise to help me better understand Python inspection as > well as metaclass programming. Note that there is no metaclass in the above code, unless mapper() is introducing one behind the scene... I also am using it in a EntitySingleton > metaclass that I adapted from the SQLAlchemy wiki > (http://www.sqlalchemy.org/trac/wiki/UsageRecipes/UniqueObject). Some of my > classes have unique constraints, and I want the metaclass to check these > unique constraints and return an object from the database if an object > meeting these constraints already exists. > > For example: > > class User: > __unique__ = ['firstname', 'lastname'] > __metaclass__ = EntitySingleton > > def __init__(self, firstname, lastname, password): > pass > > The metaclass knows what the "unique" constraints are based on the > __unique__ list, but needs to use inspect.getargspec() to get the variable > names and match them up with the *args list that EntitySingleton.__call__ > recieves. At least, that's how I'm trying to do it, but I expect this might > not be the best way to do it? Either case, when the class is mapped to a > database table, I lose all this information, so will need to figure out a > different way of approaching this. You should probably look for a different way to do it. Depending on your tolerance for hacks, it may be possible to work around the decorator. The original function is probably contained within the closure of the decorator and you can dig it out. For example, make a simple decorator and decorate a function: In [5]: def deco(f): ...: def _deco(*args, **kwds): ...: print 'about to call', f.__name__ ...: f(*args, **kwds) ...: return _deco ...: In [6]: @deco ...: def f(): print 'foo here' ...: Hey, it works! In [7]: f() about to call f foo here but the decorated function has the signature of the decoration: In [8]: import inspect In [9]: inspect.getargspec(f) Out[9]: ([], 'args', 'kwds', None) If we dig hard enough we can find the original and get its signature: In [11]: f.func_closure Out[11]: (<cell at 0x2087d70: function object at 0x20ad2f0>,) In [14]: f.func_closure[0].cell_contents Out[14]: <function f at 0x20ad2f0> In [15]: inspect.getargspec(f.func_closure[0].cell_contents) Out[15]: ([], None, None, None) In [16]: f.func_closure[0].cell_contents.__name__ Out[16]: 'f' I don't think I would want to rely on this in production code though... Kent From kent37 at tds.net Thu Sep 6 02:57:02 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 05 Sep 2007 20:57:02 -0400 Subject: [Tutor] Condensing Some Massive Code In-Reply-To: <c070fc970709021024t67aed76ai2b3a1fd75b728886@mail.gmail.com> References: <c070fc970709021024t67aed76ai2b3a1fd75b728886@mail.gmail.com> Message-ID: <46DF505E.6010107@tds.net> David Millar wrote: > Hello. I'm working on a text adventure game right now, and I seem to be > kind of stuck. There's a huge chunk of code called moreaction() that > pulls scripted events for certain locations. It's ever-changing so I'm > not looking for specifics, but can anyone suggest good ways to clean up > or condense the code without sacrificing clarity? The latest version of > the source is found at http://thegriddle.net/python/v006.txt Any help is > much appreciated :) - Dave M. One way to help with this is to use functions and a dispatch table. For example instead of elif lookup == "COVER": print "\nYou close the book and stare dumbly at the cover, sideways:" return elif lookup == "TOC": print "\nYou glance over the table of contents. You have recipes for the following:" b = book.keys() b.sort() for r in b: print "*",r, print "*" return elif lookup == "SYRUP": print "\n* SYRUP *" print "* SYRUP is an interesting drink." return you could write def cover(): print "\nYou close the book and stare dumbly at the cover, sideways:" def toc(): print "\nYou close the book and stare dumbly at the cover, sideways:" return elif lookup == "TOC": print "\nYou glance over the table of contents. You have recipes for the following:" b = book.keys() b.sort() for r in b: print "*",r, print "*" def syrup(): print "\n* SYRUP *" print "* SYRUP is an interesting drink." return dispatch = dict(COVER=cover, TOC=toc, SYRUP=syrup) fn = dispatch[lookup] fn() That is the basic idea. There are a lot of possible complications and variations. If some of the functions need arguments, you need to make a common protocol for passing arguments and returning values. You might want to make the functions methods of a class so they can share state. Clever use of introspection can make the dispatch table unnecessary. You might want to look at the cmd module in the Python standard library as an example of this approach. Kent From saradhi.dinavahi at gmail.com Thu Sep 6 04:07:41 2007 From: saradhi.dinavahi at gmail.com (saradhi dinavahi) Date: Wed, 5 Sep 2007 21:07:41 -0500 Subject: [Tutor] Importing Excel sheet data Message-ID: <1f51e43b0709051907q753c556pa319d12992cbc3ce@mail.gmail.com> hello all, I am new to the Python Programming. I want to Import Excel sheet data using Python. Can any one please provide me the code and explain the basic steps and method of executing the code. Thank You All -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070905/486c77b9/attachment.htm From witham.ian at gmail.com Thu Sep 6 05:06:50 2007 From: witham.ian at gmail.com (Ian Witham) Date: Thu, 6 Sep 2007 15:06:50 +1200 Subject: [Tutor] Importing Excel sheet data In-Reply-To: <1f51e43b0709051907q753c556pa319d12992cbc3ce@mail.gmail.com> References: <1f51e43b0709051907q753c556pa319d12992cbc3ce@mail.gmail.com> Message-ID: <a04dbf4b0709052006x105a25f5tc25a68ffba597439@mail.gmail.com> Hi, You should look at the 'csv' module in the Python Standard Library. If you export your excel data to csv format, you can easily import the data in to python using the csv module. Ian On 9/6/07, saradhi dinavahi <saradhi.dinavahi at gmail.com> wrote: > > hello all, > > I am new to the Python Programming. I want to Import Excel sheet data > using Python. Can any one please provide me the code and explain the basic > steps and method of executing the code. > > Thank You All > > > _______________________________________________ > 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/20070906/8a34f219/attachment.htm From witham.ian at gmail.com Thu Sep 6 05:24:55 2007 From: witham.ian at gmail.com (Ian Witham) Date: Thu, 6 Sep 2007 15:24:55 +1200 Subject: [Tutor] Importing Excel sheet data In-Reply-To: <1f51e43b0709052017o76dea43dqb04bbfba6dc5ceb9@mail.gmail.com> References: <1f51e43b0709051907q753c556pa319d12992cbc3ce@mail.gmail.com> <a04dbf4b0709052006x105a25f5tc25a68ffba597439@mail.gmail.com> <1f51e43b0709052017o76dea43dqb04bbfba6dc5ceb9@mail.gmail.com> Message-ID: <a04dbf4b0709052024i29ae70fv6301f055f824d6f6@mail.gmail.com> HI Saradhi, I too am fairly new to Python, but I use the csv module successfully for my work. Could you be a little more specific as to what your requirements are and where you are finding difficulty? Ian. On 9/6/07, saradhi dinavahi <saradhi.dinavahi at gmail.com> wrote: > > hi Ian , > > I have read the CSV module. But I felt difficult to write a code for my > requirement. > > Thank You. > > > On 9/5/07, Ian Witham <witham.ian at gmail.com> wrote: > > > > Hi, > > > > You should look at the 'csv' module in the Python Standard Library. If > > you export your excel data to csv format, you can easily import the data in > > to python using the csv module. > > > > Ian > > > > On 9/6/07, saradhi dinavahi < saradhi.dinavahi at gmail.com > wrote: > > > > > > hello all, > > > > > > I am new to the Python Programming. I want to Import Excel sheet data > > > using Python. Can any one please provide me the code and explain the basic > > > steps and method of executing the code. > > > > > > Thank You All > > > > > > > > > _______________________________________________ > > > 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/20070906/4ba60d24/attachment-0001.htm From david.bear at asu.edu Thu Sep 6 05:51:10 2007 From: david.bear at asu.edu (David Bear) Date: Wed, 05 Sep 2007 20:51:10 -0700 Subject: [Tutor] unicode encoding hell Message-ID: <3408212.QD0Uz6TdxC@teancum> I'm using universal feed parser to grab an rss feed. I'm carefull not to use any sys.out, print, file write ops, etc, UNLESS I use a decode('utf-i') to convert the unicode string I get from feed parser to utf-8. However, I'm still getting the blasted decode error stating that one of the items in the unicode string is out range. I've checked the encoding from the feed and it does indeed say it is utf-8. The content-type header is set to application/rss+xml . I am using the following syntax on a feedparser object: feedp.entry.title.decode('utf-8', 'xmlcharrefreplace') I assume it would take any unicode character and 'do the right thing', including replacing higher ordinal chars with xml entity refs. But I still get UnicodeEncodeError: 'ascii' codec can't encode character u'\u2019' in position 31: ordinal not in range(128) Clearly, I completely do not understand how unicode is working here. Can anyone enlighten me? -- David Bear College of Public Programs at Arizona State University From witham.ian at gmail.com Thu Sep 6 06:14:37 2007 From: witham.ian at gmail.com (Ian Witham) Date: Thu, 6 Sep 2007 16:14:37 +1200 Subject: [Tutor] Importing Excel sheet data In-Reply-To: <1f51e43b0709052032y209fa9bg3b9b470585dc9b05@mail.gmail.com> References: <1f51e43b0709051907q753c556pa319d12992cbc3ce@mail.gmail.com> <a04dbf4b0709052006x105a25f5tc25a68ffba597439@mail.gmail.com> <1f51e43b0709052017o76dea43dqb04bbfba6dc5ceb9@mail.gmail.com> <a04dbf4b0709052024i29ae70fv6301f055f824d6f6@mail.gmail.com> <1f51e43b0709052032y209fa9bg3b9b470585dc9b05@mail.gmail.com> Message-ID: <a04dbf4b0709052114u19f3305m752482c12f479ea5@mail.gmail.com> Hi Saradhi, The first step is to export your excel data to the .csv format. This is done in Excel from the file menu. CSV means "comma separated values". If you have exported the data correctly it may look something like this: "8803","16/9/2007","299000","BEO","13B Mandeville Crescent","Grenada Village","2.00PM","","3" "8844","16/9/2007","599000","BEO","89 Kahu Road","Paremata","2.00PM","","4" "8855","16/9/2007","370000","BEO","8 Salford Street","Newlands","2.00PM ","","2" Lots of values, separated by commas, often with quotation marks containing the values. The code I use to import this type of data looks like this: >>> import csv >>> oh_reader = csv.reader(open('openhomes.csv', 'U'), dialect='excel') >>> for row in oh_reader: print row ['8803', '16/9/2007', '299000', 'BEO', '13B Mandeville Crescent', 'Grenada Village', '2.00PM', '', '3'] ['8844', '16/9/2007', '599000', 'BEO', '89 Kahu Road', 'Paremata', '2.00PM', '', '4'] ['8855', '16/9/2007', '370000', 'BEO', '8 Salford Street', 'Newlands', ' 2.00PM', '', '2'] There is all my data in list format. There is also another class in csv called DictReader which presents your data in dictionary form. To do this you must provide a list of 'keys' to use for your dictionary. Think of these keys as being analogous to a header row in excel. eg: my_header_row = ['list_number', ' >>> my_header_row = ['list_number', 'date', 'price', 'price2', 'add1', 'add2', 'start', 'finish', 'bedrooms'] >>> dict_reader = csv.DictReader(open('openhomes.csv', 'U'), my_header_row, dialect='excel') >>> for row in dict_reader: print row {'finish': '', 'add2': 'Grenada Village', 'add1': '13B Mandeville Crescent', 'price': '299000', 'list_number': '8803', 'start': '2.00PM', 'bedrooms': '3', 'date': '16/9/2007', 'price2': 'BEO'} {'finish': '', 'add2': 'Paremata', 'add1': '89 Kahu Road', 'price': '599000', 'list_number': '8844', 'start': '2.00PM', 'bedrooms': '4', 'date': '16/9/2007', 'price2': 'BEO'} {'finish': '', 'add2': 'Newlands', 'add1': '8 Salford Street', 'price': '370000', 'list_number': '8855', 'start': '2.00PM', 'bedrooms': '2', 'date': '16/9/2007', 'price2': 'BEO'} And there is my data in dictionary format. CSV also has tools for exporting both lists and dicts to csv format again, and from there you can import the data back to excel. I hope I have been helpful to you. Ian. On 9/6/07, saradhi dinavahi <saradhi.dinavahi at gmail.com> wrote: > > Hi Ian, > > I have read the Python CSV module .But I cant understand to use that > module to Import Excel Sheet data.As I am new to the Python programming , > I dont know the way to write code using that module to meet my > requirement. > > On 9/5/07, Ian Witham <witham.ian at gmail.com> wrote: > > > > HI Saradhi, > > > > I too am fairly new to Python, but I use the csv module successfully for > > my work. Could you be a little more specific as to what your requirements > > are and where you are finding difficulty? > > > > Ian. > > > > On 9/6/07, saradhi dinavahi <saradhi.dinavahi at gmail.com > wrote: > > > > > > hi Ian , > > > > > > I have read the CSV module. But I felt difficult to write a code for > > > my requirement. > > > > > > Thank You. > > > > > > > > > On 9/5/07, Ian Witham <witham.ian at gmail.com > wrote: > > > > > > > > Hi, > > > > > > > > You should look at the 'csv' module in the Python Standard Library. > > > > If you export your excel data to csv format, you can easily import the data > > > > in to python using the csv module. > > > > > > > > Ian > > > > > > > > On 9/6/07, saradhi dinavahi < saradhi.dinavahi at gmail.com > wrote: > > > > > > > > > > hello all, > > > > > > > > > > I am new to the Python Programming. I want to Import Excel sheet > > > > > data using Python. Can any one please provide me the code and explain the > > > > > basic steps and method of executing the code. > > > > > > > > > > Thank You All > > > > > > > > > > > > > > > _______________________________________________ > > > > > 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/20070906/fc691c9d/attachment.htm From janos.juhasz at VELUX.com Thu Sep 6 08:55:12 2007 From: janos.juhasz at VELUX.com (=?ISO-8859-1?Q?J=E1nos_Juh=E1sz?=) Date: Thu, 6 Sep 2007 08:55:12 +0200 Subject: [Tutor] Importing Excel sheet data In-Reply-To: <mailman.373.1189049101.2656.tutor@python.org> Message-ID: <OFBE4D14BF.ABFE9DDE-ONC125734E.00236FAD-C125734E.0026036F@velux.com> Dear Saradhi, I am using COM on Win32 for this, based on the sample of Mark Hammond & Andy Robinson in the "Programing Python on Win32" book. That is a fairly simple way to do that. The code itself can be downloaded from http://examples.oreilly.com/pythonwin32/ppw32_samples.zip You can find some information about it googling for EasyExcel. The book itself is an essential to work on win32 with python. # My personal favorite chapters are the ones about double-entry bookkeeping :) > Date: Wed, 5 Sep 2007 21:07:41 -0500 > From: "saradhi dinavahi" <saradhi.dinavahi at gmail.com> > I am new to the Python Programming. I want to Import Excel sheet data using > Python. Can any one please provide me the code and explain the basic steps > and method of executing the code. Janos Juhasz -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070906/d0d93d4e/attachment.htm From steve at alchemy.com Thu Sep 6 08:59:11 2007 From: steve at alchemy.com (Steve Willoughby) Date: Wed, 05 Sep 2007 23:59:11 -0700 Subject: [Tutor] Importing Excel sheet data In-Reply-To: <1f51e43b0709051907q753c556pa319d12992cbc3ce@mail.gmail.com> References: <1f51e43b0709051907q753c556pa319d12992cbc3ce@mail.gmail.com> Message-ID: <46DFA53F.1050504@alchemy.com> saradhi dinavahi wrote: > I am new to the Python Programming. I want to Import Excel sheet data > using Python. Can any one please provide me the code and explain the > basic steps and method of executing the code. If you can get your Excel data into CSV format, the csv module others have already mentioned is a great way to go. It makes it very easy to read and write CSV-format files, which can be used with other spreadsheets and other programs, too. However, if you need to create or input actual Excel worksheets, which contain more than simple data tables like CSV supports, check out a third-party module called pyExcelerator. http://sourceforge.net/projects/pyexcelerator From kent37 at tds.net Thu Sep 6 12:38:46 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 06 Sep 2007 06:38:46 -0400 Subject: [Tutor] Importing Excel sheet data In-Reply-To: <a04dbf4b0709052024i29ae70fv6301f055f824d6f6@mail.gmail.com> References: <1f51e43b0709051907q753c556pa319d12992cbc3ce@mail.gmail.com> <a04dbf4b0709052006x105a25f5tc25a68ffba597439@mail.gmail.com> <1f51e43b0709052017o76dea43dqb04bbfba6dc5ceb9@mail.gmail.com> <a04dbf4b0709052024i29ae70fv6301f055f824d6f6@mail.gmail.com> Message-ID: <46DFD8B6.1080608@tds.net> Ian Witham wrote: > HI Saradhi, > > I too am fairly new to Python, but I use the csv module successfully for > my work. Could you be a little more specific as to what your > requirements are and where you are finding difficulty? > > Ian. > > On 9/6/07, *saradhi dinavahi* <saradhi.dinavahi at gmail.com > <mailto:saradhi.dinavahi at gmail.com>> wrote: > > hi Ian , > > I have read the CSV module. But I felt difficult to write a code for > my requirement. For reading only there is also xlrd: http://www.lexicon.net/sjmachin/xlrd.htm The csv module was recently covered here: http://blog.doughellmann.com/2007/08/pymotw-csv.html If you are having trouble with the basics you would do well to read one of the tutorials here or an introductory book: http://wiki.python.org/moin/BeginnersGuide/NonProgrammers BTW we usually bottom post on this list. http://catb.org/jargon/html/B/bottom-post.html Kent From kent37 at tds.net Thu Sep 6 12:45:08 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 06 Sep 2007 06:45:08 -0400 Subject: [Tutor] unicode encoding hell In-Reply-To: <3408212.QD0Uz6TdxC@teancum> References: <3408212.QD0Uz6TdxC@teancum> Message-ID: <46DFDA34.3020200@tds.net> David Bear wrote: > feedp.entry.title.decode('utf-8', 'xmlcharrefreplace') > > I assume it would take any unicode character and 'do the right thing', > including replacing higher ordinal chars with xml entity refs. But I still > get > > UnicodeEncodeError: 'ascii' codec can't encode character u'\u2019' in > position 31: ordinal not in range(128) > > Clearly, I completely do not understand how unicode is working here. Can > anyone enlighten me? It sounds like you already have Unicode. Notice that you are trying to decode but the error is for encoding. In [17]: u'\u2019'.decode('utf-8') ------------------------------------------------------------ Traceback (most recent call last): File "<ipython console>", line 1, in <module> File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/encodings/utf_8.py", line 16, in decode return codecs.utf_8_decode(input, errors, True) <type 'exceptions.UnicodeEncodeError'>: 'ascii' codec can't encode character u'\u2019' in position 0: ordinal not in range(128) decode() goes towards unicode, encode() goes away from unicode. Kent From wormwood_3 at yahoo.com Thu Sep 6 15:40:21 2007 From: wormwood_3 at yahoo.com (wormwood_3) Date: Thu, 6 Sep 2007 06:40:21 -0700 (PDT) Subject: [Tutor] Socket Timeout Handling Message-ID: <178570.97550.qm@web32401.mail.mud.yahoo.com> I am trying to figure out the optimal way to make socket connections (INET) and check for timeouts. The socket module has settimeout(timeout) and setdefaulttimeout(timeout). However, so far as I can tell, these apply to socket objects. The type of socket connection I want to make is getfqdn(address). So I can set the default timeout for socket, but not a socket object (makes sense so far). I cannot use the getfqdn(address) method on a socket object, I have to use it on socket. This means (as I understand it thus far), that while I can set a timeout value for socket objects, this will not apply to when I use the getfqdn() method, which is where I need a timeout check! Some example code for the steps so far: >>> import socket >>> conn = socket.socket() >>> conn.setdefaulttimeout(2.0) Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: '_socketobject' object has no attribute 'setdefaulttimeout' >>> socket.setdefaulttimeout(2.0) >>> conn.getfqdn("64.33.212.2") Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: '_socketobject' object has no attribute 'getfqdn' >>> socket.getfqdn("64.33.212.2") '64-33-212-2.customers.pingtone.net' >>> # Disconnected network connection here ... >>> socket.getfqdn("64.33.212.2") '64.33.212.2' >>> # Reconnected network connection here >>> socket.getfqdn("64.33.212.2") '64-33-212-2.customers.pingtone.net' After I disconnected my network connection and called getfqdn(), it returned the IP address I called it with after about 25 seconds. So the default timeout was ignored? Is there some other way to call this function so that I can check for timeouts? Should I instead just put my network calls in a thread and see how long they take, stopping them after a certain period? Thanks for any help. -Sam From fiyawerx at gmail.com Thu Sep 6 17:35:14 2007 From: fiyawerx at gmail.com (Fiyawerx) Date: Thu, 6 Sep 2007 11:35:14 -0400 Subject: [Tutor] Python / CGI Message-ID: <1b31ae500709060835g9ba5268w7ba57289c7de7f53@mail.gmail.com> Hi guys, quick question, I've been trying to learn python lately, and have written a few little apps to help with some day to day stuff I do, and recently my fiance asked me if it was possible to come up with a simple web based schedule she can use with the other teachers in her school to schedule library time. (She's the librarian). Basically, it will be a small calendar like app that will have 'slots' teachers can sign up for. It doesn't sound like it would be too complicated, and may be a good learning project. I was wondering if python as cgi would be good for this, and if there are any pitfalls I need to watch out for before I start delving into it. I'm also fairly new to writing my own html so will basically be learning it all from scratch. TIA, Lee McClintock -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070906/7c460fdf/attachment.htm From connorsml at gmail.com Thu Sep 6 17:44:52 2007 From: connorsml at gmail.com (Michael Connors) Date: Thu, 6 Sep 2007 16:44:52 +0100 Subject: [Tutor] Python / CGI In-Reply-To: <1b31ae500709060835g9ba5268w7ba57289c7de7f53@mail.gmail.com> References: <1b31ae500709060835g9ba5268w7ba57289c7de7f53@mail.gmail.com> Message-ID: <d9e7db140709060844m3b852311qefa8d9e9338a8bfd@mail.gmail.com> Hi, If you have your own server to run it on, I think it would make sense to use one of the Python web frameworks that are out there. I used cherrypy for my first web-based python project and I found it very easy to learn and develop in quickly. Regards, Michael On 06/09/07, Fiyawerx <fiyawerx at gmail.com> wrote: > > Hi guys, quick question, I've been trying to learn python lately, and have > written a few little apps to help with some day to day stuff I do, and > recently my fiance asked me if it was possible to come up with a simple web > based schedule she can use with the other teachers in her school to schedule > library time. (She's the librarian). Basically, it will be a small calendar > like app that will have 'slots' teachers can sign up for. It doesn't sound > like it would be too complicated, and may be a good learning project. I was > wondering if python as cgi would be good for this, and if there are any > pitfalls I need to watch out for before I start delving into it. I'm also > fairly new to writing my own html so will basically be learning it all from > scratch. > > TIA, > Lee McClintock > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Michael Connors -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070906/20e6eff5/attachment.htm From fiyawerx at gmail.com Thu Sep 6 17:57:55 2007 From: fiyawerx at gmail.com (Fiyawerx) Date: Thu, 6 Sep 2007 11:57:55 -0400 Subject: [Tutor] Python / CGI In-Reply-To: <d9e7db140709060844m3b852311qefa8d9e9338a8bfd@mail.gmail.com> References: <1b31ae500709060835g9ba5268w7ba57289c7de7f53@mail.gmail.com> <d9e7db140709060844m3b852311qefa8d9e9338a8bfd@mail.gmail.com> Message-ID: <1b31ae500709060857u674045f8l8334896ec502f320@mail.gmail.com> Thanks Michael, I'll be using my dreamhost account, and I'm pretty sure cherrypy works there, will check into it. On 9/6/07, Michael Connors <connorsml at gmail.com> wrote: > > Hi, > If you have your own server to run it on, I think it would make sense to > use one of the Python web frameworks that are out there. I used cherrypy for > my first web-based python project and I found it very easy to learn and > develop in quickly. > Regards, > Michael > > On 06/09/07, Fiyawerx <fiyawerx at gmail.com> wrote: > > > Hi guys, quick question, I've been trying to learn python lately, and > > have written a few little apps to help with some day to day stuff I do, and > > recently my fiance asked me if it was possible to come up with a simple web > > based schedule she can use with the other teachers in her school to schedule > > library time. (She's the librarian). Basically, it will be a small calendar > > like app that will have 'slots' teachers can sign up for. It doesn't sound > > like it would be too complicated, and may be a good learning project. I was > > wondering if python as cgi would be good for this, and if there are any > > pitfalls I need to watch out for before I start delving into it. I'm also > > fairly new to writing my own html so will basically be learning it all from > > scratch. > > > > TIA, > > Lee McClintock > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > -- > Michael Connors > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070906/1c331fc4/attachment.htm From brunson at brunson.com Thu Sep 6 18:07:32 2007 From: brunson at brunson.com (Eric Brunson) Date: Thu, 06 Sep 2007 10:07:32 -0600 Subject: [Tutor] Python / CGI In-Reply-To: <d9e7db140709060844m3b852311qefa8d9e9338a8bfd@mail.gmail.com> References: <1b31ae500709060835g9ba5268w7ba57289c7de7f53@mail.gmail.com> <d9e7db140709060844m3b852311qefa8d9e9338a8bfd@mail.gmail.com> Message-ID: <46E025C4.6010000@brunson.com> Michael Connors wrote: > Hi, > If you have your own server to run it on, I think it would make sense > to use one of the Python web frameworks that are out there. I used > cherrypy for my first web-based python project and I found it very > easy to learn and develop in quickly. That's debatable. I find the frameworks to be overly complicated and obfuscated. They're great when you're going through the tutorials, but try to do something "outside the box" and I find myself digging through documentation for longer than it would take me to write it from scratch. For this you'd need: some sort of backing store and some display routines with a simple interface to click on a slot and enter your name in it. I think I could write it in about 75 lines of python. Maybe 50. Just my opinion, e. > Regards, > Michael > > On 06/09/07, *Fiyawerx* <fiyawerx at gmail.com > <mailto:fiyawerx at gmail.com>> wrote: > > Hi guys, quick question, I've been trying to learn python lately, > and have written a few little apps to help with some day to day > stuff I do, and recently my fiance asked me if it was possible to > come up with a simple web based schedule she can use with the > other teachers in her school to schedule library time. (She's the > librarian). Basically, it will be a small calendar like app that > will have 'slots' teachers can sign up for. It doesn't sound like > it would be too complicated, and may be a good learning project. I > was wondering if python as cgi would be good for this, and if > there are any pitfalls I need to watch out for before I start > delving into it. I'm also fairly new to writing my own html so > will basically be learning it all from scratch. > > TIA, > Lee McClintock > > _______________________________________________ > Tutor maillist - Tutor at python.org <mailto:Tutor at python.org> > http://mail.python.org/mailman/listinfo/tutor > > > > > -- > Michael Connors > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Thu Sep 6 18:25:52 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 06 Sep 2007 12:25:52 -0400 Subject: [Tutor] Python / CGI In-Reply-To: <1b31ae500709060835g9ba5268w7ba57289c7de7f53@mail.gmail.com> References: <1b31ae500709060835g9ba5268w7ba57289c7de7f53@mail.gmail.com> Message-ID: <46E02A10.6040507@tds.net> Fiyawerx wrote: > Hi guys, quick question, I've been trying to learn python lately, and > have written a few little apps to help with some day to day stuff I do, > and recently my fiance asked me if it was possible to come up with a > simple web based schedule she can use with the other teachers in her > school to schedule library time. (She's the librarian). Basically, it > will be a small calendar like app that will have 'slots' teachers can > sign up for. It doesn't sound like it would be too > complicated, and may be a good learning project. I would look for prior art, myself. This sounds like a project that could easily get complicated. Here are some promising links: http://python.about.com/b/a/000088.htm http://www.schooltool.org/products/schooltool-calendar For that matter you might find that Google Calendar does everything you need: http://www.google.com/calendar It has a Python API FWIW: http://code.google.com/apis/calendar/overview.html Kent From kent37 at tds.net Thu Sep 6 18:39:02 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 06 Sep 2007 12:39:02 -0400 Subject: [Tutor] Python / CGI In-Reply-To: <46E025C4.6010000@brunson.com> References: <1b31ae500709060835g9ba5268w7ba57289c7de7f53@mail.gmail.com> <d9e7db140709060844m3b852311qefa8d9e9338a8bfd@mail.gmail.com> <46E025C4.6010000@brunson.com> Message-ID: <46E02D26.9090300@tds.net> Eric Brunson wrote: > Michael Connors wrote: >> Hi, >> If you have your own server to run it on, I think it would make sense >> to use one of the Python web frameworks that are out there. I used >> cherrypy for my first web-based python project and I found it very >> easy to learn and develop in quickly. > > That's debatable. I find the frameworks to be overly complicated and > obfuscated. They're great when you're going through the tutorials, but > try to do something "outside the box" and I find myself digging through > documentation for longer than it would take me to write it from scratch. Hmm. As my boss likes to say, "Reasonable people may disagree." I have been developing with Django for about six months now and I love it. Much of what I have wanted to do is directly supported and easy in Django; sometimes I have to push at it but only a few times have I really felt like I was trying to make it do something it really didn't want to do. I find both the documentation and code informative and easy to read. Kent From brunson at brunson.com Thu Sep 6 18:57:58 2007 From: brunson at brunson.com (Eric Brunson) Date: Thu, 06 Sep 2007 10:57:58 -0600 Subject: [Tutor] Python / CGI In-Reply-To: <46E02D26.9090300@tds.net> References: <1b31ae500709060835g9ba5268w7ba57289c7de7f53@mail.gmail.com> <d9e7db140709060844m3b852311qefa8d9e9338a8bfd@mail.gmail.com> <46E025C4.6010000@brunson.com> <46E02D26.9090300@tds.net> Message-ID: <46E03196.60509@brunson.com> Kent Johnson wrote: > Eric Brunson wrote: > >> Michael Connors wrote: >> >>> Hi, >>> If you have your own server to run it on, I think it would make sense >>> to use one of the Python web frameworks that are out there. I used >>> cherrypy for my first web-based python project and I found it very >>> easy to learn and develop in quickly. >>> >> That's debatable. I find the frameworks to be overly complicated and >> obfuscated. They're great when you're going through the tutorials, but >> try to do something "outside the box" and I find myself digging through >> documentation for longer than it would take me to write it from scratch. >> > > Hmm. As my boss likes to say, "Reasonable people may disagree." I have > been developing with Django for about six months now and I love it. Much > of what I have wanted to do is directly supported and easy in Django; > sometimes I have to push at it but only a few times have I really felt > like I was trying to make it do something it really didn't want to do. I > find both the documentation and code informative and easy to read. > I'll admit, though I looked at it briefly, Django was not one of the frameworks I spent much time on (didn't care for the templating style). I do most of my web development to run under mod_python and I've developed my own libraries to do what I need to do the way I think it should be done. :-) From david.bear at asu.edu Thu Sep 6 19:40:34 2007 From: david.bear at asu.edu (David Bear) Date: Thu, 06 Sep 2007 10:40:34 -0700 Subject: [Tutor] getting iteration level Message-ID: <9103560.YZBuXKBE9u@teancum> Lets say I have a list object that I iterate over like this: for item in myList: process(item) During execution of the for loop something happens and I want to know how many items have be iterated over, how do I find out? Without resorting to some counter inside the loop, is there some python object I can ask? -- David Bear College of Public Programs at Arizona State University From eike.welk at gmx.net Thu Sep 6 19:12:16 2007 From: eike.welk at gmx.net (Eike Welk) Date: Thu, 06 Sep 2007 19:12:16 +0200 Subject: [Tutor] Dynamically changing a class In-Reply-To: <0B363C44ED4B4945A08E20094B57144A18ECC4@venus-san> References: <0B363C44ED4B4945A08E20094B57144A18ECC4@venus-san> Message-ID: <200709061912.16530.eike.welk@gmx.net> On Wednesday 05 September 2007 16:59, Jason Doege wrote: > Thanks for the good and useful information on this. Now for the > why... > > I am building an API and for various reasons I have chosen Python > to implement it. I'd like to separate the implementation from the > interface as, for instance, C++ does with separate .hpp and .cpp > files. Apart from defining a class with a bunch of empty methods > and then redefining them, I have not seen a good way to do this in > Python. Can you recommend the Pythonic way to do this? > If you want to describe the data and validate it, Enthought traits may be interesting for you: http://code.enthought.com/traits/ They additionally have a library that can automatically generate a graphical user interface to change the data of a traits using class. Regards, Eike. From eric at ericwalstad.com Thu Sep 6 19:53:27 2007 From: eric at ericwalstad.com (Eric Walstad) Date: Thu, 06 Sep 2007 10:53:27 -0700 Subject: [Tutor] Python / CGI In-Reply-To: <d9e7db140709060844m3b852311qefa8d9e9338a8bfd@mail.gmail.com> References: <1b31ae500709060835g9ba5268w7ba57289c7de7f53@mail.gmail.com> <d9e7db140709060844m3b852311qefa8d9e9338a8bfd@mail.gmail.com> Message-ID: <46E03E97.3050808@ericwalstad.com> Michael Connors wrote: > Hi, > If you have your own server to run it on, I think it would make sense to > use one of the Python web frameworks that are out there. I used cherrypy > for my first web-based python project and I found it very easy to learn > and develop in quickly. > Regards, > Michael I'd argue that sticking with a Python CGI would be a great way to start because the OP can focus on the basics rather than on the framework API. The Python CGI stuff I've written in the past was helpful in my understanding of how and why Django works the way it does. After his Web Calendar is functioning as a CGI he'll have lots of ideas on how to improve it. A framework might help at that point. This article looks like it might have some useful information: [http://python.about.com/od/advancedpython/ss/howtocal.htm] Sounds like a fun project. Eric. From kent37 at tds.net Thu Sep 6 19:55:45 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 06 Sep 2007 13:55:45 -0400 Subject: [Tutor] getting iteration level In-Reply-To: <9103560.YZBuXKBE9u@teancum> References: <9103560.YZBuXKBE9u@teancum> Message-ID: <46E03F21.7000605@tds.net> David Bear wrote: > Lets say I have a list object that I iterate over like this: > > for item in myList: > process(item) > > During execution of the for loop something happens and I want to know how > many items have be iterated over, how do I find out? Without resorting to > some counter inside the loop, is there some python object I can ask? Use enumerate(), it generates the list index for you: for i, item in enumerate(myList): process(item) print 'processed item', i Kent From wormwood_3 at yahoo.com Thu Sep 6 22:46:08 2007 From: wormwood_3 at yahoo.com (wormwood_3) Date: Thu, 6 Sep 2007 13:46:08 -0700 (PDT) Subject: [Tutor] Socket Timeout Handling Message-ID: <469084.61038.qm@web32405.mail.mud.yahoo.com> Since no one bit on this yet, let me simplify to the core issue I am having: What is the best practice for checking for network connectivity errors when making network calls? Is it better to wrap the functions that make said calls in threads and time them? Or to use timeout variables for modules like socket? Something else? I found some good general info here: http://www.onlamp.com/pub/a/python/2003/11/06/python_nio.html But I have had a hard time finding info on network error handling specifically. Thoughts? ______________________________________ ----- Original Message ---- From: wormwood_3 <wormwood_3 at yahoo.com> To: Python Tutorlist <tutor at python.org> Sent: Thursday, September 6, 2007 9:40:21 AM Subject: [Tutor] Socket Timeout Handling I am trying to figure out the optimal way to make socket connections (INET) and check for timeouts. The socket module has settimeout(timeout) and setdefaulttimeout(timeout). However, so far as I can tell, these apply to socket objects. The type of socket connection I want to make is getfqdn(address). So I can set the default timeout for socket, but not a socket object (makes sense so far). I cannot use the getfqdn(address) method on a socket object, I have to use it on socket. This means (as I understand it thus far), that while I can set a timeout value for socket objects, this will not apply to when I use the getfqdn() method, which is where I need a timeout check! Some example code for the steps so far: >>> import socket >>> conn = socket.socket() >>> conn.setdefaulttimeout(2.0) Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: '_socketobject' object has no attribute 'setdefaulttimeout' >>> socket.setdefaulttimeout(2.0) >>> conn.getfqdn("64.33.212.2") Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: '_socketobject' object has no attribute 'getfqdn' >>> socket.getfqdn("64.33.212.2") '64-33-212-2.customers.pingtone.net' >>> # Disconnected network connection here ... >>> socket.getfqdn("64.33.212.2") '64.33.212.2' >>> # Reconnected network connection here >>> socket.getfqdn("64.33.212.2") '64-33-212-2.customers.pingtone.net' After I disconnected my network connection and called getfqdn(), it returned the IP address I called it with after about 25 seconds. So the default timeout was ignored? Is there some other way to call this function so that I can check for timeouts? Should I instead just put my network calls in a thread and see how long they take, stopping them after a certain period? Thanks for any help. -Sam _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From steve at alchemy.com Thu Sep 6 22:59:58 2007 From: steve at alchemy.com (Steve Willoughby) Date: Thu, 6 Sep 2007 13:59:58 -0700 Subject: [Tutor] Python / CGI In-Reply-To: <1b31ae500709060835g9ba5268w7ba57289c7de7f53@mail.gmail.com> References: <1b31ae500709060835g9ba5268w7ba57289c7de7f53@mail.gmail.com> Message-ID: <20070906205958.GB14020@dragon.alchemy.com> On Thu, Sep 06, 2007 at 11:35:14AM -0400, Fiyawerx wrote: > recently my fiance asked me if it was possible to come up with a simple web > based schedule she can use with the other teachers in her school to schedule > library time. (She's the librarian). Basically, it will be a small calendar > like app that will have 'slots' teachers can sign up for. It doesn't sound I wrote something like that in a couple of hours using straight Python, so I know it's doable. I haven't checked out any of the frameworks, but it would be really interesting to see what it would take to build a couple of apps in Django or whatever. If you're interested in just banging out a Python app, though, my experience was writing a calendaring tool for a group of my friends who get together once a month or so for gaming days. The app displays a year's calendar (any year desired) and shows what days we're playing or not. You click on a link to get a version of that calendar view with "slots" open for you to vote on which days you prefer or which you can't play on. Then I have an admin view which displays all the votes, and lets me make the "play/not play" decision for each date, which is what is displayed in the normal calendar view. The whole thing only took 318 lines of straight Python code, including all the HTML displayed on all those forms. The "calendar" module is your friend for apps like this, by the way :) -- Steve Willoughby | Using billion-dollar satellites steve at alchemy.com | to hunt for Tupperware. From alan.gauld at btinternet.com Fri Sep 7 01:41:32 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 7 Sep 2007 00:41:32 +0100 Subject: [Tutor] Socket Timeout Handling References: <469084.61038.qm@web32405.mail.mud.yahoo.com> Message-ID: <fbq37q$moh$1@sea.gmane.org> "wormwood_3" <wormwood_3 at yahoo.com> wrote > Since no one bit on this yet, let me simplify to the core issue I am > having: That may be because your question ventures into fairly deep areas of networking that most folk who are just learning Python(ie readers of this list) have probably not encountered. I've used python for network programming but not extensively and certainly not for hard core production use so can't help you. Similarly I've used sockets extesively from C/C++ but I'm not sure how well that transfers to Python without doing more digging than I hsave time for right now. If you do want to get into depth on Python networking you may find the A-Press book Python Network Programming useful - I do regularly :-). However the only information I could see about timeouts there was related to socket.settimeout() which ISTR you didn't want to/couldn't use... > What is the best practice for checking for network connectivity > errors when making network calls? Is it better to wrap the functions > that make said calls in threads and time them? > Or to use timeout variables for modules like socket? Personally if i was doingt that I'd almost certainy put it in a thread and apply a timeout within the thread. but not having tried that I don't know how easy it would be! > But I have had a hard time finding info on network error handling > specifically. The A-Press book does devote several pages in total to socket error handling including connection errors, timeout errors and transmission errors. > > I am trying to figure out the optimal way to make socket connections > (INET) and check for timeouts. The socket module has > settimeout(timeout) > and setdefaulttimeout(timeout). However, so far as I can tell, these > apply > to socket objects. The type of socket connection I want to make is > getfqdn(address). I don't understand, getfqdn() returns a domain name not an a socket? > So I can set the default timeout for socket, but not a socket object > (makes sense so far). I cannot use the getfqdn(address) method on > a socket object, I have to use it on socket. Sorry it's not making sense to me, getfqdn takes a host name not a socket. >>>> import socket >>>> conn = socket.socket() >>>> conn.setdefaulttimeout(2.0) setdefaulttimout is a function in the socket module not a method of socket. Thus you woulfd call that before reating a new socket: >>> socket.setdefaulttimeout(5) # set default t/o of 5 secs >>> conn = socket.socket() # with timeout of 5 >>>> socket.setdefaulttimeout(2.0) >>>> conn.getfqdn("64.33.212.2") Again getfqdn is a function in the socket module not a method. But if you give it an IP saddress it will just return that IP address! >>>> socket.getfqdn("64.33.212.2") > '64-33-212-2.customers.pingtone.net' OK, Apparently it will give you more... :-) >>>> # Disconnected network connection here > ... >>>> socket.getfqdn("64.33.212.2") > '64.33.212.2' > After I disconnected my network connection and called getfqdn(), > it returned the IP address I called it with after about 25 seconds. > So the default timeout was ignored? Yes because there was no socket being created it was doing a name lookup using standard DNS etc, and with the network disconnected timed out at the OS level I suspect. If you want to control the DNS lookup you will need to cofde that manually I suspect. (As I say, this is way deeper than I've needed to peer into these type of operations, the defaults have worked for me!) > Is there some other way to call this function so that I can check > for timeouts? Should I instead just put my network calls in a > thread and see how long they take, stopping them after a certain > period? I don't think that would necessarily help here. What are you trying to do? Establish a socket connection to something or just do a name check that times out more quickly?(or slowly) > Thanks for any help. Not sure how much help, not even sure I understand what you are up to, but it might spark an idea... -- 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 Sep 7 01:50:31 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 7 Sep 2007 00:50:31 +0100 Subject: [Tutor] Python / CGI References: <1b31ae500709060835g9ba5268w7ba57289c7de7f53@mail.gmail.com> Message-ID: <fbq3ok$nt3$1@sea.gmane.org> "Fiyawerx" <fiyawerx at gmail.com> wrote > Hi guys, quick question, I've been trying to learn python lately, > and have > written a few little apps to help with some day to day stuff I do, > and > recently my fiance asked me if it was possible to come up with a > simple web > based schedule she can use with the other teachers in her school to > schedule > library time. > wondering if python as cgi would be good for this, and if there are > any > pitfalls I need to watch out for before I start delving into it. If you want to do it as a learning excercise then I recommend using vanilla CGI. Everyone should write a couple of CGI apps to understand what really goes on. But two is enough and then move onto a framework for the sake of your sanity! Django has gotten a mention, personally I've been using TurboGears a bit and like it. Its an amalgamation of CherryPy (already mentioned) to convert http requests into python method calls with kid for templating (aka isolating your HTML from your code) and SQL Objects for providing OO style database access - you may not even need this, flat files may be adequate.(It can also use SQL Alchemy for this but I've not used it) www.turbogears.org But frankly all web objects provide the same basic features and for "conventional" web apps there is little to choose IMHO! ) And not just in Python, the same applies to Ruby on Rails, Struts(Java), IBM Websphere etc. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From cspears2002 at yahoo.com Fri Sep 7 02:13:09 2007 From: cspears2002 at yahoo.com (Christopher Spears) Date: Thu, 6 Sep 2007 17:13:09 -0700 (PDT) Subject: [Tutor] manually sorting variables Message-ID: <618185.53245.qm@web51609.mail.re2.yahoo.com> I'm working out of Core Python Programming (2nd Edition) by Wesley Chun. Here is the problem: Have the user enter three numeric values and store them in three different variables. Without using lists or sorting algorithms, manually sort these three numbers from smallest to largest. Here is what I have so far: #!/usr/bin/env python def smallest_var(x,y): if x < y: return x elif y < x: return y else: print "x equals y" var1 = raw_input("Enter a number for var1: ") var2 = raw_input("Enter a number for var2: ") var3 = raw_input("Enter a number for var3: ") small = smallest_var(var1, var2) #print small_var_1 smallest = smallest_var(small, var3) print smallest I'm not sure what the next step would be. If I was using a list, I could try to remove the smallest variable and then just compare the two remaining variables. Any hints? "I'm the last person to pretend that I'm a radio. I'd rather go out and be a color television set." -David Bowie "Who dares wins" -British military motto "I generally know what I'm doing." -Buster Keaton From kent37 at tds.net Fri Sep 7 03:12:49 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 06 Sep 2007 21:12:49 -0400 Subject: [Tutor] manually sorting variables In-Reply-To: <618185.53245.qm@web51609.mail.re2.yahoo.com> References: <618185.53245.qm@web51609.mail.re2.yahoo.com> Message-ID: <46E0A591.9030002@tds.net> Christopher Spears wrote: > I'm working out of Core Python Programming (2nd > Edition) by Wesley Chun. > > Here is the problem: > > Have the user enter three numeric values and store > them in three different variables. Without using > lists or sorting algorithms, manually sort these three > numbers from smallest to largest. > > Here is what I have so far: > #!/usr/bin/env python > > def smallest_var(x,y): > if x < y: > return x > elif y < x: > return y > else: > print "x equals y" > > var1 = raw_input("Enter a number for var1: ") > var2 = raw_input("Enter a number for var2: ") > var3 = raw_input("Enter a number for var3: ") > > small = smallest_var(var1, var2) > #print small_var_1 > smallest = smallest_var(small, var3) > print smallest > > I'm not sure what the next step would be. If I was > using a list, I could try to remove the smallest > variable and then just compare the two remaining > variables. Any hints? Do you know how to do a bubble sort? You could use comparison and swapping to sort the values so x is the smallest, y is the middle and z is the largest. I think it can be done with three comparisons and three or fewer swaps. Think of x, y and z as the three positions of a list. Kent From washakie at gmail.com Fri Sep 7 07:31:27 2007 From: washakie at gmail.com (John) Date: Thu, 6 Sep 2007 22:31:27 -0700 Subject: [Tutor] dynamic attribute assignment Message-ID: <aaf235960709062231r6b4d2605lf5a53357f344f871@mail.gmail.com> I've just noticed that you can use the import statement to import variables, such that a simple file such as vars.py: # File with predefined variables var1= 'some text' var2= 2 var3=['a','b','c'] Would then, upon import, provide: >>>vars.var1 'some text' >>>vars.var2 2 >>>vars.var3 ['a','b','c'] This is great, I had no idea! However, is there then a way to reassign or update the values? For instance, can you say: >>>vars.var1='some new text' ?? Just curious! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070906/1bd8e816/attachment.htm From alan.gauld at btinternet.com Fri Sep 7 09:08:05 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 7 Sep 2007 08:08:05 +0100 Subject: [Tutor] manually sorting variables References: <618185.53245.qm@web51609.mail.re2.yahoo.com> Message-ID: <fbqtd3$etp$1@sea.gmane.org> "Christopher Spears" <cspears2002 at yahoo.com> wrote > Have the user enter three numeric values and store > them in three different variables. Without using > lists or sorting algorithms, manually sort these three > numbers from smallest to largest. Hmm, the restriction of not using a sorting algorithm is interesting. But if you only have three values its doable. With more than three I'm not sure how it would be done. > def smallest_var(x,y): So you can get the smallest var. Now if you could get the biggest then the one that's neither must be in the middle. You are then left with selecting one of 6 possible outcomes: 1,2,3, 1,3,2 2,1,3 2.3.1, 3,1,2 3,2,1 Does that help? Alternatively you could write a comparison function rather than a get smallest/get biggest. That way you can compare the original variables rather than creating new ones. > var1 = raw_input("Enter a number for var1: ") > var2 = raw_input("Enter a number for var2: ") > var3 = raw_input("Enter a number for var3: ") You should convert these to integers! > small = smallest_var(var1, var2) > #print small_var_1 > smallest = smallest_var(small, var3) > print smallest 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 Fri Sep 7 09:10:31 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 7 Sep 2007 08:10:31 +0100 Subject: [Tutor] dynamic attribute assignment References: <aaf235960709062231r6b4d2605lf5a53357f344f871@mail.gmail.com> Message-ID: <fbqthl$fbu$1@sea.gmane.org> "John" <washakie at gmail.com> wrote >>>>vars.var3 > ['a','b','c'] > > This is great, I had no idea! However, is there then a way to > reassign or > update the values? For instance, can you say: > >>>>vars.var1='some new text' Why not try it at the >>> prompt? Thats the great thing about python, its very easy to try things like that out and get a definitive answer! (Even faster than posting to a mailing list! :-) In this case its a yes... -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From steve at alchemy.com Fri Sep 7 10:23:13 2007 From: steve at alchemy.com (Steve Willoughby) Date: Fri, 07 Sep 2007 01:23:13 -0700 Subject: [Tutor] Python / CGI In-Reply-To: <aaf235960709062225g25b9c37fycc69cfe661de7ca5@mail.gmail.com> References: <1b31ae500709060835g9ba5268w7ba57289c7de7f53@mail.gmail.com> <20070906205958.GB14020@dragon.alchemy.com> <aaf235960709062225g25b9c37fycc69cfe661de7ca5@mail.gmail.com> Message-ID: <46E10A71.8090902@alchemy.com> John wrote: > Steve, > > If you're interested in just banging out a Python app, though, my > experience > was writing a calendaring tool for a group of my friends who get > together > [...] > This sounds very cool, is it something you could post? Okay. It's not the greatest implementation (as I said it was kind of a quick hack) but here it is... A few notes to help understand the app: It's a single stand-alone CGI script in Python, and serves the three calendar views (scheduled games, the form for players to vote on good dates, and a form for the admin to decide on the game dates based on the votes) within this one script. It stores the data for the calendar in a MySQL database. The users need to authenticate to the web server in order to get to the page, so we can look in the script's environment to see who they are (so we know who voted for what days, and who gets the admin access page). The admin (and only the admin) can add a "?for=username" to the URL to access the application as if they were one of the players (in case they can't get in to the calendar but wish to change their vote data). #!/usr/bin/python # # Display a calendar of our game days, allow "voting" for what days any person # is available or not. # import cgitb; cgitb.enable() import os import sys import calendar import datetime import cgi import MySQLdb monthnames = ('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December') daynames = ('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat') calendar.setfirstweekday(6) # start weeks on Sunday currentdaybg = "#999933" votecolors = ( "#ff0000", "#00ff00", "#ffff00" ) form = cgi.FieldStorage() today = datetime.date.today() print "Content-Type: text/html\n" print '<html><body bgcolor=#000000 link=#ffffff vlink=#eeeeee text=#ffffff>' if 'year' in form: year = int(form.getfirst('year')) if not 2000 < year < 2020: print "Sorry, we're not supporting that year right now." sys.exit(0) else: year = today.year print """<style> .popup { COLOR: #9999ff; CURSOR: help; TEXT-DECORATION: none; } </style>""" if 'REMOTE_USER' not in os.environ: print "Sorry, this page cannot be used without authentication." sys.exit(0) me = os.environ['REMOTE_USER'] admin = (me == 'login-name-of-admin-1' or me == 'login-name-of-admin-2') #admin = False mode = 'normal' forWhom = None if admin and 'for' in form: me = form.getfirst('for') forWhom=me print "***",me,"***" if 'mode' in form: mode = form.getfirst('mode') if mode == 'admin' and not admin: print "Sorry, restricted access to this application is denied." sys.exit(0) if mode == 'admin' or mode == 'vote': print '<form action=calendar method=POST>' if mode == 'vote': print ''' <H1>Voting For Game Dates</H1> Generally, we play on Saturdays. If there's a special date we are considering playing on, such as a holiday, indicate your preference for that, but otherwise we're looking just for Saturdays. <P> Indicate your preferences by selecting the appropriate response under each date: <blockquote> <b>---</b>: I am available, most likely, and willing to play that date.<br> <b>Best</b>: This date is <b>particularly good</b> for me. Please play on that date if possible.<br> <b>NO</b>: This date is not good, I most likely will <b>not</b> be able to play. </blockquote> The default is "available", so if you're ok with playing any weekend in a month, just leave them all as "---". Don't mark them all as "best". The "best" setting is provided so that you can indicate unusually favorable dates, like when your SO is away or something. <P> When finished, click the "Save" button at the bottom. You'll be brought back to this form again in case you want to make more changes. Click the "Return to Calendar View" link (or navigate away from this page) when you're done and have saved all the changes you want to keep. <P> ''' # # Connect to database # db = MySQLdb.connect(host='HHH', user='XXX', passwd='YYY', db='ZZZ') # # Accept updates from user # votelist = None if mode == 'vote' or mode == 'admin': for key in form: if len(key) == 4: try: vmonth = int(key[0:2]) vdate = int(key[2:4]) vv = form.getfirst(key) except: # must not be the four-digit key we're looking for continue if 1 <= vmonth <= 12 and 1 <= vdate <= 31: if votelist is None: votelist = [] if mode == 'vote': if vv == '-': pass # just let the old vote (if any) die elif vv == 'Y': votelist.append((datetime.date(year,vmonth,vdate), me, True)) elif vv == 'N': votelist.append((datetime.date(year,vmonth,vdate), me, False)) else: print "***WARNING*** Invalid vote field encountered; vote for %d/%d NOT counted.<br>" % (vmonth,vdate) elif mode == 'admin': if vv == '-': pass # just let the old vote (if any) die elif vv == 'P': votelist.append((datetime.date(year,vmonth,vdate), 'GAME', True)) elif vv == 'A': votelist.append((datetime.date(year,vmonth,vdate), 'GAME', False)) else: print "***WARNING*** Invalid schedule field encountered; setting for %d/%d NOT counted.<br>" % (vmonth,vdate) if votelist is not None: # # Record new list of votes for this user # if mode == 'admin': duser = 'GAME' else: duser = me q = db.cursor() q.execute('DELETE FROM votes WHERE vuser=%s AND vdate >= %s AND vdate <= %s', (duser, '%04d-01-01'%year, '%04d-12-31'%year)) q.executemany('INSERT INTO votes (vdate, vuser, vote) values (%s,%s,%s)', votelist) logfile = open("/var/log/gamecal", "a") print >>logfile, "%d %s %s %s" % (year, os.environ['REMOTE_USER'], duser, votelist) logfile.close() myvotes = {} allvotes = {} gamedates = {} if mode == 'vote': # # Get my votes from database to display # --> myvotes # maps 'mmdd':0/1 (0=no, 1=yes). Dates not in dict=no preference # q = db.cursor() q.execute('SELECT vdate, vote FROM votes WHERE vuser=%s AND vdate >= %s AND vdate <= %s', (me, '%04d-01-01'%year, '%04d-12-31'%year)) for vote in q.fetchall(): myvotes['%02d%02d' % (vote[0].month, vote[0].day)] = vote[1] if mode == 'admin': # # Get everyone's votes from database # --> gamedates # maps 'mmdd':'ALT'/'PRI' (alternate/primary play date) # --> allvotes # maps 'mmdd':(0/1/2, string) 0=no, 1=yes, 2=mixed; string describes votes collected # q = db.cursor() q.execute('SELECT vdate, vuser, vote FROM votes WHERE vdate >= %s AND vdate <= %s', ('%04d-01-01'%year, '%04d-12-31'%year)) for vote in q.fetchall(): key = '%02d%02d' % (vote[0].month, vote[0].day) if vote[1] == 'GAME': gamedates[key] = ('ALT','PRI')[vote[2]] elif key not in allvotes: allvotes[key] = [vote[2], "%s: %s" % (vote[1], ('no','best')[vote[2]])] else: if allvotes[key][0] != vote[2]: allvotes[key][0] = 2 allvotes[key][1] += "; %s: %s" % (vote[1], ('no','best')[vote[2]]) else: q = db.cursor() q.execute("SELECT vdate, vote FROM votes WHERE vdate >= %s AND vdate <= %s AND vuser='GAME'", ('%04d-01-01'%year, '%04d-12-31'%year)) for vote in q.fetchall(): key = '%02d%02d' % (vote[0].month, vote[0].day) gamedates[key] = ('ALT','PRI')[vote[1]] if mode == 'admin' or mode == 'vote': print '<center><font size=5><b>Editing %d</b></font></center><P><P>' % year else: print ''' <table border=0 width=100%%> <tr> <td align=left> <font color=#666666 size=3><a href="calendar?year=%d">%d</a></font> </td><td align=center> <font color=#ffffff size=5>%d</font> </td><td align=right> <font color=#666666 size=3><a href="calendar?year=%d">%d</a></font> </td> </tr> </table><P><P> ''' % (year-1,year-1, year, year+1,year+1) print ''' <center> <table border=0> ''' for month in range(0, 12, 3): print "<tr><td> </td></tr><tr>" caldates = [] # # Month Names # for m in range(0,3): print "<th colspan=7><font size=+2>%s</font></th><td> </td>" % monthnames[month+m] caldates.append(calendar.monthcalendar(year,month+m+1)) print "</tr><tr>" # # Day Names # for m in range(0,3): for d in range(0,7): print "<th><small>%s</small></th>" % daynames[d] print "<td></td>" print "</tr>" # # Dates # for week in range(0,max([len(i) for i in caldates])): print "<tr>" for m in range(0,3): if week >= len(caldates[m]): print "<td colspan=7></td>" else: for d in range(0,7): if caldates[m][week][d] == 0: print "<td></td>" else: key = '%02d%02d' % (month+m+1, caldates[m][week][d]) if mode == 'admin' and key in allvotes: print "<td align=right bgcolor="+votecolors[allvotes[key][0]]+'><span title="%s" class="popup">%d</span></td>' % (allvotes[key][1], caldates[m][week][d]) elif key in gamedates: if gamedates[key] == 'PRI': print "<td align=right bgcolor=#009900><b>[%d]</b></td>" % caldates[m][week][d] else: print "<td align=right bgcolor=#000099>(%d)</td>" % caldates[m][week][d] else: if month+m+1 == today.month and caldates[m][week][d] == today.day and year == today.year: print "<td align=right bgcolor="+currentdaybg+">" else: print "<td align=right>" print "%d</td>" % caldates[m][week][d] print "<td></td>" print "</tr>" if mode == 'vote' or mode == 'admin': # make another row of voting buttons under the dates. print "<tr>" for m in range(0,3): if week >= len(caldates[m]): print "<td colspan=7></td>" else: for d in range(0,7): if caldates[m][week][d] == 0: print "<td></td>" else: key = '%02d%02d' % (month+m+1, caldates[m][week][d]) print '<td><select name=%s>' % key print '<option value="-">---' if mode == 'admin': print '<option value="P"', if gamedates.get(key) == 'PRI': print 'SELECTED', print '>Play' print '<option value="A"', if gamedates.get(key) == 'ALT': print 'SELECTED', print '>Alt' print '</select></td>' else: print '<option value="Y"', if myvotes.get(key) == 1: print 'SELECTED', print '>Best' print '<option value="N"', if myvotes.get(key) == 0: print 'SELECTED', print '>NO' print '</select></td>' print "<td></td>" print "</tr>" print "</table></center>" if mode == 'admin' or mode == 'vote': if forWhom is not None: print '<input type=hidden name="for" value="%s">' % cgi.escape(forWhom) print '<input type=hidden name="year" value="%d">' % year print '<input type=hidden name="mode" value="%s">' % mode print '<input type=submit value="Save Changes"></form>' print '<P><a href="calendar?year=%d">Return to calendar view</a> (abandons unsaved changes!)' % year else: print '<a href="calendar?mode=vote&year=%d">Indicate your good/bad dates</a><br>' % year if admin: print '<a href="calendar?mode=admin&year=%d">Set Game Dates</a><br>' % year print '<table border=0>' if mode == 'admin': print ''' <tr><td bgcolor=%s> </td><td>Today</td></tr> <tr><td bgcolor=%s> </td><td>Preferred Date </td></tr> <tr><td bgcolor=%s> </td><td>Problem Date</td></tr> <tr><td bgcolor=%s> </td><td>Mixed Bag</td></tr> ''' % (currentdaybg, votecolors[1], votecolors[0], votecolors[2]) else: print ''' <tr><td bgcolor=%s> </td><td>Today</td></tr> <tr><td bgcolor=%s> </td><td>Play Date</td></tr> <tr><td bgcolor=%s> </td><td>Alternate</td></tr> ''' % (currentdaybg, '#009900', '#000099') print '</table>' print "</body></html>" ------------------------------------------------------------------------------ After I put that on the website, I wrote another script which runs out of cron and automatically sends out reminder messages to the players a few days in advance of a game date: #!/usr/bin/python # import sys import datetime import MySQLdb import smtplib # # The gamecal.votes table looks like this: # #+-------+-------------+------+-----+------------+-------+ #| Field | Type | Null | Key | Default | Extra | #+-------+-------------+------+-----+------------+-------+ #| vdate | date | NO | PRI | 0000-00-00 | | #| vuser | varchar(20) | NO | PRI | NULL | | #| vote | tinyint(1) | NO | | 0 | | #+-------+-------------+------+-----+------------+-------+ # # If the vuser is 'GAME', the "vote" indicates a scheduled # game date and not a player's vote. In this case, 'vote' # is 1 for a primary date and 0 for an alternate date. # db = MySQLdb.connect(host='HHH', user='XXX', passwd='YYY', db='ZZZ') today = datetime.date.today() query = db.cursor() query.execute(''' SELECT vdate, vote FROM votes WHERE vdate >= %s AND vdate < %s AND vuser='GAME' ORDER BY vdate ''', (today, today + datetime.timedelta(180))) gamedates = query.fetchall() query.close() db.close() msg = '''From: me at XXX.com To: our-game-mailing-list at XXX.com Subject: Reminder of Upcoming D&D Game ''' # # Find closest actual game date # nextGame = None for game in gamedates: if game[1] == 1: nextGame = (game[0] - today).days break if nextGame is not None: if nextGame == 2: msg += "This is an automated reminder that the next D&D game is nearly here!\n\n" elif nextGame == 6: msg += "This is an automated reminder of the upcoming D&D game in less than a week.\n\n" else: sys.exit(0) msg += "The next several game dates are:\n" msg += "Date----------- Days Notes------\n" for game in gamedates: msg += "%-15s %4d" % (game[0].strftime('%a %b %d %Y'), (game[0]-today).days) if game[1] == 0: msg += " (Alternate)" msg += '\n' msg += ''' Please remember that you can always check the schedule by visiting http://url-to-calendar-application You may also go to that webpage and indicate what days are particularly good or bad for you in the future. ''' mail = smtplib.SMTP('mailserver.XXX.com') mail.sendmail('me at XXX.com','our-game-mailing-list at XXX.com', msg) mail.quit() From mailinglistmatt at gmail.com Fri Sep 7 13:41:43 2007 From: mailinglistmatt at gmail.com (matte) Date: Fri, 7 Sep 2007 13:41:43 +0200 Subject: [Tutor] Problem with while loop Message-ID: <ad53d62e0709070441x5a0b6d78pd6aec129e46190fd@mail.gmail.com> Hi guys Please excuse me but I've been out of Python for a while since my laptop was stolen... I'm battling with a very basic while loop.... -------------- 8< ---------------------- #!/usr/bin/python from random import randint counter = 0 howmany = raw_input( "How many: " ) while counter < howmany: pin = randint(0000,9999) print pin counter += 1 -------------- 8< ---------------------- For some reason if I use an integer in place of "howmany" it works, but I'd like it to work as I can logically see it above. What am I missing ? -m -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070907/a8faff46/attachment.htm From connorsml at gmail.com Fri Sep 7 13:54:18 2007 From: connorsml at gmail.com (Michael Connors) Date: Fri, 7 Sep 2007 12:54:18 +0100 Subject: [Tutor] Problem with while loop In-Reply-To: <ad53d62e0709070441x5a0b6d78pd6aec129e46190fd@mail.gmail.com> References: <ad53d62e0709070441x5a0b6d78pd6aec129e46190fd@mail.gmail.com> Message-ID: <d9e7db140709070454q27a93d88k767a9ef671b25e9c@mail.gmail.com> I think it will work if you cast your input to an int: howmany = int(raw_input( "How many: " )) On 07/09/2007, matte <mailinglistmatt at gmail.com> wrote: > > Hi guys > > Please excuse me but I've been out of Python for a while since my laptop > was stolen... > > I'm battling with a very basic while loop.... > > -------------- 8< ---------------------- > #!/usr/bin/python > > from random import randint > > counter = 0 > > howmany = raw_input( "How many: " ) > > while counter < howmany: > > pin = randint(0000,9999) > print pin > counter += 1 > > -------------- 8< ---------------------- > > For some reason if I use an integer in place of "howmany" it works, but > I'd > like it to work as I can logically see it above. > > What am I missing ? > > -m > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Michael Connors -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070907/c8980748/attachment.htm From mailinglistmatt at gmail.com Fri Sep 7 14:25:47 2007 From: mailinglistmatt at gmail.com (matte) Date: Fri, 7 Sep 2007 14:25:47 +0200 Subject: [Tutor] Problem with while loop In-Reply-To: <d9e7db140709070454q27a93d88k767a9ef671b25e9c@mail.gmail.com> References: <ad53d62e0709070441x5a0b6d78pd6aec129e46190fd@mail.gmail.com> <d9e7db140709070454q27a93d88k767a9ef671b25e9c@mail.gmail.com> Message-ID: <ad53d62e0709070525t3ddc022bq786ff541380f3b9a@mail.gmail.com> Perfect... Thanks very much for your help... On 9/7/07, Michael Connors <connorsml at gmail.com> wrote: > > I think it will work if you cast your input to an int: > howmany = int(raw_input( "How many: " )) Now I just need to figure out how to only get 4 digit pin numbers :) -m -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070907/2d8b379b/attachment.htm From connorsml at gmail.com Fri Sep 7 14:40:24 2007 From: connorsml at gmail.com (Michael Connors) Date: Fri, 7 Sep 2007 13:40:24 +0100 Subject: [Tutor] Problem with while loop In-Reply-To: <ad53d62e0709070525t3ddc022bq786ff541380f3b9a@mail.gmail.com> References: <ad53d62e0709070441x5a0b6d78pd6aec129e46190fd@mail.gmail.com> <d9e7db140709070454q27a93d88k767a9ef671b25e9c@mail.gmail.com> <ad53d62e0709070525t3ddc022bq786ff541380f3b9a@mail.gmail.com> Message-ID: <d9e7db140709070540g241944fcjc5db46f6b3d030b3@mail.gmail.com> You could use string formatting to output all pin numbers as 4 character strings. http://docs.python.org/lib/typesseq-strings.html On 07/09/2007, matte <mailinglistmatt at gmail.com> wrote: > > Perfect... > > Thanks very much for your help... > > On 9/7/07, Michael Connors <connorsml at gmail.com> wrote: > > > > I think it will work if you cast your input to an int: > > howmany = int(raw_input( "How many: " )) > > > Now I just need to figure out how to only get 4 digit pin numbers :) > > -m > -- Michael Connors -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070907/3da1b1bc/attachment.htm From tinoloc at gmail.com Fri Sep 7 17:08:33 2007 From: tinoloc at gmail.com (Tino Dai) Date: Fri, 7 Sep 2007 11:08:33 -0400 Subject: [Tutor] Multi-threading help Message-ID: <e033edfb0709070808i55a2af0fkea8a381fa55f4494@mail.gmail.com> Hi there, I'm working on a multi-threaded utility to monitor network connections between three machines The configuration of the three machines are: a web machine that feeds back to two machines for processing. Sometimes when the web connection is closed, the corresponding processes on the two backend machines don't close. How, I have the current set up is: class web: def __init__(self): <set some stuff> def run(self,args): <loop to get some data> class mach1: def __init__(self): <set some stuff> def run(self,args): <loop to get some data> class mach2: def __init__(self): <set some stuff> def run(self,args): <loop to get some data> class target: def run(self,args): ... collect data from web, mach1, mach2 classes, monitor connections, yada yada yada My question is how to get the information to the target class. The target class must have the web, mach1, mach2 data sets before doing any sort of matching up of information. Now the ways that I have thought of are: -Directing sending the information to the target object (there will only be one) -Using the Observer pattern to send the information from the web, mach1, mach2 classes to the target object And other question that I do have are: -Is there a way to "block" run until I get information from the three other objects. Presently, I can only think of looping and polling to see if the information has come in yet. I'm sure there is a way because I have seen it used in the SocketHandler class. -Is there any way that I can be sure that two different objects are not writing to target at the same time? The present way that I'm thinking about is using locking. Thanks Tino -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070907/e244c4f5/attachment.htm From fiyawerx at gmail.com Fri Sep 7 17:49:12 2007 From: fiyawerx at gmail.com (Fiyawerx) Date: Fri, 7 Sep 2007 11:49:12 -0400 Subject: [Tutor] Python / CGI In-Reply-To: <46E10A71.8090902@alchemy.com> References: <1b31ae500709060835g9ba5268w7ba57289c7de7f53@mail.gmail.com> <20070906205958.GB14020@dragon.alchemy.com> <aaf235960709062225g25b9c37fycc69cfe661de7ca5@mail.gmail.com> <46E10A71.8090902@alchemy.com> Message-ID: <1b31ae500709070849k4d2c460rce9f59c006d1972d@mail.gmail.com> Wow, thanks for all the info guys, more than i was expecting :). After looking around at various options, I did download the python gdata module for google's calendar. What I'm thinking is, since my fiance has two schools, she can just log into her google account and create a calendar for each school. I'm going to try to make a custom cgi front-end that will pull the data, and offer 'slots' to sign up for. When you sign up for a slot, you have to use a username for the front-end, I'm thinking I can store them in a db. That way I don't have to worry about everyone needing google calendars to be able to access hers. So when someone picks a slot and submits it, the program behind the scenes will actually just use her google account to submit, and append the username to the entry, so you can tell who did what, but it still will only require one real google account. Gdata comes with some really nice samples, one that basically does any of the calendar functions i'm going to need, so I think I should bea ble to rip the code out of that module to use, so I still get to learn the cgi doing my front-end, but that way I know I have a well functioning back-end to easy some of my troubles. http://code.google.com/apis/calendar/developers_guide_python.html Here is a bit of the output from their 'sample' python script that comes with the package. -------- C:\Python25\gdata.py-1.0.8\samples\calendar>python calendarExample.py --user fiyawerx at gmail.com --pw xxxxxxx Printing allcalendars: Lee McClintock's Calendar List 0. Lee McClintock Printing owncalendars: Lee McClintock's Calendar List 0. Lee McClintock Events on Primary Calendar: Lee McClintock 0. Rent 0. fiyawerx at gmail.com Lee McClintock None Full text query for events on Primary Calendar: 'Tennis' Date range query for events on Primary Calendar: 2007-01-01 to 2007-07-01 0. Rent Start time: 2007-03-01 End time: 2007-03-02 Start time: 2007-06-01 End time: 2007-06-02 Start time: 2007-01-01 End time: 2007-01-02 Start time: 2007-05-01 End time: 2007-05-02 Start time: 2007-04-01 End time: 2007-04-02 Start time: 2007-02-01 End time: 2007-02-02 New single event inserted: http://www.google.com/calendar/feeds/default/private/full/cmvade9oqrd95oeaaf9b7ha5cc Event edit URL: http://www.google.com/calendar/feeds/default/private/full/cmvade9oqrd95oeaaf9b7ha5cc/63324787637 Event HTML URL: http://www.google.com/calendar/event?eid=Y212YWRlOW9xcmQ5NW9lYWFmOWI3aGE1Y2MgZml5YXdlcnhAbQ Updating title of event from:'One-time Tennis with Beth' to:'New title for single event' Adding 30 minute reminder to event Adding extended property to event: 'propname'='propvalue' New recurring event inserted: http://www.google.com/calendar/feeds/default/private/full/dpjp06smht75o466g8s0gfdnro Event edit URL: http://www.google.com/calendar/feeds/default/private/full/dpjp06smht75o466g8s0gfdnro/63324787638 Event HTML URL: http://www.google.com/calendar/event?eid=ZHBqcDA2c21odDc1bzQ2Nmc4czBnZmRucm9fMjAwNzA1MDEgZml5YXdlcnhAbQ Inserting Simple Web Content Event Inserting Web Content Gadget Event Lee McClintock's access control list 0. owner Role: http://schemas.google.com/gCal/2005#owner Scope user - fiyawerx at gmail.com 1. editor Role: http://schemas.google.com/gCal/2005#editor Scope user - poprockpixie at yahoo.com freebusy Role: http://schemas.google.com/gCal/2005#freebusy Scope user - user at gmail.com Creating new calendar with title "Little League Schedule" Updating the calendar titled "Little League Schedule" with the title "New Title" Subscribing to the calendar with ID: c4o4i7m2lbamc4k26sc2vokh5g%40group.calendar.google.com Updating the calendar subscription with ID: c4o4i7m2lbamc4k26sc2vokh5g%40group.calendar.google.com ------ So it seems it already has samples of anything I'm going to need to do. (Got a message that the mail bounced due to being too learge, cut out the quoted section) -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070907/b00df54d/attachment-0001.htm From Jason.Timms at shawinc.com Fri Sep 7 17:55:16 2007 From: Jason.Timms at shawinc.com (Jason.Timms at shawinc.com) Date: Fri, 7 Sep 2007 11:55:16 -0400 Subject: [Tutor] Jason Timms is out of the office. Message-ID: <OF88CA43A8.E12FC7DA-ON8525734F.0057755A-8525734F.0057755C@shawinc.com> I will be out of the office starting 09/07/2007 and will not return until 09/09/2007. I will respond to your message when I return. ********************************************************** Privileged and/or confidential information may be contained in this message. If you are not the addressee indicated in this message (or are not responsible for delivery of this message to that person) , you may not copy or deliver this message to anyone. In such case, you should destroy this message and notify the sender by reply e-mail. If you or your employer do not consent to Internet e-mail for messages of this kind, please advise the sender. Shaw Industries does not provide or endorse any opinions, conclusions or other information in this message that do not relate to the official business of the company or its subsidiaries. ********************************************************** From lawrence.barrott at btinternet.com Fri Sep 7 19:00:17 2007 From: lawrence.barrott at btinternet.com (Lawrence Barrott) Date: Fri, 7 Sep 2007 18:00:17 +0100 Subject: [Tutor] (no subject) Message-ID: <73E5623316494C47AAB09AEB6612567F@PC3> using the built in function "open" how do you specify non local files such as the C: drive without copying the program there thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070907/c6883d85/attachment.htm From alan.gauld at btinternet.com Fri Sep 7 20:13:31 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 7 Sep 2007 19:13:31 +0100 Subject: [Tutor] (no subject) References: <73E5623316494C47AAB09AEB6612567F@PC3> Message-ID: <fbs4cq$k0t$1@sea.gmane.org> "Lawrence Barrott" <lawrence.barrott at btinternet.com> wrote > using the built in function "open" how do you specify non local > files such as the C: drive without copying the program there Just provide the full path to the file. f = open(r"C:\TEMP\somefile.txt") Note the use of raw to avoid problems with the DOS backslash character. Another option is to use forward slashes which python accepts too: f = open("C:/TEMP/somefile.txt") -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From aezell at gmail.com Fri Sep 7 20:28:34 2007 From: aezell at gmail.com (Alex Ezell) Date: Fri, 7 Sep 2007 13:28:34 -0500 Subject: [Tutor] Fun with Cookies Message-ID: <71dd7f400709071128j1cba3b5fm2341cf4aa81d511b@mail.gmail.com> Hi all, I am trying to create a cookie and send it a long with a request. I searched the archives and found this code from Kent Johnson: import cookielib, urllib2 cj = cookielib.CookieJar() cookie = cookielib.Cookie(...your cookie data here...) cj.set_cookie(cookie) opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) urllib2.install_opener(opener) data = urllib2.urlopen(...).read() It seemed to solve a problem I was having with SimpleCookie(), but I cannot figure out what I should put where Kent has written "...your cookie data here...". I have tried strings, SimpleCookie instances, etc. and I always get this error on that line: __init__() takes at least 17 arguments (2 given) Thanks for your time. Alex Ezell From kent37 at tds.net Fri Sep 7 20:58:35 2007 From: kent37 at tds.net (Kent Johnson) Date: Fri, 07 Sep 2007 14:58:35 -0400 Subject: [Tutor] Fun with Cookies In-Reply-To: <71dd7f400709071128j1cba3b5fm2341cf4aa81d511b@mail.gmail.com> References: <71dd7f400709071128j1cba3b5fm2341cf4aa81d511b@mail.gmail.com> Message-ID: <46E19F5B.7090608@tds.net> Alex Ezell wrote: > Hi all, > I am trying to create a cookie and send it a long with a request. > > I searched the archives and found this code from Kent Johnson: > > import cookielib, urllib2 > > cj = cookielib.CookieJar() > cookie = cookielib.Cookie(...your cookie data here...) > cj.set_cookie(cookie) > > opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) > urllib2.install_opener(opener) > > data = urllib2.urlopen(...).read() > > It seemed to solve a problem I was having with SimpleCookie(), but I > cannot figure out what I should put where Kent has written "...your > cookie data here...". I have tried strings, SimpleCookie instances, > etc. and I always get this error on that line: > > __init__() takes at least 17 arguments (2 given) The Cookie constructor is def __init__(self, version, name, value, port, port_specified, domain, domain_specified, domain_initial_dot, path, path_specified, secure, expires, discard, comment, comment_url, rest, rfc2109=False, ) You should specify at least name, value, domain and path (all strings). The rest can be None. Kent From aezell at gmail.com Fri Sep 7 21:48:36 2007 From: aezell at gmail.com (Alex Ezell) Date: Fri, 7 Sep 2007 14:48:36 -0500 Subject: [Tutor] Fun with Cookies In-Reply-To: <46E19F5B.7090608@tds.net> References: <71dd7f400709071128j1cba3b5fm2341cf4aa81d511b@mail.gmail.com> <46E19F5B.7090608@tds.net> Message-ID: <71dd7f400709071248g1d73a72bje41e5c4074b60ea1@mail.gmail.com> Kent, Thanks so much. I will give that a try. Your name is all over these kinds of questions on the web. I guess you fought through it a while back? Here's where I show off my Python newb status. What's the best way to specify those attributes? If I only include the 4 you mention (name, value, domain and path), it seems messy to have a bunch of "None"s in there. Thanks again, Alex On 9/7/07, Kent Johnson <kent37 at tds.net> wrote: > Alex Ezell wrote: > > Hi all, > > I am trying to create a cookie and send it a long with a request. > > > > I searched the archives and found this code from Kent Johnson: > > > > import cookielib, urllib2 > > > > cj = cookielib.CookieJar() > > cookie = cookielib.Cookie(...your cookie data here...) > > cj.set_cookie(cookie) > > > > opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) > > urllib2.install_opener(opener) > > > > data = urllib2.urlopen(...).read() > > > > It seemed to solve a problem I was having with SimpleCookie(), but I > > cannot figure out what I should put where Kent has written "...your > > cookie data here...". I have tried strings, SimpleCookie instances, > > etc. and I always get this error on that line: > > > > __init__() takes at least 17 arguments (2 given) > > The Cookie constructor is > > def __init__(self, version, name, value, > port, port_specified, > domain, domain_specified, domain_initial_dot, > path, path_specified, > secure, > expires, > discard, > comment, > comment_url, > rest, > rfc2109=False, > ) > > You should specify at least name, value, domain and path (all strings). > The rest can be None. > > Kent > From kent37 at tds.net Fri Sep 7 22:03:00 2007 From: kent37 at tds.net (Kent Johnson) Date: Fri, 07 Sep 2007 16:03:00 -0400 Subject: [Tutor] Fun with Cookies In-Reply-To: <71dd7f400709071248g1d73a72bje41e5c4074b60ea1@mail.gmail.com> References: <71dd7f400709071128j1cba3b5fm2341cf4aa81d511b@mail.gmail.com> <46E19F5B.7090608@tds.net> <71dd7f400709071248g1d73a72bje41e5c4074b60ea1@mail.gmail.com> Message-ID: <46E1AE74.9060109@tds.net> Alex Ezell wrote: > Kent, > Thanks so much. I will give that a try. Your name is all over these > kinds of questions on the web. I guess you fought through it a while > back? I figured it out for part of the Python Challenge :-) http://www.pythonchallenge.com/ Don't know how it got all over the web though...it's not the first time it has come up here... > Here's where I show off my Python newb status. What's the best way to > specify those attributes? If I only include the 4 you mention (name, > value, domain and path), it seems messy to have a bunch of "None"s in > there. You have to include the None's. Kent From ricaraoz at gmail.com Sat Sep 8 02:04:50 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Fri, 07 Sep 2007 21:04:50 -0300 Subject: [Tutor] Problem with while loop In-Reply-To: <ad53d62e0709070441x5a0b6d78pd6aec129e46190fd@mail.gmail.com> References: <ad53d62e0709070441x5a0b6d78pd6aec129e46190fd@mail.gmail.com> Message-ID: <46E1E722.2090702@bigfoot.com> matte wrote: > Hi guys > > Please excuse me but I've been out of Python for a while since my laptop > was stolen... > > I'm battling with a very basic while loop.... > > -------------- 8< ---------------------- > #!/usr/bin/python > > from random import randint > > counter = 0 > > howmany = raw_input( "How many: " ) > > while counter < howmany: > > pin = randint(0000,9999) > print pin > counter += 1 > > -------------- 8< ---------------------- > > For some reason if I use an integer in place of "howmany" it works, but I'd > like it to work as I can logically see it above. > > What am I missing ? > raw_input returns a string. Have to convert it. BTW, instead of the while loop you might try this : for i in xrange(int(howmany)) : print randint(0000, 9999) saves you some code and a few variables. Or if what you want is a list for further processing : randomInts = [randint(0000, 9999) for i in xrange(int(howmany))] From trey at opmstech.org Sat Sep 8 02:47:05 2007 From: trey at opmstech.org (Trey Keown) Date: Fri, 7 Sep 2007 19:47:05 -0500 (CDT) Subject: [Tutor] WxPython Splashscreen? Message-ID: <61555.68.191.136.241.1189212425.squirrel@webmail.opmstech.org> Hey all, Does anyone know how to make a wxPython splashscreen? It would be great if you could show a (working) example, as I have googled this topic, yet have not found any working examples. Thanks. From cspears2002 at yahoo.com Sat Sep 8 07:24:40 2007 From: cspears2002 at yahoo.com (Christopher Spears) Date: Fri, 7 Sep 2007 22:24:40 -0700 (PDT) Subject: [Tutor] rewriting script Message-ID: <877291.75369.qm@web51610.mail.re2.yahoo.com> I have written a script that reads and displays text files: #!/usr/bin/env python 'readTextFile.py -- read and display text file' import os # get filename while True: fname = raw_input('Enter file name: ') print if os.path.exists(fname): fobj = open(fname, 'r') for eachLine in fobj: print eachLine, fobj.close() else: print"*** File doesn't exist" break However, whenever I run the script, I get this result: io at io-station-1 ./chap3 314> python readTextFile1.py Enter file name: datefile Fri Sep 7 22:13:03 PDT 2007 Traceback (most recent call last): File "readTextFile1.py", line 13, in ? for eachLine in fobj: ValueError: I/O operation on closed file The original script appeared in 'Core Python Programming' in this form: #!/usr/bin/env python 'readTextFile.py -- read and display text file' # get filename fname = raw_input('Enter file name: ') print # attempt to open file for reading try: fobj = open(fname, 'r') except IOError, e: print"*** file open error:", e else: # display contents to the screen for eachLine in fobj: print eachLine, fobj.close() I modified the script as an answer to one of the end of chapter questions. Basically, I am supposed to rewrite the script, so that runs with 'try' and 'except'. What is causing the error message? I thought the file was opened earlier in the script. From silas428 at gmail.com Sat Sep 8 07:27:33 2007 From: silas428 at gmail.com (Ryan) Date: Fri, 07 Sep 2007 22:27:33 -0700 Subject: [Tutor] Python scripting Message-ID: <46E232C5.2050302@gmail.com> I am on a linux machine and I was wondering about python scripting. Mainly to get it up and running but also what can I do with it etc. Any help would be appreciated, Thnx From cspears2002 at yahoo.com Sat Sep 8 07:43:22 2007 From: cspears2002 at yahoo.com (Christopher Spears) Date: Fri, 7 Sep 2007 22:43:22 -0700 (PDT) Subject: [Tutor] replacing while loop Message-ID: <28664.62638.qm@web51608.mail.re2.yahoo.com> I've been reading 'Core Python Programming (2nd Edition)'. I have been given the following script: #!/usr/bin/env python 'makeTextFile.py -- create text file' import os # get filename while True: fname = raw_input('Enter file name: ') if os.path.exists(fname): print"*** ERROR: '%s' already exists" % fname else: break # get file content (text) lines all = [] print "\nEnter lines ('.' by itself to quit).\n" # loop until user terminates input while True: entry = raw_input('> ') if entry == '.': break else: all.append(entry) # write lines to file with NEWLINE line terminator fobj = open(fname, 'w') fobj.write('\n'.join(all)) fobj.close() print 'DONE!' I have been asked to replace this while loop with a try and except clause: while True: fname = raw_input('Enter file name: ') if os.path.exists(fname): print"*** ERROR: '%s' already exists" % fname else: break I'm not sure how to do this. I looked at the back of the book, and I don't see an exception that is raised when a previously existing file is found. Any hints? From steve at alchemy.com Sat Sep 8 07:51:32 2007 From: steve at alchemy.com (Steve Willoughby) Date: Fri, 07 Sep 2007 22:51:32 -0700 Subject: [Tutor] rewriting script In-Reply-To: <877291.75369.qm@web51610.mail.re2.yahoo.com> References: <877291.75369.qm@web51610.mail.re2.yahoo.com> Message-ID: <46E23864.5080501@alchemy.com> Christopher Spears wrote: > I have written a script that reads and displays text > files: > > #!/usr/bin/env python > > 'readTextFile.py -- read and display text file' > > import os > > # get filename > while True: > fname = raw_input('Enter file name: ') > print > if os.path.exists(fname): > fobj = open(fname, 'r') > for eachLine in fobj: > print eachLine, > fobj.close() You're closing the file after reading the first line. You want that fobj.close() line to be outside the for loop (outdent one level) From trey at opmstech.org Sat Sep 8 07:52:42 2007 From: trey at opmstech.org (Trey Keown) Date: Sat, 8 Sep 2007 00:52:42 -0500 (CDT) Subject: [Tutor] Undo/Redo in wxpython? Message-ID: <62340.68.191.136.241.1189230762.squirrel@webmail.opmstech.org> What is the proper way to undo/redo changes in a text box? I read somewhere that the default undo depth is 1. How could I change this to, say, about 35? Here's a snippet of my code- #!/usr/bin/python import wx import os ... ... ... class MainWin(wx.Frame): def __init__(self, parent, id, title): wx.Frame.__init__(self, parent, id, title, size=(850, 450)) ... ... ... #Program body section start self.code = wx.TextCtrl(self, ID_TEXTBOX, size=(200, 130), style=wx.TE_MULTILINE) ... ... ... app = MyApp(redirect=True, filename = "_error.log") app.MainLoop() Now, how would it be possible for me to do undo/redo for the "self.code" TextCtrl widget? Help is greatly appreciated. From alan.gauld at btinternet.com Sat Sep 8 09:19:47 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 8 Sep 2007 08:19:47 +0100 Subject: [Tutor] rewriting script References: <877291.75369.qm@web51610.mail.re2.yahoo.com> Message-ID: <fbtif3$1mk$1@sea.gmane.org> "Christopher Spears" <cspears2002 at yahoo.com> wrote >I have written a script that reads and displays text > files: > while True: > if os.path.exists(fname): > fobj = open(fname, 'r') > for eachLine in fobj: > print eachLine, > fobj.close() > However, whenever I run the script, I get this result: > for eachLine in fobj: > ValueError: I/O operation on closed file You are closing the file inside the for loop, before you finish processing it. That is one reason why iterating over the file like this is often more helpful: for line in open(fname): print line because that will automatically close the file after you are done iterating. 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 Sep 8 09:24:38 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 8 Sep 2007 08:24:38 +0100 Subject: [Tutor] Python scripting References: <46E232C5.2050302@gmail.com> Message-ID: <fbtio6$29k$1@sea.gmane.org> "Ryan" <silas428 at gmail.com> wrote >I am on a linux machine and I was wondering about python scripting. Python is usually installed on linux. Just type python at a shell prompt. > Mainly to get it up and running but also what can I do with > it etc. Any help would be appreciated, Thnx Python is probably installed or you can use your distros installer to get a package, eg rpm for it. So installation should be easy. Don't forget to get the documentation too, sometimes its a separate download on Linux. What you can do? It can replace a lot of shjell scripting for administrative tasks. It can create small tools, analyze text, or even create fiull blown applications.It depends on how skillful you become and how much time you have. Take a look on sourceforge for Python based projects. That should give you an idea of the potential. And visit the beginners pages of the Python web site for more info about Python and tutorial links to get you started. 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 Sep 8 09:31:42 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 8 Sep 2007 08:31:42 +0100 Subject: [Tutor] replacing while loop References: <28664.62638.qm@web51608.mail.re2.yahoo.com> Message-ID: <fbtj5d$34m$1@sea.gmane.org> "Christopher Spears" <cspears2002 at yahoo.com> wrote > I have been asked to replace this while loop with a > try and except clause: > > while True: > fname = raw_input('Enter file name: ') > if os.path.exists(fname): > print"*** ERROR: '%s' already exists" % fname > else: > break > > I'm not sure how to do this. I looked at the back of > the book, and I don't see an exception that is raised > when a previously existing file is found. Any hints? The loop simply detects if the file exists *or not* If the file does not exist you exit the loop. Can you find a way using try/except to detect if the file does not exist? That will replace the body of the while loop, I can't think of any way to replace the loop itself with try./except... And I agree this is not an obvious place to use try/except. Your earlier example is more typical. -- 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 Sep 8 09:38:08 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 8 Sep 2007 08:38:08 +0100 Subject: [Tutor] WxPython Splashscreen? References: <61555.68.191.136.241.1189212425.squirrel@webmail.opmstech.org> Message-ID: <fbtjhg$3qs$1@sea.gmane.org> "Trey Keown" <trey at opmstech.org> wrote > Does anyone know how to make a wxPython splashscreen? Using the wxSplashScreen widget? > not found any working examples. The wxPython book offers this: class SketchApp(wx.App): def OnInit(self): image = wx.image('splash.bmp', wx.BITMAP_TYPE_BMP) bmp = image.ConvertToBitmap() wx.SpashScreen(bmp,wx.SPLASH_NO_CENTER|wx.SPLAS_TIMEOUT,1000,None,-1) wx.Yield() frame = SketchFrame(None) etc... The book is invaluable for wxPython users. -- 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 Sep 8 09:50:40 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 8 Sep 2007 08:50:40 +0100 Subject: [Tutor] Undo/Redo in wxpython? References: <62340.68.191.136.241.1189230762.squirrel@webmail.opmstech.org> Message-ID: <fbtk8v$5ch$1@sea.gmane.org> "Trey Keown" <trey at opmstech.org> wrote > What is the proper way to undo/redo changes in a text box? I read > somewhere that the default undo depth is 1. How could I change this > to, > say, about 35? I dunno, its not in the book ;-) But just typing dir(TextCtrl) showed those two methods... Unfortunately there is no real help() info just tat they take *args and **kwargs... And trying it at the >>> prompt yields t.Redo(35) Traceback (most recent call last): File "<input>", line 1, in ? File "C:\Python24\Lib\site-packages\wx-2.8-msw-ansi\wx\_controls.py", line 1888, in Redo return _controls_.TextCtrl_Redo(*args, **kwargs) TypeError: TextCtrl_Redo() takes exactly one argument (2 given) So now you know where the code is and can go take a peek... Or it might be one for the wxPython mailing list? Alan G. From paul at alanweberassociates.com Sat Sep 8 11:31:38 2007 From: paul at alanweberassociates.com (Paul McGuire) Date: Sat, 8 Sep 2007 04:31:38 -0500 Subject: [Tutor] More class questions Message-ID: <008801c7f1fb$0ee432b0$6500a8c0@AWA2> Ara - I found your question about the Pyparsing-based adventure game that I wrote. You can find more info on this from the presentation I made at PyCon'06, (http://www.python.org/pycon/2006/papers/4/). This link opens up at the title page, there are navigation controls in the lower right corner of the screen if you move your mouse over them. This program uses the following classes: - Room - Item - Player - Command The Room and Item instances are created during the game setup. Each Room contains pointers to neighboring rooms to the north, south, east, and west. Rooms also have a list of items that are currently in the room. As the game ensues, items can be picked up and dropped, so this list will change over time. I guess you could change the room connections also - wouldn't be hard - perhaps as a result of using a special Item while in the Room. Items are fairly passive, free-standing objects, containing some attributes, and a possible useAction. They don't have much behavior, they don't know what room they are in, they can be picked up, dropped, and used, and they have a name that describes them when you look in a room, or list your player's inventory. Player is the "status" object of the game. Player has an inventory of Items, and has a reference to the Room the player is currently in. I think an easy mistake when writing a game is to make the Player status and attributes global variables. This will work okay, but by keeping this info in an object, the game could easily extend to having multiple players, just by adding a second instance, and adding support for the players to take turns giving commands. Command is the class that actually makes things happen. Command itself is an "abstract" class, that defines the basic form of what different commands can do, and how they are created. There are several subclasses of Command: - TakeCommand - DropCommand - InventoryCommand - UseCommand - LookCommand - DoorsCommand - MoveCommand - HelpCommand - QuitCommand Commands are created based on the input that the game player types in at the game prompt (this is where pyparsing comes in). The pyparsing grammar parses the input string, and if it is a valid command, the grammar's parse actions create the appropriate Command subclass. For instance, typing in "help" will create a HelpCommand instance. Typing in "take shovel" will create a TakeCommand, with the target object of "shovel". After the Command is created, it is executed against the Player object. The results of the Command can: - have the Player take something from the current Room - have the Player drop something in his inventory, and leave it in the current Room - list the Player's inventory - etc. The MoveCommand will move the player to an adjoining room. To tie it all together, the game engine runs in a basic loop: # create a player, let's call him Bob player = Player("Bob") # give Bob the sword for protection player.take( Item.items["sword"] ) # read commands, and then invoke them on Bob (and his surroundings) while not player.gameOver: cmdstr = raw_input(">> ") cmd = parser.parseCmd(cmdstr) if cmd is not None: cmd.command( player ) And that's it. All of the logic about the moving from room to room is captured in the N,S,E,W references between Room objects. Moving Bob from room to room is done by MoveCommands, as they are dynamically created based on user input. I hope that gives you a little more idea of how the pyparsing adventure game works. -- Paul From ca17005 at bellsouth.net Sun Sep 9 04:43:48 2007 From: ca17005 at bellsouth.net (ca17005 at bellsouth.net) Date: Sat, 8 Sep 2007 22:43:48 -0400 Subject: [Tutor] inserting csv file into a sqlite3 memory connected table Message-ID: <20070909024355.6F4221E400D@bag.python.org> I am just getting started been though some tutorials for python and wx. I am basically just a visual basic person trying to learn python. Anyway I have spent hours experimenting with CSV and sqllite3 tutorial samples and misc snippets, Does anyone have any code samples that might get me going? From silas428 at gmail.com Sun Sep 9 21:26:56 2007 From: silas428 at gmail.com (Ryan) Date: Sun, 09 Sep 2007 12:26:56 -0700 Subject: [Tutor] Apache, CGI-BIN, Python Message-ID: <46E44900.6050003@gmail.com> I am running a Linux box and cannot find my Apache cgi-bin to put some python scripts in. I know I probably have to create one but don't know where and how. Also on my windows machine,where I do have the bin, and normally everything works fine except: #!c:/Python25/python import cgi reshtml = """Content-type: text/html\n\n" <html> <head><title>Hello Python</title></head> <body> <h1>Welcome To A Python Script!</h1> </body> </html>""" form = cgi.FieldStorage() #This is where everything goes wrong #I get error messages for either the lastname line or firstname lastname = form['lastname'].value firstname =form['firstname'].value message = firstname + " " + lastname print reshtml % message From steve at alchemy.com Mon Sep 10 00:02:19 2007 From: steve at alchemy.com (Steve Willoughby) Date: Sun, 09 Sep 2007 15:02:19 -0700 Subject: [Tutor] Apache, CGI-BIN, Python In-Reply-To: <46E44900.6050003@gmail.com> References: <46E44900.6050003@gmail.com> Message-ID: <46E46D6B.6030007@alchemy.com> Ryan wrote: > I am running a Linux box and cannot find my Apache cgi-bin to put some > python scripts in. I know I probably have to create one but don't know > where and how. On Linux under Apache 2.2, I've seen it in /usr/lib/cgi-bin which always struck me as weird, but there you go. On BSD, it tends to live in /var/www/cgi-bin. YMMV. > > Also on my windows machine,where I do have the bin, and normally > everything works fine except: > > #!c:/Python25/python > import cgi > > reshtml = """Content-type: text/html\n\n" > <html> > <head><title>Hello Python</title></head> > > <body> > <h1>Welcome To A Python Script!</h1> > </body> > </html>""" > > form = cgi.FieldStorage() > > #This is where everything goes wrong > #I get error messages for either the lastname line or firstname > > lastname = form['lastname'].value > firstname =form['firstname'].value What error message do you get? I'd recommend, actually, using form.getfirst('lastname') instead. It's more robust in case there are multiple occurrences of a field on the form the user submits. You can also check to see if the form even has the fields you're trying to read, but again, knowing what error message you're getting would be very helpful to point you in the right direction on this. > message = firstname + " " + lastname > print reshtml % message I think you need a %s or something in the reshtml string, too. From spmcinerney at hotmail.com Mon Sep 10 02:31:19 2007 From: spmcinerney at hotmail.com (Stephen McInerney) Date: Sun, 09 Sep 2007 17:31:19 -0700 Subject: [Tutor] Suggested books for Agile Programming & Testing? Message-ID: <BAY111-F3685BD79DCC7E60F354F80A0C00@phx.gbl> Can anyone recommend me the best single must-read book for Agile Programming? Also Agile Testing. (If they compare Agile in general to the other methodologies, that would be great) Also, can anyone comment on the limits or caveats of agile development? Thanks, Stephen _________________________________________________________________ Kick back and relax with hot games and cool activities at the Messenger Caf?. http://www.cafemessenger.com?ocid=TXT_TAGHM_SeptHMtagline1 From lists at mostrom.pp.se Mon Sep 10 10:00:26 2007 From: lists at mostrom.pp.se (=?UTF-8?Q?Jan_Erik_Mostr=C3=B6?= =?UTF-8?Q?m?=) Date: Mon, 10 Sep 2007 10:00:26 +0200 Subject: [Tutor] Apache, CGI-BIN, Python Message-ID: <r219-1049-i386-2A052955722745849BE4647997537DD9@infinitum.cs.umu.se> Ryan <silas428 at gmail.com> 07-09-09 12:26 >I am running a Linux box and cannot find my Apache cgi-bin to >put some python scripts in. I know I probably have to create >one but don't know where and how. Look in Apaches config file, you should find something like this ScriptAlias /cgi-bin/ "/Library/WebServer/CGI-Executables/" this is from my Mac, on my debian machine it looks like this ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/ And you can of course have different catalogs for different virtual domains jem -- Jan Erik Mostr?m, www.mostrom.pp.se From vishnu at montalvosystems.com Mon Sep 10 12:40:46 2007 From: vishnu at montalvosystems.com (Vishnu Mohan) Date: Mon, 10 Sep 2007 16:10:46 +0530 Subject: [Tutor] Problem with while loop In-Reply-To: <ad53d62e0709070525t3ddc022bq786ff541380f3b9a@mail.gmail.com> References: <ad53d62e0709070441x5a0b6d78pd6aec129e46190fd@mail.gmail.com> <d9e7db140709070454q27a93d88k767a9ef671b25e9c@mail.gmail.com> <ad53d62e0709070525t3ddc022bq786ff541380f3b9a@mail.gmail.com> Message-ID: <46E51F2E.2070602@montalvosystems.com> > Now I just need to figure out how to only get 4 digit pin numbers :) > Use regular expressions.... The following is the code with re. from random import randint import re counter = 0 pinPattern = re.compile(r'^\d{4}$') howmany = raw_input( "How many: " ) if pinPattern.match(howmany): while counter < int(howmany): pin = randint(0000,9999) print pin counter += 1 else: print "%s is not valid 4 digit integer"%howmany -vishnuMohan From connorsml at gmail.com Mon Sep 10 13:28:47 2007 From: connorsml at gmail.com (Michael Connors) Date: Mon, 10 Sep 2007 12:28:47 +0100 Subject: [Tutor] Problem with while loop In-Reply-To: <46E51F2E.2070602@montalvosystems.com> References: <ad53d62e0709070441x5a0b6d78pd6aec129e46190fd@mail.gmail.com> <d9e7db140709070454q27a93d88k767a9ef671b25e9c@mail.gmail.com> <ad53d62e0709070525t3ddc022bq786ff541380f3b9a@mail.gmail.com> <46E51F2E.2070602@montalvosystems.com> Message-ID: <d9e7db140709100428k72f56381g14cc44065c23cc63@mail.gmail.com> Hi, I would do it as follows, adding 0s to front to make them valid PINs. while counter < howmany: pin = randint(0000,9999) print "%04i" % (pin) counter += 1 On 10/09/2007, Vishnu Mohan <vishnu at montalvosystems.com> wrote: > > > > Now I just need to figure out how to only get 4 digit pin numbers :) > > > Use regular expressions.... > The following is the code with re. > > > from random import randint > import re > > counter = 0 > pinPattern = re.compile(r'^\d{4}$') > howmany = raw_input( "How many: " ) > if pinPattern.match(howmany): > while counter < int(howmany): > pin = randint(0000,9999) > print pin > counter += 1 > else: > print "%s is not valid 4 digit integer"%howmany > > > -vishnuMohan > -- Michael Connors -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070910/d71b35db/attachment.htm From pilyad at gmail.com Mon Sep 10 12:51:16 2007 From: pilyad at gmail.com (Arvind Deshpande) Date: Mon, 10 Sep 2007 16:21:16 +0530 Subject: [Tutor] replacing while loop In-Reply-To: <fbtj5d$34m$1@sea.gmane.org> References: <28664.62638.qm@web51608.mail.re2.yahoo.com> <fbtj5d$34m$1@sea.gmane.org> Message-ID: <5d2af29a0709100351x7bbde0f4q8f7b83a2229e4f56@mail.gmail.com> Is this what you are looking for? #!/usr/bin/python 'makeTextFile.py -- create text file' import os # get filename #while True: # fname = raw_input('Enter file name: ') # if os.path.exists(fname): # print"*** ERROR: '%s' already exists" % fname # else: # break while True: fname = raw_input('Enter file name: ') try: fobj = open(fname, 'r') except: break # get file content (text) lines all = [] print "\nEnter lines ('.' by itself to quit).\n" # loop until user terminates input while True: entry = raw_input('> ') if entry == '.': break else: all.append(entry) # write lines to file with NEWLINE line terminator fobj = open(fname, 'w') fobj.write('\n'.join(all)) fobj.close() print 'DONE!' -- Arvind Deshpande On 9/8/07, Alan Gauld <alan.gauld at btinternet.com> wrote: > > "Christopher Spears" <cspears2002 at yahoo.com> wrote > > > I have been asked to replace this while loop with a > > try and except clause: > > > > while True: > > fname = raw_input('Enter file name: ') > > if os.path.exists(fname): > > print"*** ERROR: '%s' already exists" % fname > > else: > > break > > > > I'm not sure how to do this. I looked at the back of > > the book, and I don't see an exception that is raised > > when a previously existing file is found. Any hints? > > The loop simply detects if the file exists *or not* > If the file does not exist you exit the loop. > Can you find a way using try/except to detect > if the file does not exist? > > That will replace the body of the while loop, > I can't think of any way to replace the loop itself > with try./except... > > And I agree this is not an obvious place to use > try/except. Your earlier example is more typical. > > -- > 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/20070910/517b0b39/attachment-0001.htm From sacharook at hotmail.co.uk Mon Sep 10 13:29:24 2007 From: sacharook at hotmail.co.uk (sacha rook) Date: Mon, 10 Sep 2007 12:29:24 +0100 Subject: [Tutor] Livewires Message-ID: <BAY111-W4C4ABD47B42DBA13A2AC6F3C00@phx.gbl> Hi all just learning python really and been using the livewires tutorial / worksheets to get some experience. I have hit an issue which is just my lack of understanding around looping concepts and execution. My issue: in worksheet 5-robots.pdf attached, page 4 the challenge "Challenge: Write a loop that makes the circle move smoothly from (0,0) to (640,480): in other words, from the bottom leftto the top right of the screen." this has got me a bit stumped because its an (x,y) co-ordinate pair that I want to update. I think in a loop i need to draw a circle, move a circle, remove the circle. I thought I needed to for loops to iterate through two ranges but this is wrong, here is my code though! from livewires import *begin_graphics() allow_moveables()x=range(10,640,10)y=range(10,480,10) for xco in x: for yco in y: c = circle(xco,yco,5) move_to(c, xco,yco)# remove_from_screen(c) /*commented this out to see output on graphics window */end_graphics() Can anyone look at the worksheet challenge and my poor code and show me the error of my ways? :) I appreciate it may be my inexperience in program flow/logic which is the problem also, I don't my help or suggestion to improve in any area. Thanks for your help in advance Sacha _________________________________________________________________ The next generation of MSN Hotmail has arrived - Windows Live Hotmail http://www.newhotmail.co.uk -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070910/9f0f42b4/attachment-0001.htm -------------- next part -------------- A non-text attachment was scrubbed... Name: 5-robots.pdf Type: application/pdf Size: 89940 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20070910/9f0f42b4/attachment-0001.pdf From Dean.Gardner at barco.com Mon Sep 10 14:55:39 2007 From: Dean.Gardner at barco.com (Gardner, Dean) Date: Mon, 10 Sep 2007 14:55:39 +0200 Subject: [Tutor] Printing HTML files Message-ID: <ED2EA636E2C9744A96B417491D4793BBFF9BDE@KUUMEX03.barco.com> Hi I am currently trying to print out a html file that is essentially a summary table and I am running into problems. From the link below it seems that the method I am using to print the table doesn't handle column width and wrapping but confusingly we use a similar method elsewhere in the code and it works fine. This is the summary builder class TestingSummary: def __init__(self,records): self.records = records def splitRecordAndBuildSummaryText(self): summary_dict={} test_fields=[] keys=[] fields = ["TestedDate:","TestId:","Branch:","Version:","SpecId:","PassOrFail:"] records = self.records.split("\n\n") for record in records: record=record.split("\n") for item in record: if "TestId" in item: testid=record.pop(1) testid = testid.replace("TestId:","") for field in record: for item in fields: #print item field = field.replace(item,"") test_fields.append(field) summary_dict[testid]=test_fields test_fields = [] # print summary_dict summary = self.buildHtmlSummaryPage(summary_dict) return summary def buildHtmlSummaryPage(self,dict_of_summary): #print list_of_ids test_summary_details="" for key, value in dict_of_summary.items(): #print value #print details test_summary_details+="""<tr><td width="11%%">%s</td><td width="18%%">%s</td><td width="12%%">%s</td><td width="29%%">%s</td></tr>\n""" % (key,value[3],value[-1],"".join(value[1]+value[2])) summary = "".join(["""<html><head><title></title></head><body><table border="0" width="88%">\n""", """<tr><td width="24%"><b><font face="Arial">Testing Summary</font></b></td><td width="31%"> </td><td width="26%"> </td></tr>\n""", """<tr><td width="24%"><b><font face="Arial Black">Tested by:</font></b></td><td width="31%"> </td>\n""", """<td width="26%"><b><font face="Arial Black">Machine Name:</font></b> </td></tr>\n""", """<tr><td width="24%"> </td><td width="31%"> </td><td width="26%"> </td></tr>\n""", """<tr><td width="24%"> </td><td width="31%"> </td><td width="26%"> </td></tr>\n""", """<tr><td width="11%"><b><u><font face="Arial">TestID</font></u></b></td><td width="18%"><b><u><font face="Arial">Specification</font></u></b></td>\n""", """<td width="12%"><b><u><font face="Arial">Result</font></u></b></td><td width="39%"><b><u><font face="Arial">BuildID</font></u></b></td></tr><tr>\n"""]) summary+=test_summary_details summary+="</body></html>" return summary and the mechanism for printing def printSummary(self,summary): print_dialog = wx.PrintDialog(self) if print_dialog.ShowModal() == wx.ID_CANCEL: return print_dialog_data = print_dialog.GetPrintDialogData() printer = wx.Printer(print_dialog_data) printout = wx.html.HtmlPrintout("Printing Test Summary") # margins (top, bottom, left, right) printout.SetMargins(15, 15, 20, 20) #REMOVE #-----This was for testing purposes only htmlOutput = open("TestingSummary.html","w") htmlOutput.write(summary) htmlOutput.close() #------------------------------------------------- printout.SetHtmlText(summary) printout.SetFooter(self.HtmlFooterForPrint(1, 1)) printer.Print(self, printout, False) When I save the file as html the browser will open it fine and it is I expect but if I print it I end up with Testing Summary Tested by: Machine Name: TestIDSpecificationResultBuildID 000003 -0000-0009 Pass 0000 1111 000002 Specification-0000-0009 Pass 0000 1111 000001 Specification-0000-0009 Pass 0000 1111 http://archives.devshed.com/forums/python-122/printing-problem-1843805.h tml Am I doing something silly? Thanks Dean Gardner DISCLAIMER: Unless indicated otherwise, the information contained in this message is privileged and confidential, and is intended only for the use of the addressee(s) named above and others who have been specifically authorized to receive it. If you are not the intended recipient, you are hereby notified that any dissemination, distribution or copying of this message and/or attachments is strictly prohibited. The company accepts no liability for any damage caused by any virus transmitted by this email. Furthermore, the company does not warrant a proper and complete transmission of this information, nor does it accept liability for any delays. If you have received this message in error, please contact the sender and delete the message. Thank you. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070910/e445bd08/attachment-0001.htm From christopher.henk at allisontransmission.com Mon Sep 10 15:33:39 2007 From: christopher.henk at allisontransmission.com (christopher.henk at allisontransmission.com) Date: Mon, 10 Sep 2007 09:33:39 -0400 Subject: [Tutor] Livewires In-Reply-To: <BAY111-W4C4ABD47B42DBA13A2AC6F3C00@phx.gbl> Message-ID: <OF6DC14350.68314EB7-ON85257352.00491D97-85257352.004A7E2C@gm.com> tutor-bounces at python.org wrote on 09/10/2007 07:29:24 AM: > Hi all > > just learning python really and been using the livewires tutorial / worksheets to get some experience. > > I have hit an issue which is just my lack of understanding around looping concepts and execution. > > My issue: > > in worksheet 5-robots.pdf attached, page 4 the challenge > > "Challenge: Write a loop that makes the circle move smoothly from (0,0) to (640,480): in other words, from the bottom left > to the top right of the screen." > > this has got me a bit stumped because its an (x,y) co-ordinate pair that I want to update. > I think in a loop i need to draw a circle, move a circle, remove the circle. > > I thought I needed to for loops to iterate through two ranges but this is wrong, here is my code though! > > from livewires import * > begin_graphics() > > allow_moveables() > x=range(10,640,10) > y=range(10,480,10) > for xco in x: > for yco in y: > c = circle(xco,yco,5) > move_to(c, xco,yco) > # remove_from_screen(c) /*commented this out to see output on graphics window */ > end_graphics() > If I understand the requirements correctly: you are moving along the diagonal of the map. So say 100 time steps to move the distance. time step: 0 position: (0,0) time step: 1 position: (64,48) time step: 2 position: (128,96) ... so the new x and y move together with a different delta so that they reach their max at the same time. Your only loop would be what time step you are on. timesteps=100 x,y =0,0 deltax=640/timesteps deltay=480/timesteps for time in range (timesteps): c=circle(x,y,5) x+=deltax y+=deltay move_to(c,x,y) remove_from_screen(c) I would think that would do the trick. But I haven't had any coffee yet this morning, so if I missed something, let me know. Chris -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070910/d2da35b1/attachment.htm From tmikk at umn.edu Mon Sep 10 17:33:47 2007 From: tmikk at umn.edu (Tonu Mikk) Date: Mon, 10 Sep 2007 10:33:47 -0500 Subject: [Tutor] Livewires In-Reply-To: <BAY111-W4C4ABD47B42DBA13A2AC6F3C00@phx.gbl> References: <BAY111-W4C4ABD47B42DBA13A2AC6F3C00@phx.gbl> Message-ID: <46E563DA.4090106@umn.edu> Hi Sacha, I am very much a beginner to Python myself, but I tried my hand on the Livewires modules. Here is how I solved the challenge. from livewires import * begin_graphics() allow_moveables() x=0 y=0 c = circle(x, y,5) while x < 640: x=x+5 y=y+3.822 move_to (c, x, y) time.sleep(0.1) Tonu sacha rook wrote: > Hi all > > just learning python really and been using the livewires tutorial / > worksheets to get some experience. > > I have hit an issue which is just my lack of understanding around > looping concepts and execution. > > My issue: > > in worksheet 5-robots.pdf attached, page 4 the challenge > > "Challenge: Write a loop that makes the circle move smoothly from > (0,0) to (640,480): in other words, from the bottom left > to the top right of the screen." > > this has got me a bit stumped because its an (x,y) co-ordinate pair > that I want to update. > I think in a loop i need to draw a circle, move a circle, remove the > circle. > > I thought I needed to for loops to iterate through two ranges but this > is wrong, here is my code though! > > from livewires import * > begin_graphics() > > allow_moveables() > x=range(10,640,10) > y=range(10,480,10) > for xco in x: > for yco in y: > c = circle(xco,yco,5) > move_to(c, xco,yco) > # remove_from_screen(c) /*commented this out to see output on > graphics window */ > end_graphics() > > Can anyone look at the worksheet challenge and my poor code and show > me the error of my ways? :) > I appreciate it may be my inexperience in program flow/logic which is > the problem also, I don't my help or suggestion to improve in any area. > Thanks for your help in advance > Sacha > > > > ------------------------------------------------------------------------ > Play Movie Mash-up and win BIG prizes! <https://www.moviemashup.co.uk> > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From lawrence.barrott at btinternet.com Mon Sep 10 22:02:46 2007 From: lawrence.barrott at btinternet.com (Lawrence Barrott) Date: Mon, 10 Sep 2007 21:02:46 +0100 Subject: [Tutor] Running other files Message-ID: <83F34925E6FC4A0E95539E3C3387DDEF@PC3> is it possible to run other non-python files using python such as .exe or other files. Thanks, Lawrence -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070910/970b09af/attachment.htm From rikard.bosnjakovic at gmail.com Mon Sep 10 23:24:52 2007 From: rikard.bosnjakovic at gmail.com (Rikard Bosnjakovic) Date: Mon, 10 Sep 2007 23:24:52 +0200 Subject: [Tutor] Running other files In-Reply-To: <83F34925E6FC4A0E95539E3C3387DDEF@PC3> References: <83F34925E6FC4A0E95539E3C3387DDEF@PC3> Message-ID: <d9e88eaf0709101424j755f8047g1c58f7ae0bd7d19@mail.gmail.com> On 10/09/2007, Lawrence Barrott <lawrence.barrott at btinternet.com> wrote: > is it possible to run other non-python files using python such as .exe or > other files. Have a look at os.system(). -- - Rikard - http://bos.hack.org/cv/ From dos.fool at gmail.com Tue Sep 11 00:28:23 2007 From: dos.fool at gmail.com (max baseman) Date: Mon, 10 Sep 2007 16:28:23 -0600 Subject: [Tutor] making math problems mmmm fun Message-ID: <1C99EFF7-A12C-4DEF-8595-B42DA3E3F103@gmail.com> hello all this is a homework in math i dont need to program it but i would like to :) so like any other time pleas dont just give a answer tutorials or a explanation. i dont like to use script something i dont understand :) thanks basically the problem is to find a bunch of ways to put 1,2,3,4,5 into different math problems to that equal 1-25, i haven't spent to much time thinking about how to do this but i cant think of a way to do it it without writing making the program rather long here is the page from the book for the rules i will be working on this for the next week or so thanks for any help :) . you may use any of the four basic arithmetic operations- addition, subtraction, multiplication, and division (according to the order of operations rules). for example, 2+1x3-4 is a 1-2-3-4 expression for the number 1. . you may use exponents. for example, 2? - 4 - 1 is a 1234 expression for the number 3 . you may use radicals for EX: ?4x2+1 is equal to 3 so 3+?4x2+1 is a 1234 expression for 6 . you may use factorials for EX: 4! means 4x3x2x1 so 3+4!+1-2 is a 1234 expression for the number 26 . you may juxtapose two or more digits (that is put them next to each other) to form a number such as 12. for example 43-12 is a 1234 expression for 31 . you may use parentheses and brackets to change the meaning of a expression for example according to the rules of order of operations 1 +4x3? is a 1234 expression for 37. you can add parentheses and brackets to get [(1+4)x3]? which is a 1234 expression for 225 . must use 1,2,3,4 exactly once thanks for the help ill post if i find anything From dos.fool at gmail.com Tue Sep 11 00:22:06 2007 From: dos.fool at gmail.com (max baseman) Date: Mon, 10 Sep 2007 16:22:06 -0600 Subject: [Tutor] making math problems mmmm fun Message-ID: <4F76223C-4540-4ECC-BB9D-D143BBD2ED86@gmail.com> hello all this is a homework in math i dont need to program it but i would like to :) so like any other time pleas dont just give a answer tutorials or a explanation. i dont like to use script something i dont understand :) thanks basically the problem is to find a bunch of ways to put 1,2,3,4,5 into different math problems to that equal 1-25, i haven't spent to much time thinking about how to do this but i cant think of a way to do it it without writing making the program rather long here is the page from the book for the rules i will be working on this for the next week or so thanks for any help :) . you may use any of the four basic arithmetic operations- addition, subtraction, multiplication, and division (according to the order of operations rules). for example, 2+1x3-4 is a 1-2-3-4 expression for the number 1. . you may use exponents. for example, 2? - 4 - 1 is a 1234 expression for the number 3 . you may use radicals for EX: ?4x2+1 is equal to 3 so 3+?4x2+1 is a 1234 expression for 6 . you may use factorials for EX: 4! means 4x3x2x1 so 3+4!+1-2 is a 1234 expression for the number 26 . you may juxtapose two or more digits (that is put them next to each other) to form a number such as 12. for example 43-12 is a 1234 expression for 31 . you may use parentheses and brackets to change the meaning of a expression for example according to the rules of order of operations 1 +4x3? is a 1234 expression for 37. you can add parentheses and brackets to get [(1+4)x3]? which is a 1234 expression for 225 . must use 1,2,3,4 exactly once thanks for the help ill post if i find anything From abooth at stanford.edu Tue Sep 11 00:40:49 2007 From: abooth at stanford.edu (Ashley Booth) Date: Mon, 10 Sep 2007 15:40:49 -0700 Subject: [Tutor] Making a python script to feed files into another python script Message-ID: <e5210f1c0709101540w56e63c02pe0d0d23e6df28a84@mail.gmail.com> I am trying to create a script that will get files from a directory that the user specifies, then feeds the relevant input and output (which are input and output paths) into another python script whose path is also given by the user. I'm pretty lazy after all and I would rather spend my time making tools than doing the busy-work myself. So far I can get it to read the directory fine but it ends up just opening the script I want the files to be fed into instead of giving it the input and output to run and running it. Any ideas? Here is what I have so far: import sys, os indir = raw_input('input directory path ') # input directory script1 = os.system(raw_input('python script path ')) for j in os.listdir(indir): input = os.path.join(indir,j) output = os.path.join(indir,j.split('rovctd')[0]+'.txt') script1(input,output) If this is going to be too complicated, I would at least be happy with how to tack on the list directory stuff to then of the script1- it would not be a stand alone script but at least it would work. I tired to do that too but it only processed the first file in the directory instead of all of them. Thanks! From john at fouhy.net Tue Sep 11 01:11:00 2007 From: john at fouhy.net (John Fouhy) Date: Tue, 11 Sep 2007 11:11:00 +1200 Subject: [Tutor] Making a python script to feed files into another python script In-Reply-To: <e5210f1c0709101540w56e63c02pe0d0d23e6df28a84@mail.gmail.com> References: <e5210f1c0709101540w56e63c02pe0d0d23e6df28a84@mail.gmail.com> Message-ID: <5e58f2e40709101611q3898b627r73f5f260c38e21b2@mail.gmail.com> On 11/09/2007, Ashley Booth <abooth at stanford.edu> wrote: > I am trying to create a script that will get files from a directory > that the user specifies, then feeds the relevant input and output > (which are input and output paths) into another python script whose > path is also given by the user. I'm pretty lazy after all and I would > rather spend my time making tools than doing the busy-work myself. Hi Ashley, You've basically got two options: 1. You can build a command line and then use os.system to call it: script2 = raw_input('python script path:') input, output = # whatever os.system('python %s %s %s' % (script2, input, output)) 2. You can import your second script and call its main function directly. How well this works will depend on the structure of the second script. -- John. From wormwood_3 at yahoo.com Tue Sep 11 03:12:07 2007 From: wormwood_3 at yahoo.com (wormwood_3) Date: Mon, 10 Sep 2007 18:12:07 -0700 (PDT) Subject: [Tutor] Socket Timeout Handling Message-ID: <841606.52273.qm@web32408.mail.mud.yahoo.com> Have not gotten any responses on this, nor very much by way of searching, which is strange and a little disappointing for such a seemingly basic thing. (May just be too obvious of a thing, so no one wanted to post the solution:-). ) But, I did find a decent recipe on ASPN that serves the purpose, so I will share in case others needed to do the same check as I did. Before I needed to make the network call in my program, I have the following: if checkURL('http://www.google.com/'): networkup = True else: networkup = False if networkup: print "Internet connection seems to be up." else: print "Internet connection seems to be down. Please check it", print "and retry." sys.exit() Then I continue with my network calls. The function I use is: def checkURL(url): """For checking internet connection. Taken from recipe: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/101276""" try: p = urlparse(url) h = HTTP(p[1]) h.putrequest('HEAD', p[2]) h.endheaders() if h.getreply()[0] == 200: return 1 else: return 0 except: return 0 The nice thing about this check is that is just looks at the head of the site, and so is rather fast. One other consideration: While it is a rare day indeed that Google.com is ever down, to be even safer, would could check against several reliable sites, such as Amazon, Yahoo, w3c.org, etc. The status of each check could be put in a list, and if any list item was networkup, then the internet connection may be considered up. Hope someone finds this useful. -Sam _______________________ ----- Original Message ---- From: wormwood_3 <wormwood_3 at yahoo.com> To: Python Tutorlist <tutor at python.org> Sent: Thursday, September 6, 2007 4:46:08 PM Subject: Re: [Tutor] Socket Timeout Handling Since no one bit on this yet, let me simplify to the core issue I am having: What is the best practice for checking for network connectivity errors when making network calls? Is it better to wrap the functions that make said calls in threads and time them? Or to use timeout variables for modules like socket? Something else? I found some good general info here: http://www.onlamp.com/pub/a/python/2003/11/06/python_nio.html But I have had a hard time finding info on network error handling specifically. Thoughts? ______________________________________ ----- Original Message ---- From: wormwood_3 <wormwood_3 at yahoo.com> To: Python Tutorlist <tutor at python.org> Sent: Thursday, September 6, 2007 9:40:21 AM Subject: [Tutor] Socket Timeout Handling I am trying to figure out the optimal way to make socket connections (INET) and check for timeouts. The socket module has settimeout(timeout) and setdefaulttimeout(timeout). However, so far as I can tell, these apply to socket objects. The type of socket connection I want to make is getfqdn(address). So I can set the default timeout for socket, but not a socket object (makes sense so far). I cannot use the getfqdn(address) method on a socket object, I have to use it on socket. This means (as I understand it thus far), that while I can set a timeout value for socket objects, this will not apply to when I use the getfqdn() method, which is where I need a timeout check! Some example code for the steps so far: >>> import socket >>> conn = socket.socket() >>> conn.setdefaulttimeout(2.0) Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: '_socketobject' object has no attribute 'setdefaulttimeout' >>> socket.setdefaulttimeout(2.0) >>> conn.getfqdn("64.33.212.2") Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: '_socketobject' object has no attribute 'getfqdn' >>> socket.getfqdn("64.33.212.2") '64-33-212-2.customers.pingtone.net' >>> # Disconnected network connection here ... >>> socket.getfqdn("64.33.212.2") '64.33.212.2' >>> # Reconnected network connection here >>> socket.getfqdn("64.33.212.2") '64-33-212-2.customers.pingtone.net' After I disconnected my network connection and called getfqdn(), it returned the IP address I called it with after about 25 seconds. So the default timeout was ignored? Is there some other way to call this function so that I can check for timeouts? Should I instead just put my network calls in a thread and see how long they take, stopping them after a certain period? Thanks for any help. -Sam _______________________________________________ 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 wormwood_3 at yahoo.com Tue Sep 11 03:16:04 2007 From: wormwood_3 at yahoo.com (wormwood_3) Date: Mon, 10 Sep 2007 18:16:04 -0700 (PDT) Subject: [Tutor] making math problems mmmm fun Message-ID: <824735.66478.qm@web32401.mail.mud.yahoo.com> Don't have any ideas to Pythonize this problem for you, but I must say that I hope this problem was listed in a chapter entitled "Cruel and Unusual"! -Sam ____________________________________ ----- Original Message ---- From: max baseman <dos.fool at gmail.com> To: tutor at python.org Sent: Monday, September 10, 2007 6:28:23 PM Subject: [Tutor] making math problems mmmm fun hello all this is a homework in math i dont need to program it but i would like to :) so like any other time pleas dont just give a answer tutorials or a explanation. i dont like to use script something i dont understand :) thanks basically the problem is to find a bunch of ways to put 1,2,3,4,5 into different math problems to that equal 1-25, i haven't spent to much time thinking about how to do this but i cant think of a way to do it it without writing making the program rather long here is the page from the book for the rules i will be working on this for the next week or so thanks for any help :) . you may use any of the four basic arithmetic operations- addition, subtraction, multiplication, and division (according to the order of operations rules). for example, 2+1x3-4 is a 1-2-3-4 expression for the number 1. . you may use exponents. for example, 2? - 4 - 1 is a 1234 expression for the number 3 . you may use radicals for EX: ?4x2+1 is equal to 3 so 3+?4x2+1 is a 1234 expression for 6 . you may use factorials for EX: 4! means 4x3x2x1 so 3+4!+1-2 is a 1234 expression for the number 26 . you may juxtapose two or more digits (that is put them next to each other) to form a number such as 12. for example 43-12 is a 1234 expression for 31 . you may use parentheses and brackets to change the meaning of a expression for example according to the rules of order of operations 1 +4x3? is a 1234 expression for 37. you can add parentheses and brackets to get [(1+4)x3]? which is a 1234 expression for 225 . must use 1,2,3,4 exactly once thanks for the help ill post if i find anything _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From wormwood_3 at yahoo.com Tue Sep 11 03:20:53 2007 From: wormwood_3 at yahoo.com (wormwood_3) Date: Mon, 10 Sep 2007 18:20:53 -0700 (PDT) Subject: [Tutor] Image Analysis Message-ID: <15059.1222.qm@web32403.mail.mud.yahoo.com> I have thought up a project for myself that is rather beyond my current knowledge, but I think it will be fun and very informative. I'll leave out the details right now, but the task that will be the hardest is that I need some way to analyze an image for color patterns. I would like to be able to load an image file of some format, and be able to determine what color the pixels are, in short. From this, I need to generate statistics, such as what color is most common, find patterns in the image, etc. If anyone knows ANYTHING about this sort of analysis in Python, or even any helpful tutorials on image analysis that are more general, I would greatly appreciate it. My only lead right now is PIL, and I am not sure if it will meet my needs. Thanks, Sam From dos.fool at gmail.com Tue Sep 11 04:40:26 2007 From: dos.fool at gmail.com (max baseman) Date: Mon, 10 Sep 2007 20:40:26 -0600 Subject: [Tutor] making math problems mmmm fun In-Reply-To: <824735.66478.qm@web32401.mail.mud.yahoo.com> References: <824735.66478.qm@web32401.mail.mud.yahoo.com> Message-ID: <D71EF62E-E8E5-43DA-9CC2-4C41A7A0BD49@gmail.com> haha :) yeah it's the new imp stuff i like parts of the idea but other parts i really dislike basically it TRIES to make math more interactive and world like i really enjoy how most of it is really programable stuff :) where compared to normal math books it's a bit harder to program just a problem instead of a story but imp needs help with it's grading and teaching the grading is terrible i can get a A as long as i can explain and know how my way of doing it wrong "works" but will fail if i just write the write answer without explanation i dont mind the explanations bit but that what i write matters more than if i can do the work is odd adn i just haven't learned anything new yet :) On Sep 10, 2007, at 7:16 PM, wormwood_3 wrote: > Don't have any ideas to Pythonize this problem for you, but I must > say that I hope this problem was listed in a chapter entitled > "Cruel and Unusual"! > > -Sam > ____________________________________ > ----- Original Message ---- > From: max baseman <dos.fool at gmail.com> > To: tutor at python.org > Sent: Monday, September 10, 2007 6:28:23 PM > Subject: [Tutor] making math problems mmmm fun > > hello all this is a homework in math i dont need to program it but i > would like to :) so like any other time pleas dont just give a > answer tutorials or a explanation. i dont like to use script > something i dont understand :) > > thanks > > basically the problem is to find a bunch of ways to put 1,2,3,4,5 > into different math problems to that equal 1-25, i haven't spent to > much time thinking about how to do this but i cant think of a way to > do it it without writing making the program rather long here is the > page from the book for the rules i will be working on this for the > next week or so thanks for any help :) > > > > > . you may use any of the four basic arithmetic operations- > addition, subtraction, multiplication, and division (according to the > order of operations rules). for example, 2+1x3-4 is a 1-2-3-4 > expression for the number 1. > > . you may use exponents. for example, 2? - 4 - 1 is a 1234 expression > for the number 3 > > . you may use radicals for EX: ?4x2+1 is equal to 3 so 3+?4x2+1 is > a 1234 expression for 6 > > . you may use factorials for EX: 4! means 4x3x2x1 so 3+4!+1-2 is a > 1234 expression for the number 26 > > > . you may juxtapose two or more digits (that is put them next to > each other) to form a number such as 12. for example 43-12 is a 1234 > expression for 31 > > . you may use parentheses and brackets to change the meaning of a > expression for example according to the rules of order of operations 1 > +4x3? is a 1234 expression for 37. you can add parentheses and > brackets to get [(1+4)x3]? which is a 1234 expression for 225 > > . must use 1,2,3,4 exactly once > > > > thanks for the help ill post if i find anything > _______________________________________________ > 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 john at fouhy.net Tue Sep 11 04:47:22 2007 From: john at fouhy.net (John Fouhy) Date: Tue, 11 Sep 2007 14:47:22 +1200 Subject: [Tutor] making math problems mmmm fun In-Reply-To: <4F76223C-4540-4ECC-BB9D-D143BBD2ED86@gmail.com> References: <4F76223C-4540-4ECC-BB9D-D143BBD2ED86@gmail.com> Message-ID: <5e58f2e40709101947k9ca36f4lab9529e2273b9e6a@mail.gmail.com> On 11/09/2007, max baseman <dos.fool at gmail.com> wrote: > basically the problem is to find a bunch of ways to put 1,2,3,4,5 > into different math problems to that equal 1-25, i haven't spent to > much time thinking about how to do this but i cant think of a way to > do it it without writing making the program rather long here is the > page from the book for the rules i will be working on this for the > next week or so thanks for any help :) I've seen this kind of problem before.. though not usually with quite as much freedom as this one :-) You could brute force it, by trying all possible combinations of numbers and operators. The only problem is that the freedom they give you means you get horrible combinatorial explosion. I'll give you my attempt at brute-force code. Basically, my thought process was: 1. Solve the problem for N digits by solving it for N-1 digits, then combining those solutions with the last remaining digit. 2. Because of non-commutivity and non-associativity, we need to pick do this for each possible digit we could remove, and for both directions. 3. If I stick to binary operators, I guarantee that the number of digits always reduces. So I will forget about factorial and square root for now. Anyway, here's my code. I'm happy to answer questions about it if you like. I guess I could be doing your homework for you, but only if you've got access to some pretty staunch hardware -- it's pretty snappy on [1, 2, 3], but if I try it on [1, 2, 3, 4] on my machine, python gets up to about 1.3GB memory usage before crashing with a MemoryError :-) ####### import operator binops = { 'add':operator.add, 'sub':operator.sub, 'mul':operator.mul, 'div':operator.truediv, 'pow':operator.pow, 'join':lambda x, y: int(str(x)+str(y)) } patterns = { 'add':'(%s) + (%s)', 'sub':'(%s) - (%s)', 'mul':'(%s) * (%s)', 'div':'(%s) / (%s)', 'pow':'(%s)^(%s)', 'join':'%s%s' } def combine(digits): """ digits :: set(int) output :: [ (value, expression) ] value :: int expression :: str -- string representation of math expression """ # We're going to solve this instance in terms of the solution # for a list with one fewer digit. # Because of non-commutativity, we have to do this twice for each # possible start digit. res = [] # Base case. if len(digits) == 1: return [(digit, str(digit)) for digit in digits] # Otherwise.. for digit in digits: remainder = digits - set([digit]) for val, exp in combine(remainder): for binop in binops: if binop == 'join': # Ensure we only join numbers, not expressions. try: int(exp) except ValueError: continue try: newval1 = binops[binop](digit, val) pattern1 = patterns[binop] % (str(digit), exp) res.append((newval1, pattern1)) except ZeroDivisionError: pass try: newval2 = binops[binop](val, digit) pattern2 = patterns[binop] % (exp, str(digit)) res.append((newval2, pattern2)) except ZeroDivisionError: pass return res if __name__ == '__main__': res = combine(set(range(1, 4))) From dos.fool at gmail.com Tue Sep 11 05:02:09 2007 From: dos.fool at gmail.com (max baseman) Date: Mon, 10 Sep 2007 21:02:09 -0600 Subject: [Tutor] making math problems mmmm fun In-Reply-To: <5e58f2e40709101947k9ca36f4lab9529e2273b9e6a@mail.gmail.com> References: <4F76223C-4540-4ECC-BB9D-D143BBD2ED86@gmail.com> <5e58f2e40709101947k9ca36f4lab9529e2273b9e6a@mail.gmail.com> Message-ID: <ED2070F5-FF83-4DA0-93B3-1480F87757AD@gmail.com> wow this is a bit over my range of knowledge im impressed :) ill be happy to look at it but i think i will see if i can end up writing my own :) worse case ill do it by hand will not take long hmm wow thanks :) On Sep 10, 2007, at 8:47 PM, John Fouhy wrote: > ####### > import operator > > binops = { 'add':operator.add, > 'sub':operator.sub, > 'mul':operator.mul, > 'div':operator.truediv, > 'pow':operator.pow, > 'join':lambda x, y: int(str(x)+str(y)) > } > > patterns = { 'add':'(%s) + (%s)', > 'sub':'(%s) - (%s)', > 'mul':'(%s) * (%s)', > 'div':'(%s) / (%s)', > 'pow':'(%s)^(%s)', > 'join':'%s%s' > } > > def combine(digits): > """ digits :: set(int) > > output :: [ (value, expression) ] > value :: int > expression :: str -- string representation of math expression > """ > > # We're going to solve this instance in terms of the solution > # for a list with one fewer digit. > > # Because of non-commutativity, we have to do this twice for each > # possible start digit. > > res = [] > > # Base case. > if len(digits) == 1: > return [(digit, str(digit)) for digit in digits] > > # Otherwise.. > for digit in digits: > remainder = digits - set([digit]) > > for val, exp in combine(remainder): > for binop in binops: > if binop == 'join': > # Ensure we only join numbers, not expressions. > try: > int(exp) > except ValueError: > continue > > try: > newval1 = binops[binop](digit, val) > pattern1 = patterns[binop] % (str(digit), exp) > res.append((newval1, pattern1)) > except ZeroDivisionError: > pass > > try: > newval2 = binops[binop](val, digit) > pattern2 = patterns[binop] % (exp, str(digit)) > res.append((newval2, pattern2)) > except ZeroDivisionError: > pass > > return res > > if __name__ == '__main__': > res = combine(set(range(1, 4))) -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070910/0e66d30b/attachment-0001.htm From alan.gauld at btinternet.com Sun Sep 9 16:15:03 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 9 Sep 2007 15:15:03 +0100 Subject: [Tutor] inserting csv file into a sqlite3 memory connected table References: <20070909024355.6F4221E400D@bag.python.org> Message-ID: <fc0v5o$363$1@sea.gmane.org> <ca17005 at bellsouth.net> wrote > I am basically just a visual basic person trying to learn python. > > Anyway I have spent hours experimenting with CSV and sqllite3 > tutorial samples and misc snippets, Does anyone have any > code samples that might get me going? Doing what? Where are you having problems? Most tutorials will have code samples and snippets but unless we know what you are trying to do or not understanding we can't be more precise than point you at what you have probavbly already found. My tutorial has a database topic that uses SQLite. I donlt have anything on CSV but the module does have reasonable documentation. But are you trying to store a CSV file content in your database? Or convert a data table to a CSV format? or use a CSV to traslate between databases? We need a more specific question to direct our responses to your needs. -- 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 Sep 9 23:38:37 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 9 Sep 2007 22:38:37 +0100 Subject: [Tutor] Apache, CGI-BIN, Python References: <46E44900.6050003@gmail.com> Message-ID: <fc1p5e$cdo$1@sea.gmane.org> "Ryan" <silas428 at gmail.com> wrote >I am running a Linux box and cannot find my Apache cgi-bin to put >some > python scripts in. I know I probably have to create one but don't > know > where and how. I think there are several places that you can create cgi-bin depending on how you configure apache. But the place I usually see it is directly under the apache root directory - ie the one that is equivalent to / in the url. > everything works fine except: > > form = cgi.FieldStorage() > > #This is where everything goes wrong > #I get error messages for either the lastname line or firstname Can you tell us a) exactly what error messages and b) How you are invoking the script - where are the values supposed to be coming from? > lastname = form['lastname'].value > firstname =form['firstname'].value > message = firstname + " " + lastname > print reshtml % message HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From timmichelsen at gmx-topmail.de Tue Sep 11 00:33:24 2007 From: timmichelsen at gmx-topmail.de (Tim Michelsen) Date: Tue, 11 Sep 2007 00:33:24 +0200 Subject: [Tutor] input file encoding Message-ID: <fc4gnk$ors$1@sea.gmane.org> Hello, I want to process some files encoded in latin-1 (iso-8859-1) in my python script that I write on Ubuntu which has UTF-8 as standard encoding. When I use the "print lines_in_myfile" is get some wired symbols. How shold I read those files in or convert their encoding to utf-8? Thanks in advance, Tim From kent37 at tds.net Mon Sep 10 03:15:56 2007 From: kent37 at tds.net (Kent Johnson) Date: Sun, 09 Sep 2007 21:15:56 -0400 Subject: [Tutor] Suggested books for Agile Programming & Testing? In-Reply-To: <BAY111-F3685BD79DCC7E60F354F80A0C00@phx.gbl> References: <BAY111-F3685BD79DCC7E60F354F80A0C00@phx.gbl> Message-ID: <46E49ACC.3010507@tds.net> Stephen McInerney wrote: > > Can anyone recommend me the best single must-read book for Agile > Programming? Quoting myself from the archives: I recommend Robert Martin's "Agile Software Development: Principles, Patterns, and Practices" http://www.objectmentor.com/resources/bookstore/books/AgileSoftwareDevelopmentPPP This is the best book I know for learning object-oriented design the way I do it ;) - a very agile, pragmatic approach. It shows you the nitty-gritty details of how to create classes as you develop a solution. Also a good introduction to the agile development style. Much of the content of the book is available as essays on the ObjectMentor website: http://w ww.objectmentor.com/resources/listArticles?key=author&author=Robert%20C.%20Martin ----------------------------------- Some of the highlights from my bookshelf: Martin, Agile Software Development http://www.objectmentor.com/resources/bookstore/books/AgileSoftwareDevelopmentPPP Fowler, Refactoring: Improving the Design of Existing Code http://martinfowler.com/books.html#refactoring Beck, Extreme Programming Explained http://www.amazon.com/exec/obidos/ASIN/0201616416/ref%3Dnosim/armaties/102-7636110-6481700 Kent From alan.gauld at btinternet.com Tue Sep 11 01:13:57 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 11 Sep 2007 00:13:57 +0100 Subject: [Tutor] Running other files References: <83F34925E6FC4A0E95539E3C3387DDEF@PC3> <d9e88eaf0709101424j755f8047g1c58f7ae0bd7d19@mail.gmail.com> Message-ID: <fc4j47$197$1@sea.gmane.org> "Rikard Bosnjakovic" <rikard.bosnjakovic at gmail.com> wrote >> is it possible to run other non-python files using python such as >> .exe or >> other files. > > Have a look at os.system(). Or the more recent subprocess module which supercedes os.system etc. 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 Sep 11 06:41:56 2007 From: brunson at brunson.com (Eric Brunson) Date: Mon, 10 Sep 2007 22:41:56 -0600 Subject: [Tutor] making math problems mmmm fun In-Reply-To: <D71EF62E-E8E5-43DA-9CC2-4C41A7A0BD49@gmail.com> References: <824735.66478.qm@web32401.mail.mud.yahoo.com> <D71EF62E-E8E5-43DA-9CC2-4C41A7A0BD49@gmail.com> Message-ID: <46E61C94.8000701@brunson.com> When you get done with this math problem you should consider a book on punctuation. Not using it makes your sentences run together and difficult to read. :-) Honestly, I just gave up after the first two lines. max baseman wrote: > haha :) yeah it's the new imp stuff i like parts of the idea but > other parts i really dislike basically it TRIES to make math more > interactive and world like i really enjoy how most of it is really > programable stuff :) where compared to normal math books it's a bit > harder to program just a problem instead of a story but imp needs > help with it's grading and teaching the grading is terrible i can get > a A as long as i can explain and know how my way of doing it wrong > "works" but will fail if i just write the write answer without > explanation i dont mind the explanations bit but that what i write > matters more than if i can do the work is odd > adn i just haven't learned anything new yet :) > > On Sep 10, 2007, at 7:16 PM, wormwood_3 wrote: > > >> Don't have any ideas to Pythonize this problem for you, but I must >> say that I hope this problem was listed in a chapter entitled >> "Cruel and Unusual"! >> >> -Sam >> ____________________________________ >> ----- Original Message ---- >> From: max baseman <dos.fool at gmail.com> >> To: tutor at python.org >> Sent: Monday, September 10, 2007 6:28:23 PM >> Subject: [Tutor] making math problems mmmm fun >> >> hello all this is a homework in math i dont need to program it but i >> would like to :) so like any other time pleas dont just give a >> answer tutorials or a explanation. i dont like to use script >> something i dont understand :) >> >> thanks >> >> basically the problem is to find a bunch of ways to put 1,2,3,4,5 >> into different math problems to that equal 1-25, i haven't spent to >> much time thinking about how to do this but i cant think of a way to >> do it it without writing making the program rather long here is the >> page from the book for the rules i will be working on this for the >> next week or so thanks for any help :) >> >> >> >> >> . you may use any of the four basic arithmetic operations- >> addition, subtraction, multiplication, and division (according to the >> order of operations rules). for example, 2+1x3-4 is a 1-2-3-4 >> expression for the number 1. >> >> . you may use exponents. for example, 2?? - 4 - 1 is a 1234 expression >> for the number 3 >> >> . you may use radicals for EX: ???4x2+1 is equal to 3 so 3+???4x2+1 is >> a 1234 expression for 6 >> >> . you may use factorials for EX: 4! means 4x3x2x1 so 3+4!+1-2 is a >> 1234 expression for the number 26 >> >> >> . you may juxtapose two or more digits (that is put them next to >> each other) to form a number such as 12. for example 43-12 is a 1234 >> expression for 31 >> >> . you may use parentheses and brackets to change the meaning of a >> expression for example according to the rules of order of operations 1 >> +4x3?? is a 1234 expression for 37. you can add parentheses and >> brackets to get [(1+4)x3]?? which is a 1234 expression for 225 >> >> . must use 1,2,3,4 exactly once >> >> >> >> thanks for the help ill post if i find anything >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> >> >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From brunson at brunson.com Tue Sep 11 06:43:38 2007 From: brunson at brunson.com (Eric Brunson) Date: Mon, 10 Sep 2007 22:43:38 -0600 Subject: [Tutor] Apache, CGI-BIN, Python In-Reply-To: <fc1p5e$cdo$1@sea.gmane.org> References: <46E44900.6050003@gmail.com> <fc1p5e$cdo$1@sea.gmane.org> Message-ID: <46E61CFA.4000901@brunson.com> Alan Gauld wrote: > "Ryan" <silas428 at gmail.com> wrote > > >> I am running a Linux box and cannot find my Apache cgi-bin to put >> some >> python scripts in. I know I probably have to create one but don't >> know >> where and how. >> > > I think there are several places that you can create cgi-bin depending > on how you configure apache. But the place I usually see it is > directly > under the apache root directory - ie the one that is equivalent to / > in > the url. > But, if you read the apache configuration files, it will tell you were it is. :-) > >> everything works fine except: >> >> form = cgi.FieldStorage() >> >> #This is where everything goes wrong >> #I get error messages for either the lastname line or firstname >> > > Can you tell us > a) exactly what error messages and > b) How you are invoking the script - where are the values > supposed to be coming from? > > >> lastname = form['lastname'].value >> firstname =form['firstname'].value >> message = firstname + " " + lastname >> print reshtml % message >> > > HTH, > > > From alan.gauld at btinternet.com Tue Sep 11 09:21:59 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 11 Sep 2007 08:21:59 +0100 Subject: [Tutor] Socket Timeout Handling References: <841606.52273.qm@web32408.mail.mud.yahoo.com> Message-ID: <fc5fna$d69$1@sea.gmane.org> "wormwood_3" <wormwood_3 at yahoo.com> wrote > Have not gotten any responses on this, I did send you a response and it is listed on the gmane archive so if you didn't see it something has gone adrift somewhere. > But, I did find a decent recipe on ASPN that serves the purpose, The solution you posted seems to bear no resemblence to the problem you posted? How does this relate to setting socket timeouts or using getfqdn()? This solution simply does a ping on a site to see if the network is available. If you had asked how to check if you were connected to the network you likely would have gotten several responses! As ever, if you ask the wrong question you will get the wrong answer! :-) > def checkURL(url): > """For checking internet connection. Taken from recipe: > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/101276""" > try: > p = urlparse(url) > h = HTTP(p[1]) > h.putrequest('HEAD', p[2]) > h.endheaders() > if h.getreply()[0] == 200: return 1 > else: return 0 > except: > return 0 > > The nice thing about this check is that is just looks at the head of > the site, and so is rather fast. > I am trying to figure out the optimal way to make socket connections > (INET) and check for timeouts. The socket module has > settimeout(timeout) > and setdefaulttimeout(timeout). However, so far as I can tell, these > apply to socket objects. The type of socket connection I want to > make is getfqdn(address). So I can set the default timeout for > socket, > but not a socket object (makes sense so far). I cannot use the > getfqdn(address) method on a socket object, I have to use it on > socket. This means (as I understand it thus far), that while I can > set a timeout value for socket objects, this will not apply to when > I use the getfqdn() method, which is where I need a timeout check! -- 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 Sep 11 09:37:35 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 11 Sep 2007 08:37:35 +0100 Subject: [Tutor] making math problems mmmm fun References: <1C99EFF7-A12C-4DEF-8595-B42DA3E3F103@gmail.com> Message-ID: <fc5gki$g59$1@sea.gmane.org> "max baseman" <dos.fool at gmail.com> wrote > basically the problem is to find a bunch of ways to put 1,2,3,4,5 > into different math problems to that equal 1-25, i haven't spent to > much time thinking about how to do this but i cant think of a way to > do it it without writing making the program rather long This is quite a difficult problem to program (cue someone with a really short solution! :-) Its similar in concept to decyphering codes, there are lots of possible permutations but only a few are viable. There are lots of rules too. The normal approach is to search for inconsistencies but because its math and operators can cancel each other out it will be hard to define consistency rules. If you only had the 4 operators or you weren't allowed to use parentheses it would be fairly doable but by adding parentheses and operators like factorials and finally juxtaposition I'm not sure I'd like to try coding it! I suspect this might be the kind of pattern spotting problem better suited to the human brain! Computers are best with large quantities of data composed in finite ways, brains are best at small data sets combined in many combinations. Alan G. > page from the book for the rules i will be working on this for the > next week or so thanks for any help :) > > . you may use any of the four basic arithmetic operations- > addition, subtraction, multiplication, and division (according to > the > order of operations rules). for example, 2+1x3-4 is a 1-2-3-4 > expression for the number 1. > > . you may use exponents. for example, 2? - 4 - 1 is a 1234 > expression > for the number 3 > > . you may use radicals for EX: ?4x2+1 is equal to 3 so 3+?4x2+1 is > a 1234 expression for 6 > > . you may use factorials for EX: 4! means 4x3x2x1 so 3+4!+1-2 is a > 1234 expression for the number 26 > > > . you may juxtapose two or more digits (that is put them next to > each other) to form a number such as 12. for example 43-12 is a 1234 > expression for 31 > > . you may use parentheses and brackets to change the meaning of a > expression for example according to the rules of order of operations > 1 > +4x3? is a 1234 expression for 37. you can add parentheses and > brackets to get [(1+4)x3]? which is a 1234 expression for 225 > > . must use 1,2,3,4 exactly once > > > > thanks for the help ill post if i find anything > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at btinternet.com Tue Sep 11 09:47:41 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 11 Sep 2007 08:47:41 +0100 Subject: [Tutor] Making a python script to feed files into another pythonscript References: <e5210f1c0709101540w56e63c02pe0d0d23e6df28a84@mail.gmail.com> Message-ID: <fc5h7f$i5p$1@sea.gmane.org> "Ashley Booth" <abooth at stanford.edu> wrote > So far I can get it to read the directory fine but it ends up just > opening the script I want the files to be fed into instead of giving > it the input and output to run and running it. Any ideas? > > Here is what I have so far: > > import sys, os > > indir = raw_input('input directory path ') # input directory > script1 = os.system(raw_input('python script path ')) os.system only returnms the error code of the operation not the results, so script1 will usually contain 0 (for success). You need to look at the subprocess module and the examples of replacing popen. Specifically using the communicate() method of Popen. > for j in os.listdir(indir): > input = os.path.join(indir,j) > output = os.path.join(indir,j.split('rovctd')[0]+'.txt') You might find os.path.basename more reliable here. > script1(input,output) This won't work see above. > If this is going to be too complicated, No, this is exactly the kind of thing Python is good at. > I would at least be happy with how to tack on the list > directory stuff to then of the script1- it would not be a > stand alone script but at least it would work. Sorry you lost me there. Which script? The one above or the ones you are trying to execute? -- 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 Sep 11 09:54:04 2007 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Tue, 11 Sep 2007 07:54:04 +0000 (GMT) Subject: [Tutor] Fw: Apache, CGI-BIN, Python Message-ID: <767740.51285.qm@web86109.mail.ird.yahoo.com> Forwarding to the list.... NB Use Reply-All when replying to the tutor list. Alan G. ----- Forwarded Message ---- From: Ryan <silas428 at gmail.com> To: Alan Gauld <alan.gauld at btinternet.com> Sent: Tuesday, 11 September, 2007 5:32:33 AM Subject: Re: [Tutor] Apache, CGI-BIN, Python Alan Gauld wrote: > "Ryan" <silas428 at gmail.com> wrote > > >> I am running a Linux box and cannot find my Apache cgi-bin to put >> some >> python scripts in. I know I probably have to create one but don't >> know >> where and how. >> > > I think there are several places that you can create cgi-bin depending > on how you configure apache. But the place I usually see it is > directly > under the apache root directory - ie the one that is equivalent to / > in > the url. > > >> everything works fine except: >> >> form = cgi.FieldStorage() >> >> #This is where everything goes wrong >> #I get error messages for either the lastname line or firstname >> > > Can you tell us > a) exactly what error messages and > b) How you are invoking the script - where are the values > supposed to be coming from? > > >> lastname = form['lastname'].value >> firstname =form['firstname'].value >> message = firstname + " " + lastname >> print reshtml % message >> > The HTML Doc: > <html> <form action = "test1.py"> <p> Enter your first name:</p> <input type="text" name="firstname" size="40"> <input type="text" name="lastname" size="40"> <input type = "submit"> <input type ="reset"> </form> </html> Error: Mod_python error: "PythonHandler mod_python.publisher" Traceback (most recent call last): File "/usr/lib/python2.5/site-packages/mod_python/apache.py", line 299, in HandlerDispatch result = object(req) File "/usr/lib/python2.5/site-packages/mod_python/publisher.py", line 204, in handler module = page_cache[req] File "/usr/lib/python2.5/site-packages/mod_python/cache.py", line 82, in __getitem__ return self._checkitem(name)[2] File "/usr/lib/python2.5/site-packages/mod_python/cache.py", line 124, in _checkitem value = self.build(key, name, opened, entry) File "/usr/lib/python2.5/site-packages/mod_python/publisher.py", line 77, in build return ModuleCache.build(self, key, req, opened, entry) File "/usr/lib/python2.5/site-packages/mod_python/cache.py", line 371, in build exec opened in module.__dict__ File "/var/www/python/test1.py", line 16, in lastname = form['lastname'].value File "cgi.py", line 567, in __getitem__ raise KeyError, key KeyError: 'lastname' But I can get this script to work properly: def index(req): return "Test succesful"; > HTH, > > > From alan.gauld at btinternet.com Tue Sep 11 09:50:34 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 11 Sep 2007 08:50:34 +0100 Subject: [Tutor] Image Analysis References: <15059.1222.qm@web32403.mail.mud.yahoo.com> Message-ID: <fc5hct$ioc$1@sea.gmane.org> "wormwood_3" <wormwood_3 at yahoo.com> wrote > I need some way to analyze an image for color patterns. > > My only lead right now is PIL, and I am not sure if it will meet my > needs. PIL should be usable but I think there is also a Pyton wrapper for ImageMagick and I think it has some colour management type functions exposed too. Never tried any of this kind of thing though so I can't recommend anything with certainty. Alan G From mail at timgolden.me.uk Tue Sep 11 10:06:12 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 11 Sep 2007 09:06:12 +0100 Subject: [Tutor] input file encoding In-Reply-To: <fc4gnk$ors$1@sea.gmane.org> References: <fc4gnk$ors$1@sea.gmane.org> Message-ID: <46E64C74.9030303@timgolden.me.uk> Tim Michelsen wrote: > Hello, > I want to process some files encoded in latin-1 (iso-8859-1) in my > python script that I write on Ubuntu which has UTF-8 as standard encoding. Not sure what you mean by "standard encoding" (is this an Ubuntu thing?) but essentially whenever you're pulling stuff into Python which is encoded and which you want to treat as Unicode, you need to decode it explicitly, either on a string-by-string basis or by using the codecs module to treat the whole of a file as encoded. In this case, assuming you have files in iso-8859-1, something like this: <code> import codecs filenames = ['a.txt', 'b.txt', 'c.txt'] for filename in filenames: f = codecs.open (filename, encoding="iso-8859-1") text = f.read () # # If you want to re-encode this -- not sure why -- # you could do this: # text = text.encode ("utf-8") print repr (text) </code> TJG From brunson at brunson.com Tue Sep 11 10:25:42 2007 From: brunson at brunson.com (Eric Brunson) Date: Tue, 11 Sep 2007 02:25:42 -0600 Subject: [Tutor] Fw: Apache, CGI-BIN, Python In-Reply-To: <767740.51285.qm@web86109.mail.ird.yahoo.com> References: <767740.51285.qm@web86109.mail.ird.yahoo.com> Message-ID: <46E65106.7050505@brunson.com> ALAN GAULD wrote: > Forwarding to the list.... > > NB Use Reply-All when replying to the tutor list. > > Alan G. > > ----- Forwarded Message ---- > From: Ryan <silas428 at gmail.com> > To: Alan Gauld <alan.gauld at btinternet.com> > Sent: Tuesday, 11 September, 2007 5:32:33 AM > Subject: Re: [Tutor] Apache, CGI-BIN, Python > > Alan Gauld wrote: > >> "Ryan" <silas428 at gmail.com> wrote >> >> >> >>> I am running a Linux box and cannot find my Apache cgi-bin to put >>> some >>> python scripts in. I know I probably have to create one but don't >>> know >>> where and how. >>> >>> >> I think there are several places that you can create cgi-bin depending >> on how you configure apache. But the place I usually see it is >> directly >> under the apache root directory - ie the one that is equivalent to / >> in >> the url. >> >> >> >>> everything works fine except: >>> >>> form = cgi.FieldStorage() >>> >>> #This is where everything goes wrong >>> #I get error messages for either the lastname line or firstname >>> >>> >> Can you tell us >> a) exactly what error messages and >> b) How you are invoking the script - where are the values >> supposed to be coming from? >> >> >> >>> lastname = form['lastname'].value >>> firstname =form['firstname'].value >>> message = firstname + " " + lastname >>> print reshtml % message >>> >>> >> The HTML Doc: >> >> > <html> > > <form action = "test1.py"> > <p> Enter your first name:</p> > <input type="text" name="firstname" size="40"> > <input type="text" name="lastname" size="40"> > <input type = "submit"> > <input type ="reset"> > </form> > </html> > > Error: > > Mod_python error: "PythonHandler mod_python.publisher" > You don't use the cgi module when using the mod_python publisher handler. Your function will be called with the form variables as named parameters, like this: def handle_form_input( req, firstname, lastname ): # do something here I would recommend giving defaults for the parameters so if the user doesn't submit a value it, it doesn't throw an exception, like this: def handle_form_input( req, firstname=None, lastname=None ): # whatever And, I've been known to simulate the cgi behavior like this: def handler_form_input( req, **form ): # access your form variables as an array print "You entered %s %s" % ( form[lastname], form[firstname] ) But, remember that this "form" is a simple dict, not a cgi.FieldStorage and I don't know what it does with multiple values with the same key. FieldStorage puts them in an array, you'd have to experiment with this in the publisher handler. See how much better answers you get when you ask good questions and include error messages. :-) Hope that helps, e. > Traceback (most recent call last): > > File "/usr/lib/python2.5/site-packages/mod_python/apache.py", line 299, in HandlerDispatch > result = object(req) > > File "/usr/lib/python2.5/site-packages/mod_python/publisher.py", line 204, in handler > module = page_cache[req] > > File "/usr/lib/python2.5/site-packages/mod_python/cache.py", line 82, in __getitem__ > return self._checkitem(name)[2] > > File "/usr/lib/python2.5/site-packages/mod_python/cache.py", line 124, in _checkitem > value = self.build(key, name, opened, entry) > > File "/usr/lib/python2.5/site-packages/mod_python/publisher.py", line 77, in build > return ModuleCache.build(self, key, req, opened, entry) > > File "/usr/lib/python2.5/site-packages/mod_python/cache.py", line 371, in build > exec opened in module.__dict__ > > File "/var/www/python/test1.py", line 16, in > lastname = form['lastname'].value > > File "cgi.py", line 567, in __getitem__ > raise KeyError, key > > KeyError: 'lastname' > > But I can get this script to work properly: > def index(req): > return "Test succesful"; > > > > >> HTH, >> >> >> >> > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From brunson at brunson.com Tue Sep 11 10:31:34 2007 From: brunson at brunson.com (Eric Brunson) Date: Tue, 11 Sep 2007 02:31:34 -0600 Subject: [Tutor] Fw: Apache, CGI-BIN, Python In-Reply-To: <46E65106.7050505@brunson.com> References: <767740.51285.qm@web86109.mail.ird.yahoo.com> <46E65106.7050505@brunson.com> Message-ID: <46E65266.1090106@brunson.com> Eric Brunson wrote: > ALAN GAULD wrote: > >> Forwarding to the list.... >> >> NB Use Reply-All when replying to the tutor list. >> >> Alan G. >> >> ----- Forwarded Message ---- >> From: Ryan <silas428 at gmail.com> >> To: Alan Gauld <alan.gauld at btinternet.com> >> Sent: Tuesday, 11 September, 2007 5:32:33 AM >> Subject: Re: [Tutor] Apache, CGI-BIN, Python >> >> Alan Gauld wrote: >> >> >>> "Ryan" <silas428 at gmail.com> wrote >>> >>> >>> >>> >>>> I am running a Linux box and cannot find my Apache cgi-bin to put >>>> some >>>> python scripts in. I know I probably have to create one but don't >>>> know >>>> where and how. >>>> >>>> >>>> >>> I think there are several places that you can create cgi-bin depending >>> on how you configure apache. But the place I usually see it is >>> directly >>> under the apache root directory - ie the one that is equivalent to / >>> in >>> the url. >>> >>> >>> >>> >>>> everything works fine except: >>>> >>>> form = cgi.FieldStorage() >>>> >>>> #This is where everything goes wrong >>>> #I get error messages for either the lastname line or firstname >>>> >>>> >>>> >>> Can you tell us >>> a) exactly what error messages and >>> b) How you are invoking the script - where are the values >>> supposed to be coming from? >>> >>> >>> >>> >>>> lastname = form['lastname'].value >>>> firstname =form['firstname'].value >>>> message = firstname + " " + lastname >>>> print reshtml % message >>>> >>>> >>>> >>> The HTML Doc: >>> >>> >>> >> <html> >> >> <form action = "test1.py"> >> <p> Enter your first name:</p> >> <input type="text" name="firstname" size="40"> >> <input type="text" name="lastname" size="40"> >> <input type = "submit"> >> <input type ="reset"> >> </form> >> </html> >> >> Error: >> >> Mod_python error: "PythonHandler mod_python.publisher" >> >> > > You don't use the cgi module when using the mod_python publisher > handler. Your function will be called with the form variables as named > parameters, like this: > > def handle_form_input( req, firstname, lastname ): > # do something here > > I would recommend giving defaults for the parameters so if the user > doesn't submit a value it, it doesn't throw an exception, like this: > > def handle_form_input( req, firstname=None, lastname=None ): > # whatever > > And, I've been known to simulate the cgi behavior like this: > > def handler_form_input( req, **form ): > # access your form variables as an array > print "You entered %s %s" % ( form[lastname], form[firstname] ) > > It's late, that should read: def handler_form_input( req, **form ): # access your form variables as a dict return "You entered %s %s" % ( form['lastname'], form['firstname'] ) > But, remember that this "form" is a simple dict, not a cgi.FieldStorage > and I don't know what it does with multiple values with the same key. > FieldStorage puts them in an array, you'd have to experiment with this > in the publisher handler. > > See how much better answers you get when you ask good questions and > include error messages. :-) > > Hope that helps, > e. > > > >> Traceback (most recent call last): >> >> File "/usr/lib/python2.5/site-packages/mod_python/apache.py", line 299, in HandlerDispatch >> result = object(req) >> >> File "/usr/lib/python2.5/site-packages/mod_python/publisher.py", line 204, in handler >> module = page_cache[req] >> >> File "/usr/lib/python2.5/site-packages/mod_python/cache.py", line 82, in __getitem__ >> return self._checkitem(name)[2] >> >> File "/usr/lib/python2.5/site-packages/mod_python/cache.py", line 124, in _checkitem >> value = self.build(key, name, opened, entry) >> >> File "/usr/lib/python2.5/site-packages/mod_python/publisher.py", line 77, in build >> return ModuleCache.build(self, key, req, opened, entry) >> >> File "/usr/lib/python2.5/site-packages/mod_python/cache.py", line 371, in build >> exec opened in module.__dict__ >> >> File "/var/www/python/test1.py", line 16, in >> lastname = form['lastname'].value >> >> File "cgi.py", line 567, in __getitem__ >> raise KeyError, key >> >> KeyError: 'lastname' >> >> But I can get this script to work properly: >> def index(req): >> return "Test succesful"; >> >> >> >> >> >>> HTH, >>> >>> >>> >>> >>> >> >> >> _______________________________________________ >> 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 le.dahut at laposte.net Tue Sep 11 10:27:45 2007 From: le.dahut at laposte.net (le dahut) Date: Tue, 11 Sep 2007 10:27:45 +0200 Subject: [Tutor] file read and write Message-ID: <46E65181.6030605@laposte.net> I noticed that it is possible to write this : """ file('/tmp/myfile', 'w').write('Hello world\n') contnt = file('/tmp/sourcefile').read() """ instead of : """ fh = file('/tmp/myfile', 'w') fh.write('Hello world\n') fh.close() fh = file('/tmp/sourcefile') contnt = fh.read() fh.close() """ is there a reason not to use the first example ? K. From alan.gauld at btinternet.com Tue Sep 11 11:33:55 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 11 Sep 2007 10:33:55 +0100 Subject: [Tutor] file read and write References: <46E65181.6030605@laposte.net> Message-ID: <fc5nem$79l$1@sea.gmane.org> "le dahut" <le.dahut at laposte.net> wrote >I noticed that it is possible to write this : > """ > file('/tmp/myfile', 'w').write('Hello world\n') > contnt = file('/tmp/sourcefile').read() > """ Yes, it just creates temporary objects and relies on garbage collection to close/dispose of them. > instead of : > """ > fh = file('/tmp/myfile', 'w') > fh.write('Hello world\n') > fh.close() > > fh = file('/tmp/sourcefile') > contnt = fh.read() > fh.close() > """ > > is there a reason not to use the first example ? Not really although its rather limited in what it can do for you. Also error handling will not be as robust since you can't check that the file was/was not created. But if you just want a very short file it's fine and in fact you will often see examples of s = open('foo.txt').read() in code, it is quite common, more so than the write version. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Tue Sep 11 12:50:11 2007 From: kent37 at tds.net (Kent Johnson) Date: Tue, 11 Sep 2007 06:50:11 -0400 Subject: [Tutor] input file encoding In-Reply-To: <46E64C74.9030303@timgolden.me.uk> References: <fc4gnk$ors$1@sea.gmane.org> <46E64C74.9030303@timgolden.me.uk> Message-ID: <46E672E3.2050702@tds.net> Tim Golden wrote: > Tim Michelsen wrote: >> Hello, >> I want to process some files encoded in latin-1 (iso-8859-1) in my >> python script that I write on Ubuntu which has UTF-8 as standard encoding. > > Not sure what you mean by "standard encoding" (is this an Ubuntu > thing?) Probably referring to the encoding the terminal application expects - writing latin-1 chars when the terminal expects utf-8 will not work well. Python also has a default encoding but that is ascii unless you change it yourself. > In this case, assuming you have files in iso-8859-1, something > like this: > > <code> > import codecs > > filenames = ['a.txt', 'b.txt', 'c.txt'] > for filename in filenames: > f = codecs.open (filename, encoding="iso-8859-1") > text = f.read () > # > # If you want to re-encode this -- not sure why -- This is needed to put the text into the proper encoding for the terminal. If you print a unicode string directly it will be encoded using the system default encoding (ascii) which will fail: In [13]: print u'\xe2' ------------------------------------------------------------ Traceback (most recent call last): File "<ipython console>", line 1, in <module> <type 'exceptions.UnicodeEncodeError'>: 'ascii' codec can't encode character u'\xe2' in position 0: ordinal not in range(128) In [14]: print u'\xe2'.encode('utf-8') ? > # you could do this: > # text = text.encode ("utf-8") > print repr (text) No, not repr, that will print with \ escapes and quotes. In [15]: print repr(u'\xe2'.encode('utf-8')) '\xc3\xa2' And he may not want to change text itself to utf-8. Just print text.encode('utf-8') Kent From mail at timgolden.me.uk Tue Sep 11 12:58:37 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 11 Sep 2007 11:58:37 +0100 Subject: [Tutor] input file encoding In-Reply-To: <46E672E3.2050702@tds.net> References: <fc4gnk$ors$1@sea.gmane.org> <46E64C74.9030303@timgolden.me.uk> <46E672E3.2050702@tds.net> Message-ID: <46E674DD.1060108@timgolden.me.uk> Kent Johnson wrote: > Tim Golden wrote: >> Not sure what you mean by "standard encoding" (is this an Ubuntu >> thing?) > > Probably referring to the encoding the terminal application expects - > writing latin-1 chars when the terminal expects utf-8 will not work well. Ah, I see. I'm so used to Windows where there is, technically an encoding for the console window, but you can't really do anything about it (apart from the awkward chcp) and it isn't really in your face. I do *use* Linux sometimes, but I don't really think in it :) >> Tim Golden >> # you could do this: >> # text = text.encode ("utf-8") >> print repr (text) > > No, not repr, that will print with \ escapes and quotes. I knew that (no, honestly ;). Since I wasn't sure what the OP was after, I was using repr to *show* the escapes and quotes really to indicate that he may not have wanted them! (All right, I'll shut up now). Thanks for clarifying, Kent. TJG From kent37 at tds.net Tue Sep 11 13:45:38 2007 From: kent37 at tds.net (Kent Johnson) Date: Tue, 11 Sep 2007 07:45:38 -0400 Subject: [Tutor] file read and write In-Reply-To: <46E65181.6030605@laposte.net> References: <46E65181.6030605@laposte.net> Message-ID: <46E67FE2.80503@tds.net> le dahut wrote: > I noticed that it is possible to write this : > """ > file('/tmp/myfile', 'w').write('Hello world\n') ISTM I have had trouble with this. I always explicitly close a file that is open for writing. > contnt = file('/tmp/sourcefile').read() I use this often but never in any kind of loop where multiple files are being read. Note that the behaviour of the garbage collector is implementation-dependent. It is an implementation detail of CPython that GC is implemented with reference counting and objects are disposed when there are no longer any references to them. Jython uses Java's GC which does not behave the same way; PyPy and IronPython may have different GC as well. So if you want your code to be portable between implementations of Python you should not rely on this behaviour. Kent From kent37 at tds.net Tue Sep 11 13:59:35 2007 From: kent37 at tds.net (Kent Johnson) Date: Tue, 11 Sep 2007 07:59:35 -0400 Subject: [Tutor] input file encoding In-Reply-To: <46E674DD.1060108@timgolden.me.uk> References: <fc4gnk$ors$1@sea.gmane.org> <46E64C74.9030303@timgolden.me.uk> <46E672E3.2050702@tds.net> <46E674DD.1060108@timgolden.me.uk> Message-ID: <46E68327.5010404@tds.net> Tim Golden wrote: > Ah, I see. I'm so used to Windows where there is, technically an encoding > for the console window, but you can't really do anything about > it (apart from the awkward chcp) and it isn't really in your face. I > do *use* Linux sometimes, but I don't really think in it :) Actually you would run into the same problems on Windows if you tried to print UTF-8 or Unicode data. The only reason the Windows encoding is not in your face is that enough data is in ascii/latin-1/cp1252 that you can coast along in blissful ignorance. As soon as you have to deal with text in Japanese/Chinese/Korean/Russian/Turkish/Arabic/Greek/Hebrew/Thai/Klingon/etc you will have a rude awakening and a quick lesson in encoding awareness. Kent From dos.fool at gmail.com Tue Sep 11 14:24:16 2007 From: dos.fool at gmail.com (max baseman) Date: Tue, 11 Sep 2007 06:24:16 -0600 Subject: [Tutor] making math problems mmmm fun In-Reply-To: <46E61C94.8000701@brunson.com> References: <824735.66478.qm@web32401.mail.mud.yahoo.com> <D71EF62E-E8E5-43DA-9CC2-4C41A7A0BD49@gmail.com> <46E61C94.8000701@brunson.com> Message-ID: <749331EF-8430-49EE-B890-9AF26D046494@gmail.com> lol sorry i was born with bad grammar and hand writing (although it's the bit after being born that matters) On Sep 10, 2007, at 10:41 PM, Eric Brunson wrote: > > When you get done with this math problem you should consider a book > on punctuation. Not using it makes your sentences run together and > difficult to read. :-) Honestly, I just gave up after the first two > lines. > > max baseman wrote: >> haha :) yeah it's the new imp stuff i like parts of the idea but >> other parts i really dislike basically it TRIES to make math >> more interactive and world like i really enjoy how most of it is >> really programable stuff :) where compared to normal math books >> it's a bit harder to program just a problem instead of a story >> but imp needs help with it's grading and teaching the grading is >> terrible i can get a A as long as i can explain and know how my >> way of doing it wrong "works" but will fail if i just write the >> write answer without explanation i dont mind the explanations bit >> but that what i write matters more than if i can do the work is odd >> adn i just haven't learned anything new yet :) >> >> On Sep 10, 2007, at 7:16 PM, wormwood_3 wrote: >> >> >>> Don't have any ideas to Pythonize this problem for you, but I >>> must say that I hope this problem was listed in a chapter >>> entitled "Cruel and Unusual"! >>> >>> -Sam >>> ____________________________________ >>> ----- Original Message ---- >>> From: max baseman <dos.fool at gmail.com> >>> To: tutor at python.org >>> Sent: Monday, September 10, 2007 6:28:23 PM >>> Subject: [Tutor] making math problems mmmm fun >>> >>> hello all this is a homework in math i dont need to program it but i >>> would like to :) so like any other time pleas dont just give a >>> answer tutorials or a explanation. i dont like to use script >>> something i dont understand :) >>> >>> thanks >>> >>> basically the problem is to find a bunch of ways to put 1,2,3,4,5 >>> into different math problems to that equal 1-25, i haven't spent to >>> much time thinking about how to do this but i cant think of a way to >>> do it it without writing making the program rather long here is the >>> page from the book for the rules i will be working on this for the >>> next week or so thanks for any help :) >>> >>> >>> >>> >>> . you may use any of the four basic arithmetic operations- >>> addition, subtraction, multiplication, and division (according to >>> the >>> order of operations rules). for example, 2+1x3-4 is a 1-2-3-4 >>> expression for the number 1. >>> >>> . you may use exponents. for example, 2?? - 4 - 1 is a 1234 >>> expression >>> for the number 3 >>> >>> . you may use radicals for EX: ???4x2+1 is equal to 3 so 3+???4x2 >>> +1 is >>> a 1234 expression for 6 >>> >>> . you may use factorials for EX: 4! means 4x3x2x1 so 3+4!+1-2 is a >>> 1234 expression for the number 26 >>> >>> >>> . you may juxtapose two or more digits (that is put them next to >>> each other) to form a number such as 12. for example 43-12 is a 1234 >>> expression for 31 >>> >>> . you may use parentheses and brackets to change the meaning of a >>> expression for example according to the rules of order of >>> operations 1 >>> +4x3?? is a 1234 expression for 37. you can add parentheses and >>> brackets to get [(1+4)x3]?? which is a 1234 expression for 225 >>> >>> . must use 1,2,3,4 exactly once >>> >>> >>> >>> thanks for the help ill post if i find anything >>> _______________________________________________ >>> Tutor maillist - Tutor at python.org >>> http://mail.python.org/mailman/listinfo/tutor >>> >>> >>> >>> _______________________________________________ >>> Tutor maillist - Tutor at python.org >>> http://mail.python.org/mailman/listinfo/tutor >>> >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> > From wormwood_3 at yahoo.com Tue Sep 11 14:37:21 2007 From: wormwood_3 at yahoo.com (wormwood_3) Date: Tue, 11 Sep 2007 05:37:21 -0700 (PDT) Subject: [Tutor] Socket Timeout Handling Message-ID: <998382.86173.qm@web32408.mail.mud.yahoo.com> >I did send you a response and it is listed on the gmane archive >so if you didn't see it something has gone adrift somewhere. Just searched all my mail, for some reason I did not get this. I will check the archive. Thanks! >The solution you posted seems to bear no resemblence >to the problem you posted? How does this relate to setting >socket timeouts or using getfqdn()? Initially I was asking about how to set socket timeouts. But my general query was just suggestions on how best to detect internet connection upness. Since I "did not" get any responses to the question in the form of socket timeouts in particular, I resent the question in a more general form. It was that form that my last reply was to address. You are right on what it does. I thought at first it would be best to use something native to the classes/functions I was using in the standard library if possible. The solution I ended up with was more general, but serves the purpose. -Sam From rabidpoobear at gmail.com Tue Sep 11 14:38:33 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Tue, 11 Sep 2007 07:38:33 -0500 Subject: [Tutor] making math problems mmmm fun In-Reply-To: <749331EF-8430-49EE-B890-9AF26D046494@gmail.com> References: <824735.66478.qm@web32401.mail.mud.yahoo.com> <D71EF62E-E8E5-43DA-9CC2-4C41A7A0BD49@gmail.com> <46E61C94.8000701@brunson.com> <749331EF-8430-49EE-B890-9AF26D046494@gmail.com> Message-ID: <46E68C49.30205@gmail.com> max baseman wrote: > lol sorry i was born with bad grammar and hand writing (although it's > the bit after being born that matters) > Just imagine you're talking instead of writing. Everywhere you'd put a pause, put a comma. If it seems like the end of a sentence, put a period. In most cases, even bad punctuation will be better than no punctuation. People's inner monologues will just take on a Christopher Walken accent as they read over your e-mails, but this is arguably not a bad thing. Grammar is something you can learn, not something inborn. Now is as good a time as any to start learning it. -Luke From wormwood_3 at yahoo.com Tue Sep 11 14:59:45 2007 From: wormwood_3 at yahoo.com (wormwood_3) Date: Tue, 11 Sep 2007 05:59:45 -0700 (PDT) Subject: [Tutor] Socket Timeout Handling Message-ID: <5957.71351.qm@web32415.mail.mud.yahoo.com> Ok, just found your message in the archives. Thanks very much for that! By way of response-- >>That may be because your question ventures into fairly deep areas of >> networking >> that most folk who are just learning Python(ie readers of this list) >> have probably >> not encountered. True enough:-) I am learning this as I go. >>If you do want to get into depth on Python networking you may find the >> A-Press book Python Network Programming useful - I do regularly :-). I came across it a few times, was not sure if it would be as useful as more general books, but I think I will get it soon. >> However the only information I could see about timeouts there was >>related to socket.settimeout() which ISTR you didn't want to/couldn't >>use... The docs show there is settimeout() and setdefaulttimeout(). I will try to explain below why I did not think I could use these. I might have been wrong... > What is the best practice for checking for network connectivity > errors when making network calls? Is it better to wrap the functions > that make said calls in threads and time them? > Or to use timeout variables for modules like socket? >> Personally if i was doingt that I'd almost certainy put it in a thread >> and apply a timeout within the thread. but not having tried that I >> don't >> know how easy it would be! A friend shared an implementation of this with me that works well. I have attached it. Maybe you will find it useful! > I am trying to figure out the optimal way to make socket connections > (INET) and check for timeouts. The socket module has > settimeout(timeout) > and setdefaulttimeout(timeout). However, so far as I can tell, these > apply > to socket objects. The type of socket connection I want to make is > getfqdn(address). >> I don't understand, getfqdn() returns a domain name not an a socket? Yes. Example: >>> import socket >>> socket.getfqdn("64.233.169.99") 'yo-in-f99.google.com' And therein lies the rub! The main function of the script I have this in is to go through a list of IP addresses, and find their FQDN, and other information. It is at this step, when I get the FQDN, that I wanted to do some find of timeout setting. But since it is *not* a socket object, I cannot use settimeout()... > So I can set the default timeout for socket, but not a socket object > (makes sense so far). I cannot use the getfqdn(address) method on > a socket object, I have to use it on socket. >> Sorry it's not making sense to me, getfqdn takes a host name not a >> socket. Exactly my problem:-) >> setdefaulttimout is a function in the socket module not a method of >> socket. >> Thus you woulfd call that before reating a new socket: Thanks for the clarification, I will try this. >> What are you trying to do? Establish a socket connection to something >> or just do a name check that times out more quickly?(or slowly) Just trying to get the FQDNs from a list of IPs, and want to have some sane error handling in place in case my connection dies during the queries. Thanks! -------------- next part -------------- A non-text attachment was scrubbed... Name: TimeoutThread.py Type: text/x-python Size: 1432 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20070911/36d5c88e/attachment-0001.py From janos.juhasz at VELUX.com Tue Sep 11 15:31:44 2007 From: janos.juhasz at VELUX.com (=?ISO-8859-1?Q?J=E1nos_Juh=E1sz?=) Date: Tue, 11 Sep 2007 15:31:44 +0200 Subject: [Tutor] Unicode question In-Reply-To: <mailman.1209.1189515591.2656.tutor@python.org> Message-ID: <OFEDB72C62.832B4332-ONC1257353.00480111-C1257353.004A4FCA@velux.com> Dear All, I would like to convert my DOS txt file into pdf with reportlab. The file can be seen correctly in Central European (DOS) encoding in Explorer. My winxp uses cp852 as default codepage. When I open the txt file in notepad and set OEM/DOS script for terminal fonts, it shows the file correctly. I tried to convert the file with the next way: from reportlab.platypus import * from reportlab.lib.styles import getSampleStyleSheet from reportlab.rl_config import defaultPageSize PAGE_HEIGHT=defaultPageSize[1] styles = getSampleStyleSheet() def MakePdfInvoice(InvoiceNum, page): style = styles["Normal"] PdfInv = [Spacer(0,0)] PdfInv.append(Preformatted(page, styles['Normal'])) doc = SimpleDocTemplate(InvoiceNum) doc.build(PdfInv) if __name__ == '__main__': content = open('invoice01_0707.txt').readlines() page = ''.join(content[:92]) page = unicode(page, 'Latin-1') MakePdfInvoice('test.pdf', page) But it made funny chars somewhere. I tried it so eighter if __name__ == '__main__': content = open('invoice01_0707.txt').readlines() page = ''.join(content[:92]) page = page.encode('cp852') MakePdfInvoice('test.pdf', page) But it raised exception: debugger.run(codeObject, __main__.__dict__, start_stepping=0) File "C:\Python24\Lib\site-packages\pythonwin\pywin\debugger\__init__.py", line 60, in run _GetCurrentDebugger().run(cmd, globals,locals, start_stepping) File "C:\Python24\Lib\site-packages\pythonwin\pywin\debugger\debugger.py", line 631, in run exec cmd in globals, locals File "D:\devel\reportlab\MakePdfInvoice.py", line 18, in ? page = page.encode('cp852') File "c:\Python24\lib\encodings\cp852.py", line 18, in encode return codecs.charmap_encode(input,errors,encoding_map) UnicodeDecodeError: 'ascii' codec can't decode byte 0xb5 in position 112: ordinal not in range(128) >>> May someone point me where I made it wrong ? Best regards, Janos Juhasz From kent37 at tds.net Tue Sep 11 15:49:24 2007 From: kent37 at tds.net (Kent Johnson) Date: Tue, 11 Sep 2007 09:49:24 -0400 Subject: [Tutor] Unicode question In-Reply-To: <OFEDB72C62.832B4332-ONC1257353.00480111-C1257353.004A4FCA@velux.com> References: <OFEDB72C62.832B4332-ONC1257353.00480111-C1257353.004A4FCA@velux.com> Message-ID: <46E69CE4.9000803@tds.net> J?nos Juh?sz wrote: > Dear All, > > I would like to convert my DOS txt file into pdf with reportlab. > The file can be seen correctly in Central European (DOS) encoding in > Explorer. > > My winxp uses cp852 as default codepage. > > When I open the txt file in notepad and set OEM/DOS script for terminal > fonts, it shows the file correctly. > > I tried to convert the file with the next way: > > from reportlab.platypus import * > from reportlab.lib.styles import getSampleStyleSheet > from reportlab.rl_config import defaultPageSize > PAGE_HEIGHT=defaultPageSize[1] > > styles = getSampleStyleSheet() > > def MakePdfInvoice(InvoiceNum, page): > style = styles["Normal"] > PdfInv = [Spacer(0,0)] > PdfInv.append(Preformatted(page, styles['Normal'])) > doc = SimpleDocTemplate(InvoiceNum) > doc.build(PdfInv) > > if __name__ == '__main__': > content = open('invoice01_0707.txt').readlines() > page = ''.join(content[:92]) > page = unicode(page, 'Latin-1') Why latin-1? Try page = unicode(page, 'cp852') > MakePdfInvoice('test.pdf', page) > > But it made funny chars somewhere. > > I tried it so eighter > > if __name__ == '__main__': > content = open('invoice01_0707.txt').readlines() > page = ''.join(content[:92]) > page = page.encode('cp852') Use decode() here, not encode(). decode() goes towards Unicode encode() goes away from Unicode As a mnemonic I think of Unicode as pure unencoded data. (This is *not* accurate, it is a memory aid!) Then it's easy to remember that decode() removes encoding == convert to Unicode, encode() adds encoding == convert from Unicode. > MakePdfInvoice('test.pdf', page) > > But it raised exception: > debugger.run(codeObject, __main__.__dict__, start_stepping=0) > File > "C:\Python24\Lib\site-packages\pythonwin\pywin\debugger\__init__.py", line > 60, in run > _GetCurrentDebugger().run(cmd, globals,locals, start_stepping) > File > "C:\Python24\Lib\site-packages\pythonwin\pywin\debugger\debugger.py", line > 631, in run > exec cmd in globals, locals > File "D:\devel\reportlab\MakePdfInvoice.py", line 18, in ? > page = page.encode('cp852') > File "c:\Python24\lib\encodings\cp852.py", line 18, in encode > return codecs.charmap_encode(input,errors,encoding_map) > UnicodeDecodeError: 'ascii' codec can't decode byte 0xb5 in position 112: > ordinal not in range(128) When you call encode on a string (instead of a unicode object) the string is first decoded to Unicode using ascii encoding. This usually fails. Kent From jecarnell at saintfrancis.com Tue Sep 11 15:45:30 2007 From: jecarnell at saintfrancis.com (Carnell, James E) Date: Tue, 11 Sep 2007 08:45:30 -0500 Subject: [Tutor] Image Analysis In-Reply-To: <mailman.1193.1189503270.2656.tutor@python.org> Message-ID: <CEFAE560FE3E3C458A2335A1AA37A82D06763964@MAIL2W2K3.WarrenNT.SaintFrancis.Loc> "wormwood_3" <wormwood_3 at yahoo.com> wrote > I need some way to analyze an image for color patterns. > > My only lead right now is PIL, and I am not sure if it will meet my > needs. I am using PIL and numpy ##### something hat at least looks sorta like import numpy import PIL myImage = Image.open("C:\\file.bmp") myImage.assarray(stuff) I can't remember the code and am at work, but this will give you a big array to work with. Each pixel for RGB looks kind of like [100,150,250] then each line is in a matrix etc. It's a bit of a pain traversing the matrices, but you can do anything you would do to an array. Pyro Robotics also has a small tutorial about this. http://pyrorobotics.org/?page=PyroModuleVisionSystem From dperlman at wisc.edu Tue Sep 11 15:15:49 2007 From: dperlman at wisc.edu (David Perlman) Date: Tue, 11 Sep 2007 08:15:49 -0500 Subject: [Tutor] making math problems mmmm fun In-Reply-To: <46E68C49.30205@gmail.com> References: <824735.66478.qm@web32401.mail.mud.yahoo.com> <D71EF62E-E8E5-43DA-9CC2-4C41A7A0BD49@gmail.com> <46E61C94.8000701@brunson.com> <749331EF-8430-49EE-B890-9AF26D046494@gmail.com> <46E68C49.30205@gmail.com> Message-ID: <D097B5BD-37BC-4F66-B113-C1EF3E758448@wisc.edu> Also keep in mind that if you want your code to work, your grammar and punctuation in code has to be absolutely flawless. Writing English well is excellent practice for writing code well; writing English poorly is excellent practice for writing code poorly. You get what you pay for. If you put in the effort, you will reap the reward. If you don't put in the effort, you will reap the reward of that instead, which is "teh suck"... :) On Sep 11, 2007, at 7:38 AM, Luke Paireepinart wrote: > max baseman wrote: >> lol sorry i was born with bad grammar and hand writing (although it's >> the bit after being born that matters) >> > Just imagine you're talking instead of writing. Everywhere you'd > put a > pause, put a comma. If it seems like the end of a sentence, put a > period. In most cases, even bad punctuation will be better than no > punctuation. People's inner monologues will just take on a > Christopher > Walken accent as they read over your e-mails, but this is arguably > not a > bad thing. > Grammar is something you can learn, not something inborn. Now is as > good > a time as any to start learning it. > -Luke > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- -dave---------------------------------------------------------------- All I ask is that the kind of unsolvable that it turns out to be has respectable precedents. -Jerry Fodor From timmichelsen at gmx-topmail.de Tue Sep 11 16:22:25 2007 From: timmichelsen at gmx-topmail.de (Tim Michelsen) Date: Tue, 11 Sep 2007 16:22:25 +0200 Subject: [Tutor] input file encoding In-Reply-To: <46E64C74.9030303@timgolden.me.uk> References: <fc4gnk$ors$1@sea.gmane.org> <46E64C74.9030303@timgolden.me.uk> Message-ID: <fc68b2$3s6$1@sea.gmane.org> > Not sure what you mean by "standard encoding" (is this an Ubuntu > thing?) but essentially whenever you're pulling stuff into Python As it was lined out by others I was printing to a linux terminal which had the encoding set to UTF-8. Therefore and for further processing of the data I had to open it with the right encoding. > In this case, assuming you have files in iso-8859-1, something > like this: > > <code> > import codecs > > filenames = ['a.txt', 'b.txt', 'c.txt'] > for filename in filenames: > f = codecs.open (filename, encoding="iso-8859-1") This piece of code did the trick. After a short adaption I had exactly what I wanted to achive. Thanks you for your help. From wormwood_3 at yahoo.com Tue Sep 11 16:42:32 2007 From: wormwood_3 at yahoo.com (wormwood_3) Date: Tue, 11 Sep 2007 07:42:32 -0700 (PDT) Subject: [Tutor] Image Analysis Message-ID: <205832.8269.qm@web32403.mail.mud.yahoo.com> Thanks very much! This may be exactly what I need, and in any case will be a great starting point! -Sam ___________________________ ----- Original Message ---- From: "Carnell, James E" <jecarnell at saintfrancis.com> To: tutor at python.org Sent: Tuesday, September 11, 2007 9:45:30 AM Subject: Re: [Tutor] Image Analysis "wormwood_3" <wormwood_3 at yahoo.com> wrote > I need some way to analyze an image for color patterns. > > My only lead right now is PIL, and I am not sure if it will meet my > needs. I am using PIL and numpy ##### something hat at least looks sorta like import numpy import PIL myImage = Image.open("C:\\file.bmp") myImage.assarray(stuff) I can't remember the code and am at work, but this will give you a big array to work with. Each pixel for RGB looks kind of like [100,150,250] then each line is in a matrix etc. It's a bit of a pain traversing the matrices, but you can do anything you would do to an array. Pyro Robotics also has a small tutorial about this. http://pyrorobotics.org/?page=PyroModuleVisionSystem _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From silas428 at gmail.com Tue Sep 11 17:39:44 2007 From: silas428 at gmail.com (Ryan) Date: Tue, 11 Sep 2007 08:39:44 -0700 Subject: [Tutor] Apache, CGI-BIN, Python In-Reply-To: <r219-1049-i386-C7B36ACF52CA4D59945800F800A72A6E@AdInfinitum.local> References: <r219-1049-i386-C7B36ACF52CA4D59945800F800A72A6E@AdInfinitum.local> Message-ID: <46E6B6C0.8050205@gmail.com> Jan Erik Mostr?m wrote: > Ryan <silas428 at gmail.com> 07-09-10 15:35 > >> Once I edit the config files for cgi scripts the browser says I don't >> have permission to access the file. > > You must make sure that the script file has execute/read permissions > for the process/user who runs the apache server. On my ubuntu machine > that is 'www-data' > > jem I found the lines with 'www-data' but I am not sure what exactly I have to do. I have User and Group-www-data. From pacbaby27 at yahoo.com Tue Sep 11 17:36:18 2007 From: pacbaby27 at yahoo.com (Latasha Marks) Date: Tue, 11 Sep 2007 08:36:18 -0700 (PDT) Subject: [Tutor] (no subject) Message-ID: <303826.19489.qm@web56401.mail.re3.yahoo.com> need help writting a program of pick up sticks. --------------------------------- Luggage? GPS? Comic books? Check out fitting gifts for grads at Yahoo! Search. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070911/e2fc3fa8/attachment.htm From kent37 at tds.net Tue Sep 11 18:01:26 2007 From: kent37 at tds.net (Kent Johnson) Date: Tue, 11 Sep 2007 12:01:26 -0400 Subject: [Tutor] (no subject) In-Reply-To: <303826.19489.qm@web56401.mail.re3.yahoo.com> References: <303826.19489.qm@web56401.mail.re3.yahoo.com> Message-ID: <46E6BBD6.30707@tds.net> Latasha Marks wrote: > need help writting a program of pick up sticks. That is pretty vague. What help do you need? What do you want the program to do? Kent From noufal at airtelbroadband.in Tue Sep 11 18:16:40 2007 From: noufal at airtelbroadband.in (Noufal Ibrahim) Date: Tue, 11 Sep 2007 21:46:40 +0530 Subject: [Tutor] Running other files In-Reply-To: <d9e88eaf0709101424j755f8047g1c58f7ae0bd7d19@mail.gmail.com> References: <83F34925E6FC4A0E95539E3C3387DDEF@PC3> <d9e88eaf0709101424j755f8047g1c58f7ae0bd7d19@mail.gmail.com> Message-ID: <46E6BF68.9050303@airtelbroadband.in> Rikard Bosnjakovic wrote: > On 10/09/2007, Lawrence Barrott <lawrence.barrott at btinternet.com> wrote: > >> is it possible to run other non-python files using python such as .exe or >> other files. > > Have a look at os.system(). > Or more generally, the subprocess module. -- ~noufal From sacharook at hotmail.co.uk Tue Sep 11 18:18:18 2007 From: sacharook at hotmail.co.uk (sacha rook) Date: Tue, 11 Sep 2007 17:18:18 +0100 Subject: [Tutor] extract hosts from html write to file Message-ID: <BAY111-W12B6EB2404726524287448F3C10@phx.gbl> Hi I wonder if anyone can help with the following I am trying to read a html page extract only fully qualified hostnames from the page and output these hostnames to a file on disk to be used later as input to another program. I have this so far import urllib2f=open("c:/tmp/newfile.txt", "w")for line in urllib2.urlopen("http://www.somedomain.uk"): if "href" in line and "http://" in line: print line f.write(line)f.close()fu=open("c:/tmp/newfile.txt", "r") for line in fu.readlines(): print line so i have opened a file to write to, got a page of html, printed and written those to file that contain href & http:// references. closed file opened file read all the lines from file and printed out Can someone point me in right direction please on the flow of this program, the best way to just extract the hostnames and print these to file on disk? As you can see I am newish to this Thanks in advance for any help given! s _________________________________________________________________ Feel like a local wherever you go. http://www.backofmyhand.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070911/ebd60715/attachment.htm From srikanth007m at gmail.com Tue Sep 11 18:54:37 2007 From: srikanth007m at gmail.com (chinni) Date: Tue, 11 Sep 2007 22:24:37 +0530 Subject: [Tutor] automate daily tasks Message-ID: <b5300ea90709110954v38e84b3fo3af2c0a346784dcc@mail.gmail.com> Hi all, I am working on MAC OS x my project is updating all ready installed products.I have to automate this in python.so,can any one will give some suggestions and some examples how to automate.some basic things of my project is ... i think u all know that there will be a plist file for each product in mac.i have to degrade the version of plist automatically through my script and it has to edit the plist file and degrade it to least version and as to check for updates by itself.like this there are 15 products under this now each time i can't go and degrade the version and save it and run updates manually..so,that can any one plz..tell me how to start from first step... -- Best Regards, M.Srikanth Kumar, -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070911/75c73c5e/attachment.htm From tktucker at gmail.com Tue Sep 11 19:03:54 2007 From: tktucker at gmail.com (Tom Tucker) Date: Tue, 11 Sep 2007 13:03:54 -0400 Subject: [Tutor] automate daily tasks In-Reply-To: <b5300ea90709110954v38e84b3fo3af2c0a346784dcc@mail.gmail.com> References: <b5300ea90709110954v38e84b3fo3af2c0a346784dcc@mail.gmail.com> Message-ID: <2a278ffe0709111003v5d89101fvebdcde704fc9a5b7@mail.gmail.com> Are you looking for a method to automate the execution of your Python program? Is that the question? If yes, have you tried using cron or at jobs (man cron or man at). Tom On 9/11/07, chinni <srikanth007m at gmail.com> wrote: > > Hi all, > > I am working on MAC OS x my project is updating all ready installed > products.I have to automate this in python.so,can any one will give some > suggestions and some examples how to automate.some basic things of my > project is ... i think u all know that there will be a plist file for each > product in mac.i have to degrade the version of plist automatically > through my script and it has to edit the plist file and degrade it to least > version and as to check for updates by itself.like this there are 15 > products under this now each time i can't go and degrade the version and > save it and run updates manually..so,that can any one plz..tell me how to > start from first step... > > -- > Best Regards, > M.Srikanth Kumar, > > > _______________________________________________ > 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/20070911/ea45fd19/attachment.htm From alan.gauld at btinternet.com Tue Sep 11 19:37:33 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 11 Sep 2007 18:37:33 +0100 Subject: [Tutor] automate daily tasks References: <b5300ea90709110954v38e84b3fo3af2c0a346784dcc@mail.gmail.com> Message-ID: <fc6jpg$ihc$1@sea.gmane.org> "chinni" <srikanth007m at gmail.com> wrote > I am working on MAC OS x my project is updating all ready installed > products.I have to automate this in python.so,can any one will give > some sounds fair. > project is ... i think u all know that there will be a plist file > for each > product in mac. I wouldn't assume too much knowledge of how MacOS works, despite Apple's recent successes its still very much a minority OS! I own an iBook and use the Terminal for unix type stuff but I rarely delve inside the MacOs specifics. > i have to degrade the version of plist automatically through > my script and it has to edit the plist file and degrade it to least > version > and as to check for updates by itself.like this there are 15 > products under > this now each time i can't go and degrade the version and save it > and run > updates manually..so,that can any one plz..tell me how to start from > first > step... Nope, sorry. You lost me on that one. Can you give some example data formats. And maybe show us what you are trying to do with them? -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From brunson at brunson.com Tue Sep 11 19:46:00 2007 From: brunson at brunson.com (Eric Brunson) Date: Tue, 11 Sep 2007 11:46:00 -0600 Subject: [Tutor] extract hosts from html write to file In-Reply-To: <BAY111-W12B6EB2404726524287448F3C10@phx.gbl> References: <BAY111-W12B6EB2404726524287448F3C10@phx.gbl> Message-ID: <46E6D458.6020303@brunson.com> sacha rook wrote: > Hi I wonder if anyone can help with the following > > I am trying to read a html page extract only fully qualified hostnames > from the page and output these hostnames to a file on disk to be used > later as input to another program. > > I have this so far > > import urllib2 > f=open("c:/tmp/newfile.txt", "w") > for line in urllib2.urlopen("_http://www.somedomain.uk_ > <http://www.somedomain.uk/>"): > if "href" in line and "http://" in line: > print line > f.write(line) > f.close() > fu=open("c:/tmp/newfile.txt", "r") > > for line in fu.readlines(): > print line > > so i have opened a file to write to, got a page of html, printed and > written those to file that contain href & http:// references. > closed file opened file read all the lines from file and printed out > > Can someone point me in right direction please on the flow of this > program, the best way to just extract the hostnames and print these to > file on disk? I would start with a Regular Expression to match the text of the URL, it will match exactly the text of the URL and you can extract that. You can probably even find one in a web search. Read up on regular expressions to start with, they're extremely powerful, but a little bit of a learning curve to start with. Google "regular expression tutorial" or search the list archive for a reference. > > As you can see I am newish to this > > Thanks in advance for any help given! > > s > > ------------------------------------------------------------------------ > Do you know a place like the back of your hand? Share local knowledge > with BackOfMyHand.com <http://www.backofmyhand.com> > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From eric at ericwalstad.com Tue Sep 11 19:51:36 2007 From: eric at ericwalstad.com (Eric Walstad) Date: Tue, 11 Sep 2007 10:51:36 -0700 Subject: [Tutor] Apache, CGI-BIN, Python In-Reply-To: <46E6B6C0.8050205@gmail.com> References: <r219-1049-i386-C7B36ACF52CA4D59945800F800A72A6E@AdInfinitum.local> <46E6B6C0.8050205@gmail.com> Message-ID: <46E6D5A8.3050907@ericwalstad.com> Ryan wrote: > Jan Erik Mostr?m wrote: >> Ryan <silas428 at gmail.com> 07-09-10 15:35 >> >>> Once I edit the config files for cgi scripts the browser says I don't >>> have permission to access the file. >> You must make sure that the script file has execute/read permissions >> for the process/user who runs the apache server. On my ubuntu machine >> that is 'www-data' >> >> jem > I found the lines with 'www-data' but I am not sure what exactly I have > to do. I have User and Group-www-data. Hi Ryan, Have you RTFM? Googled for something like "apache file permission", etc? http://httpd.apache.org/docs/2.0/ http://httpd.apache.org/docs/2.0/howto/cgi.html http://www.google.com/search?q=apache+cgi+file+permission http://catb.org/~esr/faqs/smart-questions.html#before Eric. From dperlman at wisc.edu Wed Sep 12 00:20:03 2007 From: dperlman at wisc.edu (David Perlman) Date: Tue, 11 Sep 2007 17:20:03 -0500 Subject: [Tutor] automate daily tasks In-Reply-To: <b5300ea90709110954v38e84b3fo3af2c0a346784dcc@mail.gmail.com> References: <b5300ea90709110954v38e84b3fo3af2c0a346784dcc@mail.gmail.com> Message-ID: <22780F5F-E3CA-41E4-8E1F-DB8EAF2045EF@wisc.edu> As far as making something run automatically at various times, if you're certain that you want to do it in a Mac-only way, Apple's recommended method for timing jobs is described here: http://developer.apple.com/macosx/launchd.html "Getting started with launchd" otherwise use cron or at, as Tom said. On Sep 11, 2007, at 11:54 AM, chinni wrote: > I am working on MAC OS x my project is updating all ready installed > products.I have to automate this in python.so,can any one will give > some suggestions and some examples how to automate.some basic > things of my project is ... i think u all know that there will be a > plist file for each product in mac.i have to degrade the version of > plist automatically through my script and it has to edit the plist > file and degrade it to least version and as to check for updates by > itself.like this there are 15 products under this now each time i > can't go and degrade the version and save it and run updates > manually..so,that can any one plz..tell me how to start from first > step... -- -dave---------------------------------------------------------------- "Pseudo-colored pictures of a person's brain lighting up are undoubtedly more persuasive than a pattern of squiggles produced by a polygraph. That could be a big problem if the goal is to get to the truth." -Dr. Steven Hyman, Harvard From kent37 at tds.net Wed Sep 12 00:29:43 2007 From: kent37 at tds.net (Kent Johnson) Date: Tue, 11 Sep 2007 18:29:43 -0400 Subject: [Tutor] extract hosts from html write to file In-Reply-To: <BAY111-W12B6EB2404726524287448F3C10@phx.gbl> References: <BAY111-W12B6EB2404726524287448F3C10@phx.gbl> Message-ID: <46E716D7.1010500@tds.net> sacha rook wrote: > Hi I wonder if anyone can help with the following > > I am trying to read a html page extract only fully qualified hostnames > from the page and output these hostnames to a file on disk to be used > later as input to another program. I would use BeautifulSoup to parse out the hrefs and urlparse.urlparse() to split the hostname out of the href. http://www.crummy.com/software/BeautifulSoup/documentation.html Kent From eike.welk at gmx.net Wed Sep 12 01:57:35 2007 From: eike.welk at gmx.net (Eike Welk) Date: Wed, 12 Sep 2007 01:57:35 +0200 Subject: [Tutor] Image Analysis In-Reply-To: <15059.1222.qm@web32403.mail.mud.yahoo.com> References: <15059.1222.qm@web32403.mail.mud.yahoo.com> Message-ID: <200709120157.35935.eike.welk@gmx.net> Hello Sam; if you seriously want to do image analysis, you should use Numpy, Scipy, and Matplotlib. Scipy has a sub-project named 'ndimage' which implements many common image analysis algorithms. You should also subscribe to the mailinglists of these projects. Numpy and Scipy: http://www.scipy.org/ Matplotlib: http://matplotlib.sourceforge.net/ A nice Python enhancement is Ipython: http://ipython.scipy.org/moin/ You should also bookmark this page: http://www.scipy.org/Numpy_Example_List I have written a little program, to illustrate how it works. The program tries to recognize red blood cells in a microscopic image (from Wikipedia). It also counts the cells and measures their diameter. (The program does not work very well, although I've spent way too much time on it.) I have attached the program, the input image, and the output image. Usage: Start Ipython with: ipython --pylab Then type: run "image.py" The program should run with regular Python as well. Kind regards, Eike. -------------- next part -------------- A non-text attachment was scrubbed... Name: image.py Type: application/x-python Size: 4144 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20070912/aa19e71e/attachment-0001.bin -------------- next part -------------- A non-text attachment was scrubbed... Name: Blood_smear.png Type: image/png Size: 391016 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20070912/aa19e71e/attachment-0002.png -------------- next part -------------- A non-text attachment was scrubbed... Name: Blood-final-image.png Type: image/png Size: 392002 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20070912/aa19e71e/attachment-0003.png From dkuhlman at rexx.com Wed Sep 12 05:09:36 2007 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Tue, 11 Sep 2007 20:09:36 -0700 Subject: [Tutor] Image Analysis In-Reply-To: <200709120157.35935.eike.welk@gmx.net> References: <15059.1222.qm@web32403.mail.mud.yahoo.com> <200709120157.35935.eike.welk@gmx.net> Message-ID: <20070912030936.GA45033@cutter.rexx.com> On Wed, Sep 12, 2007 at 01:57:35AM +0200, Eike Welk wrote: > I have attached the program, the input image, and the output image. > Please do not stuff 1 MB emails in my mailbox. Either (1) post the images on the Web and provide a link or (2) ask before emailing large attachments. Thank you. Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman From ghashsnaga at gmail.com Wed Sep 12 05:12:59 2007 From: ghashsnaga at gmail.com (Ara Kooser) Date: Tue, 11 Sep 2007 21:12:59 -0600 Subject: [Tutor] calling class instances in functions Message-ID: <2107481c0709112012v70e8c18eh60332158c2f13914@mail.gmail.com> Thank you for your help on classes. I am working on an old program I started in 2005. This time around I am trying to model cell behavior using a PD model. I have the main program and then a file called yeast_cell.py that contains the classes I want to instance. In the main program at the function def add_yeast(world): I want to instance the class GoodYeast and have the global variable @ change to G on the world. I tried just creating an instance but that did not go over so well. I was wondering what is the proper and pythonic way to create an instance that the user will be selecting in a function. I eventually want to add a bunch of different cell classes. Thank you for your help. Ara Kooser Main Program ######################################################################## #Yeast Cooperation Model #by Ara Kooser #Version 1.0 no PD, 070906 # #This code contain just the world setup and not the actually PD code #for copperation behavior. This is better left to classes not functions # #TO DO LIST: Add error handling, dump to text file, data gathering, #different classes of yeast # #Many thanks to: Danny Yoo, Lee Haar, Max Noel, Kent Johnson ######################################################################## import random import copy import textwrap import yeast_cell ######################################################################### #This section of the code sets up and prints out the starting conditions #of the world and the yeast ######################################################################## YEAST, EMPTY, GROUP = '@', '.', 'Q' def percolation(perc): #Sets up a percolation threshold value randval = random.random() if randval > perc: return EMPTY else: return YEAST def random_world(M, N): #Constructs random world of size MxN world = {} for j in range(N): for i in range(M): world[i, j] = percolation(perc) world['dimensions'] = (M, N) return world def print_world(world): #Prints out a string representation of a world. M, N = world['dimensions'] for j in range(N): for i in range(M): print world[i, j], print def add_yeast(world): #Allows the user to add a yeast cell at point m,n M,N = world['dimensions'] new_world = copy.copy(world) counta = 0 yy = raw_input("How many yeast cells do you wish to add?") yy = int(yy) while counta<yy: zz = raw_iput("What kind of yeast cell do you want to add? Options:GoodYeast") #Here I want to call this instace of GoodYeast from yeast_cell.py print "Please place this yeast cell using an m,n point" print "The upper left hand corner is (0,0)" i = int(raw_input("Please enter a m value for the yeast cell.")) j = int(raw_input("Please enter a n value for the yeast cell.")) new_world[i,j] = YEAST for j in range(N): for i in range(M): world[i,j]=new_world[i,j] counta = counta+1 print_world(small_world) ################################## #The following code gets the state of the world and determines #what is next to each cell, sensing ################################# def get_state(world,i,j): #Returns the state of the cell at position (i,j) return world.get((i,j), EMPTY) def count_neighbors(world,i,j): #Returns the number of cells next to this one live_count = 0 for i_delta in [-1,0,1]: for j_delta in [-1,0,1]: if(i_delta,j_delta)==(0,0): continue if get_state(world, i+i_delta, j+j_delta)==YEAST: live_count+=1 return live_count def is_grouped(world,i,j): #Returns a true value if the cell at (i,j) is connected by 1-8 others return(get_state(world,i,j)==YEAST and (1 <=count_neighbors(world,i,j)<=8)) def next_world(world): #Shows which yeast are in a group using Q M,N = world['dimensions'] new_world=copy.copy(world) for j in range(N): for i in range(M): if is_grouped(world,i,j): new_world[i,j] = GROUP for j in range(N): for i in range(M): world[i,j]=new_world[i,j] def AddYeast(): print "If you selected 0 for your percolation you may now add yeast to the world." print "The upper left hand corner is point (0,0)." zz = raw_input("Do you want to add a yeast cell? y or n") if zz == "y": add_yeast(small_world) elif zz == "n": print_world(small_world) raw_input("Please press return to group your yeast cells.") ##################################################### #This is where the PD portion of the program starts ##################################################### def PD_yeast(): print textwrap.fill ("The PD will added later in the OOP version") print"REFERENCES" print textwrap.fill ("Learning to program. By Alan Gauld") print textwrap.fill ("How to Think Like a Computer Scientist. By Downey, Elkner, and Meyers") print textwrap.fill("Cooperation amoung Microorganisms. Wingreen and Levin.") print textwrap.fill ("Synthetic cooperation in engineered yeast populations. Shou, Ram, and Vilar") print textwrap.fill ("Evolution in group-structured populations can resolve the tragedy of the commons. Killingback, Bieri, and Flatt") ############################################################################### #Start of program ############################################################################### raw_input("Please press return to start the program.") perc = raw_input("Please enter a thresold between 0-1 for the population.") perc = float(perc) n = int(raw_input("Please enter a n dimension. ")) m = int(raw_input("Please enter a m dimension. ")) small_world = random_world(m,n) print_world(small_world) AddYeast() next_world(small_world) print_world(small_world) print "Q indictates that the yeast cells found a group." print print print "Please press return to start the PD program." print print PD_yeast() yeast_cell.py ############################################################### #yeast_cell.py #Contains the different types of yeast behavior #By Ara Kooser ############################################################### #0 = cooperate #1 = defect class GoodYeast: #Cooperates all the time YEAST = 'G' #Should change generic variable @ in the world to G??? def __init__(self,name): self.name = name currency = 0 location = [] def response(self): return 0 def location(world,i,j): return world.get(i,j) #I believe this allows the cell to know it's coordinates -- Quis hic locus, quae regio, quae mundi plaga. Ubi sum. Sub ortu solis an sub cardine glacialis ursae. From john at fouhy.net Wed Sep 12 06:03:23 2007 From: john at fouhy.net (John Fouhy) Date: Wed, 12 Sep 2007 16:03:23 +1200 Subject: [Tutor] calling class instances in functions In-Reply-To: <2107481c0709112012v70e8c18eh60332158c2f13914@mail.gmail.com> References: <2107481c0709112012v70e8c18eh60332158c2f13914@mail.gmail.com> Message-ID: <5e58f2e40709112103r7e246238l9d65caf2222380e4@mail.gmail.com> I'm not sure I understnad your quesiton.. You can put classes into lists, dictionaries, et cetera. For example: ## class Foo(object): pass class Bar(object): pass class Baz(object): pass my_classes = { 'foo':Foo, 'bar':Bar, 'baz':Baz } thing = my_classes['bar']() ## It seems quite strange to me, though, to have the instantiation of a class change a global variable. Maybe you could do something like this: ## class GoodYeast(object): pass # etc class BadYeast(object): pass # etc class World(object): yeasts = { 'good':GoodYeast, 'bad':'BadYeast } def init(self): self.yeast = None def setYeast(self, yeast): self.yeast = self.yeasts[yeast]() w = World() w.setYeast('good') ## But I confess that I have not read or run your code, so I'm not sure if this is the best way forward for you.. -- John. From brunson at brunson.com Wed Sep 12 07:10:27 2007 From: brunson at brunson.com (Eric Brunson) Date: Tue, 11 Sep 2007 23:10:27 -0600 Subject: [Tutor] Image Analysis In-Reply-To: <20070912030936.GA45033@cutter.rexx.com> References: <15059.1222.qm@web32403.mail.mud.yahoo.com> <200709120157.35935.eike.welk@gmx.net> <20070912030936.GA45033@cutter.rexx.com> Message-ID: <46E774C3.4090405@brunson.com> Just my opinion, but I didn't mind the attachments, I felt they added quite a bit to the discussion and I certainly appreciated the input on the application of the libraries. My opinion on your tone, I'll keep to myself. Dave Kuhlman wrote: > On Wed, Sep 12, 2007 at 01:57:35AM +0200, Eike Welk wrote: > > >> I have attached the program, the input image, and the output image. >> >> > > Please do not stuff 1 MB emails in my mailbox. Either (1) post the > images on the Web and provide a link or (2) ask before emailing > large attachments. > > Thank you. > > Dave > > > From bill at celestial.net Wed Sep 12 07:40:11 2007 From: bill at celestial.net (Bill Campbell) Date: Tue, 11 Sep 2007 22:40:11 -0700 Subject: [Tutor] Image Analysis In-Reply-To: <46E774C3.4090405@brunson.com> References: <15059.1222.qm@web32403.mail.mud.yahoo.com> <200709120157.35935.eike.welk@gmx.net> <20070912030936.GA45033@cutter.rexx.com> <46E774C3.4090405@brunson.com> Message-ID: <20070912054011.GA5480@ayn.mi.celestial.com> On Tue, Sep 11, 2007, Eric Brunson wrote: > >Just my opinion, but I didn't mind the attachments, I felt they added >quite a bit to the discussion and I certainly appreciated the input on >the application of the libraries. > >My opinion on your tone, I'll keep to myself. Figure out the total size sending a megabyte+ mail message to hundreds of list recipients. Most mailing lists limit the size of messages to 40k or less. While large messages aren't much of an issue on broadband connections, they can be a problem for those on dialup or with tight disk quotas. 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 We'll show the world we are prosperous, even if we have to go broke to do it. Will Rogers From alan.gauld at btinternet.com Wed Sep 12 09:59:00 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 12 Sep 2007 08:59:00 +0100 Subject: [Tutor] calling class instances in functions References: <2107481c0709112012v70e8c18eh60332158c2f13914@mail.gmail.com> Message-ID: <fc868o$211$1@sea.gmane.org> "Ara Kooser" <ghashsnaga at gmail.com> wrote > In the main program at the function def add_yeast(world): I want to > instance the class GoodYeast and have the global variable @ change > to > G on the world. I tried just creating an instance but that did not > go > over so well. "did no go over so well" is not very useful to us. Can you be a bit more specific? How did you create the instance? What happened? Did you get an error message? If so what? Can you show us the specific code where you create the instance? I don't see it in the code you posted? But theres rather a lot. Can you show us a shorter example of what you are trying to do? -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Wed Sep 12 13:24:12 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 12 Sep 2007 07:24:12 -0400 Subject: [Tutor] Image Analysis In-Reply-To: <20070912054011.GA5480@ayn.mi.celestial.com> References: <15059.1222.qm@web32403.mail.mud.yahoo.com> <200709120157.35935.eike.welk@gmx.net> <20070912030936.GA45033@cutter.rexx.com> <46E774C3.4090405@brunson.com> <20070912054011.GA5480@ayn.mi.celestial.com> Message-ID: <46E7CC5C.5090204@tds.net> Bill Campbell wrote: > Most mailing lists limit the size > of messages to 40k or less. On this list large messages go to moderation. I think I was so captivated with the images that I forgot about the size. A better way to present this would be to put the images on a web site and reference them from email. Sorry about that... Kent From kent37 at tds.net Wed Sep 12 13:33:20 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 12 Sep 2007 07:33:20 -0400 Subject: [Tutor] calling class instances in functions In-Reply-To: <2107481c0709112012v70e8c18eh60332158c2f13914@mail.gmail.com> References: <2107481c0709112012v70e8c18eh60332158c2f13914@mail.gmail.com> Message-ID: <46E7CE80.2000608@tds.net> Ara Kooser wrote: Your question is not very clear but I made some guesses below. > zz = raw_iput("What kind of yeast cell do you want to add? > Options:GoodYeast") > #Here I want to call this instace of GoodYeast from yeast_cell.py So you want the user to input the name of a class and you create an instance of the class? Try cls = getattr(yeast_cell, zz) instance = cls() > class GoodYeast: > #Cooperates all the time > YEAST = 'G' > #Should change generic variable @ in the world to G??? This is just assigning a class variable. The assignment is made at the time the class is defined, not when an instance is created, so that is not what you want either. > def __init__(self,name): > self.name = name > currency = 0 > location = [] I agree with John that changing a global variable in another module when a class instance is created doesn't seem like a great design, but you can do it here with import main # or whatever the main module is called main.YEAST = 'G' In general it is good to avoid circular dependencies like this, they lead to a variety of complications. Maybe YEAST could be a variable in the yeast_cell module? Kent From janos.juhasz at VELUX.com Wed Sep 12 14:00:30 2007 From: janos.juhasz at VELUX.com (=?ISO-8859-1?Q?J=E1nos_Juh=E1sz?=) Date: Wed, 12 Sep 2007 14:00:30 +0200 Subject: [Tutor] Unicode question In-Reply-To: <46E69CE4.9000803@tds.net> Message-ID: <OF835298AD.203BD673-ONC1257354.003D1787-C1257354.0041F542@velux.com> Dear Kent, thanks for your respond. It is clear now. > As a mnemonic I think of Unicode as pure unencoded data. (This is *not* > accurate, it is a memory aid!) Then it's easy to remember that decode() > removes encoding == convert to Unicode, encode() adds encoding == > convert from Unicode. So I had to convert cp852 ascii file into unicode, that can be made with page.decode('cp852') There was another problem also about, o with double acute and O with double acute, as they were missed from the font files. It works well now. from reportlab.platypus import * from reportlab.lib.styles import getSampleStyleSheet from reportlab.lib import pagesizes from reportlab.lib.units import cm PAGE_HEIGHT=defaultPageSize[1] import copy styles = getSampleStyleSheet() InvStyle = copy.deepcopy(styles["Normal"]) InvStyle.fontSize = 8 InvStyle.leading = 9 InvStyle.fontName = 'Courier' InvLineNum = 92 im = Image("bimbambumm.bmp", width=100, height=35) im.hAlign = 'RIGHT' def MakePdfInvoice(InvoiceNum, pages): PdfInv = [] for page in pages: PdfInv.append(im) PdfInv.append(Preformatted(page, InvStyle)) PdfInv.append(PageBreak()) PdfInv = PdfInv[:-1] doc = SimpleDocTemplate(InvoiceNum) doc.topMargin = 1*cm doc.bottomMargin = 0 doc.leftMargin = 0 doc.rightMArgin = 0 doc.build(PdfInv) def BreakIntoPages(content): while len(content) > InvLineNum: page = content[:InvLineNum] content = content[InvLineNum:] yield page else: yield content if __name__ == '__main__': content = open('invoice01_0707.txt').readlines() content = [line.replace('\x8a','\x99').replace('\x8b','\x94') for line in content] pages = [] for page in BreakIntoPages(content): page = ''.join(page) pages.append(page.decode('cp852')) MakePdfInvoice('test.pdf', pages) Kent Johnson <kent37 at tds.net> wrote on 2007.09.11 15:49:24: > J?nos Juh?sz wrote: > > Dear All, > > > > I would like to convert my DOS txt file into pdf with reportlab. > > The file can be seen correctly in Central European (DOS) encoding in > > Explorer. > > > > My winxp uses cp852 as default codepage. > > > > When I open the txt file in notepad and set OEM/DOS script for terminal > > fonts, it shows the file correctly. > > > > I tried to convert the file with the next way: > > > Use decode() here, not encode(). > decode() goes towards Unicode > encode() goes away from Unicode > As a mnemonic I think of Unicode as pure unencoded data. (This is *not* > accurate, it is a memory aid!) Then it's easy to remember that decode() > removes encoding == convert to Unicode, encode() adds encoding == > convert from Unicode. > > MakePdfInvoice('test.pdf', page) > > > > But it raised exception: > > ordinal not in range(128) > When you call encode on a string (instead of a unicode object) the > string is first decoded to Unicode using ascii encoding. This usually fails. > Kent From wormwood_3 at yahoo.com Wed Sep 12 15:21:28 2007 From: wormwood_3 at yahoo.com (wormwood_3) Date: Wed, 12 Sep 2007 06:21:28 -0700 (PDT) Subject: [Tutor] Image Analysis Message-ID: <443787.8228.qm@web32405.mail.mud.yahoo.com> Very strange. This is the second time that I know of in the last month that I have not received some emails from the list. I did not get the message Eike Welk sent out. Checking archives... ----- Original Message ---- From: Dave Kuhlman <dkuhlman at rexx.com> To: tutor at python.org Sent: Tuesday, September 11, 2007 11:09:36 PM Subject: Re: [Tutor] Image Analysis On Wed, Sep 12, 2007 at 01:57:35AM +0200, Eike Welk wrote: > I have attached the program, the input image, and the output image. > Please do not stuff 1 MB emails in my mailbox. Either (1) post the images on the Web and provide a link or (2) ask before emailing large attachments. Thank you. Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From mlangford.cs03 at gtalumni.org Wed Sep 12 15:38:18 2007 From: mlangford.cs03 at gtalumni.org (Michael Langford) Date: Wed, 12 Sep 2007 09:38:18 -0400 Subject: [Tutor] calling class instances in functions In-Reply-To: <2107481c0709112012v70e8c18eh60332158c2f13914@mail.gmail.com> References: <2107481c0709112012v70e8c18eh60332158c2f13914@mail.gmail.com> Message-ID: <82b4f5810709120638v17f89247i40fd6331c511e8b8@mail.gmail.com> I too am a little confused what exactly you're going for, but here is a shot at the two things I think you could be asking for: If you're trying to create a world where you have it populated with several different types of cells at different coordinates, and you'd like to make it so the user can select one of the already created cells, I suggest making a class for the world, and having its str method create a text list something like so you can use it for printing out to the user if they need to interact with the individual cells. 1. Yeast(0,4) 2. Malaria(5,6) 3. Gondrii(5,8) 4. Yeast(5,9) ... Etc. World would use getattr to get the name of the class of each cell on it, and would append the position. I'd make a function that will be able to get cells based on the number that the user selected. Also, a dictionary keyed off a positions tuple will probably work just fine for your world and will also be a lot easier and faster to access and enumerate, especially if you make the field very very large. ie, You could populate the world like this non interactively: world_data = {} word_data[(0,4)] = Yeast() word_data[(5,6)] = Malaria() word_data[(5,8)] = Gondrii() word_data[(5,9)] = Yeast() ================ Now if I've misunderstood, and you're talking about making NEW cells of various types and the user dynamically tells you what places to put what cells, here is how you do that. In your main, I would collect a list of all the types of microbes you can create and cycle through them to get their names, and use the users choices to make them and use the users choice of position to insert them in the world: myWorld = World() theMicrobes = [Yeast,Malaria,Gondrii] print "Please type the name of the microbe you wish to create:" for each in theMicrobes: cls = getattr(each,"__class__") print cls.__name__ microbeToCreateRaw= raw_input() # #do some stuff here to cleanup the input # for each in theMicrobes: cls = getattr(each,"__class__") if microbeToCreate == cls.__name__: newMicrobe = cls() #Now you find where they wish to drop it in the world print "Where do you want it in the world?" rawCoords = raw_input() #parse out the x and y # # Left to the reader to parse out # myWorld.insertAt(newMicrobe,x,y) #assuming you made a class for the world --Michael On 9/11/07, Ara Kooser <ghashsnaga at gmail.com> wrote: > > Thank you for your help on classes. I am working on an old program I > started in 2005. This time around I am trying to model cell behavior > using a PD model. I have the main program and then a file called > yeast_cell.py that contains the classes I want to instance. > > In the main program at the function def add_yeast(world): I want to > instance the class GoodYeast and have the global variable @ change to > G on the world. I tried just creating an instance but that did not go > over so well. I was wondering what is the proper and pythonic way to > create an instance that the user will be selecting in a function. I > eventually want to add a bunch of different cell classes. > > Thank you for your help. > > Ara Kooser > > > Main Program > ######################################################################## > #Yeast Cooperation Model > #by Ara Kooser > #Version 1.0 no PD, 070906 > # > #This code contain just the world setup and not the actually PD code > #for copperation behavior. This is better left to classes not functions > # > #TO DO LIST: Add error handling, dump to text file, data gathering, > #different classes of yeast > # > #Many thanks to: Danny Yoo, Lee Haar, Max Noel, Kent Johnson > ######################################################################## > > import random > import copy > import textwrap > import yeast_cell > > > ######################################################################### > #This section of the code sets up and prints out the starting conditions > #of the world and the yeast > ######################################################################## > > > YEAST, EMPTY, GROUP = '@', '.', 'Q' > > > def percolation(perc): > #Sets up a percolation threshold value > randval = random.random() > if randval > perc: > return EMPTY > else: > return YEAST > > def random_world(M, N): > #Constructs random world of size MxN > world = {} > for j in range(N): > for i in range(M): > world[i, j] = percolation(perc) > world['dimensions'] = (M, N) > return world > > def print_world(world): > #Prints out a string representation of a world. > M, N = world['dimensions'] > for j in range(N): > for i in range(M): > print world[i, j], > print > > > def add_yeast(world): > #Allows the user to add a yeast cell at point m,n > M,N = world['dimensions'] > new_world = copy.copy(world) > > counta = 0 > > yy = raw_input("How many yeast cells do you wish to add?") > yy = int(yy) > > while counta<yy: > zz = raw_iput("What kind of yeast cell do you want to add? > Options:GoodYeast") > #Here I want to call this instace of GoodYeast from yeast_cell.py > > > print "Please place this yeast cell using an m,n point" > print "The upper left hand corner is (0,0)" > i = int(raw_input("Please enter a m value for the yeast cell.")) > j = int(raw_input("Please enter a n value for the yeast cell.")) > > new_world[i,j] = YEAST > for j in range(N): > for i in range(M): > world[i,j]=new_world[i,j] > > counta = counta+1 > > print_world(small_world) > > > ################################## > #The following code gets the state of the world and determines > #what is next to each cell, sensing > ################################# > > def get_state(world,i,j): > #Returns the state of the cell at position (i,j) > return world.get((i,j), EMPTY) > > def count_neighbors(world,i,j): > #Returns the number of cells next to this one > live_count = 0 > for i_delta in [-1,0,1]: > for j_delta in [-1,0,1]: > if(i_delta,j_delta)==(0,0): > continue > if get_state(world, i+i_delta, j+j_delta)==YEAST: > live_count+=1 > return live_count > > def is_grouped(world,i,j): > #Returns a true value if the cell at (i,j) is connected by 1-8 others > return(get_state(world,i,j)==YEAST and > (1 <=count_neighbors(world,i,j)<=8)) > > def next_world(world): > #Shows which yeast are in a group using Q > M,N = world['dimensions'] > new_world=copy.copy(world) > for j in range(N): > for i in range(M): > if is_grouped(world,i,j): > new_world[i,j] = GROUP > for j in range(N): > for i in range(M): > world[i,j]=new_world[i,j] > > def AddYeast(): > print "If you selected 0 for your percolation you may now add > yeast to the world." > print "The upper left hand corner is point (0,0)." > zz = raw_input("Do you want to add a yeast cell? y or n") > if zz == "y": > add_yeast(small_world) > > elif zz == "n": > print_world(small_world) > > raw_input("Please press return to group your yeast cells.") > > ##################################################### > #This is where the PD portion of the program starts > ##################################################### > > def PD_yeast(): > print textwrap.fill ("The PD will added later in the OOP version") > print"REFERENCES" > print textwrap.fill ("Learning to program. By Alan Gauld") > print textwrap.fill ("How to Think Like a Computer Scientist. By > Downey, Elkner, and Meyers") > print textwrap.fill("Cooperation amoung Microorganisms. Wingreen > and Levin.") > print textwrap.fill ("Synthetic cooperation in engineered yeast > populations. Shou, Ram, and Vilar") > print textwrap.fill ("Evolution in group-structured populations > can resolve the tragedy of the commons. Killingback, Bieri, and > Flatt") > > > ############################################################################### > #Start of program > > ############################################################################### > > > > raw_input("Please press return to start the program.") > > perc = raw_input("Please enter a thresold between 0-1 for the > population.") > perc = float(perc) > > > n = int(raw_input("Please enter a n dimension. ")) > m = int(raw_input("Please enter a m dimension. ")) > > > small_world = random_world(m,n) > > print_world(small_world) > > AddYeast() > > next_world(small_world) > print_world(small_world) > > print "Q indictates that the yeast cells found a group." > print > print > print "Please press return to start the PD program." > print > print > > > PD_yeast() > > > yeast_cell.py > ############################################################### > #yeast_cell.py > #Contains the different types of yeast behavior > #By Ara Kooser > ############################################################### > > > #0 = cooperate > #1 = defect > > > class GoodYeast: > #Cooperates all the time > YEAST = 'G' > #Should change generic variable @ in the world to G??? > def __init__(self,name): > self.name = name > currency = 0 > location = [] > > def response(self): > return 0 > > def location(world,i,j): > return world.get(i,j) > #I believe this allows the cell to know it's coordinates > > > -- > 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 > -- Michael Langford Phone: 404-386-0495 Consulting: http://www.TierOneDesign.com/ Entertaining: http://www.ThisIsYourCruiseDirectorSpeaking.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070912/744c4289/attachment-0001.htm From wormwood_3 at yahoo.com Wed Sep 12 15:43:35 2007 From: wormwood_3 at yahoo.com (wormwood_3) Date: Wed, 12 Sep 2007 06:43:35 -0700 (PDT) Subject: [Tutor] Image Analysis Message-ID: <75672.43946.qm@web32413.mail.mud.yahoo.com> Could not find it. The searchable interface at ActiveState's site does not have it, and I don't know of any way to search the zipped archives... Eike, if you would be able to send me your post, even just to my address and not the tutor list, I would greatly appreciate it! Seems it had some neat things in it. -Sam ----- Original Message ---- From: wormwood_3 <wormwood_3 at yahoo.com> To: Python Tutorlist <tutor at python.org> Sent: Wednesday, September 12, 2007 9:21:28 AM Subject: Re: [Tutor] Image Analysis Very strange. This is the second time that I know of in the last month that I have not received some emails from the list. I did not get the message Eike Welk sent out. Checking archives... ----- Original Message ---- From: Dave Kuhlman <dkuhlman at rexx.com> To: tutor at python.org Sent: Tuesday, September 11, 2007 11:09:36 PM Subject: Re: [Tutor] Image Analysis On Wed, Sep 12, 2007 at 01:57:35AM +0200, Eike Welk wrote: > I have attached the program, the input image, and the output image. > Please do not stuff 1 MB emails in my mailbox. Either (1) post the images on the Web and provide a link or (2) ask before emailing large attachments. Thank you. Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman _______________________________________________ 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 python at mrfab.info Wed Sep 12 15:58:46 2007 From: python at mrfab.info (Michael) Date: Wed, 12 Sep 2007 21:58:46 +0800 Subject: [Tutor] interpreted or compiled? Message-ID: <46E7F096.8050408@mrfab.info> Hi As a new Python user I was curious if you can run Python without the environment, ie make it an executable? Thanks Michael From kent37 at tds.net Wed Sep 12 16:14:20 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 12 Sep 2007 10:14:20 -0400 Subject: [Tutor] Image Analysis In-Reply-To: <75672.43946.qm@web32413.mail.mud.yahoo.com> References: <75672.43946.qm@web32413.mail.mud.yahoo.com> Message-ID: <46E7F43C.3060604@tds.net> wormwood_3 wrote: > Could not find it. The searchable interface at ActiveState's site does not have it, and I don't know of any way to search the zipped archives... There is a plaintext archive at http://mail.python.org/pipermail/tutor/ Here is the post you want though without the attachments: http://mail.python.org/pipermail/tutor/2007-September/057012.html Kent From wormwood_3 at yahoo.com Wed Sep 12 16:19:28 2007 From: wormwood_3 at yahoo.com (wormwood_3) Date: Wed, 12 Sep 2007 07:19:28 -0700 (PDT) Subject: [Tutor] interpreted or compiled? Message-ID: <836611.73027.qm@web32403.mail.mud.yahoo.com> Michael, The most common method I know of to do this is py2exe: http://www.py2exe.org/ This lets you turn scripts into executable Windows programs. A different, and perhaps better, method is PyInstaller: http://pyinstaller.python-hosting.com/ This creates executables for Windows and Linux. If you just meant run a script without calling Python, you can add the she-bang line (#!/usr/bin/python as the first line. Change to wherever Python lives on your system), and make the file executable (this is all assuming you are on Linux, sorry). Then you can just do "./mycoolscript.py" and run it. Hope these help! -Sam ----- Original Message ---- From: Michael <python at mrfab.info> To: tutor at python.org Sent: Wednesday, September 12, 2007 9:58:46 AM Subject: [Tutor] interpreted or compiled? Hi As a new Python user I was curious if you can run Python without the environment, ie make it an executable? Thanks Michael _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From python at mrfab.info Wed Sep 12 16:27:27 2007 From: python at mrfab.info (Michael) Date: Wed, 12 Sep 2007 22:27:27 +0800 Subject: [Tutor] interpreted or compiled? In-Reply-To: <836611.73027.qm@web32403.mail.mud.yahoo.com> References: <836611.73027.qm@web32403.mail.mud.yahoo.com> Message-ID: <46E7F74F.5050405@mrfab.info> wormwood_3 wrote: > Michael, > > The most common method I know of to do this is py2exe: http://www.py2exe.org/ This lets you turn scripts into executable Windows programs. > > A different, and perhaps better, method is PyInstaller: http://pyinstaller.python-hosting.com/ This creates executables for Windows and Linux. > > If you just meant run a script without calling Python, you can add the she-bang line (#!/usr/bin/python as the first line. Change to wherever Python lives on your system), and make the file executable (this is all assuming you are on Linux, sorry). Then you can just do "./mycoolscript.py" and run it. > > Hope these help! > > -Sam > > ----- Original Message ---- > From: Michael <python at mrfab.info> > To: tutor at python.org > Sent: Wednesday, September 12, 2007 9:58:46 AM > Subject: [Tutor] interpreted or compiled? > > Hi > > As a new Python user I was curious if you can run Python without the > environment, ie make it an executable? > > Thanks > > Michael > _______________________________________________ > 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 > > Thanks guys. Amazingly quick response. From srikanth007m at gmail.com Wed Sep 12 16:39:12 2007 From: srikanth007m at gmail.com (chinni) Date: Wed, 12 Sep 2007 20:09:12 +0530 Subject: [Tutor] Tutor Digest, Vol 43, Issue 36 In-Reply-To: <mailman.1288.1189549813.2656.tutor@python.org> References: <mailman.1288.1189549813.2656.tutor@python.org> Message-ID: <b5300ea90709120739h1a4379d7q3cf480bfe1ae63d1@mail.gmail.com> Hi, Thanx for Responding for the Query. The actual Output what i want is my python script has to change the version number(degrade) in plist file.and automatically change the time to 25 hrs more from present time cause my product will check for updates for every 25hrs. But u all told that cronjob and at inbuilt features of UNIX but every time ihave to manually go and change the version.i can't so that's why i want to write a script for this 1.open the app 2.degrade the version automatically to least version 3.change the time to 25hrs more 4.check for updates(1.force Update and silent update) 5.the whole procedure is for admin and non-admin users can i implement this by using both python and shell scripting.if possible give the reference book for quick learn. > > > Message: 2 > Date: Tue, 11 Sep 2007 22:24:37 +0530 > From: chinni <srikanth007m at gmail.com> > Subject: [Tutor] automate daily tasks > To: tutor at python.org > Message-ID: > <b5300ea90709110954v38e84b3fo3af2c0a346784dcc at mail.gmail.com> > Content-Type: text/plain; charset="iso-8859-1" > > Hi all, > > I am working on MAC OS x my project is updating all ready installed > products.I have to automate this in python.so,can any one will give some > suggestions and some examples how to automate.some basic things of my > project is ... i think u all know that there will be a plist file for each > product in mac.i have to degrade the version of plist automatically > through > my script and it has to edit the plist file and degrade it to least > version > and as to check for updates by itself.like this there are 15 products > under > this now each time i can't go and degrade the version and save it and run > updates manually..so,that can any one plz..tell me how to start from first > step... > > -- > Best Regards, > M.Srikanth Kumar, > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: > http://mail.python.org/pipermail/tutor/attachments/20070911/75c73c5e/attachment-0001.htm > > ------------------------------ > > Message: 3 > Date: Tue, 11 Sep 2007 13:03:54 -0400 > From: "Tom Tucker" <tktucker at gmail.com> > Subject: Re: [Tutor] automate daily tasks > To: srikanthkumar007m at rediffmail.com > Cc: tutor at python.org > Message-ID: > <2a278ffe0709111003v5d89101fvebdcde704fc9a5b7 at mail.gmail.com> > Content-Type: text/plain; charset="iso-8859-1" > > Are you looking for a method to automate the execution of your Python > program? Is that the question? > If yes, have you tried using cron or at jobs (man cron or man at). > > Tom > > On 9/11/07, chinni <srikanth007m at gmail.com> wrote: > > > > Hi all, > > > > I am working on MAC OS x my project is updating all ready installed > > products.I have to automate this in python.so,can any one will give some > > suggestions and some examples how to automate.some basic things of my > > project is ... i think u all know that there will be a plist file for > each > > product in mac.i have to degrade the version of plist automatically > > through my script and it has to edit the plist file and degrade it to > least > > version and as to check for updates by itself.like this there are 15 > > products under this now each time i can't go and degrade the version and > > save it and run updates manually..so,that can any one plz..tell me how > to > > start from first step... > > > > -- > > Best Regards, > > M.Srikanth Kumar, > > > > > > _______________________________________________ > > 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/20070911/ea45fd19/attachment-0001.htm > > ------------------------------ > > Message: 4 > Date: Tue, 11 Sep 2007 18:37:33 +0100 > From: "Alan Gauld" <alan.gauld at btinternet.com> > Subject: Re: [Tutor] automate daily tasks > To: tutor at python.org > Message-ID: <fc6jpg$ihc$1 at sea.gmane.org> > Content-Type: text/plain; format=flowed; charset="iso-8859-1"; > reply-type=original > > > "chinni" <srikanth007m at gmail.com> wrote > > > I am working on MAC OS x my project is updating all ready installed > > products.I have to automate this in python.so,can any one will give > > some > > sounds fair. > > > project is ... i think u all know that there will be a plist file > > for each > > product in mac. > > I wouldn't assume too much knowledge of how MacOS works, > despite Apple's recent successes its still very much a > minority OS! I own an iBook and use the Terminal for unix > type stuff but I rarely delve inside the MacOs specifics. > > > i have to degrade the version of plist automatically through > > my script and it has to edit the plist file and degrade it to least > > version > > and as to check for updates by itself.like this there are 15 > > products under > > this now each time i can't go and degrade the version and save it > > and run > > updates manually..so,that can any one plz..tell me how to start from > > first > > step... > > Nope, sorry. You lost me on that one. > Can you give some example data formats. > And maybe show us what you are trying to do with them? > > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.freenetpages.co.uk/hp/alan.gauld > > > > > > -- Best Regards, M.Srikanth Kumar, -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070912/3966890a/attachment.htm From eike.welk at gmx.net Wed Sep 12 16:40:52 2007 From: eike.welk at gmx.net (Eike Welk) Date: Wed, 12 Sep 2007 16:40:52 +0200 Subject: [Tutor] Image Analysis In-Reply-To: <75672.43946.qm@web32413.mail.mud.yahoo.com> References: <75672.43946.qm@web32413.mail.mud.yahoo.com> Message-ID: <200709121640.53212.eike.welk@gmx.net> On Wednesday 12 September 2007 15:43, wormwood_3 wrote: > Eike, if you would be able to send me your post, even just to my > address and not the tutor list, I would greatly appreciate it! > Seems it had some neat things in it. I've sent it to your e-mail address (wormwood_3 at yahoo.com). From eike.welk at gmx.net Wed Sep 12 17:05:01 2007 From: eike.welk at gmx.net (Eike Welk) Date: Wed, 12 Sep 2007 17:05:01 +0200 Subject: [Tutor] Image Analysis In-Reply-To: <20070912030936.GA45033@cutter.rexx.com> References: <15059.1222.qm@web32403.mail.mud.yahoo.com> <200709120157.35935.eike.welk@gmx.net> <20070912030936.GA45033@cutter.rexx.com> Message-ID: <200709121705.02818.eike.welk@gmx.net> On Wednesday 12 September 2007 05:09, Dave Kuhlman wrote: > Please do not stuff 1 MB emails in my mailbox. Either (1) post the > images on the Web and provide a link or (2) ask before emailing > large attachments. Sorry! I guess I'm spoiled by my ADSL connection. I did not know that the limit is so low (40 KB). I did really consider to put the images on a web server, but the Berlios ftp server was down last night. (It's the only one where I have bookmarked the upload directory.) It was also late and I wanted to send the message before it would become pointless; so I sent it with the images attached. To the moderators: Thank you for posting my big message. Kind regards, Eike. From tktucker at gmail.com Wed Sep 12 17:06:28 2007 From: tktucker at gmail.com (Tom Tucker) Date: Wed, 12 Sep 2007 11:06:28 -0400 Subject: [Tutor] Tutor Digest, Vol 43, Issue 36 In-Reply-To: <b5300ea90709120739h1a4379d7q3cf480bfe1ae63d1@mail.gmail.com> References: <mailman.1288.1189549813.2656.tutor@python.org> <b5300ea90709120739h1a4379d7q3cf480bfe1ae63d1@mail.gmail.com> Message-ID: <2a278ffe0709120806i7f86a62avc3caef70e2a5440a@mail.gmail.com> Comments below. On 9/12/07, chinni <srikanth007m at gmail.com> wrote: > > Hi, > Thanx for Responding for the Query. > The actual Output what i want is my python script has to change the > version number(degrade) in plist file.and automatically change the time to > 25 hrs more from present time cause my product will check for updates for > every 25hrs. > But u all told that cronjob and at inbuilt features of UNIX but every time > ihave to manually go and change the version.i can't so that's why i want > to write a script for this > > 1.open the app > 2.degrade the version automatically to least version What is the manual process for this task? More info is need here. Is plist a text file? 3.change the time to 25hrs more Are we changing the system time 25 hours ahead, changing a time variable in the script, or flag/timestamp in the plist file? 4.check for updates(1.force Update and silent update) This is achievable with a system call. 5.the whole procedure is for admin and non-admin users We change the unix file permission to restrict which user and groups are allowed access to the file. can i implement this by using both python and shell scripting.if possible > give the reference book for quick learn. >From what we know so far, yes. Please share what you have coded so far. Message: 2 > > Date: Tue, 11 Sep 2007 22:24:37 +0530 > > From: chinni <srikanth007m at gmail.com> > > Subject: [Tutor] automate daily tasks > > To: tutor at python.org > > Message-ID: > > <b5300ea90709110954v38e84b3fo3af2c0a346784dcc at mail.gmail.com> > > Content-Type: text/plain; charset="iso-8859-1" > > > > Hi all, > > > > I am working on MAC OS x my project is updating all ready installed > > products.I have to automate this in python.so,can any one will give some > > suggestions and some examples how to automate.some basic things of my > > project is ... i think u all know that there will be a plist file for > > each > > product in mac.i have to degrade the version of plist automatically > > through > > my script and it has to edit the plist file and degrade it to least > > version > > and as to check for updates by itself.like this there are 15 products > > under > > this now each time i can't go and degrade the version and save it and > > run > > updates manually..so,that can any one plz..tell me how to start from > > first > > step... > > > > -- > > Best Regards, > > M.Srikanth Kumar, > > -------------- next part -------------- > > An HTML attachment was scrubbed... > > URL: > > http://mail.python.org/pipermail/tutor/attachments/20070911/75c73c5e/attachment-0001.htm > > > > ------------------------------ > > > > Message: 3 > > Date: Tue, 11 Sep 2007 13:03:54 -0400 > > From: "Tom Tucker" < tktucker at gmail.com> > > Subject: Re: [Tutor] automate daily tasks > > To: srikanthkumar007m at rediffmail.com > > Cc: tutor at python.org > > Message-ID: > > <2a278ffe0709111003v5d89101fvebdcde704fc9a5b7 at mail.gmail.com> > > Content-Type: text/plain; charset="iso-8859-1" > > > > Are you looking for a method to automate the execution of your Python > > program? Is that the question? > > If yes, have you tried using cron or at jobs (man cron or man at). > > > > Tom > > > > On 9/11/07, chinni < srikanth007m at gmail.com> wrote: > > > > > > Hi all, > > > > > > I am working on MAC OS x my project is updating all ready installed > > > products.I have to automate this in python.so,can any one will give > > some > > > suggestions and some examples how to automate.some basic things of my > > > project is ... i think u all know that there will be a plist file for > > each > > > product in mac.i have to degrade the version of plist automatically > > > through my script and it has to edit the plist file and degrade it to > > least > > > version and as to check for updates by itself.like this there are 15 > > > products under this now each time i can't go and degrade the version > > and > > > save it and run updates manually..so,that can any one plz..tell me how > > to > > > start from first step... > > > > > > -- > > > Best Regards, > > > M.Srikanth Kumar, > > > > > > > > > _______________________________________________ > > > 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/20070911/ea45fd19/attachment-0001.htm > > > > > > ------------------------------ > > > > Message: 4 > > Date: Tue, 11 Sep 2007 18:37:33 +0100 > > From: "Alan Gauld" <alan.gauld at btinternet.com> > > Subject: Re: [Tutor] automate daily tasks > > To: tutor at python.org > > Message-ID: <fc6jpg$ihc$1 at sea.gmane.org> > > Content-Type: text/plain; format=flowed; charset="iso-8859-1"; > > reply-type=original > > > > > > "chinni" <srikanth007m at gmail.com> wrote > > > > > I am working on MAC OS x my project is updating all ready installed > > > products.I have to automate this in python.so,can any one will give > > > some > > > > sounds fair. > > > > > project is ... i think u all know that there will be a plist file > > > for each > > > product in mac. > > > > I wouldn't assume too much knowledge of how MacOS works, > > despite Apple's recent successes its still very much a > > minority OS! I own an iBook and use the Terminal for unix > > type stuff but I rarely delve inside the MacOs specifics. > > > > > i have to degrade the version of plist automatically through > > > my script and it has to edit the plist file and degrade it to least > > > version > > > and as to check for updates by itself.like this there are 15 > > > products under > > > this now each time i can't go and degrade the version and save it > > > and run > > > updates manually..so,that can any one plz..tell me how to start from > > > first > > > step... > > > > Nope, sorry. You lost me on that one. > > Can you give some example data formats. > > And maybe show us what you are trying to do with them? > > > > > > -- > > Alan Gauld > > Author of the Learn to Program web site > > http://www.freenetpages.co.uk/hp/alan.gauld > > > > > > > > > > > > > > -- > Best Regards, > M.Srikanth Kumar, > > > _______________________________________________ > 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/20070912/2c1c4a01/attachment.htm From abooth at stanford.edu Wed Sep 12 17:35:48 2007 From: abooth at stanford.edu (Ashley Booth) Date: Wed, 12 Sep 2007 08:35:48 -0700 Subject: [Tutor] Making a python script to feed files into another pythonscript In-Reply-To: <e5210f1c0709111451h397293ffq75bee693e8555976@mail.gmail.com> References: <e5210f1c0709101540w56e63c02pe0d0d23e6df28a84@mail.gmail.com> <fc5h7f$i5p$1@sea.gmane.org> <e5210f1c0709111451h397293ffq75bee693e8555976@mail.gmail.com> Message-ID: <e5210f1c0709120835r3bd84b4agb221669065d334c8@mail.gmail.com> Unfortunately I was confused by both responses I received. I have only been working with Python for a week, so everything is new. Thanks for your patience. John- I was not sure what you meant by "command line". I took what you said quite literally and created this: indir = raw_input('input directory path ') # asks for input directory script1 = raw_input('python script path ') # asks for path to desired script for j in os.listdir(indir): input = os.path.join(indir,j) output = os.path.join(indir,j.split('rovctd')[0]+'.txt') os.system('python %s %s %s' % (script1, input, output) which does not run and I was confused by all the % symbols. I think I completely misinterpreted your comment. Alan-I am confused about how to used the communicate() module. Could you please give me an example? the format should be(?): communicate(input=None) where input is the file path I want to give my child process (script1) (what if I have two files paths I need to give it?- one for the input file path and one for the output? and I want to put PIPE and not None so that it will deliver that input? What I was trying to say before at the end of my post: > I would at least be happy with how to tack on the list > directory stuff to THE END of the script1- it would not be a > stand alone script but at least it would work. In other words, instead of having a stand alone script that feeds files into script1 (the program I want the files to be fed into-it reformats files so it requires a file path input and output), could I have script1 ask me for a directory instead of a specific input and output file path as it does now. Then it would theoretically go through and reformat each file in that directory, rename them and put the formatted files back in that directory. I hope that is clearer. Thanks again! From agunnerson at gmail.com Wed Sep 12 17:45:48 2007 From: agunnerson at gmail.com (Andy) Date: Wed, 12 Sep 2007 09:45:48 -0600 Subject: [Tutor] Would an emulator be possible in Python? Message-ID: <26e972870709120845s1e597fcelc41708ab6ef3fce5@mail.gmail.com> Ok, I'm pretty sure the answer is no but I'm hoping that someone will prove me wrong. I have decided that I would like to try and write an emulator, I'm going to start out with a couple of simpler systems like the Chip 8 and maybe a well documented arcade game but I would like to do an NES emulator eventually. Is Python anywhere near fast enough to do this and have it be playable? I hope so because I really don't like C/C++. -- -Andy "I have a great faith in fools; self-confidence my friends call it." ? Edgar Allen Poe From kent37 at tds.net Wed Sep 12 19:31:40 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 12 Sep 2007 13:31:40 -0400 Subject: [Tutor] Would an emulator be possible in Python? In-Reply-To: <26e972870709120845s1e597fcelc41708ab6ef3fce5@mail.gmail.com> References: <26e972870709120845s1e597fcelc41708ab6ef3fce5@mail.gmail.com> Message-ID: <46E8227C.7000702@tds.net> Andy wrote: > Ok, I'm pretty sure the answer is no but I'm hoping that someone will > prove me wrong. I have decided that I would like to try and write an > emulator, I'm going to start out with a couple of simpler systems like > the Chip 8 and maybe a well documented arcade game but I would like to > do an NES emulator eventually. Is Python anywhere near fast enough to > do this and have it be playable? I hope so because I really don't > like C/C++. GIYF... Chip8 emulator, they claim it is *too* fast! http://www.pygame.org/projects/20/190/ Apparently Java was fast enough in 2003: http://www.peterbe.com/plog/blogitem-20031211-1300 Kent From alan.gauld at btinternet.com Wed Sep 12 19:51:03 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 12 Sep 2007 18:51:03 +0100 Subject: [Tutor] Making a python script to feed files into anotherpythonscript References: <e5210f1c0709101540w56e63c02pe0d0d23e6df28a84@mail.gmail.com><fc5h7f$i5p$1@sea.gmane.org><e5210f1c0709111451h397293ffq75bee693e8555976@mail.gmail.com> <e5210f1c0709120835r3bd84b4agb221669065d334c8@mail.gmail.com> Message-ID: <fc98ur$73t$1@sea.gmane.org> "Ashley Booth" <abooth at stanford.edu> wrote > John- I was not sure what you meant by "command line". I took what > you > said quite literally and created this: > > indir = raw_input('input directory path ') # asks for input > directory > script1 = raw_input('python script path ') # asks for path to > desired script > > for j in os.listdir(indir): > input = os.path.join(indir,j) > output = os.path.join(indir,j.split('rovctd')[0]+'.txt') > os.system('python %s %s %s' % (script1, input, output) Count the parens, you are one short... > which does not run and I was confused by all the % symbols. I think > I > completely misinterpreted your comment. This uises a "format string2 which is a Python feature enabling you to insert values into a string. In this case the string takes three values, all themselves strings - thats what %s means. The bit after the % on its own is the tuple of values to be inserted, in this case the values of script1, input and output. See the simple sequences topic in my tutorial for more info. > Alan-I am confused about how to used the communicate() module. Could > you please give me an example? > > the format should be(?): > > communicate(input=None) Look at the subprocess module for lots of examples of how to use the Popen class. It has a method called communicate which allows you to communicate with the running process and access its output. This is explained fuerther in the Using the OS topic in my tutorial... about three quarters down under the heading Running an External Program > What I was trying to say before at the end of my post: > >> I would at least be happy with how to tack on the list >> directory stuff to THE END of the script1- it would not be a >> stand alone script but at least it would work. > > In other words, instead of having a stand alone script that feeds > files into script1 (the program I want the files to be fed into-it > reformats files so it requires a file path input and output), This is the bit that confuses me. You want the initial program to reformat the files (which files?) so that it requires a path instead of a filename? > have script1 ask me for a directory instead of a specific input and > output file path as it does now. Sure, but it doesn't win you much if any advantage. > Then it would theoretically go > through and reformat each file in that directory, rename them and > put > the formatted files back in that directory. Why not just do that in the tiop level script? Or do you want a top level script that will do something like run any given script/command on any given file pattern? In other words a Python version of the unix find -exec command? Can you give us a sample user session to sjhow what this would look like if you got it working? 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 Wed Sep 12 19:54:01 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 12 Sep 2007 18:54:01 +0100 Subject: [Tutor] Image Analysis References: <75672.43946.qm@web32413.mail.mud.yahoo.com> Message-ID: <fc994e$7mo$1@sea.gmane.org> "wormwood_3" <wormwood_3 at yahoo.com> wrote > Could not find it. The searchable interface at ActiveState's site > does not have it, > and I don't know of any way to search the zipped archives... I use the gmane news inteface, I dunno about Eike, but its possible the problem lies in gmane's interface to the mailing list! > Very strange. This is the second time that I know of in the last > month > that I have not received some emails from the list. I did not get > the > message Eike Welk sent out. -- 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 Sep 12 20:01:41 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 12 Sep 2007 19:01:41 +0100 Subject: [Tutor] interpreted or compiled? References: <46E7F096.8050408@mrfab.info> Message-ID: <fc99iq$9de$1@sea.gmane.org> "Michael" <python at mrfab.info> wrote > As a new Python user I was curious if you can run Python without the > environment, ie make it an executable? There are two separate issues here. First: Can you make executable Python scripts? Yes, see Sam's response re py2exe etc Second: Can you run Python without the environment? No. py2exe and the other installers simply bundle up the interpreter and other modules you need into a single executable file. The environment is still present. This is somewhat analagous to a C/C++ program which is compiled. You can either link the libraries it needs statically or dynamically. If you do it statically you don't need those DLLs on the host PC but the file is much bigger, but if you do it dynamically the libraries need to be installed as well as the basic exe. Same with py2exe, the basic text files might only be a few kilobytes but the combined exe will be 5-10 Megabytes typically. 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 Sep 12 20:07:42 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 12 Sep 2007 19:07:42 +0100 Subject: [Tutor] Tutor Digest, Vol 43, Issue 36 References: <mailman.1288.1189549813.2656.tutor@python.org> <b5300ea90709120739h1a4379d7q3cf480bfe1ae63d1@mail.gmail.com> Message-ID: <fc99u3$ak6$1@sea.gmane.org> "chinni" <srikanth007m at gmail.com> wrote > But u all told that cronjob and at inbuilt features of UNIX but > every time > ihave to manually go and change the version.i can't The first question to answer is why not? If you can't do it manually you probably can't get a script to do it either! Assuming its a text file youb should be able to use sed to edit the file from a shell script using cron. > 1.open the app > 2.degrade the version automatically to least version > 3.change the time to 25hrs more Down to here, nomproblem and pyhon can do it all so far. > 4.check for updates(1.force Update and silent update) Not sure what this means. I suspect its Pythonable... > 5.the whole procedure is for admin and non-admin users A Unix issue mainly. > can i implement this by using both python and shell scripting. Yes I think so. In fact you can probably do it in shell only or python only or a mix of both. > if possible give the reference book for quick learn. Thee are lots of free tutorials on the Python web site under the beginners section. You could try my tutorial, just do the first "The Basics" section and take a look at the later "Using the OS" topic too. 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 Sep 12 21:26:46 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 12 Sep 2007 20:26:46 +0100 Subject: [Tutor] Would an emulator be possible in Python? References: <26e972870709120845s1e597fcelc41708ab6ef3fce5@mail.gmail.com> Message-ID: <fc9eib$r9i$1@sea.gmane.org> "Andy" <agunnerson at gmail.com> wrote > prove me wrong. I have decided that I would like to try and write > an > emulator, I'm going to start out with a couple of simpler systems > like > the Chip 8 and maybe a well documented arcade game but I would like > to > do an NES emulator eventually. That's pretty challenging but not that difficult techically for the CPU. The hardest bit is simulating the I/O subsystem and all the quirks of the monitor/OS. > Is Python anywhere near fast enough to do this and have > it be playable? Probably. Modern PCs are arpund 4000 times faster than the older machines and you can do a lot of emulation in 4000 instructions! And because you are doing it in a high level language a single machine instruction should only translate to a few Python commands which hopefully translate to a few hundred CPU commands. > I hope so because I really don't like C/C++. C is simple enough and quite good for this kind of thing because its so close to the hardware. C++ doesn't add much for this kind of job in my experience. Its basically a big jump table (aka dictionary) with a whole lot of very small functions. But python makes it easier to experiment because the jump table is almost fgree and the functions should be only a handful of lines each. The most technically challenging bit is likely to be reading the programs from the other machine - extracting and decoding the binary data format. If you have that documented then its a fairly straightforward if tedious job! -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From bill at celestial.net Thu Sep 13 01:01:05 2007 From: bill at celestial.net (Bill Campbell) Date: Wed, 12 Sep 2007 16:01:05 -0700 Subject: [Tutor] Image Analysis In-Reply-To: <46E7CC5C.5090204@tds.net> References: <15059.1222.qm@web32403.mail.mud.yahoo.com> <200709120157.35935.eike.welk@gmx.net> <20070912030936.GA45033@cutter.rexx.com> <46E774C3.4090405@brunson.com> <20070912054011.GA5480@ayn.mi.celestial.com> <46E7CC5C.5090204@tds.net> Message-ID: <20070912230105.GA1851@ayn.mi.celestial.com> On Wed, Sep 12, 2007, Kent Johnson wrote: >Bill Campbell wrote: >> Most mailing lists limit the size >> of messages to 40k or less. > >On this list large messages go to moderation. I think I was so >captivated with the images that I forgot about the size. A better way to >present this would be to put the images on a web site and reference them >from email. > >Sorry about that... I've done the same thing on occassion on lists I manage :-). One of the things I really like about the IMP webmail package is that it makes it easy for people to provide links to attachments rather than sending the files. It automatically copies the files to the web server, adding the links to the bottom of the message. I don't generally like web e-mail interfaces, but do use IMP when dealing with large attachment. 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 I don't make jokes, I just watch the Government and report the facts... Will Rogers From ghashsnaga at gmail.com Thu Sep 13 03:45:48 2007 From: ghashsnaga at gmail.com (Ara Kooser) Date: Wed, 12 Sep 2007 19:45:48 -0600 Subject: [Tutor] Classes: global name not defined Message-ID: <2107481c0709121845o7610a67aucebe485538dabe50@mail.gmail.com> So taking the advice given my John, Kent, and Michael I reworked the program and created a class for world. I was able to solve the first several errors that came up as a I moved functions into class methods but this one stumps me. The error I am getting is: Traceback (most recent call last): File "/Users/ara/Documents/yeast/oop_yeast_nocaps.py", line 87, in <module> first_instance.print_world() File "/Users/ara/Documents/yeast/oop_yeast_nocaps.py", line 40, in print_world m, n = world['dimensions'] NameError: global name 'world' is not defined I understand that the error refers to the method print_world(). In the instance before first_instance.print_world() I define what world is but that is not being carried over to the print_world method. In the print world method do I need to refer back to the random_world method so it knows what world is? Thank you. CODE STARTS HERE: import random import copy YEAST = '@' EMPTY = '.' GROUP = 'Q' class World: #What makes this a world def __init__(self,name): self.name = name #Add other things later #Methods def percolation(self,perc): #Sets up a percolation threshold value perc = float(perc) randval = random.random() if randval > perc: return EMPTY else: return YEAST def random_world(self): #Constructs random world of size MxN world = {} for j in range(n): for i in range(m): world[i, j] = self.percolation(perc) world['dimensions'] = (m, n) return world def print_world(self): #Prints out a string representation of a world. m, n = world['dimensions'] for j in range(n): for i in range(m): print world[i, j], print def add_yeast(self): #Allows the user to add a yeast cell at point m,n m,n = world['dimensions'] new_world = copy.copy(world) counta = 0 print "The upper left corner is the point (0,0)" yy = raw_input("How many yeast cells do you wish to add?") yy = int(yy) while counta<yy: i = int(raw_input("Please enter a m value for the yeast cell.")) j = int(raw_input("Please enter a n value for the yeast cell.")) new_world[i,j] = YEAST for j in range(n): for i in range(m): world[i,j]=new_world[i,j] counta = counta+1 def debug(self): print self.name ########################################################## #Start of prgram ########################################################## first_instance = World("small_world") #first_instance.debug() raw_input("Please press return to start the program.") perc = raw_input("Please enter a thresold between 0-1 for the population.") first_instance.percolation(perc) n = int(raw_input("Please enter a n dimension. ")) m = int(raw_input("Please enter a m dimension. ")) first_instance.random_world() first_instance.print_world() first_instance.add_yeast() -- Quis hic locus, quae regio, quae mundi plaga. Ubi sum. Sub ortu solis an sub cardine glacialis ursae. From cspears2002 at yahoo.com Thu Sep 13 05:36:01 2007 From: cspears2002 at yahoo.com (Christopher Spears) Date: Wed, 12 Sep 2007 20:36:01 -0700 (PDT) Subject: [Tutor] editTextFile.py Message-ID: <846024.78106.qm@web51612.mail.re2.yahoo.com> I created a script that opens an existing text file, allows the user to write over the original contents, and then save the file. The original contents are then saved in a separate file. Here is the script: #!/usr/bin/python 'editTextFile.py -- write over contents of existing text file' import os, string # get filename while True: fname = raw_input('Enter file name: ') if not (os.path.exists(fname)): print"*** ERROR: '%s' doesn't exist" % fname else: break # get file content (text) lines all = [] print "\nEnter lines ('.' by itself to quit).\n" # loop until user terminates input while True: entry = raw_input('> ') if entry == '.': break else: all.append(entry) # write lines to file with NEWLINE line terminator print "1) Replace file's contents" print "Any other key quits function without replacing file's contents" choice = raw_input("Make a choice: ") if choice == '1': fobj = open(fname, 'r') fobj_lines = fobj.readlines() fobj.close() fobj = open(fname, 'w') fname_orig = fname + '_orig' fobj_orig = open(fname_orig, 'w') stripped_lines = [] for line in fobj_lines: string.strip(line) stripped_lines.append(line) fobj_orig.write('\n'.join(stripped_lines)) fobj_orig.close() fobj.write('\n'.join(all)) fobj.close() print 'DONE!' else: print 'Bye!' I took a file called myfile. The original contents of myfile were: Hi! This is my file. It really rocks! I then ran my script: Enter file name: myfile Enter lines ('.' by itself to quit). > test > test > test > . 1) Replace file's contents Any other key quits function without replacing file's contents Make a choice: 1 DONE! Now the contents of myfile are: test test test The original contents were saved in myfile_orig. The contents of myfile_orig are: Hi! This is my file. It really rocks! Extra newlines were added. This won't do. I think the problem lies with fobj_orig.write('\n'.join(stripped_lines)) However, when I rewrite this line code as fobj_orig.write(string.join(stripped_lines)) I get Hi! This is my file. It really rocks! That doesn't work either. Any suggestions? From alan.gauld at btinternet.com Thu Sep 13 05:56:58 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 13 Sep 2007 04:56:58 +0100 Subject: [Tutor] Classes: global name not defined References: <2107481c0709121845o7610a67aucebe485538dabe50@mail.gmail.com> Message-ID: <fcacev$9je$1@sea.gmane.org> "Ara Kooser" <ghashsnaga at gmail.com> wrote > File "/Users/ara/Documents/yeast/oop_yeast_nocaps.py", line 87, in > <module> > first_instance.print_world() > File "/Users/ara/Documents/yeast/oop_yeast_nocaps.py", line 40, in > print_world > m, n = world['dimensions'] > NameError: global name 'world' is not defined > > I understand that the error refers to the method print_world(). In > the > instance before first_instance.print_world() I define what world is > but that is not being carried over to the print_world method. In the > print world method You need to work on your terminology. You are not defining world anywhere in any instance. You are calling methods of the instance. But the real problem lies inside the definition of the class methods. > class World: > #What makes this a world > > def __init__(self,name): > self.name = name > #Add other things later You should probably define world here self.world = ???? whatever > def percolation(self,perc): > perc = float(perc) This is forgotten as soon as the method ends. And you don;t use it anywhere else in the method. Are you sure you don't mean self.perc = float(perc) > randval = random.random() > if randval > perc: > return EMPTY > else: > return YEAST > def random_world(self): > #Constructs random world of size MxN > world = {} And again this is lost as soon as the methjod ends. It should be self.world = {} except that since its initialisatoon it would be better in the __init__ method. Thats what its for! > for j in range(n): > for i in range(m): > world[i, j] = self.percolation(perc) > world['dimensions'] = (m, n) > return world In this case you return world but you don't store it in your main code, so it is still lost. > def print_world(self): > #Prints out a string representation of a world. > m, n = world['dimensions'] And because world ghas never been set anywhee outside the random_world() method this fails. You should be accessing self.world. here. > for j in range(n): > for i in range(m): > print world[i, j], and here... > print > > def add_yeast(self): > #Allows the user to add a yeast cell at point m,n > m,n = world['dimensions'] and here > new_world = copy.copy(world) > > counta = 0 > print "The upper left corner is the point (0,0)" > yy = raw_input("How many yeast cells do you wish to add?") > yy = int(yy) > > while counta<yy: > i = int(raw_input("Please enter a m value for the yeast > cell.")) > j = int(raw_input("Please enter a n value for the yeast > cell.")) > > new_world[i,j] = YEAST > for j in range(n): > for i in range(m): You just got i.j from the user but now you are throwing away their input and overwriting it with the values from the for loop. I assume thats an error? > world[i,j]=new_world[i,j] and here... > > counta = counta+1 > > def debug(self): > print self.name > > > ########################################################## > #Start of prgram > ########################################################## > > first_instance = World("small_world") > #first_instance.debug() > > raw_input("Please press return to start the program.") > > perc = raw_input("Please enter a thresold between 0-1 for the > population.") > first_instance.percolation(perc) > > n = int(raw_input("Please enter a n dimension. ")) > m = int(raw_input("Please enter a m dimension. ")) These global variables are accessed from the class, it woyld be safer and more readable to put them into the init method and make them attributes which can then be accessed with self.m, self.n Its slightly more typing but makes the code more readable and more reliable. > first_instance.random_world() > first_instance.print_world() > > first_instance.add_yeast() HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From rabidpoobear at gmail.com Thu Sep 13 05:59:03 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Wed, 12 Sep 2007 22:59:03 -0500 Subject: [Tutor] editTextFile.py In-Reply-To: <846024.78106.qm@web51612.mail.re2.yahoo.com> References: <846024.78106.qm@web51612.mail.re2.yahoo.com> Message-ID: <46E8B587.6030103@gmail.com> Christopher Spears wrote: > I created a script that opens an existing text file, > allows the user to write over the original contents, > and then save the file. The original contents are > then saved in a separate file. Here is the script: > > #!/usr/bin/python > > 'editTextFile.py -- write over contents of existing > text file' > > import os, string > > # get filename > while True: > fname = raw_input('Enter file name: ') > if not (os.path.exists(fname)): > print"*** ERROR: '%s' doesn't exist" % fname > else: > break > > # get file content (text) lines > all = [] > print "\nEnter lines ('.' by itself to quit).\n" > > # loop until user terminates input > while True: > entry = raw_input('> ') > if entry == '.': > break > else: > all.append(entry) > > # write lines to file with NEWLINE line terminator > print "1) Replace file's contents" > print "Any other key quits function without replacing > file's contents" > choice = raw_input("Make a choice: ") > > if choice == '1': > fobj = open(fname, 'r') > fobj_lines = fobj.readlines() > fobj.close() > fobj = open(fname, 'w') > > fname_orig = fname + '_orig' > fobj_orig = open(fname_orig, 'w') > stripped_lines = [] > for line in fobj_lines: > string.strip(line) > stripped_lines.append(line) > fobj_orig.write('\n'.join(stripped_lines)) > fobj_orig.close() > > fobj.write('\n'.join(all)) > fobj.close() > print 'DONE!' > else: > print 'Bye!' > > I took a file called myfile. The original contents of > myfile were: > Hi! > This is my file. > It really rocks! > > I then ran my script: > Enter file name: myfile > > Enter lines ('.' by itself to quit). > > >> test >> test >> test >> . >> > 1) Replace file's contents > Any other key quits function without replacing file's > contents > Make a choice: 1 > DONE! > > Now the contents of myfile are: > test > test > test > > The original contents were saved in myfile_orig. The > contents of myfile_orig are: > Hi! > > This is my file. > > It really rocks! > > Extra newlines were added. This won't do. I think > the problem lies with > > fobj_orig.write('\n'.join(stripped_lines)) > > However, when I rewrite this line code as > > fobj_orig.write(string.join(stripped_lines)) > > I get > > Hi! > This is my file. > It really rocks! > > That doesn't work either. Any suggestions? > Before you write to the file, just use one of the os module functions to rename the original file to the new filename. Then when you go to open the original file, it'll just create a new one. The way you're currently doing it now, there's a period where both file's data is stored in memory, after you've opened both files for writing. This means that if the program were to crash at some point in here, you'll lose your original data. This is a pretty big problem for a text editor :) As per your original question, we can use reasoning to figure out what the problem is. There are extra spaces on every line except the first. However, there are still newlines. This means that your original strings must have had newlines. The spaces are explained by the string.join method. (Methods of string are deprecated anyway.) We can deduce that by default string.join uses space as the separation character. But by leiu of the example "\n".join() we know we can say "somestring".join(strings_to_join) and it will join the strings with that character in between each string. " ".join(stripped_lines) would have the same effect as string.join(stripped_lines). So what do you do if you don't want any characters at all separating your strings? Simple: use an empty string: "".join(stripped_lines) As I mentioned above, there are multiple ways to approach this problem. One other thing you could do if you wanted the program to be functionally equivalent is just use writelines() instead of write() and then you don't have to join the strings. -Luke From varsha.purohit at gmail.com Thu Sep 13 08:09:30 2007 From: varsha.purohit at gmail.com (Varsha Purohit) Date: Wed, 12 Sep 2007 23:09:30 -0700 Subject: [Tutor] printing value returning from a Class Message-ID: <c2157c790709122309o9b58472lb8898ecd49058240@mail.gmail.com> Hello friends,, I have a problem in displaying data which i have invoked from class. City is the name of the class which i havent displayed here. There is another script using that class. It has a function name setCities which takes a text file as argument. Text file contains name of the city, x and y location. there are 4 datas in 4 different lines. Code is as follows. import City def setCities(inFile): # puts city.txt content into City class objects # the field order of input file is: name x y x, y are integers. data are in newlines. f = open(inFile, 'r') body = f.readlines() f.close() cities = [] # list of cities for row in body: cityData = row.strip().split() cityName = cityData[0] cityX = cityData[1] cityY = cityData[2] newCity = City(cityName, cityX, cityY) # city class is invoked cities.append(newCity) return cities abc = setCities("C:\MS\sem5\Lab2_scripts\cities.txt") # setCities function will return the array with values read from the file. print abc I am getting output like [<city.City instance at 0x023E82D8>, <city.City instance at 0x023E8300>, < city.City instance at 0x023E8350>, <city.City instance at 0x023E83C8>] I want the data and not the instance... what should i do ?? -- Varsha Purohit, -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070912/9e162ea3/attachment.htm From washakie at gmail.com Thu Sep 13 08:45:42 2007 From: washakie at gmail.com (John) Date: Wed, 12 Sep 2007 23:45:42 -0700 Subject: [Tutor] 2.5 to 2.4 problem with Int Message-ID: <aaf235960709122345n3f799594q39ee761f2b753f35@mail.gmail.com> I've written a program which calculates areas of grid cells distributed over the globe. It works fine with Python 2.5, however, when I run it with 2.4(the Enthon edition) I get the following error: OverflowError: long int too large to convert to int It occurs on this line: for ix in range(nx): area[ix,iy]=gridarea I have no idea which int it's referring to? The values of ix/nx will not exceed 360, iy will not exceed 180. Any suggestions on what to change for the backward compatability? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070912/e25811a7/attachment.htm From kent37 at tds.net Thu Sep 13 13:01:07 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 13 Sep 2007 07:01:07 -0400 Subject: [Tutor] editTextFile.py In-Reply-To: <846024.78106.qm@web51612.mail.re2.yahoo.com> References: <846024.78106.qm@web51612.mail.re2.yahoo.com> Message-ID: <46E91873.8080007@tds.net> Christopher Spears wrote: > I created a script that opens an existing text file, > allows the user to write over the original contents, > and then save the file. The original contents are > then saved in a separate file. Here is the script: > > #!/usr/bin/python > > 'editTextFile.py -- write over contents of existing > text file' > > import os, string > > # get filename > while True: > fname = raw_input('Enter file name: ') > if not (os.path.exists(fname)): > print"*** ERROR: '%s' doesn't exist" % fname > else: > break > > # get file content (text) lines > all = [] > print "\nEnter lines ('.' by itself to quit).\n" > > # loop until user terminates input > while True: > entry = raw_input('> ') > if entry == '.': > break > else: > all.append(entry) > > # write lines to file with NEWLINE line terminator > print "1) Replace file's contents" > print "Any other key quits function without replacing > file's contents" > choice = raw_input("Make a choice: ") > > if choice == '1': > fobj = open(fname, 'r') > fobj_lines = fobj.readlines() > fobj.close() > fobj = open(fname, 'w') It would be safer to write the '_orig' file before opening the original file for writing (which erases its contents) > > fname_orig = fname + '_orig' > fobj_orig = open(fname_orig, 'w') > stripped_lines = [] > for line in fobj_lines: > string.strip(line) This doesn't change line. You need to assign the result back to line: line = string.strip(line) or, better, line = line.strip() Note that this will also strip leading and trailing whitespace from the lines so the copy will not be a duplicate of the original. A simpler way to copy a file is to read the entire contents using fobj.read() and write them as a single string. Even easier is to use shutil.copyfile() which does this for you. Kent From kent37 at tds.net Thu Sep 13 14:08:50 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 13 Sep 2007 08:08:50 -0400 Subject: [Tutor] 2.5 to 2.4 problem with Int In-Reply-To: <aaf235960709122345n3f799594q39ee761f2b753f35@mail.gmail.com> References: <aaf235960709122345n3f799594q39ee761f2b753f35@mail.gmail.com> Message-ID: <46E92852.90602@tds.net> John wrote: > I've written a program which calculates areas of grid cells distributed > over the globe. It works fine with Python 2.5, however, when I run it > with 2.4 (the Enthon edition) I get the following error: > > OverflowError: long int too large to convert to int > > It occurs on this line: > > for ix in range(nx): area[ix,iy]=gridarea > > I have no idea which int it's referring to? The values of ix/nx will not > exceed 360, iy will not exceed 180. Any suggestions on what to change > for the backward compatability? Are you sure nx is not large? The argument to range() must be an int. I would split the line in two so you know which part of it is generating the error, then insert a print statement to give you some more data. Kent From kalle.svensson at gmail.com Thu Sep 13 15:11:44 2007 From: kalle.svensson at gmail.com (Kalle Svensson) Date: Thu, 13 Sep 2007 15:11:44 +0200 Subject: [Tutor] printing value returning from a Class In-Reply-To: <c2157c790709122309o9b58472lb8898ecd49058240@mail.gmail.com> References: <c2157c790709122309o9b58472lb8898ecd49058240@mail.gmail.com> Message-ID: <9584033b0709130611g59e9661atf617a0fe0591b8cd@mail.gmail.com> Hello! On 9/13/07, Varsha Purohit <varsha.purohit at gmail.com> wrote: > Hello friends,, > I have a problem in displaying data which i have invoked from > class. City is the name of the class which i havent displayed here. There is > another script using that class. It has a function name setCities which > takes a text file as argument. Text file contains name of the city, x and y > location. there are 4 datas in 4 different lines. Code is as follows. > > import City > > def setCities(inFile): > # puts city.txt content into City class objects > # the field order of input file is: name x y x, y are integers. data > are in newlines. > f = open(inFile, 'r') > body = f.readlines() > f.close() > cities = [] # list of cities > for row in body: > cityData = row.strip().split() > cityName = cityData[0] > cityX = cityData[1] > cityY = cityData[2] > newCity = City(cityName, cityX, cityY) # city class is invoked > cities.append(newCity) > return cities > > > abc = setCities("C:\MS\sem5\Lab2_scripts\cities.txt") # > setCities function will return the array with values read from the file. > print abc > > I am getting output like > [<city.City instance at 0x023E82D8>, <city.City instance at 0x023E8300>, > <city.City instance at 0x023E8350>, <city.City instance at 0x023E83C8>] > > I want the data and not the instance... what should i do ?? Well, that depends on the City class. When you print a list, it just calls repr() on each item in the list and prints that. Now, suppose there is a method printCity() in the City class for printing the city data. In that case you should probably just loop over the list of instances and call the method, like this: >>> abc = setCities("city file") >>> for city in abc: ... city.printCity() If there is no such method, maybe you can extract the data from the class and write your own printing function, or modify the class to add one. HTH, Kalle From sacharook at hotmail.co.uk Thu Sep 13 17:33:43 2007 From: sacharook at hotmail.co.uk (sacha rook) Date: Thu, 13 Sep 2007 16:33:43 +0100 Subject: [Tutor] is this a vista issue In-Reply-To: <46E563DA.4090106@umn.edu> References: <BAY111-W4C4ABD47B42DBA13A2AC6F3C00@phx.gbl> <46E563DA.4090106@umn.edu> Message-ID: <BAY111-W228603CCC24C3A84144F5AF3C30@phx.gbl> Hi when I run this code on a winxp box I get a nice list of url's when I run this code on a win VISTA box I get this print urlparse.urlparse(href)[1]TypeError: 'module' object is not callable can a. someone tell me why & b. how do i get rid of this condition before I throw vista away :) Many thanks in advance S [CODE] from BeautifulSoup import BeautifulSoupdoc = ['<html><head><title>Page title</title></head>', '<body><p id="firstpara" align="center">This is paragraph <b>one</b>.', '<p id="secondpara" align="blah">This is paragraph <b>two</b>.', '<a href="http://www.google.co.uk"></a>', '<a href="http://www.bbc.co.uk"></a>', '<a href="http://www.amazon.co.uk"></a>', '<a href="http://www.redhat.co.uk"></a>', '</html>']soup = BeautifulSoup(''.join(doc))blist = soup.findAll('a')print blist import urlparsefor a in blist: href = a['href'] print urlparse.urlparse(href)[1] [/CODE] _________________________________________________________________ Get free emoticon packs and customisation from Windows Live. http://www.pimpmylive.co.uk -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070913/33e94f54/attachment.htm From kent37 at tds.net Thu Sep 13 17:55:58 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 13 Sep 2007 11:55:58 -0400 Subject: [Tutor] is this a vista issue In-Reply-To: <BAY111-W228603CCC24C3A84144F5AF3C30@phx.gbl> References: <BAY111-W4C4ABD47B42DBA13A2AC6F3C00@phx.gbl> <46E563DA.4090106@umn.edu> <BAY111-W228603CCC24C3A84144F5AF3C30@phx.gbl> Message-ID: <46E95D8E.7070801@tds.net> sacha rook wrote: > Hi > > when I run this code on a winxp box I get a nice list of url's > when I run this code on a win VISTA box I get this > > > print urlparse.urlparse(href)[1] > TypeError: 'module' object is not callable Please show the whole traceback. Kent > > can a. someone tell me why & b. how do i get rid of this condition > before I throw vista away :) > > Many thanks in advance > > S > > > [CODE] > > from BeautifulSoup import BeautifulSoup > doc = ['<html><head><title>Page title</title></head>', > '<body><p id="firstpara" align="center">This is paragraph > <b>one</b>.', > '<p id="secondpara" align="blah">This is paragraph <b>two</b>.', > '<a href="http://www.google.co.uk"></a>' > <http://www.google.co.uk"></a>'>, > '<a href="http://www.bbc.co.uk"></a>' <http://www.bbc.co.uk"></a>'>, > '<a href="http://www.amazon.co.uk"></a>' > <http://www.amazon.co.uk"></a>'>, > '<a href="http://www.redhat.co.uk"></a>' > <http://www.redhat.co.uk"></a>'>, > '</html>'] > soup = BeautifulSoup(''.join(doc)) > blist = soup.findAll('a') > print blist > import urlparse > for a in blist: > href = a['href'] > print urlparse.urlparse(href)[1] > > > [/CODE] > > ------------------------------------------------------------------------ > Are you the Quizmaster? Play BrainBattle with a friend now! > <http://specials.uk.msn.com/brainbattle> > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From washakie at gmail.com Thu Sep 13 21:27:07 2007 From: washakie at gmail.com (John) Date: Thu, 13 Sep 2007 12:27:07 -0700 Subject: [Tutor] 2.5 to 2.4 problem with Int In-Reply-To: <46E92852.90602@tds.net> References: <aaf235960709122345n3f799594q39ee761f2b753f35@mail.gmail.com> <46E92852.90602@tds.net> Message-ID: <aaf235960709131227u35fb7b07p27f2d66006541598@mail.gmail.com> The error occurs here: area[ix,iy]=gridarea The values of nx, ix, iy leading up to the error are: 360 0 0 360 1 0 360 2 0 360 3 0 360 4 0 360 ... ... 360 357 9 360 358 9 360 359 9 360 0 10 OverflowError: long int too large to convert to int I guess then the problem occurs when iy goes from 9 to 10, but why?? It wasn't a problem before and it's not a problem for ix??? Thanks! On 9/13/07, Kent Johnson <kent37 at tds.net> wrote: > > John wrote: > > I've written a program which calculates areas of grid cells distributed > > over the globe. It works fine with Python 2.5, however, when I run it > > with 2.4 (the Enthon edition) I get the following error: > > > > OverflowError: long int too large to convert to int > > > > It occurs on this line: > > > > for ix in range(nx): area[ix,iy]=gridarea > > > > I have no idea which int it's referring to? The values of ix/nx will not > > exceed 360, iy will not exceed 180. Any suggestions on what to change > > for the backward compatability? > > Are you sure nx is not large? The argument to range() must be an int. I > would split the line in two so you know which part of it is generating > the error, then insert a print statement to give you some more data. > > Kent > -- Configuration `````````````````````````` Plone 2.5.3-final, CMF-1.6.4, Zope (Zope 2.9.7-final, python 2.4.4, linux2), Five 1.4.1, Python 2.4.4 (#1, Jul 3 2007, 22:58:17) [GCC 4.1.1 20070105 (Red Hat 4.1.1-51)], PIL 1.1.6 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070913/031a0f60/attachment.htm From kent37 at tds.net Thu Sep 13 21:36:24 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 13 Sep 2007 15:36:24 -0400 Subject: [Tutor] 2.5 to 2.4 problem with Int In-Reply-To: <aaf235960709131227u35fb7b07p27f2d66006541598@mail.gmail.com> References: <aaf235960709122345n3f799594q39ee761f2b753f35@mail.gmail.com> <46E92852.90602@tds.net> <aaf235960709131227u35fb7b07p27f2d66006541598@mail.gmail.com> Message-ID: <46E99138.1030002@tds.net> John wrote: > The error occurs here: > area[ix,iy]=gridarea What is area? Is it a dict or something else? What is gridarea? Please show more code and the complete traceback. Kent > > The values of nx, ix, iy leading up to the error are: > 360 0 0 > 360 1 0 > 360 2 0 > 360 3 0 > 360 4 0 > 360 ... ... > 360 357 9 > 360 358 9 > 360 359 9 > 360 0 10 > OverflowError: long int too large to convert to int > > I guess then the problem occurs when iy goes from 9 to 10, but why?? It > wasn't a problem before and it's not a problem for ix??? > > Thanks! From washakie at gmail.com Thu Sep 13 21:55:44 2007 From: washakie at gmail.com (John) Date: Thu, 13 Sep 2007 12:55:44 -0700 Subject: [Tutor] 2.5 to 2.4 problem with Int In-Reply-To: <46E99138.1030002@tds.net> References: <aaf235960709122345n3f799594q39ee761f2b753f35@mail.gmail.com> <46E92852.90602@tds.net> <aaf235960709131227u35fb7b07p27f2d66006541598@mail.gmail.com> <46E99138.1030002@tds.net> Message-ID: <aaf235960709131255m78fc58b1q41d11bfe5c462b1e@mail.gmail.com> In all it's glory: I'm just a bit embarrassed because I'm sure it's poor coding: def gridarea(H): """ returns an array of area corresponding to each nx,ny,nz %=========================================== % %------------------------------------------- % input % - H : Header dict object with nx, ny, nz % % output % - Numpy array area corresponding to nx,ny,nz %------------------------------------------- % %------------------------------------------- % last changes: ww, 2007 %=========================================== """ import math import numpy as N pih=math.pi/180. r_earth=6.371e6 cosfunc = lambda y : math.cos(y*pih)*r_earth nz=H['nz'] nx=H['nx'] ny=H['ny'] outlat0=H['outlat0'] dyout=H['dyout'] dxout=H['dxout'] area=N.zeros((nx,ny)) #creates numpy array for iy in range(ny): ylata=outlat0+(float(iy)+0.5)*dyout ylatp=ylata+0.5*dyout ylatm=ylata-0.5*dyout if (ylatm<0 and ylatp>0): hzone=dyout*r_earth*pih else: cosfact=cosfunc(ylata) cosfactp=cosfunc(ylatp) cosfactm=cosfunc(ylatm) if cosfactp<cosfactm: hzone=math.sqrt(r_earth**2-cosfactp**2)-math.sqrt (r_earth**2-cosfactm**2) else: hzone=math.sqrt(r_earth**2-cosfactm**2)-math.sqrt (r_earth**2-cosfactp**2) gridarea=2.*math.pi*r_earth*hzone*dxout/360. for ix in range(nx): print nx, ix, iy area[ix,iy]=gridarea return area #returns numpy array of area Here's the traceback: ... 360 357 9 360 358 9 360 359 9 360 0 10 OverflowError: long int too large to convert to int Traceback: File "<string>", line 1, in ? File "c:\07\Programming\Python\mod_fp\getfp.py", line 11, in ? H,fail=readheader(pathname,1,0) File "c:\07\Programming\Python\mod_fp\mod_fp.py", line 170, in readheader H['area'] = gridarea(H) File "c:\07\Programming\Python\mod_fp\mod_fp.py", line 332, in gridarea area[ix,iy]=gridarea -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070913/0d07e64c/attachment-0001.htm From washakie at gmail.com Thu Sep 13 21:55:44 2007 From: washakie at gmail.com (John) Date: Thu, 13 Sep 2007 12:55:44 -0700 Subject: [Tutor] 2.5 to 2.4 problem with Int In-Reply-To: <46E99138.1030002@tds.net> References: <aaf235960709122345n3f799594q39ee761f2b753f35@mail.gmail.com> <46E92852.90602@tds.net> <aaf235960709131227u35fb7b07p27f2d66006541598@mail.gmail.com> <46E99138.1030002@tds.net> Message-ID: <aaf235960709131255m78fc58b1q41d11bfe5c462b1e@mail.gmail.com> In all it's glory: I'm just a bit embarrassed because I'm sure it's poor coding: def gridarea(H): """ returns an array of area corresponding to each nx,ny,nz %=========================================== % %------------------------------------------- % input % - H : Header dict object with nx, ny, nz % % output % - Numpy array area corresponding to nx,ny,nz %------------------------------------------- % %------------------------------------------- % last changes: ww, 2007 %=========================================== """ import math import numpy as N pih=math.pi/180. r_earth=6.371e6 cosfunc = lambda y : math.cos(y*pih)*r_earth nz=H['nz'] nx=H['nx'] ny=H['ny'] outlat0=H['outlat0'] dyout=H['dyout'] dxout=H['dxout'] area=N.zeros((nx,ny)) #creates numpy array for iy in range(ny): ylata=outlat0+(float(iy)+0.5)*dyout ylatp=ylata+0.5*dyout ylatm=ylata-0.5*dyout if (ylatm<0 and ylatp>0): hzone=dyout*r_earth*pih else: cosfact=cosfunc(ylata) cosfactp=cosfunc(ylatp) cosfactm=cosfunc(ylatm) if cosfactp<cosfactm: hzone=math.sqrt(r_earth**2-cosfactp**2)-math.sqrt (r_earth**2-cosfactm**2) else: hzone=math.sqrt(r_earth**2-cosfactm**2)-math.sqrt (r_earth**2-cosfactp**2) gridarea=2.*math.pi*r_earth*hzone*dxout/360. for ix in range(nx): print nx, ix, iy area[ix,iy]=gridarea return area #returns numpy array of area Here's the traceback: ... 360 357 9 360 358 9 360 359 9 360 0 10 OverflowError: long int too large to convert to int Traceback: File "<string>", line 1, in ? File "c:\07\Programming\Python\mod_fp\getfp.py", line 11, in ? H,fail=readheader(pathname,1,0) File "c:\07\Programming\Python\mod_fp\mod_fp.py", line 170, in readheader H['area'] = gridarea(H) File "c:\07\Programming\Python\mod_fp\mod_fp.py", line 332, in gridarea area[ix,iy]=gridarea -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070913/0d07e64c/attachment-0002.htm From washakie at gmail.com Thu Sep 13 21:57:26 2007 From: washakie at gmail.com (John) Date: Thu, 13 Sep 2007 12:57:26 -0700 Subject: [Tutor] 2.5 to 2.4 problem with Int In-Reply-To: <aaf235960709131255m78fc58b1q41d11bfe5c462b1e@mail.gmail.com> References: <aaf235960709122345n3f799594q39ee761f2b753f35@mail.gmail.com> <46E92852.90602@tds.net> <aaf235960709131227u35fb7b07p27f2d66006541598@mail.gmail.com> <46E99138.1030002@tds.net> <aaf235960709131255m78fc58b1q41d11bfe5c462b1e@mail.gmail.com> Message-ID: <aaf235960709131257k1da51c0ck22d0f8a37f7e1516@mail.gmail.com> for the record: nx=360 ny=180 nz=1 On 9/13/07, John <washakie at gmail.com> wrote: > > > In all it's glory: I'm just a bit embarrassed because I'm sure it's poor > coding: > > > > def gridarea(H): > """ returns an array of area corresponding to each nx,ny,nz > %=========================================== > % > %------------------------------------------- > % input > % - H : Header dict object with nx, ny, nz > % > % output > % - Numpy array area corresponding to nx,ny,nz > %------------------------------------------- > % > %------------------------------------------- > % last changes: ww, 2007 > %=========================================== > """ > import math > import numpy as N > > pih=math.pi/180. > r_earth=6.371e6 > cosfunc = lambda y : math.cos(y*pih)*r_earth > nz=H['nz'] > nx=H['nx'] > ny=H['ny'] > outlat0=H['outlat0'] > dyout=H['dyout'] > dxout=H['dxout'] > area=N.zeros((nx,ny)) #creates numpy array > > for iy in range(ny): > ylata=outlat0+(float(iy)+0.5)*dyout > ylatp=ylata+0.5*dyout > ylatm=ylata-0.5*dyout > if (ylatm<0 and ylatp>0): hzone=dyout*r_earth*pih > else: > cosfact=cosfunc(ylata) > cosfactp=cosfunc(ylatp) > cosfactm=cosfunc(ylatm) > if cosfactp<cosfactm: hzone=math.sqrt(r_earth**2-cosfactp**2)-math.sqrt > (r_earth**2-cosfactm**2) > else: hzone=math.sqrt(r_earth**2-cosfactm**2)-math.sqrt(r_earth**2-cosfactp**2) > > > gridarea=2.*math.pi*r_earth*hzone*dxout/360. > for ix in range(nx): > print nx, ix, iy > area[ix,iy]=gridarea > > return area #returns numpy array of area > > > > Here's the traceback: > > ... > > 360 357 9 > 360 358 9 > 360 359 9 > 360 0 10 > OverflowError: long int too large to convert to int > Traceback: > File "<string>", line 1, in ? > File "c:\07\Programming\Python\mod_fp\getfp.py", line 11, in ? > H,fail=readheader(pathname,1,0) > File "c:\07\Programming\Python\mod_fp\mod_fp.py", line 170, in > readheader > H['area'] = gridarea(H) > File "c:\07\Programming\Python\mod_fp\mod_fp.py", line 332, in gridarea > area[ix,iy]=gridarea > -- Configuration `````````````````````````` Plone 2.5.3-final, CMF-1.6.4, Zope (Zope 2.9.7-final, python 2.4.4, linux2), Five 1.4.1, Python 2.4.4 (#1, Jul 3 2007, 22:58:17) [GCC 4.1.1 20070105 (Red Hat 4.1.1-51)], PIL 1.1.6 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070913/02fe19df/attachment.htm From washakie at gmail.com Thu Sep 13 21:57:26 2007 From: washakie at gmail.com (John) Date: Thu, 13 Sep 2007 12:57:26 -0700 Subject: [Tutor] 2.5 to 2.4 problem with Int In-Reply-To: <aaf235960709131255m78fc58b1q41d11bfe5c462b1e@mail.gmail.com> References: <aaf235960709122345n3f799594q39ee761f2b753f35@mail.gmail.com> <46E92852.90602@tds.net> <aaf235960709131227u35fb7b07p27f2d66006541598@mail.gmail.com> <46E99138.1030002@tds.net> <aaf235960709131255m78fc58b1q41d11bfe5c462b1e@mail.gmail.com> Message-ID: <aaf235960709131257k1da51c0ck22d0f8a37f7e1516@mail.gmail.com> for the record: nx=360 ny=180 nz=1 On 9/13/07, John <washakie at gmail.com> wrote: > > > In all it's glory: I'm just a bit embarrassed because I'm sure it's poor > coding: > > > > def gridarea(H): > """ returns an array of area corresponding to each nx,ny,nz > %=========================================== > % > %------------------------------------------- > % input > % - H : Header dict object with nx, ny, nz > % > % output > % - Numpy array area corresponding to nx,ny,nz > %------------------------------------------- > % > %------------------------------------------- > % last changes: ww, 2007 > %=========================================== > """ > import math > import numpy as N > > pih=math.pi/180. > r_earth=6.371e6 > cosfunc = lambda y : math.cos(y*pih)*r_earth > nz=H['nz'] > nx=H['nx'] > ny=H['ny'] > outlat0=H['outlat0'] > dyout=H['dyout'] > dxout=H['dxout'] > area=N.zeros((nx,ny)) #creates numpy array > > for iy in range(ny): > ylata=outlat0+(float(iy)+0.5)*dyout > ylatp=ylata+0.5*dyout > ylatm=ylata-0.5*dyout > if (ylatm<0 and ylatp>0): hzone=dyout*r_earth*pih > else: > cosfact=cosfunc(ylata) > cosfactp=cosfunc(ylatp) > cosfactm=cosfunc(ylatm) > if cosfactp<cosfactm: hzone=math.sqrt(r_earth**2-cosfactp**2)-math.sqrt > (r_earth**2-cosfactm**2) > else: hzone=math.sqrt(r_earth**2-cosfactm**2)-math.sqrt(r_earth**2-cosfactp**2) > > > gridarea=2.*math.pi*r_earth*hzone*dxout/360. > for ix in range(nx): > print nx, ix, iy > area[ix,iy]=gridarea > > return area #returns numpy array of area > > > > Here's the traceback: > > ... > > 360 357 9 > 360 358 9 > 360 359 9 > 360 0 10 > OverflowError: long int too large to convert to int > Traceback: > File "<string>", line 1, in ? > File "c:\07\Programming\Python\mod_fp\getfp.py", line 11, in ? > H,fail=readheader(pathname,1,0) > File "c:\07\Programming\Python\mod_fp\mod_fp.py", line 170, in > readheader > H['area'] = gridarea(H) > File "c:\07\Programming\Python\mod_fp\mod_fp.py", line 332, in gridarea > area[ix,iy]=gridarea > -- Configuration `````````````````````````` Plone 2.5.3-final, CMF-1.6.4, Zope (Zope 2.9.7-final, python 2.4.4, linux2), Five 1.4.1, Python 2.4.4 (#1, Jul 3 2007, 22:58:17) [GCC 4.1.1 20070105 (Red Hat 4.1.1-51)], PIL 1.1.6 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070913/02fe19df/attachment-0001.htm From pyth0nc0d3r at gmail.com Thu Sep 13 22:03:57 2007 From: pyth0nc0d3r at gmail.com (Lamonte Harris) Date: Thu, 13 Sep 2007 15:03:57 -0500 Subject: [Tutor] Class Inheritance Message-ID: <eb79828c0709131303x57ee8591r308473a24f27c672@mail.gmail.com> Okay class A: def __init__(self,x,y): self.x = x self.y = y def save(self,fn): f = open(fn,"w") f.write(str(self.x)+ '\n') # convert to a string and add newline f.write(str(self.y)+'\n') return f # for child objects to use def restore(self, fn): f = open(fn) self.x = int(f.readline()) # convert back to original type self.y = int(f.readline()) return f class B(A): def __init__(self,x,y,z): A.__init__(self,x,y) self.z = z def save(self,fn): f = A.save(self,fn) # call parent save f.write(str(self.z)+'\n') return f # in case further children exist def restore(self, fn): f = A.restore(self,fn) self.z = int(f.readline()) return f In the class B, I'm not understanding the A.__init(self,x,y) part. So its initializing the class A, and basically you can use the A class like normal? Part im confused about is the self.z, does that belong to the class A or class B? Else I think I'm understanding it correctly. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070913/2102617a/attachment.htm From kent37 at tds.net Thu Sep 13 22:27:12 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 13 Sep 2007 16:27:12 -0400 Subject: [Tutor] 2.5 to 2.4 problem with Int In-Reply-To: <aaf235960709131257k1da51c0ck22d0f8a37f7e1516@mail.gmail.com> References: <aaf235960709122345n3f799594q39ee761f2b753f35@mail.gmail.com> <46E92852.90602@tds.net> <aaf235960709131227u35fb7b07p27f2d66006541598@mail.gmail.com> <46E99138.1030002@tds.net> <aaf235960709131255m78fc58b1q41d11bfe5c462b1e@mail.gmail.com> <aaf235960709131257k1da51c0ck22d0f8a37f7e1516@mail.gmail.com> Message-ID: <46E99D20.4000904@tds.net> I have no clue; anyone else? Maybe you should try the numpy list. Kent John wrote: > for the record: > nx=360 > ny=180 > nz=1 > > > On 9/13/07, *John* <washakie at gmail.com <mailto:washakie at gmail.com>> wrote: > > > In all it's glory: I'm just a bit embarrassed because I'm sure it's > poor coding: > > > > def gridarea(H): > """ returns an array of area corresponding to each nx,ny,nz > %=========================================== > % > %------------------------------------------- > % input > % - H : Header dict object with nx, ny, nz > % > % output > % - Numpy array area corresponding to nx,ny,nz > %------------------------------------------- > % > %------------------------------------------- > % last changes: ww, 2007 > %=========================================== > """ > import math > import numpy as N > > pih=math.pi/180. > r_earth=6.371e6 > cosfunc = lambda y : math.cos(y*pih)*r_earth > nz=H['nz'] > nx=H['nx'] > ny=H['ny'] > outlat0=H['outlat0'] > dyout=H['dyout'] > dxout=H['dxout'] > area=N.zeros((nx,ny)) #creates numpy array > > for iy in range(ny): > ylata=outlat0+(float(iy)+0.5)*dyout > ylatp=ylata+0.5*dyout > ylatm=ylata-0.5*dyout > if (ylatm<0 and ylatp>0): hzone=dyout*r_earth*pih > else: > cosfact=cosfunc(ylata) > cosfactp=cosfunc(ylatp) > cosfactm=cosfunc(ylatm) > if cosfactp<cosfactm: > hzone=math.sqrt(r_earth**2-cosfactp**2)-math.sqrt(r_earth**2-cosfactm**2) > else: > hzone=math.sqrt(r_earth**2-cosfactm**2)-math.sqrt(r_earth**2-cosfactp**2) > > > gridarea=2.*math.pi*r_earth*hzone*dxout/360. > for ix in range(nx): > print nx, ix, iy > area[ix,iy]=gridarea > > return area #returns numpy array of area > > > > Here's the traceback: > > ... > > 360 357 9 > 360 358 9 > 360 359 9 > 360 0 10 > OverflowError: long int too large to convert to int > Traceback: > File "<string>", line 1, in ? > File "c:\07\Programming\Python\mod_fp\getfp.py", line 11, in ? > H,fail=readheader(pathname,1,0) > File "c:\07\Programming\Python\mod_fp\mod_fp.py", line 170, in > readheader > H['area'] = gridarea(H) > File "c:\07\Programming\Python\mod_fp\mod_fp.py", line 332, in > gridarea > area[ix,iy]=gridarea > > > > > -- > Configuration > `````````````````````````` > Plone 2.5.3-final, > CMF-1.6.4, > Zope (Zope 2.9.7-final, python 2.4.4, linux2), > Five 1.4.1, > Python 2.4.4 (#1, Jul 3 2007, 22:58:17) [GCC 4.1.1 20070105 (Red Hat > 4.1.1-51)], > PIL 1.1.6 From brunson at brunson.com Thu Sep 13 23:32:34 2007 From: brunson at brunson.com (Eric Brunson) Date: Thu, 13 Sep 2007 15:32:34 -0600 Subject: [Tutor] Class Inheritance In-Reply-To: <eb79828c0709131303x57ee8591r308473a24f27c672@mail.gmail.com> References: <eb79828c0709131303x57ee8591r308473a24f27c672@mail.gmail.com> Message-ID: <46E9AC72.1030308@brunson.com> Lamonte Harris wrote: > Okay > > class A: > def __init__(self,x,y): > self.x = x > self.y = y > > def save(self,fn): > f = open(fn,"w") > f.write(str(self.x)+ '\n') > # convert to a string and add newline > f.write(str(self.y)+'\n') > return f # for child objects to use > > def restore(self, fn): > f = open(fn) > > self.x = int(f.readline()) # convert back to original type > self.y = int(f.readline()) > return f > > class B(A): > def __init__(self,x,y,z): > A.__init__(self,x,y) > > self.z = z > > def save(self,fn): > f = A.save(self,fn) # call parent save > f.write(str(self.z)+'\n') > return f # in case further children exist > > > def restore(self, fn): > f = A.restore(self,fn) > self.z = int(f.readline()) > return f > In the class B, I'm not understanding the A.__init(self,x,y) part. > So its initializing the class A, and basically you can use the A class > like normal? Essentially, yes, but the way you've worded it is imprecise. Any instance of B is a subclass of A, essentially an A: Every boy is a male, but not all males are boys. When you override a method in a subclass you have essentially turned off all behavior in the parent method, including "magic" methods like the constructor. You have to call the parent constructor explicitly to get its benefits. A method of an instance can be called like this: instance.method() and python makes sure that a pointer to the instance is passed in as the first argument, generally "self". But a method of a class can be called without instantiating the class, but you have to supply "self" on you own. The method you are using is valid, yet depricated. Using "new style classes" (which aren't actually that new) you'd write your code like this: class A(object): def __init__(self, a): self.aye = a class B(A): def __init__(self, a, b): self.bee = b super( B, self ).__init__( a ) Notice that you don't have to supply self. You can use any method of A in an instance of B that you haven't overridden in B without having to use super(). > Part im confused about is the self.z, does that belong to the class A > or class B? z is an attribute B only. Hope that helps, e. > Else I think I'm understanding it correctly. > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From orest.kozyar at gmail.com Thu Sep 13 23:43:08 2007 From: orest.kozyar at gmail.com (Orest Kozyar) Date: Thu, 13 Sep 2007 17:43:08 -0400 Subject: [Tutor] evaluating AND Message-ID: <000e01c7f64f$1406aea0$bd32000a@issphoenix> Given a variable x that can either be None or a tuple of two floats [i.e. (0.32, 4.2)], which syntax is considered most appropriate under Python coding standards? if x and x[0] > 0: pass =====OR===== if x: if x[0] > 0: pass In the first, I'm obviously making the assumption that if the first condition evaluates to false, then the second condition won't be evaluated. But, is this a good/valid assumption to make? Is there a more appropriate design pattern in Python? Thanks! Orest From brunson at brunson.com Fri Sep 14 00:02:24 2007 From: brunson at brunson.com (Eric Brunson) Date: Thu, 13 Sep 2007 16:02:24 -0600 Subject: [Tutor] evaluating AND In-Reply-To: <000e01c7f64f$1406aea0$bd32000a@issphoenix> References: <000e01c7f64f$1406aea0$bd32000a@issphoenix> Message-ID: <46E9B370.5010001@brunson.com> The first is how I would code it. Python guarantees that compound boolean statements are processed from left to right and also that the AND operator will "short circuit" the rest of the evaluation, since the rest of the line cannot change the falseness of the entire statement. Orest Kozyar wrote: > Given a variable x that can either be None or a tuple of two floats [i.e. > (0.32, 4.2)], which syntax is considered most appropriate under Python > coding standards? > > if x and x[0] > 0: > pass > > =====OR===== > > if x: > if x[0] > 0: > pass > > > In the first, I'm obviously making the assumption that if the first > condition evaluates to false, then the second condition won't be evaluated. > But, is this a good/valid assumption to make? Is there a more appropriate > design pattern in Python? > > Thanks! > Orest > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From ghashsnaga at gmail.com Fri Sep 14 00:03:56 2007 From: ghashsnaga at gmail.com (Ara Kooser) Date: Thu, 13 Sep 2007 16:03:56 -0600 Subject: [Tutor] Killing an instance Message-ID: <2107481c0709131503l583d631dn8624376f95d3e5c0@mail.gmail.com> I have two instances called and running. They interact with each other and I would like one of the instances to cease to exist in the second round based on a given condition. How do you kill an instance? The code is below. I have Red and Yellow as my instances and I want them to die when life = 0 and not show up in the preceding rounds of the game. Thank you. Ara CODE HERE: ########################################################################## #Red and Yellow yeast model # #Both yeast start out cooperating. #If the yeast detect that there is no ade or lys present they will defect #but die. ########################################################################## import time chemicals = [] #0 cooperates #1 defects class RedYeast: #Needs adenine to grow, releases lysine def __init__(self,name,group): self.name = name self.group = group self.life = 1 self.hate_tolerance = 0 self.choice = 0 #METHODS def lys_re(self,stuffa): #release of lys in the environment if self.choice == 0: print self.name, "-- Releasing lys" chemicals.append(stuffa) elif self.choice == 1: print self.name, "-- Withholds lys" def ade_need(self,stuffb): if stuffb != chemicals: print self.name,"is taking ade" self.life = self.life+1 chemicals.remove(stuffb) print chemicals print "Life", self.life else: print "No ade presents" self.life = self.life-1 self.choice = 1 class YellowYeast: #Needs lysine to grow, releases adenine def __init__(self,name,group): self.name = name self.group = group self.life = 1 self.hate_tolerance = 0 self.choice = 0 #METHODS def ade_re(self,stuffa): #release of lys in the environment if self.choice == 0: print self.name, "-- Releasing ade" chemicals.append(stuffa) elif self.choice == 1: print self.name, "-- Withholds ade" def lys_need(self,stuffb): if stuffb != chemicals: print self.name," is taking ade" self.life = self.life+1 chemicals.remove(stuffb) print chemicals print "Life",self.life print else: print "No ade presents" self.life = self.life-1 self.choice = 1 def death(self): ############################################################## #Start of program ############################################################## rounds = raw_input("How many rounds to you wish to play through?") print "Starting environment", chemicals rounds =int(rounds) count = 0 #Creates the instances for RedYeast and YellowYeast one = RedYeast("Red","alpha") two = YellowYeast("Yellow","alpha") #Game logic while count < rounds: print "##################################################" print one.lys_re("lys") two.ade_re("ade") print print "Chemicals in the environment",chemicals print time.sleep(1) one.ade_need("ade") two.lys_need("lys") print "##################################################" print count = count+1 print "Ending environment", chemicals -- Quis hic locus, quae regio, quae mundi plaga. Ubi sum. Sub ortu solis an sub cardine glacialis ursae. From carroll at tjc.com Fri Sep 14 00:04:02 2007 From: carroll at tjc.com (Terry Carroll) Date: Thu, 13 Sep 2007 15:04:02 -0700 (PDT) Subject: [Tutor] evaluating AND In-Reply-To: <000e01c7f64f$1406aea0$bd32000a@issphoenix> Message-ID: <Pine.LNX.4.44.0709131500070.18893-100000@violet.rahul.net> On Thu, 13 Sep 2007, Orest Kozyar wrote: > Given a variable x that can either be None or a tuple of two floats [i.e. > (0.32, 4.2)], which syntax is considered most appropriate under Python > coding standards? > > if x and x[0] > 0: > pass > > =====OR===== > > if x: > if x[0] > 0: > pass I would like either one if instead of "if x" you used "if x is not None"; that seems a lot easier to me to read. It's a bit jarring to see the same variable used in one expression as both a boolean and a list/tuple. Besides, suppose somehow x got set to zero. It would pass without error, something you wouldn't want to have happen. Even if you've set things up so that it couldn't happen, it's not obvious from looking at this code that it couldn't happen. If you really want to test for x being non-None, test for x being non-None. From kent37 at tds.net Fri Sep 14 00:05:38 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 13 Sep 2007 18:05:38 -0400 Subject: [Tutor] evaluating AND In-Reply-To: <000e01c7f64f$1406aea0$bd32000a@issphoenix> References: <000e01c7f64f$1406aea0$bd32000a@issphoenix> Message-ID: <46E9B432.3090007@tds.net> Orest Kozyar wrote: > Given a variable x that can either be None or a tuple of two floats [i.e. > (0.32, 4.2)], which syntax is considered most appropriate under Python > coding standards? > > if x and x[0] > 0: > pass > > =====OR===== > > if x: > if x[0] > 0: > pass The first is fine. > In the first, I'm obviously making the assumption that if the first > condition evaluates to false, then the second condition won't be evaluated. > But, is this a good/valid assumption to make? Yes, this is guaranteed by the language. http://docs.python.org/ref/Booleans.html Kent From mlangford.cs03 at gtalumni.org Fri Sep 14 00:12:45 2007 From: mlangford.cs03 at gtalumni.org (Michael Langford) Date: Thu, 13 Sep 2007 18:12:45 -0400 Subject: [Tutor] Killing an instance In-Reply-To: <2107481c0709131503l583d631dn8624376f95d3e5c0@mail.gmail.com> References: <2107481c0709131503l583d631dn8624376f95d3e5c0@mail.gmail.com> Message-ID: <82b4f5810709131512xb706d62i99e4b5b4370b800@mail.gmail.com> This is a little more complicated. The more object oriented way: Make each cell know its location and have a reference to the world its in. You can have the world set the object the coordinates the item is at when it adds it to itself. When the life==0, you can have the yeast cell call a remove( self.x, self.y) method on the world. This is useful if you're doing a lot of things that involve the cell knowing its position. Your life simulation could probably get this complicated. The less object oriented way...that's a lot simpler: Make a "reap()" method in the world class that removes all the tokens that are life==0. I'd make a method in the cell like isDead(). The reap function for the world will remove all cells that isDead()==True. This is a better approach when your cells don't do very much more than they already do. --Michael On 9/13/07, Ara Kooser <ghashsnaga at gmail.com> wrote: > > I have two instances called and running. They interact with each > other and I would like one of the instances to cease to exist in the > second round based on a given condition. How do you kill an instance? > > The code is below. I have Red and Yellow as my instances and I want > them to die when life = 0 and not show up in the preceding rounds of > the game. > > Thank you. > Ara > > > > > CODE HERE: > ########################################################################## > #Red and Yellow yeast model > # > #Both yeast start out cooperating. > #If the yeast detect that there is no ade or lys present they will defect > #but die. > ########################################################################## > > import time > > chemicals = [] > > #0 cooperates > #1 defects > > class RedYeast: > #Needs adenine to grow, releases lysine > def __init__(self,name,group): > self.name = name > self.group = group > self.life = 1 > self.hate_tolerance = 0 > self.choice = 0 > > #METHODS > def lys_re(self,stuffa): > #release of lys in the environment > if self.choice == 0: > print self.name, "-- Releasing lys" > chemicals.append(stuffa) > elif self.choice == 1: > print self.name, "-- Withholds lys" > > def ade_need(self,stuffb): > > if stuffb != chemicals: > print self.name,"is taking ade" > self.life = self.life+1 > chemicals.remove(stuffb) > print chemicals > print "Life", self.life > else: > print "No ade presents" > self.life = self.life-1 > self.choice = 1 > > > > class YellowYeast: > #Needs lysine to grow, releases adenine > def __init__(self,name,group): > self.name = name > self.group = group > self.life = 1 > self.hate_tolerance = 0 > self.choice = 0 > > #METHODS > def ade_re(self,stuffa): > #release of lys in the environment > if self.choice == 0: > print self.name, "-- Releasing ade" > chemicals.append(stuffa) > elif self.choice == 1: > print self.name, "-- Withholds ade" > > def lys_need(self,stuffb): > > if stuffb != chemicals: > print self.name," is taking ade" > self.life = self.life+1 > chemicals.remove(stuffb) > print chemicals > > print "Life",self.life > print > else: > print "No ade presents" > self.life = self.life-1 > self.choice = 1 > > > def death(self): > > > > ############################################################## > #Start of program > ############################################################## > > rounds = raw_input("How many rounds to you wish to play through?") > print "Starting environment", chemicals > rounds =int(rounds) > count = 0 > > #Creates the instances for RedYeast and YellowYeast > one = RedYeast("Red","alpha") > two = YellowYeast("Yellow","alpha") > > #Game logic > > while count < rounds: > print "##################################################" > print > > one.lys_re("lys") > two.ade_re("ade") > > print > print "Chemicals in the environment",chemicals > print > > time.sleep(1) > > one.ade_need("ade") > two.lys_need("lys") > > print "##################################################" > print > > > count = count+1 > > print "Ending environment", chemicals > > -- > 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 > -- Michael Langford Phone: 404-386-0495 Consulting: http://www.TierOneDesign.com/ Entertaining: http://www.ThisIsYourCruiseDirectorSpeaking.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070913/39417767/attachment-0001.htm From adam.jtm30 at gmail.com Fri Sep 14 00:15:50 2007 From: adam.jtm30 at gmail.com (Adam Bark) Date: Thu, 13 Sep 2007 23:15:50 +0100 Subject: [Tutor] evaluating AND In-Reply-To: <Pine.LNX.4.44.0709131500070.18893-100000@violet.rahul.net> References: <000e01c7f64f$1406aea0$bd32000a@issphoenix> <Pine.LNX.4.44.0709131500070.18893-100000@violet.rahul.net> Message-ID: <be4fbf920709131515x6928aa69j8a00e4cea2ecc5b1@mail.gmail.com> On 13/09/2007, Terry Carroll <carroll at tjc.com> wrote: > > On Thu, 13 Sep 2007, Orest Kozyar wrote: > > > Given a variable x that can either be None or a tuple of two floats [i.e > . > > (0.32, 4.2)], which syntax is considered most appropriate under Python > > coding standards? > > > > if x and x[0] > 0: > > pass > > > > =====OR===== > > > > if x: > > if x[0] > 0: > > pass > > I would like either one if instead of "if x" you used "if x is not None"; > that seems a lot easier to me to read. It's a bit jarring to see the same > variable used in one expression as both a boolean and a list/tuple. > > Besides, suppose somehow x got set to zero. It would pass without error, > something you wouldn't want to have happen. Even if you've set things up > so that it couldn't happen, it's not obvious from looking at this code > that it couldn't happen. > > If you really want to test for x being non-None, test for x being > non-None. The problem is what if it's an empty list or tuple? It would pass but have not value whereas if x would work fine. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070913/2cffd709/attachment.htm From carroll at tjc.com Fri Sep 14 00:34:10 2007 From: carroll at tjc.com (Terry Carroll) Date: Thu, 13 Sep 2007 15:34:10 -0700 (PDT) Subject: [Tutor] evaluating AND In-Reply-To: <be4fbf920709131515x6928aa69j8a00e4cea2ecc5b1@mail.gmail.com> Message-ID: <Pine.LNX.4.44.0709131521440.18893-100000@violet.rahul.net> On Thu, 13 Sep 2007, Adam Bark wrote: > The problem is what if it's an empty list or tuple? It would pass but have > not value > whereas if x would work fine. Exactly. The poster stated that x is supposed to be either None or a tuple of two floats. Just to put a bit of meat on the example, let's create a function whose job is to return x[1]/x[0], but only if x[0] > 0. Otherwise, it just falls off, i.e., returning None. Here are two versions, one using "if x" is None; the other using just "if x" >>> def test01(x): ... if x is not None: ... if x[0]>0: ... return x[1]/x[0] ... >>> def test02(x): ... if x: ... if x[0]>0: ... return x[1]/x[0] When x is None, both work: >>> x = None >>> print test01(x) None >>> print test02(x) None When x is, in fact, a tuple of two floats, both work: >>> x = (2.0, 5.0) >>> print test01(x) 2.5 >>> print test02(x) 2.5 Now... if x is an empty tuple: >>> x = tuple() >>> print test01(x) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 3, in test01 IndexError: tuple index out of range >>> print test02(x) None >>> The first one, which checks "if x is None" fails. This is a good thing. The second one, which just checks "if x" and is satisfied with any false value, including an empty tuple, does not raise the error condition, even though the data is bad. This is a bad thing. From alan.gauld at btinternet.com Fri Sep 14 00:50:56 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 13 Sep 2007 23:50:56 +0100 Subject: [Tutor] Suggested books for Agile Programming & Testing References: <BAY111-F3685BD79DCC7E60F354F80A0C00@phx.gbl> <c41f67b90709131523x2861f347y17fec012bce7ee57@mail.gmail.com> Message-ID: <fccet6$43l$1@sea.gmane.org> "Shannon -jj Behrens" <jjinux at gmail.com> wrote >> Also, can anyone comment on the limits or caveats of agile >> development? I posted a longish response on this but it seems not to have made to gmane! Here it is again: =================================== "Stephen McInerney" <spmcinerney at hotmail.com> wrote > Can anyone recommend me the best single must-read book for Agile > Programming? One of the most widely cited is Robert Martin's Agile Software Development. Personally I didn't like it much for agile but it is quite good on OOD. The original XP book by Kent Beck is good too, along with its sequel. > Also Agile Testing. Sorry I can't comment on any specific testing books. > (If they compare Agile in general to the other methodologies, > that would be great) The best comparison book I can recommend is Balancing Agility & Discipline by Barry Boehm. > Also, can anyone comment on the limits or caveats of agile > development? I'm sure lots of people can but Agile is such a nebulous concept that its difficult to get anything objective or useful. My own personal experieces follow for what they are wrth: Agile works well if: 1) You have very close contact with end users/requirement owners 2) Small, co-located teams - small = 20 or less people 3) The requirements are not clearly understood (even by the users). 4) You have an experienced, talented team You need *all* of those to make it work significantly better than traditional methods. If even one if missing you will be no better off. You might not be any worse off, but you will be no better. If you have only one of those items then traditional methods (NOT waterfall!) will be better. Dangers of agile: 1) Not good for building scaleable, resilient, long term flexible structures 2) Very expensive due to the large proportion of time spent in rework (aka refactoring) 3) Tendency to drift over budget as new featiures get thought up and added to the original scope. 4) Not good for long term maintenance, the documentation often being inadeqate for anyone outside of the original project team Note, All of these things can be addressed but it takes specific, directed action to do so. Some general comments: 1) Its easy for management to "embrace agile" by adopting some bits that they like. Requirements become User Stories, Progress meetings become Stand-Ups, Phased releases become iterations. in fact its just a renaming exercise not real Agile. Re-naming doesn't work, agile does (with the caveats above) 2) Agile is very open to hype. Exaggerated claims and comparisons with the waterfall method are common, even though the waterfall method has not been widely used for years and methods like RUP are more appropriate comparisons. If you compare a motorcycle to a penny farthing cycle you will get an exaggerated idea of "progress" 3) Agile badly done is just as bad as traditional badly done. 4) finally, do you need to hire an architect to build a garden shed? Agile is in some ways addressing an artificial problem. Software engineeering was invented in the late 70's to deal with very large projects. Most methodologies still tackle that problem. Many software houses now work on much smaller problems that only need small teams and can be completed in a few weeks. If you apply traditional methodologies to those problems they will be overkill. So Agile comes along. But on these very small projects, usually all that's needed is some common sense and experience - like building a garden shed! My personal career jhas been based on large projects. On most large projects there is a tools team who churn out little programs used by the main development/test teams. The tools team does not typically apply the main project methodology for each tool written, they "just get on with it". The tools team will typically be 4-10 people. A tool will typically take 1-20 days to write. In other words the small end of Agile, but they don't use Agile, they don't use anything but common sense and their experiece... That's way more than I intended writing! I'm sure others will have different views. 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 Fri Sep 14 01:28:29 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 14 Sep 2007 00:28:29 +0100 Subject: [Tutor] 2.5 to 2.4 problem with Int References: <aaf235960709122345n3f799594q39ee761f2b753f35@mail.gmail.com><46E92852.90602@tds.net><aaf235960709131227u35fb7b07p27f2d66006541598@mail.gmail.com><46E99138.1030002@tds.net> <aaf235960709131255m78fc58b1q41d11bfe5c462b1e@mail.gmail.com> Message-ID: <fcch3j$9l3$1@sea.gmane.org> "John" <washakie at gmail.com> wrote > In all it's glory: I'm just a bit embarrassed because I'm sure it's > poor > coding: > Thats what we're here for... The first thing to note is that gridarea is here a function object. So are you assigning the function object to area[x,y]. Is that what you intend? > def gridarea(H): > """ returns an array of area corresponding to each nx,ny,nz > % input > % - H : Header dict object with nx, ny, nz > % output > % - Numpy array area corresponding to nx,ny,nz > """ > import math > import numpy as N It's traditional to put the imports outside the function, especially if they will always be called. > pih=math.pi/180. > r_earth=6.371e6 > cosfunc = lambda y : math.cos(y*pih)*r_earth You could use the more conventional def cosfunc(y): return math.cos(y*pih)*r_earth lambda is fine by me but some folks find them harder to read. > nz=H['nz'] > nx=H['nx'] > ny=H['ny'] > outlat0=H['outlat0'] > dyout=H['dyout'] > dxout=H['dxout'] > area=N.zeros((nx,ny)) #creates numpy array > > for iy in range(ny): > ylata=outlat0+(float(iy)+0.5)*dyout > ylatp=ylata+0.5*dyout > ylatm=ylata-0.5*dyout > if (ylatm<0 and ylatp>0): hzone=dyout*r_earth*pih > else: > cosfact=cosfunc(ylata) > cosfactp=cosfunc(ylatp) > cosfactm=cosfunc(ylatm) > if cosfactp < cosfactm: > hzone=math.sqrt(r_earth**2-cosfactp**2)-math.sqrt > (r_earth**2-cosfactm**2) > else: hzone=math.sqrt(r_earth**2-cosfactm**2)-math.sqrt > (r_earth**2-cosfactp**2) > More whitespace will help readability and avoid errors! please... > gridarea=2.*math.pi*r_earth*hzone*dxout/360. This is a bit iffy since you are creating a variable gridarea inside a function gridarea. That effectively removes the possibility of using recursion, although otherwise I don't *think* it should cause a problem in itself. > for ix in range(nx): > print nx, ix, iy > area[ix,iy]=gridarea And here looks like we have the dodgy line because you are assigning the internal variable not the function after all. So gridarea is actually the result of that big calculation. That is a float value and potentially big, I don't know. Did you try printing the value of gridarea in your debug trace? But that shouldn't cause the error since you aren't trying to convert it to an int. Very odd. iy is set in the loop up to ny. But how does it compare to the original ny parameter you passed to N.zeros at the top? Is this a numpy index error we are actually seeing? I don't know how numpy's zeros function works... I'm clutching at straws here... > return area #returns numpy array of area > Here's the traceback: > > ... > > 360 357 9 > 360 358 9 > 360 359 9 > 360 0 10 So this is where we loop all the way back to the outer loop and then start the second loop again.. Can you add gridarea and ny to the debug data? > OverflowError: long int too large to convert to int > Traceback: > File "<string>", line 1, in ? > File "c:\07\Programming\Python\mod_fp\getfp.py", line 11, in ? > H,fail=readheader(pathname,1,0) > File "c:\07\Programming\Python\mod_fp\mod_fp.py", line 170, in > readheader > H['area'] = gridarea(H) > File "c:\07\Programming\Python\mod_fp\mod_fp.py", line 332, in > gridarea > area[ix,iy]=gridarea Personally I'd change gridarea() to take the individiual parameters rather than the dictionary. There is a shortcut way of doing that using **kwords which means you canb pass the dictionary but the unpacking will be done for you by Python... But most of my comments are stylistic, I have no real idea whats going wrong here. Sorry. -- 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 Sep 14 01:33:54 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 14 Sep 2007 00:33:54 +0100 Subject: [Tutor] Killing an instance References: <2107481c0709131503l583d631dn8624376f95d3e5c0@mail.gmail.com> Message-ID: <fcchdo$adk$1@sea.gmane.org> "Ara Kooser" <ghashsnaga at gmail.com> wrote > The code is below. I have Red and Yellow as my instances and I > want > them to die when life = 0 and not show up in the preceding rounds of > the game. I'm not sure I understand this last bit. Won't they already have shown up in the preceding bits of the game. Setting to zero won't affect the preceding rounds unless you only display all of the rounds at the end and keep the records in memory. In which case you could go back and retrospectively change the earlier displays. It sounds a bit odd tho' can you elaborate? Alan G. From alan.gauld at btinternet.com Fri Sep 14 01:30:47 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 14 Sep 2007 00:30:47 +0100 Subject: [Tutor] Killing an instance References: <2107481c0709131503l583d631dn8624376f95d3e5c0@mail.gmail.com> Message-ID: <fcch7t$a16$1@sea.gmane.org> "Ara Kooser" <ghashsnaga at gmail.com> wrote > I have two instances called and running. They interact with each > other and I would like one of the instances to cease to exist in the > second round based on a given condition. How do you kill an > instance? Either set the variable to something else or explicitly with del() class C: pass c = C() # create a C instance c = 42 # the C instance gets garbage collected or c -= C() # another instance del(c) # delete it. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From bhaaluu at gmail.com Fri Sep 14 03:58:43 2007 From: bhaaluu at gmail.com (bhaaluu) Date: Thu, 13 Sep 2007 21:58:43 -0400 Subject: [Tutor] deleting one line in multiple files Message-ID: <ea979d70709131858g71febde1ncf34b78ed6807039@mail.gmail.com> Greetings, I'm running Python 2.4.3 on a GNU/Linux box. This question is about using 'fileinput.' I have a directory of files, and I've created a file list of the files I want to work on: $ ls > file.list Each file in file.list needs to have a line removed, leaving the rest of the file intact. I found this snippet on the Net, and it works fine for one file: # the lines with '<script type' are deleted. import fileinput for line in fileinput.input("file0001.html", inplace=1): line = line.strip() if not '<script type'in line: print line The docs say: This iterates over the lines of all files listed in sys.argv[1:]... I'm not sure how to implement the argv stuff. However, the documentation also states: To specify an alternative list of filenames, pass it as the first argument to input(). A single file name is also allowed. So, when I replace file0001.html with file.list (the alternative list of filenames, nothing happens. # the lines with '<script type' are deleted. import fileinput for line in fileinput.input("file.list", inplace=1): line = line.strip() if not '<script type'in line: print line file.list has one filename on each line, ending with a newline. file0001.html file0002.html ::: ::: file0175.html Have I interpreted the documentation wrong? The goal is to delete the line that has '<script type' in it. I can supply more information if needed. TIA. -- bhaaluu at gmail dot com From wormwood_3 at yahoo.com Fri Sep 14 05:33:48 2007 From: wormwood_3 at yahoo.com (wormwood_3) Date: Thu, 13 Sep 2007 20:33:48 -0700 (PDT) Subject: [Tutor] deleting one line in multiple files Message-ID: <288966.77428.qm@web32410.mail.mud.yahoo.com> I think the problem is that the original script you borrowed looks at the file passed to input, and iterates over the lines in that file, removing them if they match your pattern. What you actually want to be doing is iterating over the lines of your list file, and for each line (which represents a file), you want to open *that* file, do the check for your pattern, and delete appropriately. Hope I am not completely off:-) If I am right so far, you want to do something like: import fileinput for file in fileinput.input("filelist.list", inplace=1): curfile = file.open() for line in curfile: line = line.strip() if not '<script type'in line: print line BUT, fileinput was made (if I understand the documentation) to avoid having to do this. This is where the sys.argv[1:] values come in. The example on this page (look under "Processing Each Line of One or More Files: The fileinput Module") helped clarify it to me: http://www.oreilly.com/catalog/lpython/chapter/ch09.html. If you do: % python myscript.py "<script type" `ls` This should pass in all the items in the folder you run this in (be sure it only contains the files you want to edit!), looking for "<script type". Continuing with the O'Reilly example: import fileinput, sys, string # take the first argument out of sys.argv and assign it to searchterm searchterm, sys.argv[1:] = sys.argv[1], sys.argv[2:] for line in fileinput.input(): num_matches = string.count(line, searchterm) if num_matches: # a nonzero count means there was a match print "found '%s' %d times in %s on line %d." % (searchterm, num_matches, fileinput.filename(), fileinput.filelineno()) To test this, I put the above code block in "mygrep.py", then made a file "test.txt" in the same folder, with some trash lines, and 1 line with the string you said you want to match on. Then I did: sam at B74kb0x:~$ python mygrep.py "<script type" test.txt found '<script type' 1 times in test.txt on line 3. So you could use the above block, and edit the print line to also edit the file as you want, maybe leaving the print to confirm it did what you expect. Hope this helps! -Sam _____________________________________ I have a directory of files, and I've created a file list of the files I want to work on: $ ls > file.list Each file in file.list needs to have a line removed, leaving the rest of the file intact. I found this snippet on the Net, and it works fine for one file: # the lines with '<script type' are deleted. import fileinput for line in fileinput.input("file0001.html", inplace=1): line = line.strip() if not '<script type'in line: print line The docs say: This iterates over the lines of all files listed in sys.argv[1:]... I'm not sure how to implement the argv stuff. However, the documentation also states: To specify an alternative list of filenames, pass it as the first argument to input(). A single file name is also allowed. So, when I replace file0001.html with file.list (the alternative list of filenames, nothing happens. # the lines with '<script type' are deleted. import fileinput for line in fileinput.input("file.list", inplace=1): line = line.strip() if not '<script type'in line: print line file.list has one filename on each line, ending with a newline. file0001.html file0002.html ::: ::: file0175.html Have I interpreted the documentation wrong? The goal is to delete the line that has '<script type' in it. I can supply more information if needed. TIA. -- bhaaluu at gmail dot com _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From pyth0nc0d3r at gmail.com Fri Sep 14 06:25:15 2007 From: pyth0nc0d3r at gmail.com (Lamonte Harris) Date: Thu, 13 Sep 2007 23:25:15 -0500 Subject: [Tutor] How can I extend my vocabulary that fits well with python. Message-ID: <eb79828c0709132125s498e7137y2666a935d4e96fda@mail.gmail.com> See theres a lot of words that I know and some that I don't know, how can I extend and improve my python vocabulary so I can interpret information in a faster manor. Makes things easier to understand if you actually understand the things the people are saying in tutorials,etc.. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070913/d81d0307/attachment.htm From rikard.bosnjakovic at gmail.com Fri Sep 14 06:34:45 2007 From: rikard.bosnjakovic at gmail.com (Rikard Bosnjakovic) Date: Fri, 14 Sep 2007 06:34:45 +0200 Subject: [Tutor] evaluating AND In-Reply-To: <Pine.LNX.4.44.0709131521440.18893-100000@violet.rahul.net> References: <be4fbf920709131515x6928aa69j8a00e4cea2ecc5b1@mail.gmail.com> <Pine.LNX.4.44.0709131521440.18893-100000@violet.rahul.net> Message-ID: <d9e88eaf0709132134s77714e82x864fa67cd6b95212@mail.gmail.com> On 14/09/2007, Terry Carroll <carroll at tjc.com> wrote: > The second one, which just checks "if x" and is satisfied with any false > value, including an empty tuple, does not raise the error condition, even > though the data is bad. This is a bad thing. For me, "if x" would be enough. If you think it's a bad thing when x is of the wrong data, then you really should check that it contains *correct* data as well. Using the the two function of yours, setting x to an integer: >>> x = 2 >>> print test01(x) Traceback (most recent call last): File "<stdin>", line 1, in ? File "/usr/tmp/python-3716vZq", line 3, in test01 TypeError: unsubscriptable object >>> print test02(x) Traceback (most recent call last): File "<stdin>", line 1, in ? File "/usr/tmp/python-3716vZq", line 8, in test02 TypeError: unsubscriptable object Rewriting your test01-function into this: def test01(x): if (type(x) == type((0,)) and (x is not None) and (length(x) == 2)): if x[0]>0: return x[1]/x[0] and testing again: >>> x = 2 >>> print test01(x) None My point is that if you think it's bad for a function to receive incorrect data you should do exhaustive checks for the input to make sure it is of correct type, size and whatever the requirements might be, not just check if it's a tuple or not. -- - Rikard - http://bos.hack.org/cv/ From rikard.bosnjakovic at gmail.com Fri Sep 14 06:38:08 2007 From: rikard.bosnjakovic at gmail.com (Rikard Bosnjakovic) Date: Fri, 14 Sep 2007 06:38:08 +0200 Subject: [Tutor] is this a vista issue In-Reply-To: <BAY111-W228603CCC24C3A84144F5AF3C30@phx.gbl> References: <BAY111-W4C4ABD47B42DBA13A2AC6F3C00@phx.gbl> <46E563DA.4090106@umn.edu> <BAY111-W228603CCC24C3A84144F5AF3C30@phx.gbl> Message-ID: <d9e88eaf0709132138n24cf229excddf360e8c7b2509@mail.gmail.com> On 13/09/2007, sacha rook <sacharook at hotmail.co.uk> wrote: > [CODE] > > from BeautifulSoup import BeautifulSoup > doc = ['<html><head><title>Page title</title></head>', > '<body><p id="firstpara" align="center">This is paragraph > <b>one</b>.', > '<p id="secondpara" align="blah">This is paragraph <b>two</b>.', > '<a href="http://www.google.co.uk"></a>', > '<a href="http://www.bbc.co.uk"></a>', > '<a href="http://www.amazon.co.uk"></a>', > '<a href="http://www.redhat.co.uk"></a>', > '</html>'] > soup = BeautifulSoup(''.join(doc)) > blist = soup.findAll('a') > print blist > import urlparse > for a in blist: > href = a['href'] > print urlparse.urlparse(href)[1] > > [/CODE] Works fine for me: >>> ## working on region in file python-tmp-371673F... [<a href="http://www.google.co.uk"></a>, <a href="http://www.bbc.co.uk"></a>, <a href="http://www.amazon.co.uk"></a>, <a href="http://www.redhat.co.uk"></a>] www.google.co.uk www.bbc.co.uk www.amazon.co.uk www.redhat.co.uk But as Kent wrote; show the whole traceback, not just the last line. -- - Rikard - http://bos.hack.org/cv/ From john at fouhy.net Fri Sep 14 06:47:17 2007 From: john at fouhy.net (John Fouhy) Date: Fri, 14 Sep 2007 16:47:17 +1200 Subject: [Tutor] evaluating AND In-Reply-To: <d9e88eaf0709132134s77714e82x864fa67cd6b95212@mail.gmail.com> References: <be4fbf920709131515x6928aa69j8a00e4cea2ecc5b1@mail.gmail.com> <Pine.LNX.4.44.0709131521440.18893-100000@violet.rahul.net> <d9e88eaf0709132134s77714e82x864fa67cd6b95212@mail.gmail.com> Message-ID: <5e58f2e40709132147u3cbe2e04jf7d986dd6b2aa0b2@mail.gmail.com> On 14/09/2007, Rikard Bosnjakovic <rikard.bosnjakovic at gmail.com> wrote: > On 14/09/2007, Terry Carroll <carroll at tjc.com> wrote: > > The second one, which just checks "if x" and is satisfied with any false > > value, including an empty tuple, does not raise the error condition, even > > though the data is bad. This is a bad thing. > My point is that if you think it's bad for a function to receive > incorrect data you should do exhaustive checks for the input to make > sure it is of correct type, size and whatever the requirements might > be, not just check if it's a tuple or not. I think Terry's viewpoint is that a function should raise an exception if it receives bad data. You don't need to do exhaustive isinstance()/type() tests; just use the data as if it is what you're expecting and let errors happen if the data is wrong. What's important is that the function should not return valid output when given invalid input. That's what could happen with Terry's hypothetical test02() if you give it an empty list. OTOH, if you give either function an integer, both will raise exceptions, which is fine. You could change the function like this, though, to ensure the list length is correct: >>> def test01(x): ... if x is not None: ... assert len(x)==2 ... if x[0]>0: ... return x[1]/x[0] ... -- John. From wormwood_3 at yahoo.com Fri Sep 14 07:14:28 2007 From: wormwood_3 at yahoo.com (wormwood_3) Date: Thu, 13 Sep 2007 22:14:28 -0700 (PDT) Subject: [Tutor] deleting one line in multiple files Message-ID: <203668.96400.qm@web32402.mail.mud.yahoo.com> Thought I would do some more testing and get you a more finalized form this time. So I took the mygrep.py script, and put it in a folder with 3 test files with content like this: I am some lines of text yep I love text 435345 345345345 <script type="text/javascript" /> Then I ran: sam at B74kb0x:~/test$ python mygrep.py "<script type" `ls` found '<script type' 1 times in test1.txt on line 6. found '<script type' 1 times in test2.txt on line 6. found '<script type' 1 times in test3.txt on line 6. This will work in your case quite well I think. Now for doing the actual delete... I could not find a way to succinctly delete a single line from the files in Python, but I am almost there. Sorry, it was late:-) import fileinput, sys, string # take the first argument out of sys.argv and assign it to searchterm searchterm, sys.argv[1:] = sys.argv[1], sys.argv[2:] for line in fileinput.input(): num_matches = string.count(line, searchterm) if num_matches: # a nonzero count means there was a match print "found '%s' %d times in %s on line %d." % (searchterm, num_matches, fileinput.filename(), fileinput.filelineno()) thisfile = open(fileinput.filename(), "r") linelist = thisfile.readlines() del linelist[(fileinput.filelineno() -1)] print linelist thisfile.close() print "Deleted %s line(s) containing pattern in %s" % (num_matches, fileinput.filename()) So this will do the search on the file you specify at runtime, look for the pattern you specify, and print out a list of the lines with the matching line removed. Now I need to write these lines back to the original file. Don't have that part yet...:-( -Sam ___________________________________________ ----- Original Message ---- From: wormwood_3 <wormwood_3 at yahoo.com> To: Python Tutorlist <tutor at python.org> Sent: Thursday, September 13, 2007 11:33:48 PM Subject: [Tutor] deleting one line in multiple files I think the problem is that the original script you borrowed looks at the file passed to input, and iterates over the lines in that file, removing them if they match your pattern. What you actually want to be doing is iterating over the lines of your list file, and for each line (which represents a file), you want to open *that* file, do the check for your pattern, and delete appropriately. Hope I am not completely off:-) If I am right so far, you want to do something like: import fileinput for file in fileinput.input("filelist.list", inplace=1): curfile = file.open() for line in curfile: line = line.strip() if not '<script type'in line: print line BUT, fileinput was made (if I understand the documentation) to avoid having to do this. This is where the sys.argv[1:] values come in. The example on this page (look under "Processing Each Line of One or More Files: The fileinput Module") helped clarify it to me: http://www.oreilly.com/catalog/lpython/chapter/ch09.html. If you do: % python myscript.py "<script type" `ls` This should pass in all the items in the folder you run this in (be sure it only contains the files you want to edit!), looking for "<script type". Continuing with the O'Reilly example: import fileinput, sys, string # take the first argument out of sys.argv and assign it to searchterm searchterm, sys.argv[1:] = sys.argv[1], sys.argv[2:] for line in fileinput.input(): num_matches = string.count(line, searchterm) if num_matches: # a nonzero count means there was a match print "found '%s' %d times in %s on line %d." % (searchterm, num_matches, fileinput.filename(), fileinput.filelineno()) To test this, I put the above code block in "mygrep.py", then made a file "test.txt" in the same folder, with some trash lines, and 1 line with the string you said you want to match on. Then I did: sam at B74kb0x:~$ python mygrep.py "<script type" test.txt found '<script type' 1 times in test.txt on line 3. So you could use the above block, and edit the print line to also edit the file as you want, maybe leaving the print to confirm it did what you expect. Hope this helps! -Sam _____________________________________ I have a directory of files, and I've created a file list of the files I want to work on: $ ls > file.list Each file in file.list needs to have a line removed, leaving the rest of the file intact. I found this snippet on the Net, and it works fine for one file: # the lines with '<script type' are deleted. import fileinput for line in fileinput.input("file0001.html", inplace=1): line = line.strip() if not '<script type'in line: print line The docs say: This iterates over the lines of all files listed in sys.argv[1:]... I'm not sure how to implement the argv stuff. However, the documentation also states: To specify an alternative list of filenames, pass it as the first argument to input(). A single file name is also allowed. So, when I replace file0001.html with file.list (the alternative list of filenames, nothing happens. # the lines with '<script type' are deleted. import fileinput for line in fileinput.input("file.list", inplace=1): line = line.strip() if not '<script type'in line: print line file.list has one filename on each line, ending with a newline. file0001.html file0002.html ::: ::: file0175.html Have I interpreted the documentation wrong? The goal is to delete the line that has '<script type' in it. I can supply more information if needed. TIA. -- bhaaluu at gmail dot com _______________________________________________ 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 steve at holdenweb.com Fri Sep 14 07:48:41 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 14 Sep 2007 01:48:41 -0400 Subject: [Tutor] Just bought Python in a Nutshell In-Reply-To: <eb79828c0709132112o5a3e7137n5ae5cd55e3e0b839@mail.gmail.com> References: <eb79828c0709132112o5a3e7137n5ae5cd55e3e0b839@mail.gmail.com> Message-ID: <fcd7bq$nrh$1@sea.gmane.org> Lamonte Harris wrote: > http://www.powells.com/biblio/63-9780596001889-7 Used, has anyone read > this book. Any additional information that you like,dislike about this > book? [I like having real books and stead of ebooks because its better > on the eyes.] Should be her 2morrow Afternoon :), few hours before I > get home great deal :D. You have just purchased the most comprehensive language reference and instructional manual currently available, written by an acknowledged expert whose pedantry ensures an excruciating level of correctness in the text. It's a well-written book, and contains enough information that almost every Python programmer will find it a useful addition to his or her bookshelf. You will enjoy it whether you choose to read from the beginning or just dip in. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From pyth0nc0d3r at gmail.com Fri Sep 14 06:12:48 2007 From: pyth0nc0d3r at gmail.com (Lamonte Harris) Date: Thu, 13 Sep 2007 23:12:48 -0500 Subject: [Tutor] Just bought Python in a Nutshell Message-ID: <eb79828c0709132112o5a3e7137n5ae5cd55e3e0b839@mail.gmail.com> http://www.powells.com/biblio/63-9780596001889-7 Used, has anyone read this book. Any additional information that you like,dislike about this book? [I like having real books and stead of ebooks because its better on the eyes.] Should be her 2morrow Afternoon :), few hours before I get home great deal :D. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070913/335d1a26/attachment.htm From alan.gauld at btinternet.com Fri Sep 14 09:46:46 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 14 Sep 2007 08:46:46 +0100 Subject: [Tutor] How can I extend my vocabulary that fits well with python. References: <eb79828c0709132125s498e7137y2666a935d4e96fda@mail.gmail.com> Message-ID: <fcde9t$boo$1@sea.gmane.org> "Lamonte Harris" <pyth0nc0d3r at gmail.com> wrote > See theres a lot of words that I know and some that I don't know, > how can I > extend and improve my python vocabulary so I can interpret > information in a > faster manor. Makes things easier to understand if you actually > understand > the things the people are saying in tutorials,etc.. It might help if you give examples of words you don't understand. In fact just posting to this list asking about any such word will usually get you an answer. Or try Wikipedia. However if you are referring to the jargon of programming, things like "source code", "compiling", etc then you may find the introductory section of my tutorial useful. I try to explain all jargon the first time I use it... And one of my aims was to ensure the student was introduced to the kind of language they would encounter on the 'net. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From sacharook at hotmail.co.uk Fri Sep 14 11:56:57 2007 From: sacharook at hotmail.co.uk (sacha rook) Date: Fri, 14 Sep 2007 10:56:57 +0100 Subject: [Tutor] list iteration question for writing to a file on disk In-Reply-To: <46E99CEE.3030304@tds.net> References: <BAY111-W4C4ABD47B42DBA13A2AC6F3C00@phx.gbl> <46E563DA.4090106@umn.edu> <BAY111-W228603CCC24C3A84144F5AF3C30@phx.gbl> <46E95D8E.7070801@tds.net> <BAY111-W1005A75AD89BC967012FEAF3C30@phx.gbl> <46E99CEE.3030304@tds.net> Message-ID: <BAY111-W57740F9C97F963177C59CF3BC0@phx.gbl> Hi can someone help with this please? i got to this point with help from the list. from BeautifulSoup import BeautifulSoupdoc = ['<html><head><title>Page title</title></head>', '<body><p id="firstpara" align="center">This is paragraph <b>one</b>.', '<p id="secondpara" align="blah">This is paragraph <b>two</b>.', '<a href="http://www.google.co.uk"></a>', '<a href="http://www.bbc.co.uk"></a>', '<a href="http://www.amazon.co.uk"></a>', '<a href="http://www.redhat.co.uk"></a>', '</html>']soup = BeautifulSoup(''.join(doc))alist = soup.findAll('a') import urlparsefor a in alist: href = a['href'] print urlparse.urlparse(href)[1] so BeautifulSoup used to find <a> tags; use urlparse to extract to fully qualified domain name use print to print a nice list of hosts 1 per line. here www.google.co.ukwww.bbc.co.ukwww.amazon.co.ukwww.redhat.co.uk nice, so i think write them out to a file; change program to this to write to disk and read them back to see what's been done. from BeautifulSoup import BeautifulSoupdoc = ['<html><head><title>Page title</title></head>', '<body><p id="firstpara" align="center">This is paragraph <b>one</b>.', '<p id="secondpara" align="blah">This is paragraph <b>two</b>.', '<a href="http://www.google.co.uk"></a>', '<a href="http://www.bbc.co.uk"></a>', '<a href="http://www.amazon.co.uk"></a>', '<a href="http://www.redhat.co.uk"></a>', '</html>']soup = BeautifulSoup(''.join(doc))alist = soup.findAll('a') import urlparseoutput = open("fqdns.txt","w") for a in alist: href = a['href'] output.write(urlparse.urlparse(href)[1]) output.close() this writes out www.google.co.ukwww.bbc.co.ukwww.amazon.co.ukwww.redhat.co.uk so I look in Alan's tutor pdf for issue and read page 120 where it suggests doing this; outp.write(line + '\n') # \n is a newline so i change my line from this output.write(urlparse.urlparse(href)[1]) to this output.write(urlparse.urlparse(href)[1] + "\n") I look at the output file and I get this www.google.co.ukwww.bbc.co.ukwww.amazon.co.ukwww.redhat.co.uk hooray I think, so then I open the file in the program to read each line to do something with it. i pop this after the last output.close() input = open("fqdns.txt","r")for j in input: print j input.close() but his prints out www.google.co.uk www.bbc.co.uk www.amazon.co.uk www.redhat.co.uk Why do i get each record with an extra new line ? Am I writing out the records incorrectly or am I handling them incorrectly when I open the file and print do I have to take out newlines as I process? any help would be great s _________________________________________________________________ Feel like a local wherever you go. http://www.backofmyhand.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070914/55a4ee06/attachment.htm From kent37 at tds.net Fri Sep 14 12:45:39 2007 From: kent37 at tds.net (Kent Johnson) Date: Fri, 14 Sep 2007 06:45:39 -0400 Subject: [Tutor] Killing an instance In-Reply-To: <2107481c0709131503l583d631dn8624376f95d3e5c0@mail.gmail.com> References: <2107481c0709131503l583d631dn8624376f95d3e5c0@mail.gmail.com> Message-ID: <46EA6653.3060300@tds.net> Ara Kooser wrote: > I have two instances called and running. They interact with each > other and I would like one of the instances to cease to exist in the > second round based on a given condition. How do you kill an instance? What you really need is for your main code to stop using the instance. You could write it like this: if one.isAlive(): one.lys_re("lys") if two.isAlive(): two.ade_re("ade") etc. But your two classes are so similar, I would try to merge them into one class and have the behaviour (which aa they consume or release) determined by configuration. Then you can keep the instances in a list and treat them uniformly. Something like yeasts = [Yeast("Red","alpha", "lys", "ade"), Yeast("Yellow","alpha", "ade", "lys")] #Game logic while count < rounds: for yeast in yeasts: yeast.release() print print "Chemicals in the environment",chemicals print time.sleep(1) for yeast in yeasts: yeast.consume() # This step removes dead yeasts from the list yeasts = [yeast for yeast in yeasts if yeast.isAlive()] > def ade_need(self,stuffb): > > if stuffb != chemicals: I'm not sure what you think you are testing, but this will always be true; stuffb is a string and chemicals is a list, they will never be equal. I think you want if stuffb in chemicals: Kent From bhaaluu at gmail.com Fri Sep 14 13:40:00 2007 From: bhaaluu at gmail.com (bhaaluu) Date: Fri, 14 Sep 2007 07:40:00 -0400 Subject: [Tutor] deleting one line in multiple files In-Reply-To: <ea979d70709140438v7c6972c4k6265a2764625aca2@mail.gmail.com> References: <319064.47122.qm@web32406.mail.mud.yahoo.com> <ea979d70709140438v7c6972c4k6265a2764625aca2@mail.gmail.com> Message-ID: <ea979d70709140440q62416e6dyf02b39daffa40b77@mail.gmail.com> On 9/13/07, wormwood_3 <wormwood_3 at yahoo.com> wrote: > I think the problem is that the original script you borrowed looks at the file passed to input, and iterates over the lines in that file, removing them if they match your pattern. What you actually want to be doing is iterating over the lines of your list file, and for each line (which represents a file), you want to open *that* file, do the check for your pattern, and delete appropriately. > > Hope I am not completely off:-) This is exactly what I'd like to do. =) After manually opening about 25 files individually and deleting the line that I wanted to delete, and seeing about 175 files left to finish, I thought to myself, 'I'm learning Python! Python is supposed to be really good at this kind of stuff.' So, since there isn't a rush deadline for this project, I figured I could play around and see what kinds of solutions I could find. The 'fileinput' snippet is one solution, but I'd rather be able to pass it a list of filenames to work on, rather than have to manually change the filename in the snippet each time. The files are numbered, in order, from 0001 to 0175, (filename0001.html to filename0175.html). One thought was to be able to change the filename number incrementally, assign it to a variable, and run it through a for loop? Isn't it amazing how a Newbie approaches a problem? =) I'm also looking into 'sed' for doing this. I've used 'sed' in the past for deleting a specific line from files, as well as doing simple search and replace in a file. I just figured that if it can be done in 'sed,' it can be done in Python much easier and maybe even more elegantly (although at this point in my Python career, elegance isn't a top priority). Happy Programming! -- bhaaluu at gmail dot com > > If I am right so far, you want to do something like: > > import fileinput > > for file in fileinput.input("filelist.list", inplace=1): > curfile = file.open() > for line in curfile: > line = line.strip() > if not '<script type'in line: > print line > > BUT, fileinput was made (if I understand the documentation) to avoid having to do this. This is where the sys.argv[1:] values come in. The example on this page (look under "Processing Each Line of One or More Files: > The fileinput Module") helped clarify it to me: http://www.oreilly.com/catalog/lpython/chapter/ch09.html. If you do: > > % python myscript.py "<script type" `ls` > This should pass in all the items in the folder you run this in (be sure it only contains the files you want to edit!), looking for "<script type". Continuing with the O'Reilly example: > > import fileinput, sys, string > # take the first argument out of sys.argv and assign it to searchterm > searchterm, sys.argv[1:] = sys.argv[1], sys.argv[2:] > for line in fileinput.input(): > num_matches = string.count(line, searchterm) > if num_matches: # a nonzero count means there was a match > print "found '%s' %d times in %s on line %d." % (searchterm, num_matches, > fileinput.filename(), fileinput.filelineno()) > > To test this, I put the above code block in "mygrep.py", then made a file "test.txt" in the same folder, with some trash lines, and 1 line with the string you said you want to match on. Then I did: > > sam at B74kb0x:~$ python mygrep.py "<script type" test.txt > found '<script type' 1 times in test.txt on line 3. > > So you could use the above block, and edit the print line to also edit the file as you want, maybe leaving the print to confirm it did what you expect. > > Hope this helps! > -Sam > > _____________________________________ > I have a directory of files, and I've created a file list > of the files I want to work on: > > $ ls > file.list > > Each file in file.list needs to have a line removed, > leaving the rest of the file intact. > > I found this snippet on the Net, and it works fine for one file: > > # the lines with '<script type' are deleted. > import fileinput > > for line in fileinput.input("file0001.html", inplace=1): > line = line.strip() > if not '<script type'in line: > print line > > The docs say: > This iterates over the lines of all files listed in sys.argv[1:]... > I'm not sure how to implement the argv stuff. > > However, the documentation also states: > To specify an alternative list of filenames, > pass it as the first argument to input(). > A single file name is also allowed. > > So, when I replace file0001.html with file.list (the alternative list > of filenames, nothing happens. > > # the lines with '<script type' are deleted. > import fileinput > > for line in fileinput.input("file.list", inplace=1): > line = line.strip() > if not '<script type'in line: > print line > > file.list has one filename on each line, ending with a newline. > file0001.html > file0002.html > ::: > ::: > file0175.html > > Have I interpreted the documentation wrong? > The goal is to delete the line that has '<script type' in it. > I can supply more information if needed. > TIA. > -- > bhaaluu at gmail dot com > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > > From kent37 at tds.net Fri Sep 14 14:06:29 2007 From: kent37 at tds.net (Kent Johnson) Date: Fri, 14 Sep 2007 08:06:29 -0400 Subject: [Tutor] deleting one line in multiple files In-Reply-To: <ea979d70709140440q62416e6dyf02b39daffa40b77@mail.gmail.com> References: <319064.47122.qm@web32406.mail.mud.yahoo.com> <ea979d70709140438v7c6972c4k6265a2764625aca2@mail.gmail.com> <ea979d70709140440q62416e6dyf02b39daffa40b77@mail.gmail.com> Message-ID: <46EA7945.8030908@tds.net> bhaaluu wrote: > On 9/13/07, wormwood_3 <wormwood_3 at yahoo.com> wrote: > >> I think the problem is that the original script you borrowed looks >> at the file passed to input, and iterates over the lines in that file, removing them if they match your pattern. What you actually want to be doing is iterating over the lines of your list file, and for each line (which represents a file), you want to open *that* file, do the check for your pattern, and delete appropriately. > > This is exactly what I'd like to do. =) > After manually opening about 25 files individually and deleting the line > that I wanted to delete, and seeing about 175 files left to finish, I thought > to myself, 'I'm learning Python! Python is supposed to be really good at > this kind of stuff.' Good idea! Python is excellent for this kind of stuff. > The 'fileinput' snippet is one solution, but I'd rather be able to pass it a > list of filenames to work on, rather than have to manually change the > filename in the snippet each time. The files are numbered, in order, > from 0001 to 0175, (filename0001.html to filename0175.html). Sam has already given you one solution - to pass the list of filenames on the command line. The first argument to fileinput.input() can be a list of filenames, so you could do filenames = open("filelist.list").read().splitlines() for line in fileinput.input(filenames, inplace=1): # etc > One thought was to be able to change the filename number incrementally, > assign it to a variable, and run it through a for loop? Isn't it amazing > how a Newbie approaches a problem? =) That is arguably a better approach than reading the file, since it avoids the effort of creating the file. for i in range(1, 176): filename = 'filename%04d.html' % i for line in fileinput.input(filename, inplace=1): # etc Kent From bhaaluu at gmail.com Fri Sep 14 14:22:35 2007 From: bhaaluu at gmail.com (bhaaluu) Date: Fri, 14 Sep 2007 08:22:35 -0400 Subject: [Tutor] deleting one line in multiple files In-Reply-To: <ea979d70709140522r2531601euf999ac8c0604e322@mail.gmail.com> References: <319064.47122.qm@web32406.mail.mud.yahoo.com> <ea979d70709140438v7c6972c4k6265a2764625aca2@mail.gmail.com> <ea979d70709140440q62416e6dyf02b39daffa40b77@mail.gmail.com> <46EA7945.8030908@tds.net> <ea979d70709140522r2531601euf999ac8c0604e322@mail.gmail.com> Message-ID: <ea979d70709140522q686a4f57o2e97119f206b3846@mail.gmail.com> Greetings, Many thanks to wormwood_3 and Kent for their help. Summary: The working script looks like this: # the lines with '<script type' are deleted. import fileinput for i in range(1, 176): filename = 'filename%04d.html' % i for line in fileinput.input(filename, inplace=1): #for line in fileinput.input("file0001.html", inplace=1): line = line.strip() if not '<script type'in line: print line It was implemented as: $ python delete.py ...and it took less than a second to delete the line from all the files! I'm working on the files in a temporary directory, so I'm going to try the other solution as well. Happy Programming! -- bhaaluu at gmail dot com On 9/14/07, Kent Johnson <kent37 at tds.net> wrote: > bhaaluu wrote: > > On 9/13/07, wormwood_3 <wormwood_3 at yahoo.com> wrote: > > > >> I think the problem is that the original script you borrowed looks > >> at > the file passed to input, and iterates over the lines in that file, > removing them if they match your pattern. What you actually want to be > doing is iterating over the lines of your list file, and for each line > (which represents a file), you want to open *that* file, do the check > for your pattern, and delete appropriately. > > > > This is exactly what I'd like to do. =) > > After manually opening about 25 files individually and deleting the line > > that I wanted to delete, and seeing about 175 files left to finish, I thought > > to myself, 'I'm learning Python! Python is supposed to be really good at > > this kind of stuff.' > > Good idea! Python is excellent for this kind of stuff. > > > > The 'fileinput' snippet is one solution, but I'd rather be able to pass it a > > list of filenames to work on, rather than have to manually change the > > filename in the snippet each time. The files are numbered, in order, > > from 0001 to 0175, (filename0001.html to filename0175.html). > > Sam has already given you one solution - to pass the list of filenames > on the command line. > > The first argument to fileinput.input() can be a list of filenames, so > you could do > > filenames = open("filelist.list").read().splitlines() > for line in fileinput.input(filenames, inplace=1): > # etc > > > One thought was to be able to change the filename number incrementally, > > assign it to a variable, and run it through a for loop? Isn't it amazing > > how a Newbie approaches a problem? =) > > That is arguably a better approach than reading the file, since it > avoids the effort of creating the file. > > for i in range(1, 176): > filename = 'filename%04d.html' % i > for line in fileinput.input(filename, inplace=1): > # etc > > Kent > -- bhaaluu at gmail dot com From mlangford.cs03 at gtalumni.org Fri Sep 14 14:26:04 2007 From: mlangford.cs03 at gtalumni.org (Michael Langford) Date: Fri, 14 Sep 2007 08:26:04 -0400 Subject: [Tutor] deleting one line in multiple files In-Reply-To: <ea979d70709140440q62416e6dyf02b39daffa40b77@mail.gmail.com> References: <319064.47122.qm@web32406.mail.mud.yahoo.com> <ea979d70709140438v7c6972c4k6265a2764625aca2@mail.gmail.com> <ea979d70709140440q62416e6dyf02b39daffa40b77@mail.gmail.com> Message-ID: <82b4f5810709140526m16c09b01pba9c62588a309f9e@mail.gmail.com> Sed is a little easier than python for this project, but python is more flexible. Sed would be sed -e "s/^.*\<script line.*$//g" file000.lst That would leave a blank line where your script line was. To run this command multiple times, you'd use xargs: ls filename* | xargs -I fn -n 1 sed -e "s/^.*\<script line.*$//g" fn fn.modified This will take each file that starts with filename, strip out the line that has <script line in it, then rename it to fn.modified. A second application of xargs will easily rename all the .modified files back to the original name ls filename* | xargs -I fn -n 1 mv fn.modified fn So your total sed solution is: ls filename* | xargs -I fn -n 1 sed -e "s/^.*\<script line.*$//g" fn fn.modified ls filename* | xargs -I fn -n 1 mv fn.modified fn As far as python goes, use of import sys.argv and xargs will get you to the same place, but a more flexible solution. --Michael As for the python one, you want to import sys.args -- Michael Langford Phone: 404-386-0495 Consulting: http://www.TierOneDesign.com/ Entertaining: http://www.ThisIsYourCruiseDirectorSpeaking.com On 9/14/07, bhaaluu <bhaaluu at gmail.com> wrote: > > On 9/13/07, wormwood_3 <wormwood_3 at yahoo.com> wrote: > > > I think the problem is that the original script you borrowed looks at > the file passed to input, and iterates over the lines in that file, removing > them if they match your pattern. What you actually want to be doing is > iterating over the lines of your list file, and for each line (which > represents a file), you want to open *that* file, do the check for your > pattern, and delete appropriately. > > > > Hope I am not completely off:-) > > This is exactly what I'd like to do. =) > After manually opening about 25 files individually and deleting the line > that I wanted to delete, and seeing about 175 files left to finish, I > thought > to myself, 'I'm learning Python! Python is supposed to be really good at > this kind of stuff.' So, since there isn't a rush deadline for this > project, > I figured I could play around and see what kinds of solutions I could > find. > > The 'fileinput' snippet is one solution, but I'd rather be able to pass it > a > list of filenames to work on, rather than have to manually change the > filename in the snippet each time. The files are numbered, in order, > from 0001 to 0175, (filename0001.html to filename0175.html). > One thought was to be able to change the filename number incrementally, > assign it to a variable, and run it through a for loop? Isn't it amazing > how a Newbie approaches a problem? =) > > I'm also looking into 'sed' for doing this. I've used 'sed' in the past > for > deleting a specific line from files, as well as doing simple search and > replace in a file. I just figured that if it can be done in 'sed,' it > can be done > in Python much easier and maybe even more elegantly (although at > this point in my Python career, elegance isn't a top priority). > > Happy Programming! > -- > bhaaluu at gmail dot com > > > > > > If I am right so far, you want to do something like: > > > > import fileinput > > > > for file in fileinput.input("filelist.list", inplace=1): > > curfile = file.open() > > for line in curfile: > > line = line.strip() > > if not '<script type'in line: > > print line > > > > BUT, fileinput was made (if I understand the documentation) to avoid > having to do this. This is where the sys.argv[1:] values come in. The > example on this page (look under "Processing Each Line of One or More Files: > > The fileinput Module") helped clarify it to me: > http://www.oreilly.com/catalog/lpython/chapter/ch09.html. If you do: > > > > % python myscript.py "<script type" `ls` > > This should pass in all the items in the folder you run this in (be sure > it only contains the files you want to edit!), looking for "<script type". > Continuing with the O'Reilly example: > > > > import fileinput, sys, string > > # take the first argument out of sys.argv and assign it to searchterm > > searchterm, sys.argv[1:] = sys.argv[1], sys.argv[2:] > > for line in fileinput.input(): > > num_matches = string.count(line, searchterm) > > if num_matches: # a nonzero count means there was > a match > > print "found '%s' %d times in %s on line %d." % (searchterm, > num_matches, > > fileinput.filename(), fileinput.filelineno()) > > > > To test this, I put the above code block in "mygrep.py", then made a > file "test.txt" in the same folder, with some trash lines, and 1 line with > the string you said you want to match on. Then I did: > > > > sam at B74kb0x:~$ python mygrep.py "<script type" test.txt > > found '<script type' 1 times in test.txt on line 3. > > > > So you could use the above block, and edit the print line to also edit > the file as you want, maybe leaving the print to confirm it did what you > expect. > > > > Hope this helps! > > -Sam > > > > _____________________________________ > > I have a directory of files, and I've created a file list > > of the files I want to work on: > > > > $ ls > file.list > > > > Each file in file.list needs to have a line removed, > > leaving the rest of the file intact. > > > > I found this snippet on the Net, and it works fine for one file: > > > > # the lines with '<script type' are deleted. > > import fileinput > > > > for line in fileinput.input("file0001.html", inplace=1): > > line = line.strip() > > if not '<script type'in line: > > print line > > > > The docs say: > > This iterates over the lines of all files listed in sys.argv[1:]... > > I'm not sure how to implement the argv stuff. > > > > However, the documentation also states: > > To specify an alternative list of filenames, > > pass it as the first argument to input(). > > A single file name is also allowed. > > > > So, when I replace file0001.html with file.list (the alternative list > > of filenames, nothing happens. > > > > # the lines with '<script type' are deleted. > > import fileinput > > > > for line in fileinput.input("file.list", inplace=1): > > line = line.strip() > > if not '<script type'in line: > > print line > > > > file.list has one filename on each line, ending with a newline. > > file0001.html > > file0002.html > > ::: > > ::: > > file0175.html > > > > Have I interpreted the documentation wrong? > > The goal is to delete the line that has '<script type' in it. > > I can supply more information if needed. > > TIA. > > -- > > bhaaluu at gmail dot com > > _______________________________________________ > > 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/20070914/ebcecf6e/attachment-0001.htm From bhaaluu at gmail.com Fri Sep 14 15:09:15 2007 From: bhaaluu at gmail.com (bhaaluu) Date: Fri, 14 Sep 2007 09:09:15 -0400 Subject: [Tutor] deleting one line in multiple files In-Reply-To: <46EA7945.8030908@tds.net> References: <319064.47122.qm@web32406.mail.mud.yahoo.com> <ea979d70709140438v7c6972c4k6265a2764625aca2@mail.gmail.com> <ea979d70709140440q62416e6dyf02b39daffa40b77@mail.gmail.com> <46EA7945.8030908@tds.net> Message-ID: <ea979d70709140609t298bcfefre62c58d1357fefcf@mail.gmail.com> Greetings, Okay, I've had a chance to experiment with both solutions, and both of them work as advertised. For those just tuning in, what I wanted to do was delete a line in each file in a directory that had a specific pattern in the line. There were over two hundred files in the directory, and I quickly discovered that deleting the line in each file, manually, was going to take quite a while. I'm learning Python, so I set out to find a Python solution. I stumbled upon the 'fileinput' module, specifically, a snippet that took a filename and deleted the line 'in place' (no need for a temporary third file). A blank line was left where the deleted line was, but that was not a problem in this case. The most flexible script is the one that uses a list of filenames, that need to be worked on, in the directory. In this case, it doesn't matter if the files are incrementaly numbered or not. I like this solution the best because it is the most versatile. 1. Create the list of files that need work: $ ls > file.list 2. Run the Python script: $ python delete2.py That's it! =) Here's the script: # delete2.py # 2007-09-14 # the lines with '<script type' are deleted. import fileinput filenames = open("file.list").read().splitlines() for line in fileinput.input(filenames, inplace=1): line = line.strip() if not '<script type' in line: print line # end delete2.py I've already posted the other solution, which iterates through incrementally numbered files, but for the purpose of Summary, here it is again: # delete1.py # 2007-09-14 # the lines with '<script type' are deleted. import fileinput for i in range(1, 176): filename = 'filename%04d.html' % i for line in fileinput.input(filename, inplace=1): line = line.strip() if not '<script type' in line: print line # end delete1.py In this case, a list of files is not used since all the files have the same name + an incremented number, and the same extension. All the files were named: filename0001.html to filename0207.html. I was able to work on a subset of the files within the stated range. Also useful! =) Finally, here is the original snippet, (I wish I'd noted where I found it!): # delete0.py # 2007-09-14 # open 00.test and the lines with '<script type' are deleted. import fileinput for line in fileinput.input("00.test", inplace=1): line = line.strip() if not '<script type'in line: print line # end delete0.py This takes one file (00.test) and deletes the lines with '<script type' in them. Finally, here is the Python documentation reference for 'fileinput' http://docs.python.org/lib/module-fileinput.html I've already placed these little scripts in my utility directory, as I'm sure to use them again. Many thanks to all the Tutors (esp. wormwood_3 and Kent). Happy Programming! -- bhaaluu at gmail dot com From sacharook at hotmail.co.uk Fri Sep 14 15:56:51 2007 From: sacharook at hotmail.co.uk (sacha rook) Date: Fri, 14 Sep 2007 14:56:51 +0100 Subject: [Tutor] remove blank list items In-Reply-To: <46EA6E65.7040506@exemail.com.au> References: <BAY111-W4C4ABD47B42DBA13A2AC6F3C00@phx.gbl> <46E563DA.4090106@umn.edu> <BAY111-W228603CCC24C3A84144F5AF3C30@phx.gbl> <46E95D8E.7070801@tds.net> <BAY111-W1005A75AD89BC967012FEAF3C30@phx.gbl> <46E99CEE.3030304@tds.net> <BAY111-W57740F9C97F963177C59CF3BC0@phx.gbl> <46EA6E65.7040506@exemail.com.au> Message-ID: <BAY111-W1931BFC57BD02170837B83F3BC0@phx.gbl> Hi i was expanding my program to write urls parsed from a html page and write them to a file so i chose www.icq.com to extract the urls from. when i wrote these out to a file and then read the file back I noticed a list of urls then some blank lines then some more urls then some blank lines, does this mean that one of the functions called has for some reason added some whitespace into some of the list items so that i wrote them out to disk? I also noticed that there are duplicate hosts/urls that have been written to the file. So my two questions are; 1. how and where do I tackle removing the whitespace from being written out to disk? 2. how do i tackle checking for duplicate entries in a list before writing them out to disk? My code is below from BeautifulSoup import BeautifulSoupimport urllib2import urlparse file = urllib2.urlopen("http://www.icq.com") soup = BeautifulSoup(''.join(file))alist = soup.findAll('a') output = open("fqdns.txt","w") for a in alist: href = a['href'] output.write(urlparse.urlparse(href)[1] + "\n") output.close() input = open("fqdns.txt","r") for j in input: print j, input.close() the chopped output is here chat.icq.comchat.icq.comchat.icq.comchat.icq.comchat.icq.com labs.icq.comdownload.icq.comgreetings.icq.comgreetings.icq.comgreetings.icq.comgames.icq.comgames.icq.com _________________________________________________________________ Celeb spotting ? Play CelebMashup and win cool prizes https://www.celebmashup.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070914/ebf494d6/attachment.htm From mlangford.cs03 at gtalumni.org Fri Sep 14 16:11:38 2007 From: mlangford.cs03 at gtalumni.org (Michael Langford) Date: Fri, 14 Sep 2007 10:11:38 -0400 Subject: [Tutor] remove blank list items In-Reply-To: <BAY111-W1931BFC57BD02170837B83F3BC0@phx.gbl> References: <BAY111-W4C4ABD47B42DBA13A2AC6F3C00@phx.gbl> <46E563DA.4090106@umn.edu> <BAY111-W228603CCC24C3A84144F5AF3C30@phx.gbl> <46E95D8E.7070801@tds.net> <BAY111-W1005A75AD89BC967012FEAF3C30@phx.gbl> <46E99CEE.3030304@tds.net> <BAY111-W57740F9C97F963177C59CF3BC0@phx.gbl> <46EA6E65.7040506@exemail.com.au> <BAY111-W1931BFC57BD02170837B83F3BC0@phx.gbl> Message-ID: <82b4f5810709140711ka53f9bfr43cee17ea44e419c@mail.gmail.com> First off: What you want is a set, not a list. Lucky for you, a python dict uses a set for its keys, so cheat and use that. change: for j in input: print j, to mySet={} for j in input: mySet[j]=j for item in mySet.keys(): print item Secondly, to not print blank lines, strip items and only add them if they aren't == "" change: for j in input: print j, to mySet={} for j in input: cleaned = j.strip() if j!="": mySet[cleaned]=cleaned for item in mySet.keys(): print item On 9/14/07, sacha rook <sacharook at hotmail.co.uk> wrote: > > Hi > > i was expanding my program to write urls parsed from a html page and write > them to a file so i chose www.icq.com to extract the urls from. > > when i wrote these out to a file and then read the file back I noticed a > list of urls then some blank lines then some more urls then some blank > lines, does this mean that one of the functions called has for some reason > added some whitespace into some of the list items so that i wrote them out > to disk? > > I also noticed that there are duplicate hosts/urls that have been written > to the file. > > So my two questions are; > 1. how and where do I tackle removing the whitespace from being written > out to disk? > > 2. how do i tackle checking for duplicate entries in a list before writing > them out to disk? > > My code is below > from BeautifulSoup import BeautifulSoup > import urllib2 > import urlparse > file = urllib2.urlopen("http://www.icq.com") > soup = BeautifulSoup(''.join(file)) > alist = soup.findAll('a') > output = open("fqdns.txt","w") > for a in alist: > href = a['href'] > output.write(urlparse.urlparse(href)[1] + "\n") > output.close() > input = open("fqdns.txt","r") > for j in input: > print j, > input.close() > > the chopped output is here > > chat.icq.com > chat.icq.com > chat.icq.com > chat.icq.com > chat.icq.com > > > labs.icq.com > download.icq.com > greetings.icq.com > greetings.icq.com > greetings.icq.com > games.icq.com > games.icq.com > > ------------------------------ > Get free emoticon packs and customisation from Windows Live. Pimp My Live!<http://www.pimpmylive.co.uk> > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Michael Langford Phone: 404-386-0495 Consulting: http://www.TierOneDesign.com/ Entertaining: http://www.ThisIsYourCruiseDirectorSpeaking.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070914/73147512/attachment.htm From kent37 at tds.net Fri Sep 14 16:34:23 2007 From: kent37 at tds.net (Kent Johnson) Date: Fri, 14 Sep 2007 10:34:23 -0400 Subject: [Tutor] remove blank list items In-Reply-To: <82b4f5810709140711ka53f9bfr43cee17ea44e419c@mail.gmail.com> References: <BAY111-W4C4ABD47B42DBA13A2AC6F3C00@phx.gbl> <46E563DA.4090106@umn.edu> <BAY111-W228603CCC24C3A84144F5AF3C30@phx.gbl> <46E95D8E.7070801@tds.net> <BAY111-W1005A75AD89BC967012FEAF3C30@phx.gbl> <46E99CEE.3030304@tds.net> <BAY111-W57740F9C97F963177C59CF3BC0@phx.gbl> <46EA6E65.7040506@exemail.com.au> <BAY111-W1931BFC57BD02170837B83F3BC0@phx.gbl> <82b4f5810709140711ka53f9bfr43cee17ea44e419c@mail.gmail.com> Message-ID: <46EA9BEF.1070000@tds.net> Michael Langford wrote: > First off: > What you want is a set, not a list. Lucky for you, a python dict uses > a set for its keys, so cheat and use that. Python has had a set type in the stdlib since 2.3 and built-in since 2.4 so there is no need to cheat any more. > change: > for j in input: > print j, > > to > mySet={} > for j in input: > mySet[j]=j mySet = set() for j in input: mySet.add(j) or just mySet = set(input) > for item in mySet.keys(): > print item for item in mySet: print item (actually the above works for dict or set, iterating a dict gives its keys) Kent From brunson at brunson.com Fri Sep 14 18:44:12 2007 From: brunson at brunson.com (Eric Brunson) Date: Fri, 14 Sep 2007 10:44:12 -0600 Subject: [Tutor] Class Inheritance In-Reply-To: <eb79828c0709132118t20890a30u5c23120909dc13d3@mail.gmail.com> References: <eb79828c0709131303x57ee8591r308473a24f27c672@mail.gmail.com> <46E9AC72.1030308@brunson.com> <eb79828c0709132118t20890a30u5c23120909dc13d3@mail.gmail.com> Message-ID: <46EABA5C.2040900@brunson.com> You're still using the wrong terminology... A "subclass" is "derived" (or "subclassed") from its "parent class" (or "super" class) A function that is part of the class definition (def func1(self): pass) is a "method" A variable that is part of the class definition or added after instantiation is an "attribute" When you create an object (a = A()) you are "instantiating" the class and the resultant object is an "instance" Lamonte Harris wrote: > So ok, when I inherit a class, all the classes methods. Classes have methods (functions) and attributes (variables). > in the parent class will overwrite override. > all the functions methods. > in the class I inherited the parent class into? No, exactly the opposite. > If they have the same class names that is? # declare a class class A(object): this = "is a class attribute" def method1(self): self.thisthing = "is an attribute" print "class A: method1" def method2(self): print "class A: method2" # subclass it class B(A): def method2(self): print "class B: method2" def method3(self): print "class B: method3" # create an "instance" of each class a = A() b = B() a.method1() OUTPUT> classA: method1 a.method2() OUTPUT> classA: method2 b.method1() OUTPUT> classA: method1 b.method2() OUTPUT> classB: method2 super(B,b).method2() OUTPUT> classA: method2 # super() only works because B is a subclass of "object" by virtue or A being derived from "object" b.method3() OUTPUT> classB: method3 a.method3() Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: A instance has no attribute 'method3' When you derive a subclass from another class all methods of the parent class are available Is that clear? > > On 9/13/07, *Eric Brunson* <brunson at brunson.com > <mailto:brunson at brunson.com>> wrote: > > Lamonte Harris wrote: > > Okay > > > > class A: > > def __init__(self,x,y): > > self.x = x > > self.y = y > > > > def save(self,fn): > > f = open(fn,"w") > > f.write(str(self.x)+ '\n') > > # convert to a string and add newline > > f.write(str(self.y)+'\n') > > return f # for child objects to use > > > > def restore(self, fn): > > f = open(fn) > > > > self.x = int(f.readline()) # convert back to original type > > self.y = int(f.readline()) > > return f > > > > class B(A): > > def __init__(self,x,y,z): > > A.__init__(self,x,y) > > > > self.z = z > > > > def save(self,fn): > > f = A.save(self,fn) # call parent save > > f.write(str(self.z)+'\n') > > return f # in case further children exist > > > > > > def restore(self, fn): > > f = A.restore(self,fn) > > self.z = int(f.readline()) > > return f > > In the class B, I'm not understanding the A.__init(self,x,y) part. > > So its initializing the class A, and basically you can use the A > class > > like normal? > > Essentially, yes, but the way you've worded it is imprecise. Any > instance of B is a subclass of A, essentially an A: Every boy is a > male, but not all males are boys. When you override a method in a > subclass you have essentially turned off all behavior in the parent > method, including "magic" methods like the constructor. You have to > call the parent constructor explicitly to get its benefits. > > A method of an instance can be called like > this: instance.method() and > python makes sure that a pointer to the instance is passed in as the > first argument, generally "self". But a method of a class can be > called > without instantiating the class, but you have to supply "self" on > you own. > > The method you are using is valid, yet depricated. Using "new style > classes" (which aren't actually that new) you'd write your code > like this: > > class A(object): > def __init__(self, a): > self.aye = a > > class B(A): > def __init__(self, a, b): > self.bee = b > super( B, self ).__init__( a ) > > Notice that you don't have to supply self. > > You can use any method of A in an instance of B that you haven't > overridden in B without having to use super(). > > > Part im confused about is the self.z, does that belong to the > class A > > or class B? > > z is an attribute B only. > > Hope that helps, > e. > > > Else I think I'm understanding it correctly. > > > ------------------------------------------------------------------------ > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org <mailto:Tutor at python.org> > > http://mail.python.org/mailman/listinfo/tutor > > > > From nephish at gmail.com Fri Sep 14 19:14:40 2007 From: nephish at gmail.com (shawn bright) Date: Fri, 14 Sep 2007 12:14:40 -0500 Subject: [Tutor] how to add arguments to a command line program Message-ID: <384c93600709141014v5850322n7b816b3d060d7c57@mail.gmail.com> lo there all, i want to write a program that will be called from another program. I need to pass it one variable. i suppose i could also do this with a module, and create a new instance of whatever i want to pass it to, but all the same, how would i go about this. like if i had a program that i wanted to pass a number into. i am sure i do it with sys args, but don't know how. like python run_my_script.py somevar does this make sense ? The other way to do this is create a class i suppose that could be called. Should probably do it that way, but still, i would like to know. thanks. shawn -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070914/4d65eb69/attachment.htm From tktucker at gmail.com Fri Sep 14 19:26:59 2007 From: tktucker at gmail.com (Tom Tucker) Date: Fri, 14 Sep 2007 13:26:59 -0400 Subject: [Tutor] how to add arguments to a command line program In-Reply-To: <384c93600709141014v5850322n7b816b3d060d7c57@mail.gmail.com> References: <384c93600709141014v5850322n7b816b3d060d7c57@mail.gmail.com> Message-ID: <2a278ffe0709141026p12ea2736re3c43b60fed14dc2@mail.gmail.com> See optparse <http://docs.python.org/lib/module-optparse.html> or sys.argv.<http://effbot.org/librarybook/sys.htm> On 9/14/07, shawn bright <nephish at gmail.com> wrote: > > lo there all, > > i want to write a program that will be called from another program. > I need to pass it one variable. > i suppose i could also do this with a module, and create a new instance of > whatever i want to pass it to, > but all the same, how would i go about this. like if i had a program that > i wanted to pass a number into. > > i am sure i do it with sys args, but don't know how. > > like > > python run_my_script.py somevar > > does this make sense ? > > The other way to do this is create a class i suppose that could be called. > Should probably do it that way, but still, i would like to know. > > thanks. > > shawn > > _______________________________________________ > 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/20070914/241116f4/attachment.htm From rgh2 at duke.edu Fri Sep 14 20:02:37 2007 From: rgh2 at duke.edu (rgh2 at duke.edu) Date: Fri, 14 Sep 2007 14:02:37 -0400 Subject: [Tutor] Problem with assigning list elements Message-ID: <20070914140237.ohbyrot3kg8gksgc@webmail.duke.edu> I'm having a problem assigning numbers to a 2-D list. for the 2d list z for example, when I type in z[0][0]=67 every zeroth element of every sublist will be set to 67, instead of just element [0,0] being set to 67. If z = [[1,2],[3,4]] then z[0][0]=100 results in z= [[100,2],[100,4]] Is this normal for python? And is there a way to assign to a specific element of a 2-dimensional list? Thanks From kent37 at tds.net Fri Sep 14 20:14:28 2007 From: kent37 at tds.net (Kent Johnson) Date: Fri, 14 Sep 2007 14:14:28 -0400 Subject: [Tutor] Problem with assigning list elements In-Reply-To: <20070914140237.ohbyrot3kg8gksgc@webmail.duke.edu> References: <20070914140237.ohbyrot3kg8gksgc@webmail.duke.edu> Message-ID: <46EACF84.6040404@tds.net> rgh2 at duke.edu wrote: > I'm having a problem assigning numbers to a 2-D list. > > for the 2d list z for example, when I type in > > z[0][0]=67 > > every zeroth element of every sublist will be set to 67, instead of just element > [0,0] being set to 67. http://effbot.org/pyfaq/how-do-i-create-a-multidimensional-list.htm Kent From bgailer at alum.rpi.edu Fri Sep 14 20:29:51 2007 From: bgailer at alum.rpi.edu (bob gailer) Date: Fri, 14 Sep 2007 14:29:51 -0400 Subject: [Tutor] Problem with assigning list elements In-Reply-To: <20070914140237.ohbyrot3kg8gksgc@webmail.duke.edu> References: <20070914140237.ohbyrot3kg8gksgc@webmail.duke.edu> Message-ID: <46EAD31F.308@alum.rpi.edu> rgh2 at duke.edu wrote: > I'm having a problem assigning numbers to a 2-D list. > > for the 2d list z for example, when I type in > > z[0][0]=67 > > every zeroth element of every sublist will be set to 67, instead of just element > [0,0] being set to 67. > > If z = [[1,2],[3,4]] > > then z[0][0]=100 results in > > z= [[100,2],[100,4]] > When I run that I see: >>> z = [[1,2],[3,4]] >>> z[0][0]=100 >>> z [[100, 2], [3, 4]] Which is what I'd expect. > Is this normal for python? And is there a way to assign to a specific element of > a 2-dimensional list? > > Thanks > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From alan.gauld at btinternet.com Fri Sep 14 20:42:42 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 14 Sep 2007 19:42:42 +0100 Subject: [Tutor] how to add arguments to a command line program References: <384c93600709141014v5850322n7b816b3d060d7c57@mail.gmail.com> Message-ID: <fceknp$h7i$1@sea.gmane.org> "shawn bright" <nephish at gmail.com> wrote > i am sure i do it with sys args, but don't know how. > > like > > python run_my_script.py somevar > > does this make sense ? > Check my Talking to the User topic in my tutorial. The second half talks about using command line arguments. -- 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 Sep 14 20:46:42 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 14 Sep 2007 19:46:42 +0100 Subject: [Tutor] deleting one line in multiple files References: <319064.47122.qm@web32406.mail.mud.yahoo.com><ea979d70709140438v7c6972c4k6265a2764625aca2@mail.gmail.com> <ea979d70709140440q62416e6dyf02b39daffa40b77@mail.gmail.com> Message-ID: <fcekv9$i7p$1@sea.gmane.org> "bhaaluu" <bhaaluu at gmail.com> wrote > I'm also looking into 'sed' for doing this. I've used 'sed' in the > past for > deleting a specific line from files, as well as doing simple search > and > replace in a file. I just figured that if it can be done in 'sed,' > it > can be done in Python much easier and maybe even more elegantly Probably not because this is exactly the kind of task sed was designed for. And using the right tool fotr the job is usually more elegant and efficient than using a general purpose configured for the job... If the editing was more complex and involved multiple files (copying from file a to file b etc) then sed begins to creak and Python becomes much better suited. Alan G. From brunson at brunson.com Fri Sep 14 21:08:13 2007 From: brunson at brunson.com (Eric Brunson) Date: Fri, 14 Sep 2007 13:08:13 -0600 Subject: [Tutor] Problem with assigning list elements In-Reply-To: <20070914140237.ohbyrot3kg8gksgc@webmail.duke.edu> References: <20070914140237.ohbyrot3kg8gksgc@webmail.duke.edu> Message-ID: <46EADC1D.9020301@brunson.com> That is not the expected behavior and not the behavior I see: Python 2.5.1 (r251:54863, May 1 2007, 13:27:01) [C] on sunos5 >>> z = [[1,2],[3,4]] >>> z[0][0]=100 >>> print z [[100, 2], [3, 4]] rgh2 at duke.edu wrote: > I'm having a problem assigning numbers to a 2-D list. > > for the 2d list z for example, when I type in > > z[0][0]=67 > > every zeroth element of every sublist will be set to 67, instead of just element > [0,0] being set to 67. > > If z = [[1,2],[3,4]] > > then z[0][0]=100 results in > > z= [[100,2],[100,4]] > > Is this normal for python? And is there a way to assign to a specific element of > a 2-dimensional list? > > Thanks > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From nephish at gmail.com Fri Sep 14 21:59:18 2007 From: nephish at gmail.com (shawn bright) Date: Fri, 14 Sep 2007 14:59:18 -0500 Subject: [Tutor] how to add arguments to a command line program In-Reply-To: <fceknp$h7i$1@sea.gmane.org> References: <384c93600709141014v5850322n7b816b3d060d7c57@mail.gmail.com> <fceknp$h7i$1@sea.gmane.org> Message-ID: <384c93600709141259y5450e4f0i1cf5c015ac87a1e6@mail.gmail.com> Just what i was looking for, thanks shawn On 9/14/07, Alan Gauld <alan.gauld at btinternet.com> wrote: > > > "shawn bright" <nephish at gmail.com> wrote > > > i am sure i do it with sys args, but don't know how. > > > > like > > > > python run_my_script.py somevar > > > > does this make sense ? > > > > Check my Talking to the User topic in my tutorial. > The second half talks about using command line arguments. > > > -- > 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/20070914/dac373db/attachment.htm From pyth0nc0d3r at gmail.com Fri Sep 14 22:12:44 2007 From: pyth0nc0d3r at gmail.com (Lamonte Harris) Date: Fri, 14 Sep 2007 15:12:44 -0500 Subject: [Tutor] Just bought Python in a Nutshell In-Reply-To: <1189784843.896396.108960@g4g2000hsf.googlegroups.com> References: <eb79828c0709132112o5a3e7137n5ae5cd55e3e0b839@mail.gmail.com> <mailman.520.1189748935.2658.python-list@python.org> <1189784843.896396.108960@g4g2000hsf.googlegroups.com> Message-ID: <eb79828c0709141312v588ef074w25c2200c37951098@mail.gmail.com> Right, I like reading books it comes handier then reading ebooks, less programs and its right there in your hands. Main reason I'm going to use it for is to find questions without asking them on the python list or tutor list for a quicker referrence. On 9/14/07, DouhetSukd at gmail.com <DouhetSukd at gmail.com> wrote: > > I respectfully disagree with Shawn, in this case. > > Don't skim Nutshell, unless you know very little Python, and even then > it is really the wrong book. It is rather dry reading and provides > very little of the usual user-friendly introductions to language > features by solving simple problems. > > Doesn't sound like that much of an endorsement, does it? Well, in > fact, it is pretty much my most used Python book (out of 7 or 8 > others). > > If you read Alex's posts in this newsgroup, you'll see that he is one > of the most pragmatic and rigorous posters who usually contributes > code that elegantly and simply solves the issue at hand with the > minimum amount of clutter. > > What Python in a Nutshell is really good at is showing you exactly > what Python is capable of doing, feature by feature, in a thoroughly > Pythonic way for the feature. With code and exact implication. For > example, I know Python well but I am kinda lacking in metaclass > comprehension. If I were to write some non-trivial metaclasses I > would surely have his 3 or 4 pages open on my desk as I write code and > skim through other internet postings. Those 3-4 pages have kinda made > my brain shrivel every time I've looked at them, but they are the > clearest overview I've seen of what is probably one of the hardest > Python features to understand. > > For normal, easy-to-understand Python, Nutshell really dissects the > languages with new insight. The information is dense, because each > word has its place and there very little filler. That's why skimming > it does not work for me, I just don't have the requisite sustained > attention span. > > So, although I read almost all other computer books like Shawn does, I > don't think it applies in this particular case. When you have a > particular aspect of Python in mind, use Nutshell. Read up on 'look > before you leap' in it if you really want a sample of how it is > written. > > Cheers > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070914/dd8748d0/attachment-0001.htm From carroll at tjc.com Fri Sep 14 23:10:38 2007 From: carroll at tjc.com (Terry Carroll) Date: Fri, 14 Sep 2007 14:10:38 -0700 (PDT) Subject: [Tutor] evaluating AND In-Reply-To: <d9e88eaf0709132134s77714e82x864fa67cd6b95212@mail.gmail.com> Message-ID: <Pine.LNX.4.44.0709141406510.11367-100000@violet.rahul.net> On Fri, 14 Sep 2007, Rikard Bosnjakovic wrote: > For me, "if x" would be enough. If you think it's a bad thing when x > is of the wrong data, then you really should check that it contains > *correct* data as well. That's an okay approach, but, but it's also non-Pythoninc; more of the look-before-you-leap approach rather than ask-forgiveness-not-permission. > Using the the two function of yours, setting x to an integer: > > >>> x = 2 > >>> print test01(x) > Traceback (most recent call last): > File "<stdin>", line 1, in ? > File "/usr/tmp/python-3716vZq", line 3, in test01 > TypeError: unsubscriptable object > >>> print test02(x) > Traceback (most recent call last): > File "<stdin>", line 1, in ? > File "/usr/tmp/python-3716vZq", line 8, in test02 > TypeError: unsubscriptable object which is exactly what I would want it to do: raise an exception on bad data. > Rewriting your test01-function into this: > > def test01(x): > if (type(x) == type((0,)) and > (x is not None) and > (length(x) == 2)): > if x[0]>0: > return x[1]/x[0] > > and testing again: > > >>> x = 2 > >>> print test01(x) > None This silently produces an incorrect result, which is a Bad Thing; and it took a lot more code to do it, too. From paulcoones at comcast.net Fri Sep 14 23:25:27 2007 From: paulcoones at comcast.net (Paul Coones) Date: Fri, 14 Sep 2007 14:25:27 -0700 Subject: [Tutor] How do I add uvs to each vert line if a texture/bump map is used? Message-ID: <6ae5a0d50676e0e0b077f1b0a25a8649@comcast.net> C3DModel 4 2 0,50 Cube 1 1 8,1,12,0 v1 1.000000,0.5000000,0.5000000,0,1,NULL.TIF "null.bump.tif" -7.028856,3.349522,4.785803,0.333323,0.666646, -0.666646,0.000000,0.000000 -7.028856,1.349522,4.785803,0.816492,-0.408246, -0.408246,0.000000,0.000000 -9.028855,1.349522,4.785803,-0.577349,-0.577349, -0.577349,0.000000,0.000000 -9.028855,3.349522,4.785803,-0.577349,0.577349, -0.577349,0.000000,0.000000 -7.028855,3.349521,6.785803,0.666646,0.333323,0.666646,0.000000,0.000000 -7.028856,1.349521,6.785803,0.408246, -0.816492,0.408246,0.000000,0.000000 -9.028855,1.349522,6.785803,-0.408246, -0.408246,0.816492,0.000000,0.000000 -9.028855,3.349522,6.785803, -0.666646,0.666646,0.333323,0.000000,0.000000 4, 0, 7 0, 3, 7 2, 6, 7 2, 7, 3 1, 5, 2 5, 6, 2 0, 4, 1 4, 5, 1 4, 7, 6 4, 6, 5 0, 1, 2 0, 2, 3 Plane 1 1 4,1,2,0 v1 1.000000,0.5000000,0.5000000,0,1,NULL.TIF "null.bump.tif" 0.991230,-2.242427,0.000000,0.000000,0.000000,1.000000,0.000000,0.000000 0.991230,-4.242427,0.000000,0.000000,0.000000,1.000000,0.000000,0.000000 -1.008770, -4.242427,0.000000,0.000000,0.000000,1.000000,0.000000,0.000000 -1.008770, -2.242426,0.000000,0.000000,0.000000,1.000000,0.000000,0.000000 0, 3, 2 0, 2, 1 NOTE: each vert line contains x,y,z,nx,ny,nz,u,v Location of smf_export.py file on savefile: http://www.savefile.com/files/1054095 Thanks, Paul ( upretirementman ) From washakie at gmail.com Sat Sep 15 00:24:51 2007 From: washakie at gmail.com (John) Date: Fri, 14 Sep 2007 15:24:51 -0700 Subject: [Tutor] summing arrays, along a dimension Message-ID: <aaf235960709141524m62d9c3f9mdff7d6a86c28e123@mail.gmail.com> >>> d array([[0, 0, 1], [1, 2, 3], [2, 2, 4], [3, 6, 8]]) >>> e=reshape((d[:,-2]+d[:,-1]),(4,1)) >>> e array([[ 1], [ 5], [ 6], [14]]) is there a better way to accomplish this? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070914/8fbe1f73/attachment.htm From ricaraoz at gmail.com Fri Sep 14 17:24:07 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Fri, 14 Sep 2007 12:24:07 -0300 Subject: [Tutor] evaluating AND In-Reply-To: <000e01c7f64f$1406aea0$bd32000a@issphoenix> References: <000e01c7f64f$1406aea0$bd32000a@issphoenix> Message-ID: <46EAA797.8020308@bigfoot.com> Orest Kozyar wrote: > Given a variable x that can either be None or a tuple of two floats [i.e. > (0.32, 4.2)], which syntax is considered most appropriate under Python > coding standards? > > if x and x[0] > 0: > pass > > =====OR===== > > if x: > if x[0] > 0: > pass > > > In the first, I'm obviously making the assumption that if the first > condition evaluates to false, then the second condition won't be evaluated. > But, is this a good/valid assumption to make? Is there a more appropriate > design pattern in Python? > > Thanks! > Orest > What about exceptions ? try : if x[0] > 0: pass # process the item except : pass # or do whatever you want if there's no item From pyth0nc0d3r at gmail.com Fri Sep 14 23:59:50 2007 From: pyth0nc0d3r at gmail.com (Lamonte Harris) Date: Fri, 14 Sep 2007 16:59:50 -0500 Subject: [Tutor] Just bought Python in a Nutshell In-Reply-To: <eb79828c0709141432t582ddccbsda4750a4011666a9@mail.gmail.com> References: <eb79828c0709132112o5a3e7137n5ae5cd55e3e0b839@mail.gmail.com> <mailman.520.1189748935.2658.python-list@python.org> <1189784843.896396.108960@g4g2000hsf.googlegroups.com> <eb79828c0709141312v588ef074w25c2200c37951098@mail.gmail.com> <59f9c5160709141412q1098a4cbi989b6eed2f2cc899@mail.gmail.com> <eb79828c0709141432t582ddccbsda4750a4011666a9@mail.gmail.com> Message-ID: <eb79828c0709141459y264bc21fg4fcd17a4217cad65@mail.gmail.com> Wow I just got it, and its nice doesn't even look used god damn. :D. On 9/14/07, Lamonte Harris <pyth0nc0d3r at gmail.com> wrote: > > Lol, you bought it, dude theres not one left imho. When I bought it, it > still said 1 More left Lol...mines should be her no less then a hour -.-... > Taking SO LONG. > > On 9/14/07, Danyelle Gragsone <ladynikon at gmail.com> wrote: > > > > Luckily that site still had one left .. so i brought it :D. I can > > always use another good and CHEAP book. > > > > Danyelle > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070914/76322e49/attachment.htm From ricaraoz at gmail.com Sat Sep 15 01:06:49 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Fri, 14 Sep 2007 20:06:49 -0300 Subject: [Tutor] summing arrays, along a dimension In-Reply-To: <aaf235960709141524m62d9c3f9mdff7d6a86c28e123@mail.gmail.com> References: <aaf235960709141524m62d9c3f9mdff7d6a86c28e123@mail.gmail.com> Message-ID: <46EB1409.3060302@bigfoot.com> John wrote: >>>> d > array([[0, 0, 1], > [1, 2, 3], > [2, 2, 4], > [3, 6, 8]]) >>>> e=reshape((d[:,-2]+d[:,-1]),(4,1)) >>>> e > array([[ 1], > [ 5], > [ 6], > [14]]) > > is there a better way to accomplish this? > >>> d [[0, 0, 1], [1, 2, 3], [2, 2, 4], [3, 6, 8]] >>> e = [sum(i) for i in d] >>> e [1, 6, 8, 17] >>> f = [sum([L[i] for L in d]) for i in xrange(len(d[0]))] >>> f [6, 10, 16] From carroll at tjc.com Sat Sep 15 01:09:11 2007 From: carroll at tjc.com (Terry Carroll) Date: Fri, 14 Sep 2007 16:09:11 -0700 (PDT) Subject: [Tutor] Just bought Python in a Nutshell In-Reply-To: <eb79828c0709132112o5a3e7137n5ae5cd55e3e0b839@mail.gmail.com> Message-ID: <Pine.LNX.4.44.0709141558550.11367-100000@violet.rahul.net> On Thu, 13 Sep 2007, Lamonte Harris wrote: > http://www.powells.com/biblio/63-9780596001889-7 Used, has anyone read this > book. Any additional information that you like,dislike about this book? I love it, and use it more than any other Python book. Much as I hate to be the bearer of bad news here, though, the URL you give above is for the first edition, published four years ago. Alex put out a second edition just last year. The edition you bought covers through Python 2.2 or 2.3. The current edition covers through 2.5. That being said... it's still very useful, and while I've thought about buying a second edition, I still find the first edition to be extremely useful. I'd suggest reviewing the Python release notes for 2.4 and 2.5 to see what's changed since then. I've bought a *lot* of slightly-out-of-date computer books used and cheap, and you can still learn an awful lot from them. > [I like having real books and stead of ebooks because its better on the > eyes.] I'm with you. I like to do my reading laying on my bed before going to sleep; and even when using a book as a reference while coding, I like to look from my editor and leaf back and forth in the book; much more effective, to me, than screen swapping. From carroll at tjc.com Sat Sep 15 01:16:07 2007 From: carroll at tjc.com (Terry Carroll) Date: Fri, 14 Sep 2007 16:16:07 -0700 (PDT) Subject: [Tutor] remove blank list items In-Reply-To: <82b4f5810709140711ka53f9bfr43cee17ea44e419c@mail.gmail.com> Message-ID: <Pine.LNX.4.44.0709141613430.11367-100000@violet.rahul.net> On Fri, 14 Sep 2007, Michael Langford wrote: > What you want is a set, not a list. Lucky for you, a python dict uses a > set for its keys, so cheat and use that. Is that true? >>> d={1:"a", 2:"b"} >>> k=d.keys() >>> type(k) <type 'list'> From alan.gauld at btinternet.com Sat Sep 15 01:34:02 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 15 Sep 2007 00:34:02 +0100 Subject: [Tutor] summing arrays, along a dimension References: <aaf235960709141524m62d9c3f9mdff7d6a86c28e123@mail.gmail.com> Message-ID: <fcf5q2$3v9$1@sea.gmane.org> "John" <washakie at gmail.com> wrote >>>> d > array([[0, 0, 1], > [1, 2, 3], > [2, 2, 4], > [3, 6, 8]]) >>>> e=reshape((d[:,-2]+d[:,-1]),(4,1)) >>>> e > array([[ 1], > [ 5], > [ 6], > [14]]) > > is there a better way to accomplish this? Better? Maybe. More readable I think is: e1 = [ [row[-2]+row[-1]] for row in d ] You can convert the 2D list to an array object if you want later Alan G. From pyth0nc0d3r at gmail.com Sat Sep 15 01:50:33 2007 From: pyth0nc0d3r at gmail.com (Lamonte Harris) Date: Fri, 14 Sep 2007 18:50:33 -0500 Subject: [Tutor] Is there some sort of Python Error log. Message-ID: <eb79828c0709141650r238b6699x6a3a3dedd3d3c157@mail.gmail.com> Command prompt is a pain and it would be pretty nice to have this feature. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070914/eb312e98/attachment.htm From paulcoones at comcast.net Sat Sep 15 01:51:13 2007 From: paulcoones at comcast.net (Paul Coones) Date: Fri, 14 Sep 2007 16:51:13 -0700 Subject: [Tutor] writing the correct map names Message-ID: <f62cf98d86aba6a0f09ab01cd110abeb@comcast.net> # Test for maps #if faceUV = 0: texture_map = "NULL.TIF" if me.hasVertexUV(): print "must be a texture map!" texture_map = current_obj.name texture_map = texture_map + ".TIF" smf_file.write(str(texture_map + '\n')) #if not map: bump_map = '"null.bump.tif"' if me.hasVertexUV(): print"must be a bump map!" bump_map = current_obj.name bump_map = bump_map + "_bump.TIF" smf_file.write(str(bump_map + '\n')) 1.000000,0.5000000,0.5000000,0,1,NULL.TIF "null.bump.tif" -7.028856,3.349522,4.785803,0.333323,0.666646, -0.666646,0.000000,0.000000 When I do have a mapped object, the script is not putting in the map name nor the bump map name. What am I missing? The python script is for the 3D graphics program Blender, which is free. -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: text/enriched Size: 978 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20070914/9158138c/attachment-0001.bin From ladynikon at gmail.com Sat Sep 15 02:35:21 2007 From: ladynikon at gmail.com (Danyelle Gragsone) Date: Fri, 14 Sep 2007 20:35:21 -0400 Subject: [Tutor] vi and python Message-ID: <59f9c5160709141735t73b15dbdgde3a21b749ed131f@mail.gmail.com> Good Evening, I am running gentoo. I want to use vi to program in python. I wondered are there any other gentooovians out there who know if python support is already installed. Thanks, LadyNikon From bgailer at alum.rpi.edu Sat Sep 15 04:00:34 2007 From: bgailer at alum.rpi.edu (bob gailer) Date: Fri, 14 Sep 2007 22:00:34 -0400 Subject: [Tutor] summing arrays, along a dimension In-Reply-To: <aaf235960709141524m62d9c3f9mdff7d6a86c28e123@mail.gmail.com> References: <aaf235960709141524m62d9c3f9mdff7d6a86c28e123@mail.gmail.com> Message-ID: <46EB3CC2.9060903@alum.rpi.edu> John wrote: > >>> d > array([[0, 0, 1], > [1, 2, 3], > [2, 2, 4], > [3, 6, 8]]) > >>> e=reshape((d[:,-2]+d[:,-1]),(4,1)) > >>> e > array([[ 1], > [ 5], > [ 6], > [14]]) > > is there a better way to accomplish this? Which module are you using? In APL we'd write +/d to reduce along the rows using +. Does the array object have a similar "reduce" method? From bhaaluu at gmail.com Sat Sep 15 04:21:23 2007 From: bhaaluu at gmail.com (bhaaluu) Date: Fri, 14 Sep 2007 22:21:23 -0400 Subject: [Tutor] vi and python In-Reply-To: <59f9c5160709141735t73b15dbdgde3a21b749ed131f@mail.gmail.com> References: <59f9c5160709141735t73b15dbdgde3a21b749ed131f@mail.gmail.com> Message-ID: <ea979d70709141921v2ed69b9dhf09e73420843a51c@mail.gmail.com> Greetings, I use vim (vi improved): http://www.ibiblio.org/obp/pyBiblio/tips/elkner/vim4python.php -- bhaaluu at gmail dot com On 9/14/07, Danyelle Gragsone <ladynikon at gmail.com> wrote: > Good Evening, > > I am running gentoo. I want to use vi to program in python. I > wondered are there any other gentooovians out there who know if python > support is already installed. > > Thanks, > LadyNikon > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From ladynikon at gmail.com Sat Sep 15 04:24:39 2007 From: ladynikon at gmail.com (Danyelle Gragsone) Date: Sat, 15 Sep 2007 02:24:39 +0000 Subject: [Tutor] vi and python In-Reply-To: <ea979d70709141921v2ed69b9dhf09e73420843a51c@mail.gmail.com> References: <59f9c5160709141735t73b15dbdgde3a21b749ed131f@mail.gmail.com> <ea979d70709141921v2ed69b9dhf09e73420843a51c@mail.gmail.com> Message-ID: <59f9c5160709141924y64b9747ala170a775bc1b502b@mail.gmail.com> Hi Bhaaluu, Sorry for the misunderstanding. Since vim points to vi automatically I have gotten used to calling it vi. But I did mean vim. LadyNikon From davmillar at gmail.com Sat Sep 15 04:31:10 2007 From: davmillar at gmail.com (David Millar) Date: Fri, 14 Sep 2007 22:31:10 -0400 Subject: [Tutor] vi and python In-Reply-To: <59f9c5160709141924y64b9747ala170a775bc1b502b@mail.gmail.com> References: <59f9c5160709141735t73b15dbdgde3a21b749ed131f@mail.gmail.com> <ea979d70709141921v2ed69b9dhf09e73420843a51c@mail.gmail.com> <59f9c5160709141924y64b9747ala170a775bc1b502b@mail.gmail.com> Message-ID: <c070fc970709141931m79216da0qa222d7886850654f@mail.gmail.com> Hi Bhaaluu and LadyNikon, I'm not exactly sure what you mean by Python support, but since I do most of my coding in plain text editors anyway I have had no trouble using vi/vim to edit/code. It's extremely useful for when my laptop is on battery mode - I have a terminal profile setup to be mostly dark and fullscreen to conserve power. Best of luck! Dave M. On 9/14/07, Danyelle Gragsone <ladynikon at gmail.com> wrote: > > Hi Bhaaluu, > > Sorry for the misunderstanding. Since vim points to vi automatically > I have gotten used to calling it vi. But I did mean vim. > > LadyNikon > _______________________________________________ > 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/20070914/8fdaaf54/attachment.htm From wormwood_3 at yahoo.com Sat Sep 15 05:58:21 2007 From: wormwood_3 at yahoo.com (wormwood_3) Date: Fri, 14 Sep 2007 20:58:21 -0700 (PDT) Subject: [Tutor] vi and python Message-ID: <498195.8121.qm@web32405.mail.mud.yahoo.com> Hello, I go back and forth between SPE and VIM for Python myself. As for Python support in VIM, you can use most editions of VIM as a plain text editor, and it is fine for Python. But, if you install vim-python (http://ddtp.debian.net/ddt.cgi?desc_id=20183), you get some nice added features such as syntax highlighting, code completion, etc. Sort of like a basic IDE all in VIM! Not sure how you have vim installed. On Ubuntu for example, I just do "sudo apt-get install vim-full", and I get all the variants, including vim-python. Other handy things: * pydiction: http://www.vim.org/scripts/script.php?script_id=850 * python.vim: http://vim.sourceforge.net/scripts/script.php?script_id=30 Best of luck! -Sam ______________________________________ ----- Original Message ---- From: Danyelle Gragsone <ladynikon at gmail.com> To: python lista <python-list at python.org>; tutor at python.org Sent: Friday, September 14, 2007 8:35:21 PM Subject: [Tutor] vi and python Good Evening, I am running gentoo. I want to use vi to program in python. I wondered are there any other gentooovians out there who know if python support is already installed. Thanks, LadyNikon _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From rikard.bosnjakovic at gmail.com Sat Sep 15 06:07:31 2007 From: rikard.bosnjakovic at gmail.com (Rikard Bosnjakovic) Date: Sat, 15 Sep 2007 06:07:31 +0200 Subject: [Tutor] Is there some sort of Python Error log. In-Reply-To: <eb79828c0709141650r238b6699x6a3a3dedd3d3c157@mail.gmail.com> References: <eb79828c0709141650r238b6699x6a3a3dedd3d3c157@mail.gmail.com> Message-ID: <d9e88eaf0709142107p16a8b4d5le61bbb9406dc6e32@mail.gmail.com> On 15/09/2007, Lamonte Harris <pyth0nc0d3r at gmail.com> wrote: > Command prompt is a pain and it would be pretty nice to have this feature. If you are using a Unixish system, do "python myscript.py 2> error.log". -- - Rikard - http://bos.hack.org/cv/ From rabidpoobear at gmail.com Sat Sep 15 06:09:52 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Fri, 14 Sep 2007 23:09:52 -0500 Subject: [Tutor] [pygame] Re: Just bought Python in a Nutshell In-Reply-To: <eb79828c0709141459y264bc21fg4fcd17a4217cad65@mail.gmail.com> References: <eb79828c0709132112o5a3e7137n5ae5cd55e3e0b839@mail.gmail.com> <mailman.520.1189748935.2658.python-list@python.org> <1189784843.896396.108960@g4g2000hsf.googlegroups.com> <eb79828c0709141312v588ef074w25c2200c37951098@mail.gmail.com> <59f9c5160709141412q1098a4cbi989b6eed2f2cc899@mail.gmail.com> <eb79828c0709141432t582ddccbsda4750a4011666a9@mail.gmail.com> <eb79828c0709141459y264bc21fg4fcd17a4217cad65@mail.gmail.com> Message-ID: <46EB5B10.2020100@gmail.com> Lamonte Harris wrote: > Wow I just got it, and its nice doesn't even look used god damn. :D. It's generally considered rude to curse in technical forums such as this. Also, please use more punctuation. You're hard to understand sometimes. -Luke From rabidpoobear at gmail.com Sat Sep 15 06:14:19 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Fri, 14 Sep 2007 23:14:19 -0500 Subject: [Tutor] remove blank list items In-Reply-To: <Pine.LNX.4.44.0709141613430.11367-100000@violet.rahul.net> References: <Pine.LNX.4.44.0709141613430.11367-100000@violet.rahul.net> Message-ID: <46EB5C1B.5090207@gmail.com> Terry Carroll wrote: > On Fri, 14 Sep 2007, Michael Langford wrote: > > >> What you want is a set, not a list. Lucky for you, a python dict uses a >> set for its keys, so cheat and use that. >> > > Is that true? > > >>>> d={1:"a", 2:"b"} >>>> k=d.keys() >>>> type(k) >>>> > <type 'list'> > He worded it incorrectly since there is actually a 'set' type, but what he meant was that there wouldn't be multiples of each key that you add, so you would effectively eliminate multiples and thus have a set when you get a list of dict keys. -Luke From rabidpoobear at gmail.com Sat Sep 15 06:15:59 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Fri, 14 Sep 2007 23:15:59 -0500 Subject: [Tutor] Is there some sort of Python Error log. In-Reply-To: <eb79828c0709141650r238b6699x6a3a3dedd3d3c157@mail.gmail.com> References: <eb79828c0709141650r238b6699x6a3a3dedd3d3c157@mail.gmail.com> Message-ID: <46EB5C7F.2070901@gmail.com> Lamonte Harris wrote: > Command prompt is a pain and it would be pretty nice to have this feature. If you're on windows, try using an IDE for your code editing. Then the errors will show up in the interactive shell that the IDE runs, and you won't have to deal with starting a DOS command prompt to catch your errors. -Luke From ladynikon at gmail.com Sat Sep 15 00:33:47 2007 From: ladynikon at gmail.com (Danyelle Gragsone) Date: Fri, 14 Sep 2007 18:33:47 -0400 Subject: [Tutor] Just bought Python in a Nutshell In-Reply-To: <eb79828c0709141459y264bc21fg4fcd17a4217cad65@mail.gmail.com> References: <eb79828c0709132112o5a3e7137n5ae5cd55e3e0b839@mail.gmail.com> <mailman.520.1189748935.2658.python-list@python.org> <1189784843.896396.108960@g4g2000hsf.googlegroups.com> <eb79828c0709141312v588ef074w25c2200c37951098@mail.gmail.com> <59f9c5160709141412q1098a4cbi989b6eed2f2cc899@mail.gmail.com> <eb79828c0709141432t582ddccbsda4750a4011666a9@mail.gmail.com> <eb79828c0709141459y264bc21fg4fcd17a4217cad65@mail.gmail.com> Message-ID: <59f9c5160709141533u7a61df4en54559ed7415bd62d@mail.gmail.com> awesome! I should see it in about 2 wks.. im poor. So I choose super snail mail. LN From ladynikon at gmail.com Fri Sep 14 23:12:12 2007 From: ladynikon at gmail.com (Danyelle Gragsone) Date: Fri, 14 Sep 2007 17:12:12 -0400 Subject: [Tutor] Just bought Python in a Nutshell In-Reply-To: <eb79828c0709141312v588ef074w25c2200c37951098@mail.gmail.com> References: <eb79828c0709132112o5a3e7137n5ae5cd55e3e0b839@mail.gmail.com> <mailman.520.1189748935.2658.python-list@python.org> <1189784843.896396.108960@g4g2000hsf.googlegroups.com> <eb79828c0709141312v588ef074w25c2200c37951098@mail.gmail.com> Message-ID: <59f9c5160709141412q1098a4cbi989b6eed2f2cc899@mail.gmail.com> Luckily that site still had one left .. so i brought it :D. I can always use another good and CHEAP book. Danyelle From kent37 at tds.net Sat Sep 15 07:53:47 2007 From: kent37 at tds.net (Kent Johnson) Date: Sat, 15 Sep 2007 01:53:47 -0400 Subject: [Tutor] Is there some sort of Python Error log. In-Reply-To: <eb79828c0709141650r238b6699x6a3a3dedd3d3c157@mail.gmail.com> References: <eb79828c0709141650r238b6699x6a3a3dedd3d3c157@mail.gmail.com> Message-ID: <46EB736B.3050002@tds.net> Lamonte Harris wrote: > Command prompt is a pain and it would be pretty nice to have this feature. I'm not sure what "this feature" is but look at the logging module. Kent From kent37 at tds.net Sat Sep 15 07:55:44 2007 From: kent37 at tds.net (Kent Johnson) Date: Sat, 15 Sep 2007 01:55:44 -0400 Subject: [Tutor] How do I add uvs to each vert line if a texture/bump map is used? In-Reply-To: <6ae5a0d50676e0e0b077f1b0a25a8649@comcast.net> References: <6ae5a0d50676e0e0b077f1b0a25a8649@comcast.net> Message-ID: <46EB73E0.5000603@tds.net> Does this have something to do with Python? What are uvs? vert line? texture/bump map? Kent Paul Coones wrote: > C3DModel > 4 > 2 > 0,50 > Cube > 1 > 1 > 8,1,12,0 > v1 > 1.000000,0.5000000,0.5000000,0,1,NULL.TIF > "null.bump.tif" > -7.028856,3.349522,4.785803,0.333323,0.666646, > -0.666646,0.000000,0.000000 > -7.028856,1.349522,4.785803,0.816492,-0.408246, > -0.408246,0.000000,0.000000 > -9.028855,1.349522,4.785803,-0.577349,-0.577349, > -0.577349,0.000000,0.000000 > -9.028855,3.349522,4.785803,-0.577349,0.577349, > -0.577349,0.000000,0.000000 > -7.028855,3.349521,6.785803,0.666646,0.333323,0.666646,0.000000,0.000000 > -7.028856,1.349521,6.785803,0.408246, > -0.816492,0.408246,0.000000,0.000000 > -9.028855,1.349522,6.785803,-0.408246, > -0.408246,0.816492,0.000000,0.000000 > -9.028855,3.349522,6.785803, > -0.666646,0.666646,0.333323,0.000000,0.000000 > 4, 0, 7 > 0, 3, 7 > 2, 6, 7 > 2, 7, 3 > 1, 5, 2 > 5, 6, 2 > 0, 4, 1 > 4, 5, 1 > 4, 7, 6 > 4, 6, 5 > 0, 1, 2 > 0, 2, 3 > Plane > 1 > 1 > 4,1,2,0 > v1 > 1.000000,0.5000000,0.5000000,0,1,NULL.TIF > "null.bump.tif" > 0.991230,-2.242427,0.000000,0.000000,0.000000,1.000000,0.000000,0.000000 > 0.991230,-4.242427,0.000000,0.000000,0.000000,1.000000,0.000000,0.000000 > -1.008770, > -4.242427,0.000000,0.000000,0.000000,1.000000,0.000000,0.000000 > -1.008770, > -2.242426,0.000000,0.000000,0.000000,1.000000,0.000000,0.000000 > 0, 3, 2 > 0, 2, 1 > > NOTE: each vert line contains x,y,z,nx,ny,nz,u,v > Location of smf_export.py file on savefile: > http://www.savefile.com/files/1054095 > > Thanks, Paul ( upretirementman ) > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at btinternet.com Sat Sep 15 10:16:24 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 15 Sep 2007 09:16:24 +0100 Subject: [Tutor] vi and python References: <59f9c5160709141735t73b15dbdgde3a21b749ed131f@mail.gmail.com><ea979d70709141921v2ed69b9dhf09e73420843a51c@mail.gmail.com> <59f9c5160709141924y64b9747ala170a775bc1b502b@mail.gmail.com> Message-ID: <fcg4df$t1f$1@sea.gmane.org> "Danyelle Gragsone" <ladynikon at gmail.com> wrote > Sorry for the misunderstanding. Since vim points to vi > automatically > I have gotten used to calling it vi. But I did mean vim. Just to be picky, vi points to vim. vim is the program vi is an alias. So if you type vi it executes vim. But different *nix versions use different editors for vi. Some use elvis, some even use the original vi! If you ask about vi you will typically get a response that covers the common subset that is the original. But that only supports (in a very limited way) C and Lisp programming features. vim has several levels of support for Python. It has syntax highlighting for python but it can also be found with Python built in as the scripting language so you can write vim macros using Python. 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 Sep 15 10:20:21 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 15 Sep 2007 09:20:21 +0100 Subject: [Tutor] Is there some sort of Python Error log. References: <eb79828c0709141650r238b6699x6a3a3dedd3d3c157@mail.gmail.com> Message-ID: <fcg4ks$tj7$1@sea.gmane.org> "Lamonte Harris" <pyth0nc0d3r at gmail.com> wrote in message > Command prompt is a pain and it would be pretty nice to have this > feature. In what respect is command prompt a pain? Which command prompt(the OS or Python >>>)? If Python are you using the vanilla interpreter or an IDE? If anIDE which one? If you are not talking about interactive mode but about running scripts then what kind of logging do you have in mind? Can you describe how you think it would work? -- 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 Sep 15 10:27:03 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 15 Sep 2007 09:27:03 +0100 Subject: [Tutor] writing the correct map names References: <f62cf98d86aba6a0f09ab01cd110abeb@comcast.net> Message-ID: <fcg51e$uan$1@sea.gmane.org> "Paul Coones" <paulcoones at comcast.net> wrote > #if faceUV = 0: > > texture_map = "NULL.TIF" > > if me.hasVertexUV(): > print "must be a texture map!" > texture_map = current_obj.name > texture_map = texture_map + ".TIF" etc/... > When I do have a mapped object, the script is not putting in the map > name nor the bump map name. > What am I missing? The python script is for the 3D graphics program > Blender, which is free. Paul, This is a list for beginners to Python. Many are also beginners to programming. Don't assume that anyone else will know anything about Blender or texture maps orr anything else specific to your problem. (There may be a few members who will know, but you limit the audience dramatically by doing that) Instead either: 1) Explain the context in simple terms and what you want to do, preferably along with the simplest possible example you can find. 2) Try posting on a Blender list where there will be a much higher proportion of folks who understand what you are saying. or do both! :-) HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From mlangford.cs03 at gtalumni.org Sat Sep 15 17:16:09 2007 From: mlangford.cs03 at gtalumni.org (Michael Langford) Date: Sat, 15 Sep 2007 11:16:09 -0400 Subject: [Tutor] remove blank list items In-Reply-To: <46EB5C1B.5090207@gmail.com> References: <Pine.LNX.4.44.0709141613430.11367-100000@violet.rahul.net> <46EB5C1B.5090207@gmail.com> Message-ID: <82b4f5810709150816p63673399k411d0b7ecb171bde@mail.gmail.com> While the keys() method returns an object of type list, the keys of a dict (when you leave them in the dict) behave as a "set", as in the mathematical/computer science idea of a collection of objects where no two objects have the same value. (http://en.wikipedia.org/wiki/Set) The keys of the dictionary may or may not be implemented with a python object that has a class of "set". The keys() method definitely returns a list, and I'm sure it does this as that's much more useful than returning a set object. For your particular problem, I would use the real set object now that python implements one. But the "python dict keys are a set" concept is an important one nonetheless, as it goes to the understanding of a dictionary data type. One thing about python: its libraries are large and innumerable. Don't expect to know all parts of all of them. You can use it quite readily without knowing every api of every module or every keyword. --Michael -- Michael Langford Phone: 404-386-0495 Consulting: http://www.TierOneDesign.com/ Entertaining: http://www.ThisIsYourCruiseDirectorSpeaking.com On 9/15/07, Luke Paireepinart <rabidpoobear at gmail.com> wrote: > > Terry Carroll wrote: > > On Fri, 14 Sep 2007, Michael Langford wrote: > > > > > >> What you want is a set, not a list. Lucky for you, a python dict uses > a > >> set for its keys, so cheat and use that. > >> > > > > Is that true? > > > > > >>>> d={1:"a", 2:"b"} > >>>> k=d.keys() > >>>> type(k) > >>>> > > <type 'list'> > > > He worded it incorrectly since there is actually a 'set' type, but what > he meant was that there wouldn't be multiples of each key that you add, > so you would effectively eliminate multiples and thus have a set when > you get a list of dict keys. > -Luke > _______________________________________________ > 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/20070915/b2489aa8/attachment.htm From washakie at gmail.com Sat Sep 15 20:50:11 2007 From: washakie at gmail.com (John) Date: Sat, 15 Sep 2007 11:50:11 -0700 Subject: [Tutor] referencing vars() Message-ID: <aaf235960709151150p403f922eqfdce806580917ceb@mail.gmail.com> #Set up writer import csv vardict=vars() for var in vardict: if var=='allcum' or var=='alldhdt': outfile=in_path+'/'+dataset+'_'+str(var)+'.csv' writer = csv.writer(open(outfile, "wb")) writer.writerows(var) I'm trying to do the above, but of course get an error because vardict is only referencing vars(), thus changes size... also, I tried vardict=[vars()], but this fails as well?? Suggestions? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070915/beb7aadb/attachment.htm From mlangford.cs03 at gtalumni.org Sat Sep 15 21:54:40 2007 From: mlangford.cs03 at gtalumni.org (Michael Langford) Date: Sat, 15 Sep 2007 15:54:40 -0400 Subject: [Tutor] referencing vars() In-Reply-To: <aaf235960709151150p403f922eqfdce806580917ceb@mail.gmail.com> References: <aaf235960709151150p403f922eqfdce806580917ceb@mail.gmail.com> Message-ID: <82b4f5810709151254g77df6el734dffac79593da1@mail.gmail.com> Please show us the function vars(). I don't think we have enough info to help without it. On 9/15/07, John <washakie at gmail.com> wrote: > > #Set up writer > import csv > vardict=vars() > for var in vardict: > if var=='allcum' or var=='alldhdt': > outfile=in_path+'/'+dataset+'_'+str(var)+'.csv' > writer = csv.writer(open(outfile, "wb")) > writer.writerows(var) > > I'm trying to do the above, but of course get an error because vardict is > only referencing vars(), thus changes size... also, I tried > vardict=[vars()], but this fails as well?? > > Suggestions? > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Michael Langford Phone: 404-386-0495 Consulting: http://www.TierOneDesign.com/ Entertaining: http://www.ThisIsYourCruiseDirectorSpeaking.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070915/14561627/attachment.htm From alan.gauld at btinternet.com Sat Sep 15 22:03:14 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 15 Sep 2007 21:03:14 +0100 Subject: [Tutor] referencing vars() References: <aaf235960709151150p403f922eqfdce806580917ceb@mail.gmail.com> Message-ID: <fchdqq$aju$1@sea.gmane.org> "John" <washakie at gmail.com> wrote > import csv > vardict=vars() > for var in vardict: > if var=='allcum' or var=='alldhdt': > > outfile=in_path+'/'+dataset+'_'+str(var)+'.csv' > writer = csv.writer(open(outfile, "wb")) > writer.writerows(var) > > I'm trying to do the above, but of course get an error because > vardict is > only referencing vars(), thus changes size... also, I tried > vardict=[vars()], but this fails as well?? I'm not too sure what you are doing but on the last point: Try converting to a list: >>> vardict = list(vars()) >>> for var in vardict: print var ... pp shell __builtins__ __file__ __doc__ vardict filling notebook var __name__ os >>> HTH, Alan G. From wormwood_3 at yahoo.com Sat Sep 15 22:21:34 2007 From: wormwood_3 at yahoo.com (wormwood_3) Date: Sat, 15 Sep 2007 13:21:34 -0700 (PDT) Subject: [Tutor] Loop optimization Message-ID: <889191.52696.qm@web32413.mail.mud.yahoo.com> Kent, You replied with the following some time ago regarding a question I asked about optimizing a loop: >> 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. I realized when reviewing this that I do not know what the "NAME_" notation is about. I know that "_METHOD/ATTR" makes a method or attribute private to an instance, but what does the trailing underscore do? Thanks, Sam From kent37 at tds.net Sat Sep 15 22:30:05 2007 From: kent37 at tds.net (Kent Johnson) Date: Sat, 15 Sep 2007 16:30:05 -0400 Subject: [Tutor] referencing vars() In-Reply-To: <aaf235960709151150p403f922eqfdce806580917ceb@mail.gmail.com> References: <aaf235960709151150p403f922eqfdce806580917ceb@mail.gmail.com> Message-ID: <46EC40CD.5030901@tds.net> John wrote: > #Set up writer > import csv > vardict=vars() > for var in vardict: > if var=='allcum' or var=='alldhdt': > outfile=in_path+'/'+dataset+'_'+str(var)+'.csv' > writer = csv.writer(open(outfile, "wb")) > writer.writerows(var) > > I'm trying to do the above, but of course get an error because vardict > is only referencing vars(), thus changes size... also, I tried > vardict=[vars()], but this fails as well?? I'm not too clear what you are trying to do here. Do you want the values of the variables allcum and alldhdt? vars() gives you a dict whose keys are varible names and values are, well, the values. I think you are trying to write the contents of allcum to a file with allcum in the name? You could do it with vars like this: for var in ['allcum', 'alldhdt']: outfile=in_path+'/'+dataset+'_'+var+'.csv' writer = csv.writer(open(outfile, "wb")) writer.writerows(vars()[var]) or you could iterate a list of name, value tuples directly: for name, value in [('allcum', allcum), ('alldhdt', alldhdt)]: outfile=in_path+'/'+dataset+'_'+name+'.csv' writer = csv.writer(open(outfile, "wb")) writer.writerows(value) I think I prefer the second, even with the duplication of names; it feels more explicit to me. Another alternative would be to accumulate the values in a dict with keys 'allcum' and 'alldhdt'. Then you would look up in that dict instead of in vars(). HTH, Kent From kent37 at tds.net Sat Sep 15 22:32:05 2007 From: kent37 at tds.net (Kent Johnson) Date: Sat, 15 Sep 2007 16:32:05 -0400 Subject: [Tutor] Loop optimization In-Reply-To: <889191.52696.qm@web32413.mail.mud.yahoo.com> References: <889191.52696.qm@web32413.mail.mud.yahoo.com> Message-ID: <46EC4145.8040904@tds.net> wormwood_3 wrote: > Kent, > > You replied with the following some time ago regarding a question I asked about optimizing a loop: > >>> 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. > > > I realized when reviewing this that I do not know what the "NAME_" notation is about. I know that "_METHOD/ATTR" makes a method or attribute private to an instance, but what does the trailing underscore do? It's nothing special, just a name. The first line should be append_ = self.potdomains.append using the underscore just signals that this is an alias for the 'real' append method. You don't have to use it. Kent From kent37 at tds.net Sat Sep 15 22:46:53 2007 From: kent37 at tds.net (Kent Johnson) Date: Sat, 15 Sep 2007 16:46:53 -0400 Subject: [Tutor] remove blank list items In-Reply-To: <82b4f5810709150816p63673399k411d0b7ecb171bde@mail.gmail.com> References: <Pine.LNX.4.44.0709141613430.11367-100000@violet.rahul.net> <46EB5C1B.5090207@gmail.com> <82b4f5810709150816p63673399k411d0b7ecb171bde@mail.gmail.com> Message-ID: <46EC44BD.7030400@tds.net> Michael Langford wrote: > While the keys() method returns an object of type list, the keys of a > dict (when you leave them in the dict) behave as a "set", as in the > mathematical/computer science idea of a collection of objects where no > two objects have the same value. ( http://en.wikipedia.org/wiki/Set) Before Python had a real set type, dicts were commonly used as a substitute for a set. > The keys of the dictionary may or may not be implemented with a python > object that has a class of "set". They are not, they are implemented as part of the hashtable that is a dict. In fact set was originally implemented in Python as a wrapper around dict. When it proved to be useful it was re-implemented in C. The original implementation still survives in the set module. The keys() method definitely returns a > list, and I'm sure it does this as that's much more useful than > returning a set object. Actually the designers of Python believe that for the value of dict.keys() to have set-like behaviour is very useful. In Python 3 that is how it will be. http://www.python.org/dev/peps/pep-3106/ From alan.gauld at btinternet.com Sun Sep 16 00:55:18 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 15 Sep 2007 23:55:18 +0100 Subject: [Tutor] referencing vars() References: <aaf235960709151150p403f922eqfdce806580917ceb@mail.gmail.com> <82b4f5810709151254g77df6el734dffac79593da1@mail.gmail.com> Message-ID: <fchnte$72n$1@sea.gmane.org> "Michael Langford" <mlangford.cs03 at gtalumni.org> wrote > Please show us the function vars(). I don't think we have enough > info to > help without it. Its a builtin, it basically is similar to locals() as used here. Try help(vars) Alan G. From wormwood_3 at yahoo.com Sun Sep 16 07:36:54 2007 From: wormwood_3 at yahoo.com (wormwood_3) Date: Sat, 15 Sep 2007 22:36:54 -0700 (PDT) Subject: [Tutor] Adding a GUI Message-ID: <3207.2005.qm@web32408.mail.mud.yahoo.com> Hi all, I am just starting to learn GUI programming, with wxPython. I have a script that that I have developed to a useful point, and I want to add a GUI to it. I am a little unsure as the the best approach to this. The script heretofore was just run at the command line. Would it make sense to add an option in the same script to have it run in "graphical mode", which would trigger the wxPython code I would add in, and otherwise use the same logic? More generally: Anyone have any tips on adding a GUI to a pre-existing script in a way that minimizes repetition of logic? I would rather not make a separate script that only used wxPython, and I do not think I have to, but perhaps there are good reasons to, etc. Thanks, Sam From wormwood_3 at yahoo.com Sun Sep 16 08:27:59 2007 From: wormwood_3 at yahoo.com (wormwood_3) Date: Sat, 15 Sep 2007 23:27:59 -0700 (PDT) Subject: [Tutor] Adding a GUI Message-ID: <330238.52170.qm@web32415.mail.mud.yahoo.com> I don't think either, I was planning on sticking with wxPython for now, since it is cross-platform, looks way better than Tkinter, and seems to have all the flexibility I would want. But regardless of what toolkit I use, the question of how best to combine it with pre-existent logic still remains the same:-) -Sam ----- Original Message ---- From: Dotan Cohen <dotancohen at gmail.com> To: wormwood_3 <wormwood_3 at yahoo.com> Sent: Sunday, September 16, 2007 2:21:53 AM Subject: Re: [Tutor] Adding a GUI On 16/09/2007, wormwood_3 <wormwood_3 at yahoo.com> wrote: > Hi all, > > I am just starting to learn GUI programming, with wxPython. I have a script that that I have developed to a useful point, and I want to add a GUI to it. I am a little unsure as the the best approach to this. The script heretofore was just run at the command line. Would it make sense to add an option in the same script to have it run in "graphical mode", which would trigger the wxPython code I would add in, and otherwise use the same logic? > > More generally: Anyone have any tips on adding a GUI to a pre-existing script in a way that minimizes repetition of logic? I would rather not make a separate script that only used wxPython, and I do not think I have to, but perhaps there are good reasons to, etc. > > Thanks, > Sam > Are you interested in Qt or Tinker bindings? Qt are much nicer in Linux, but Tinker is cross-platform. Dotan Cohen http://what-is-what.com http://gibberish.co.il ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? From alan.gauld at btinternet.com Sun Sep 16 10:02:19 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 16 Sep 2007 09:02:19 +0100 Subject: [Tutor] Adding a GUI References: <3207.2005.qm@web32408.mail.mud.yahoo.com> Message-ID: <fcinv4$3ff$1@sea.gmane.org> "wormwood_3" <wormwood_3 at yahoo.com> wrote > I am just starting to learn GUI programming, with wxPython. Good choice. If you will be doing much in wxPython get the book. It makes the whole thing much easier. > The script heretofore was just run at the command line. > Would it make sense to add an option in the same script > to have it run in "graphical mode", You can do but personally I prefer to have two separate versions, one with a CLI and the other a GUI. They both share a common module which is the core functionality represented as functions/classes so that the UI (either of them) can call them as needed. To do that the first step is to identify the core functions and refactor them into a separate module (or modules). To do that you have to remove all UI operations - print/raw_input etc from the functions and make them completely parameterised. (ideally they should be stateless too) The strings and data you need to display will be returned by the functions. Once you have that done its easy to add a CLI a GUI and even a web interface. > Anyone have any tips on adding a GUI to a pre-existing > script in a way that minimizes repetition of logic? I go through the process in the case study in my tutorial. Just scan through to the section Adding a GUI. It uses Tkinter but the conepts are identical. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From daniel.chaowang at gmail.com Sun Sep 16 15:01:01 2007 From: daniel.chaowang at gmail.com (=?BIG5?B?pP22Vw==?=) Date: Sun, 16 Sep 2007 21:01:01 +0800 Subject: [Tutor] how to match regular expression from right to left Message-ID: <57fe16f60709160601se708b5fibd0abf976de40400@mail.gmail.com> hi, I want to match the regular expression from right to left, such as: TAG_pattern = re.compile(r"(us::.*) .*(1002|1003).*$") TAG_pattern.search(line) Does the search method support this? Thanks, Daniel -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070916/14b79cf2/attachment.htm From tktucker at gmail.com Sun Sep 16 15:32:37 2007 From: tktucker at gmail.com (Tom Tucker) Date: Sun, 16 Sep 2007 09:32:37 -0400 Subject: [Tutor] how to match regular expression from right to left In-Reply-To: <57fe16f60709160601se708b5fibd0abf976de40400@mail.gmail.com> References: <57fe16f60709160601se708b5fibd0abf976de40400@mail.gmail.com> Message-ID: <2a278ffe0709160632s53d9d1a4t3a4226b226d31073@mail.gmail.com> Yep, looks like it. >>> line = 'us::blah blah2 1002 blah3' >>> import re >>> TAG_pattern = re.compile(r"(us::.*) .*(1002|1003).*$") >>> if TAG_pattern.search(line): ... print 'we have a match' ... we have a match >>> >>> line2 ='us::blah blah2 1001 blah3' >>> if TAG_pattern.search(line2): ... print 'we have a match' ... else: ... print 'no match found' ... no match found On 9/16/07, $B2&D6(B <daniel.chaowang at gmail.com> wrote: > hi, > > I want to match the regular expression from right to left, such as: > > TAG_pattern = re.compile(r"(us::.*) .*(1002|1003).*$") > TAG_pattern.search(line) > > Does the search method support this? > > Thanks, > Daniel > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From daniel.chaowang at gmail.com Sun Sep 16 16:01:41 2007 From: daniel.chaowang at gmail.com (=?BIG5?B?pP22Vw==?=) Date: Sun, 16 Sep 2007 22:01:41 +0800 Subject: [Tutor] how to match regular expression from right to left In-Reply-To: <2a278ffe0709160632s53d9d1a4t3a4226b226d31073@mail.gmail.com> References: <57fe16f60709160601se708b5fibd0abf976de40400@mail.gmail.com> <2a278ffe0709160632s53d9d1a4t3a4226b226d31073@mail.gmail.com> Message-ID: <57fe16f60709160701y62713254ub1b634d0c5b67f24@mail.gmail.com> yes, but I mean if I have the line like this: line = """38166 us::Video_Cat::Other; us::Video_Cat::Today Show; us::VC_Supplier::bc; 1002::ms://bc.wd.net/a275/video/tdy_is.asf; 1003::ms://bc.wd.net/a275/video/tdy_is_.fl;""" I want to get the part "us::MSNVideo_Cat::Other; us::MSNVideo_Cat::Today Show; us::VC_Supplier::Msnbc;" but re.compile(r"(us::.*) .*(1002|1003).*$") will get the "1002::ms://bc.wd.net/a275/video/tdy_is.asf;" included in an lazy mode. How can i filter it out in the re? Thanks, Daniel On 9/16/07, Tom Tucker <tktucker at gmail.com> wrote: > > Yep, looks like it. > > >>> line = 'us::blah blah2 1002 blah3' > >>> import re > >>> TAG_pattern = re.compile(r"(us::.*) .*(1002|1003).*$") > >>> if TAG_pattern.search(line): > ... print 'we have a match' > ... > we have a match > >>> > > >>> line2 ='us::blah blah2 1001 blah3' > >>> if TAG_pattern.search(line2): > ... print 'we have a match' > ... else: > ... print 'no match found' > ... > no match found > > > > On 9/16/07, $B2&D6(B <daniel.chaowang at gmail.com> wrote: > > hi, > > > > I want to match the regular expression from right to left, such as: > > > > TAG_pattern = re.compile(r"(us::.*) .*(1002|1003).*$") > > TAG_pattern.search(line) > > > > Does the search method support this? > > > > Thanks, > > Daniel > > > > _______________________________________________ > > 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/20070916/83d55800/attachment.htm From kent37 at tds.net Sun Sep 16 16:01:54 2007 From: kent37 at tds.net (Kent Johnson) Date: Sun, 16 Sep 2007 10:01:54 -0400 Subject: [Tutor] how to match regular expression from right to left In-Reply-To: <57fe16f60709160601se708b5fibd0abf976de40400@mail.gmail.com> References: <57fe16f60709160601se708b5fibd0abf976de40400@mail.gmail.com> Message-ID: <46ED3752.8080607@tds.net> ?? wrote: > hi, > > I want to match the regular expression from right to left, such as: > > TAG_pattern = re.compile(r"(us::.*) .*(1002|1003).*$") > TAG_pattern.search(line) > > Does the search method support this? What do you mean match from right to left? If you mean, match an re that is anchored at the end of the string, then sure, $ is supported. If you mean, find the right-most match of several (similar to the rfind method of a string) then no, it is not directly supported. You could use re.findall() and chose the last match but if the matches can overlap this may not give the correct result. Kent From mlangford.cs03 at gtalumni.org Sun Sep 16 16:22:59 2007 From: mlangford.cs03 at gtalumni.org (Michael Langford) Date: Sun, 16 Sep 2007 10:22:59 -0400 Subject: [Tutor] Adding a GUI In-Reply-To: <3207.2005.qm@web32408.mail.mud.yahoo.com> References: <3207.2005.qm@web32408.mail.mud.yahoo.com> Message-ID: <82b4f5810709160722w70456855q923723f471c9c6ec@mail.gmail.com> Wormwood, an easier way to create a crossplatform GUI than raw wxPython is to use pythoncard, which is a library that is on top of wxPython that is there to make it easier to use and to make it easier to layout GUI screens/dialogs. I've found its a much faster "whiteboard to running software time" then wxPython by itself. (I've used both, raw wxPython a lot *more* than pythoncard, as i'd not yet heard of it). Alan is right about separating the core logic of the program from the input/output methods, and using that in both a command line and a gui program. I doubt you'll need a book to use pythoncard. Its about as easy as VB to build a form with the WYSIWYG, and very pythonic to use the forms you've built. To get up an going, install a compatible version of wxPython use this link: http://pythoncard.sourceforge.net/walkthrough1.html --Michael References: Pythoncard:http://pythoncard.sourceforge.net/ On 9/16/07, wormwood_3 <wormwood_3 at yahoo.com> wrote: > > Hi all, > > I am just starting to learn GUI programming, with wxPython. I have a > script that that I have developed to a useful point, and I want to add a GUI > to it. I am a little unsure as the the best approach to this. The script > heretofore was just run at the command line. Would it make sense to add an > option in the same script to have it run in "graphical mode", which would > trigger the wxPython code I would add in, and otherwise use the same logic? > > More generally: Anyone have any tips on adding a GUI to a pre-existing > script in a way that minimizes repetition of logic? I would rather not make > a separate script that only used wxPython, and I do not think I have to, but > perhaps there are good reasons to, etc. > > Thanks, > Sam > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Michael Langford Phone: 404-386-0495 Consulting: http://www.TierOneDesign.com/ Entertaining: http://www.ThisIsYourCruiseDirectorSpeaking.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070916/f8f57b13/attachment.htm From daniel.chaowang at gmail.com Sun Sep 16 16:41:07 2007 From: daniel.chaowang at gmail.com (=?BIG5?B?pP22Vw==?=) Date: Sun, 16 Sep 2007 22:41:07 +0800 Subject: [Tutor] how to match regular expression from right to left In-Reply-To: <46ED38DE.1070809@tds.net> References: <57fe16f60709160601se708b5fibd0abf976de40400@mail.gmail.com> <2a278ffe0709160632s53d9d1a4t3a4226b226d31073@mail.gmail.com> <57fe16f60709160701y62713254ub1b634d0c5b67f24@mail.gmail.com> <46ED38DE.1070809@tds.net> Message-ID: <57fe16f60709160741u37d4f326ofce71a8a492af75b@mail.gmail.com> The number of iterms - (us::.*?) - varies. When I use re.findall with (us::*?), only several 'us::' are extracted. Daniel On 9/16/07, Kent Johnson <kent37 at tds.net> wrote: > > $B2&D6(B wrote: > > yes, but I mean if I have the line like this: > > > > line = """38166 us::Video_Cat::Other; us::Video_Cat::Today Show; > > us::VC_Supplier::bc; 1002::ms://bc.wd.net/a275/video/tdy_is.asf; > > 1003::ms://bc.wd.net/a275/video/tdy_is_.fl;""" > > > > I want to get the part "us::MSNVideo_Cat::Other; us::MSNVideo_Cat::Today > > Show; us::VC_Supplier::Msnbc;" > > > > but re.compile(r"(us::.*) .*(1002|1003).*$") will get the > > "1002::ms://bc.wd.net/a275/video/tdy_is.asf;" included in an lazy mode. > > Of course, you have asked for all the text up to the end of the string. > > Not sure what you mean by lazy mode... > > If there will always be three items you could just repeat the relevant > sections of the re, something like > > r'(us::.*?); (us::.*?); (us::.*?);' > > or even > > r'(us::Video_Cat::.*?); (us::Video_Cat::.*?); (us::VC_Supplier::.*?);' > > If the number of items varies then use re.findall() with (us::.*?); > > The non-greedy match is not strictly needed in the first case but it is > in the second. > > Kent > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070916/e773d9f0/attachment.htm From kent37 at tds.net Sun Sep 16 16:50:44 2007 From: kent37 at tds.net (Kent Johnson) Date: Sun, 16 Sep 2007 10:50:44 -0400 Subject: [Tutor] how to match regular expression from right to left In-Reply-To: <57fe16f60709160741u37d4f326ofce71a8a492af75b@mail.gmail.com> References: <57fe16f60709160601se708b5fibd0abf976de40400@mail.gmail.com> <2a278ffe0709160632s53d9d1a4t3a4226b226d31073@mail.gmail.com> <57fe16f60709160701y62713254ub1b634d0c5b67f24@mail.gmail.com> <46ED38DE.1070809@tds.net> <57fe16f60709160741u37d4f326ofce71a8a492af75b@mail.gmail.com> Message-ID: <46ED42C4.9080504@tds.net> $B2&D6(B wrote: > The number of iterms - (us::.*?) - varies. > > When I use re.findall with (us::*?), only several 'us::' are extracted. I don't understand what is going wrong now. Please show the code, the data, and tell us what you get and what you want to get. Here is an example: Without a group you get the whole match: In [3]: import re In [4]: line = """38166 us::Video_Cat::Other; us::Video_Cat::Today Show; us::VC_Supplier::bc; 1002::ms://bc.wd.net/a275/video/tdy_is.asf; 1003::ms://bc.wd.net/a275/video/tdy_is_.fl;""" In [5]: re.findall('us::.*?;', line) Out[5]: ['us::Video_Cat::Other;', 'us::Video_Cat::Today Show;', 'us::VC_Supplier::bc;'] With a group you get just the group: In [6]: re.findall('(us::.*?);', line) Out[6]: ['us::Video_Cat::Other', 'us::Video_Cat::Today Show', 'us::VC_Supplier::bc'] Kent > > Daniel > > On 9/16/07, * Kent Johnson* <kent37 at tds.net <mailto:kent37 at tds.net>> wrote: > > $B2&D6(B wrote: > > yes, but I mean if I have the line like this: > > > > line = """38166 us::Video_Cat::Other; us::Video_Cat::Today Show; > > us::VC_Supplier::bc; 1002::ms://bc.wd.net/a275/video/tdy_is.asf; > > 1003::ms://bc.wd.net/a275/video/tdy_is_.fl;""" > > > > I want to get the part "us::MSNVideo_Cat::Other; > us::MSNVideo_Cat::Today > > Show; us::VC_Supplier::Msnbc;" > > > > but re.compile(r"(us::.*) .*(1002|1003).*$") will get the > > "1002::ms://bc.wd.net/a275/video/tdy_is.asf;" included in an lazy > mode. > > Of course, you have asked for all the text up to the end of the string. > > Not sure what you mean by lazy mode... > > If there will always be three items you could just repeat the relevant > sections of the re, something like > > r'(us::.*?); (us::.*?); (us::.*?);' > > or even > > r'(us::Video_Cat::.*?); (us::Video_Cat::.*?); (us::VC_Supplier::.*?);' > > If the number of items varies then use re.findall() with (us::.*?); > > The non-greedy match is not strictly needed in the first case but it is > in the second. > > Kent > > From daniel.chaowang at gmail.com Sun Sep 16 17:13:27 2007 From: daniel.chaowang at gmail.com (=?BIG5?B?pP22Vw==?=) Date: Sun, 16 Sep 2007 23:13:27 +0800 Subject: [Tutor] how to match regular expression from right to left In-Reply-To: <46ED42C4.9080504@tds.net> References: <57fe16f60709160601se708b5fibd0abf976de40400@mail.gmail.com> <2a278ffe0709160632s53d9d1a4t3a4226b226d31073@mail.gmail.com> <57fe16f60709160701y62713254ub1b634d0c5b67f24@mail.gmail.com> <46ED38DE.1070809@tds.net> <57fe16f60709160741u37d4f326ofce71a8a492af75b@mail.gmail.com> <46ED42C4.9080504@tds.net> Message-ID: <57fe16f60709160813i7438e5a0vec4a7eafd98eb6c3@mail.gmail.com> kent: Thank you. I got the right results with re.findall('(us::.*?);', line). I used these codes before: >>> TAG_pattern = re.compile(r"(us::.*?)") >>> TAG_pattern.findall(line) and got the unwanted results 'us::' Tom: Thank you. But the number of 'us::' terms varies, and kent's solution works well. Daniel On 9/16/07, Kent Johnson <kent37 at tds.net> wrote: > > $B2&D6(B wrote: > > The number of iterms - (us::.*?) - varies. > > > > When I use re.findall with (us::*?), only several 'us::' are extracted. > > I don't understand what is going wrong now. Please show the code, the > data, and tell us what you get and what you want to get. > > Here is an example: > > Without a group you get the whole match: > > In [3]: import re > In [4]: line = """38166 us::Video_Cat::Other; us::Video_Cat::Today Show; > us::VC_Supplier::bc; 1002::ms://bc.wd.net/a275/video/tdy_is.asf; > 1003::ms://bc.wd.net/a275/video/tdy_is_.fl;""" > In [5]: re.findall('us::.*?;', line) > Out[5]: ['us::Video_Cat::Other;', 'us::Video_Cat::Today Show;', > 'us::VC_Supplier::bc;'] > > With a group you get just the group: > > In [6]: re.findall('(us::.*?);', line) > Out[6]: ['us::Video_Cat::Other', 'us::Video_Cat::Today Show', > 'us::VC_Supplier::bc'] > > Kent > > > > > Daniel > > > > On 9/16/07, * Kent Johnson* <kent37 at tds.net <mailto:kent37 at tds.net>> > wrote: > > > > $B2&D6(B wrote: > > > yes, but I mean if I have the line like this: > > > > > > line = """38166 us::Video_Cat::Other; us::Video_Cat::Today Show; > > > us::VC_Supplier::bc; 1002::ms://bc.wd.net/a275/video/tdy_is.asf; > > > 1003::ms://bc.wd.net/a275/video/tdy_is_.fl;""" > > > > > > I want to get the part "us::MSNVideo_Cat::Other; > > us::MSNVideo_Cat::Today > > > Show; us::VC_Supplier::Msnbc;" > > > > > > but re.compile(r"(us::.*) .*(1002|1003).*$") will get the > > > "1002::ms://bc.wd.net/a275/video/tdy_is.asf;" included in an lazy > > mode. > > > > Of course, you have asked for all the text up to the end of the > string. > > > > Not sure what you mean by lazy mode... > > > > If there will always be three items you could just repeat the > relevant > > sections of the re, something like > > > > r'(us::.*?); (us::.*?); (us::.*?);' > > > > or even > > > > r'(us::Video_Cat::.*?); (us::Video_Cat::.*?); > (us::VC_Supplier::.*?);' > > > > If the number of items varies then use re.findall() with (us::.*?); > > > > The non-greedy match is not strictly needed in the first case but it > is > > in the second. > > > > Kent > > > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070916/9778be11/attachment.htm From kent37 at tds.net Sun Sep 16 17:25:46 2007 From: kent37 at tds.net (Kent Johnson) Date: Sun, 16 Sep 2007 11:25:46 -0400 Subject: [Tutor] how to match regular expression from right to left In-Reply-To: <57fe16f60709160813i7438e5a0vec4a7eafd98eb6c3@mail.gmail.com> References: <57fe16f60709160601se708b5fibd0abf976de40400@mail.gmail.com> <2a278ffe0709160632s53d9d1a4t3a4226b226d31073@mail.gmail.com> <57fe16f60709160701y62713254ub1b634d0c5b67f24@mail.gmail.com> <46ED38DE.1070809@tds.net> <57fe16f60709160741u37d4f326ofce71a8a492af75b@mail.gmail.com> <46ED42C4.9080504@tds.net> <57fe16f60709160813i7438e5a0vec4a7eafd98eb6c3@mail.gmail.com> Message-ID: <46ED4AFA.2090502@tds.net> $B2&D6(B wrote: > kent: > Thank you. I got the right results with re.findall('(us::.*?);', line). > > I used these codes before: > >>> TAG_pattern = re.compile(r"(us::.*?)") > >>> TAG_pattern.findall(line) > and got the unwanted results 'us::' That is because .*? will match the empty string. You have to put the ; after it to force the match to extend. Kent From wormwood_3 at yahoo.com Sun Sep 16 19:44:29 2007 From: wormwood_3 at yahoo.com (wormwood_3) Date: Sun, 16 Sep 2007 10:44:29 -0700 (PDT) Subject: [Tutor] Adding a GUI Message-ID: <598512.41614.qm@web32404.mail.mud.yahoo.com> >> First of all Sam, thanks for your help with the fileinput() problem I >> was having! =) Sure thing:-) Sorry I could not actually solve it! I am still have a hard time getting my mind around the line.strip(), then printing based on a condition loop. Not sure why... The excerpt from Lutz' book was very helpful, thanks. One issue I still have: I do not really want to lose the ability to run the script from the CLI. This seems relatively common too, having the same script with a command line and a graphical version. Lutz seems to present the case of pure conversion, where a script was first CLI only, and will end up being GUI only, which I was hoping to avoid... I didn't mean to speak badly of Tkinter, I know it is the most ubiquitous, and can work quite well. I have used it before, and it is relatively easy to use. The main issue I have with it is just that it, well, looks bad! The windows and frames do not resemble native windows per OS, which is an advantage of wxPython. I will check out his book more, though, 300 pages on GUI programming would be helpful! Thanks, Sam From wormwood_3 at yahoo.com Sun Sep 16 19:46:52 2007 From: wormwood_3 at yahoo.com (wormwood_3) Date: Sun, 16 Sep 2007 10:46:52 -0700 (PDT) Subject: [Tutor] Adding a GUI Message-ID: <405311.19261.qm@web32402.mail.mud.yahoo.com> Hi, >> Wormwood, an easier way to create a crossplatform GUI than raw wxPython is to use pythoncard, which is a library that is on top of wxPython that is there to make it easier to use and to make it easier to >> layout GUI screens/dialogs. I have heard some good things about pythoncard. I will be sure to give it a try! >> I've found its a much faster "whiteboard to running software time" then wxPython by itself. (I've used both, raw wxPython a lot *more* than pythoncard, as i'd not yet heard of it). Awesome. >> Alan is right about separating the core logic of the program from the input/output methods, and using that in both a command line and a gui program. I hope I am not missing messages from the tutor list again. I did not see anything from Alan on my question, which you seemed to be referring to... But that aside, I definitely agree this is an important principle, which I always try to implement. >> I doubt you'll need a book to use pythoncard. Its about as easy as VB to build a form with the WYSIWYG, and very pythonic to use the forms you've built. >> To get up an going, install a compatible version of wxPython use this link: http://pythoncard.sourceforge.net/walkthrough1.html Thanks! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070916/4b03b80c/attachment.htm From carroll at tjc.com Sun Sep 16 19:49:08 2007 From: carroll at tjc.com (Terry Carroll) Date: Sun, 16 Sep 2007 10:49:08 -0700 (PDT) Subject: [Tutor] referencing vars() In-Reply-To: <aaf235960709151150p403f922eqfdce806580917ceb@mail.gmail.com> Message-ID: <Pine.LNX.4.44.0709161047530.20770-100000@violet.rahul.net> On Sat, 15 Sep 2007, John wrote: > I'm trying to do the above, but of course get an error because vardict is > only referencing vars(), thus changes size... also, I tried > vardict=[vars()], but this fails as well?? How about import copy vardict=copy.copy(vars()) That way, you've made a copy of vars, and any changes that happen in the meantime don't matter. From ghashsnaga at gmail.com Mon Sep 17 01:58:35 2007 From: ghashsnaga at gmail.com (Ara Kooser) Date: Sun, 16 Sep 2007 17:58:35 -0600 Subject: [Tutor] remove instances from a list Message-ID: <2107481c0709161658h6a7fed14y2b852ca3a4d155c@mail.gmail.com> Hello all, On my continuing quest to grapple with OO programming Kent showed me that I could call instances and store them in a list like: yeasts = [Yeast("Red_1","Red","ade","lys"),Yeast("Yellow_1","Yellow","lys","ade"), Yeast("Red_2","Red","ade","lys"),Yeast("Yellow_2","Yellow","lys","ade")] Give certain conditions I want the yeast cell to die. Kent suggested I use something this: yeasts = [yeast for yeast in yeasts if yeast.isAlive()] to clear out dead yeast. Is the translation for the above line of code into pseudocode? yeast for every yeast in the list yeasts if the yeast method returned isAlive() Or is this meant to be a true or false return? I have included the code below. Thank you again. Ara ############### CODE BELOW ############### ######################################################################### # Yeast Model # By Ara Kooser # Version beta # #Thanks to Kent, Michael, and Alan for suggestions and help ########################################################################## import random chemicals = [] class Yeast: def __init__(self,name,group,need,release): #name can be any, group is either red or yellow, need/release lys or ade self.name = name self.group = group self.need = need self.release = release self.growth = 0 self.life = 0 self.starve = 0 self.alive = True #METHODS def setup(self): #Sets up the random variable for each yeast before the game logic loop if self.group == "Red": a = random.randrange(40,160) self.life = a self.growth = 5 aa = random.randrange(20,50) self.starve = aa elif self.group == "Yellow": b = random.randrange(20,80) self.life = b self.growth = 3 bb = random.randrange(10,30) elif self.group == "Defect": pass else: pass def chem_need(self): if self.need == "ade": if self.need in chemicals: print self.name,"is taking ade" self.life = self.life+1 chemicals.remove(self.need) print chemicals print "Life", self.life print else: print self.name, "found no ade present" self.life = self.life-1 elif self.need == "lys": if self.need in chemicals: print self.name," is taking lys" self.life = self.life+1 chemicals.remove(self.need) print chemicals print "Life",self.life print else: print self.name, "found no lys present" self.life = self.life-1 else: pass def near_death(self): #release of aa in the environment near cell death if self.life <= self.starve: c = random.randrange(1,3) if c == 1: print self.name, "-- Releasing", self.release chemicals.append(self.release) if c == 2: print self.name, "-- Releasing", self.release chemicals.append(self.release) chemicals.append(self.release) if c == 3: print self.name, "-- Releasing", self.release chemicals.append(self.release) chemicals.append(self.release) chemicals.append(self.release) def isAlive(self): if self.life > 0: self.alive = True else: self.alive = False def growth(self): pass ########################################################################################### #Program Starts Here ########################################################################################### #Stores the instances in a list for easier use. Later versions will allow the user to add #instances #Instance are called: Yeast, name, group, aa need, aa release yeasts = [Yeast("Red_1","Red","ade","lys"),Yeast("Yellow_1","Yellow","lys","ade"), Yeast("Red_2","Red","ade","lys"),Yeast("Yellow_2","Yellow","lys","ade")] print "Welcome to the red/yellow yeast simulation environment." print"Red yeast cells need adenine to grow and they release lysine." print"Yellow yeast cells ned lysine to grow and release adenine." print raw_input("Please press return or enter to start the game.") rounds = raw_input("How many rounds to you wish to play through?") print "Starting environment", chemicals rounds =int(rounds) count = 0 ###Game logic for yeast in yeasts: yeast.setup() while count < rounds: print "##########################################################" print "Round number",count print for yeast in yeasts: yeast.chem_need() print print "Chemicals in the environment",chemicals print #Calls the growth code that in not yet functioning # for yeast in yeasts: # yeast.growth() #The line below will eventually clean out dead yeast #yeast for every yeast in the list yeasts if the yeast method returned isAlive yeasts = [yeast for yeast in yeasts if yeast.isAlive()] count = count + 1 print "#########################################################" print "Ending environment", chemicals -- Quis hic locus, quae regio, quae mundi plaga. Ubi sum. Sub ortu solis an sub cardine glacialis ursae. From john at fouhy.net Mon Sep 17 02:43:54 2007 From: john at fouhy.net (John Fouhy) Date: Mon, 17 Sep 2007 12:43:54 +1200 Subject: [Tutor] remove instances from a list In-Reply-To: <2107481c0709161658h6a7fed14y2b852ca3a4d155c@mail.gmail.com> References: <2107481c0709161658h6a7fed14y2b852ca3a4d155c@mail.gmail.com> Message-ID: <5e58f2e40709161743k1dceacc0y791758207c0ce813@mail.gmail.com> On 17/09/2007, Ara Kooser <ghashsnaga at gmail.com> wrote: > Give certain conditions I want the yeast cell to die. Kent suggested I > use something this: > yeasts = [yeast for yeast in yeasts if yeast.isAlive()] to clear out > dead yeast. [...] > class Yeast: [...] > def isAlive(self): > if self.life > 0: > self.alive = True > else: > self.alive = False Most programmers would see an 'isAlive' method as a method that would return True if the thing is alive, and False otherwise. So you would define it as: def isAlive(self): if self.life > 0: return True else: return False Then you could write code like this: # suppose 'y' is a yeast object # If y is alive, make it grow. if y.isAlive(): y.grow() (actually, you can write this method much more concisely: def isAlive(self): return self.life > 0 ) HTH! -- John. From kent37 at tds.net Mon Sep 17 02:51:46 2007 From: kent37 at tds.net (Kent Johnson) Date: Sun, 16 Sep 2007 20:51:46 -0400 Subject: [Tutor] remove instances from a list In-Reply-To: <2107481c0709161658h6a7fed14y2b852ca3a4d155c@mail.gmail.com> References: <2107481c0709161658h6a7fed14y2b852ca3a4d155c@mail.gmail.com> Message-ID: <46EDCFA2.8030907@tds.net> Ara Kooser wrote: > Hello all, > > On my continuing quest to grapple with OO programming Kent showed > me that I could call instances and store them in a list like: > yeasts = [Yeast("Red_1","Red","ade","lys"),Yeast("Yellow_1","Yellow","lys","ade"), > Yeast("Red_2","Red","ade","lys"),Yeast("Yellow_2","Yellow","lys","ade")] > > Give certain conditions I want the yeast cell to die. Kent suggested I > use something this: > yeasts = [yeast for yeast in yeasts if yeast.isAlive()] to clear out > dead yeast. > > Is the translation for the above line of code into pseudocode? > yeast for every yeast in the list yeasts if the yeast method returned isAlive() Almost. yeast for every yeast in the list yeasts if the yeast method isAlive() returned True This is called a list comprehension, it is a very handy way to do things with lists. Some examples here: http://docs.python.org/tut/node7.html#SECTION007140000000000000000 > def chem_need(self): > if self.need == "ade": > if self.need in chemicals: > print self.name,"is taking ade" > self.life = self.life+1 > chemicals.remove(self.need) > print chemicals > print "Life", self.life > print > else: > print self.name, "found no ade present" > self.life = self.life-1 > > elif self.need == "lys": > if self.need in chemicals: > print self.name," is taking lys" > self.life = self.life+1 > chemicals.remove(self.need) > print chemicals > print "Life",self.life > print > else: > print self.name, "found no lys present" > self.life = self.life-1 Note that the above two blocks are almost identical. The only difference is the print statements. Can you figure out a way to combine them into a single block? Then you could say if self.need in ('ade', 'lys'): # handle both ade and lys > def isAlive(self): > if self.life > 0: > self.alive = True > else: > self.alive = False This could be just self.alive = (self.life > 0) but I think what you want here is actually to *return* a flag indicating whether the yeast is alive: def isAlive(self): return (self.life > 0) > > #The line below will eventually clean out dead yeast > #yeast for every yeast in the list yeasts if the yeast method returned isAlive > yeasts = [yeast for yeast in yeasts if yeast.isAlive()] This will work correctly if you change isAlive() as above. Kent From witham.ian at gmail.com Mon Sep 17 02:59:53 2007 From: witham.ian at gmail.com (Ian Witham) Date: Mon, 17 Sep 2007 12:59:53 +1200 Subject: [Tutor] remove instances from a list In-Reply-To: <2107481c0709161658h6a7fed14y2b852ca3a4d155c@mail.gmail.com> References: <2107481c0709161658h6a7fed14y2b852ca3a4d155c@mail.gmail.com> Message-ID: <a04dbf4b0709161759n69055f28p9bf281e0253e12f8@mail.gmail.com> On 9/17/07, Ara Kooser <ghashsnaga at gmail.com> wrote: > > Hello all, > > On my continuing quest to grapple with OO programming Kent showed > me that I could call instances and store them in a list like: > yeasts = > [Yeast("Red_1","Red","ade","lys"),Yeast("Yellow_1","Yellow","lys","ade"), > > Yeast("Red_2","Red","ade","lys"),Yeast("Yellow_2","Yellow","lys","ade")] > > Give certain conditions I want the yeast cell to die. Kent suggested I > use something this: > yeasts = [yeast for yeast in yeasts if yeast.isAlive()] to clear out > dead yeast. > > Is the translation for the above line of code into pseudocode? > yeast for every yeast in the list yeasts if the yeast method returned > isAlive() ...yeast for yeast in yeasts if the yeast.isAlive() method returns True OR a value that evaluates as True. for instance 0 is false, any other integer is True, 0.0 is False, any other float is True "" is False, and any non empty string is True. Each data type has a True or False condition, which I believe is why Python didn't even have a boolean True/False data type until very recently. Or is this meant to be a true or false return? I have included the > code below. Thank you again. It does not need to return True or False, as whatever it returns can be evaluated as True or False, as I mentioned above. You should also realise that you can test for a specific return value by doing something like this: yeasts = [yeast for yeast in yeasts if yeast.isAlive() == "I'm not dead yet!"] or yeasts = [yeast for yeast in yeasts if yeast.health > -10] (this example directly tests the instance's local variable life_force rather than calling a method and testing the returned value) Hope this helps, Ian. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070917/db47a5f7/attachment.htm From jeffpeery at yahoo.com Mon Sep 17 07:51:10 2007 From: jeffpeery at yahoo.com (Jeff Peery) Date: Sun, 16 Sep 2007 22:51:10 -0700 (PDT) Subject: [Tutor] performance Message-ID: <185085.77554.qm@web43131.mail.sp1.yahoo.com> Hello, I've got a quick question regarding performance of lists. I am taking measurements and building up a list of objects for each measurement. the class I created for the objects has attributes of time, numerical value, person's name who collected the sample etc. I also have functions within my class (I think they are properly named 'accessors'?) that get a piece of data within the object, for example 'self.GetSampleTime()'. I'm wondering what happens to my performance as I add more accesors to my class. How are the accesors managed? will each object in my list of objects contain the data for each accesor or do all the objects look to the sample module for the accesor? will my list of objects become huge and slow as I add more accessors? thanks. Jeff --------------------------------- Don't let your dream ride pass you by. Make it a reality with Yahoo! Autos. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070916/1eff16b2/attachment.htm From clsdaniel at gmail.com Mon Sep 17 08:48:35 2007 From: clsdaniel at gmail.com (Carlos Daniel Ruvalcaba Valenzuela) Date: Sun, 16 Sep 2007 23:48:35 -0700 Subject: [Tutor] performance In-Reply-To: <4fae7dfa0709162347i747e10edv9399107f58d10a4b@mail.gmail.com> References: <185085.77554.qm@web43131.mail.sp1.yahoo.com> <4fae7dfa0709162347i747e10edv9399107f58d10a4b@mail.gmail.com> Message-ID: <4fae7dfa0709162348j574acd8frc24836297cee6763@mail.gmail.com> Don't worry too much for the accessors, I'm pretty sure it won't degrade your performance in a noticeable way, you objects will only grow a tiny bit by adding a function to the class, all objects share the same in memory code and each one has it's own data, the function for the object is just a reference for the class function, not the memory of the function itself (I think, it would be a waste of memory otherwise). However take it with a grain of salt, do your own benchmarks, you could do a simple measure with time.time() function, or use one of the several profiling modules for python (profile, hotshot, etc). Forwarded to Tutor list, I forgot it sorry! Regards, Carlos Daniel Ruvalcaba Valenzuela On 9/16/07, Jeff Peery <jeffpeery at yahoo.com> wrote: > Hello, > I've got a quick question regarding performance of lists. I am taking > measurements and building up a list of objects for each measurement. the > class I created for the objects has attributes of time, numerical value, > person's name who collected the sample etc. I also have functions within my > class (I think they are properly named 'accessors'?) that get a piece of > data within the object, for example 'self.GetSampleTime()'. I'm wondering > what happens to my performance as I add more accesors to my class. How are > the accesors managed? will each object in my list of objects contain the > data for each accesor or do all the objects look to the sample module for > the accesor? will my list of objects become huge and slow as I add more > accessors? thanks. > > Jeff > > ________________________________ > Don't let your dream ride pass you by. Make it a reality with Yahoo! Autos. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From washakie at gmail.com Mon Sep 17 08:59:02 2007 From: washakie at gmail.com (John) Date: Sun, 16 Sep 2007 23:59:02 -0700 Subject: [Tutor] referencing vars() In-Reply-To: <46EC40CD.5030901@tds.net> References: <aaf235960709151150p403f922eqfdce806580917ceb@mail.gmail.com> <46EC40CD.5030901@tds.net> Message-ID: <aaf235960709162359l496fa496mf892a9ec8dcdc3ad@mail.gmail.com> Kent, Thanks this is exactly the solution I am looking for... so simple. On 9/15/07, Kent Johnson <kent37 at tds.net> wrote: > > John wrote: > > #Set up writer > > import csv > > vardict=vars() > > for var in vardict: > > if var=='allcum' or var=='alldhdt': > > outfile=in_path+'/'+dataset+'_'+str(var)+'.csv' > > writer = csv.writer(open(outfile, "wb")) > > writer.writerows(var) > > > > I'm trying to do the above, but of course get an error because vardict > > is only referencing vars(), thus changes size... also, I tried > > vardict=[vars()], but this fails as well?? > > I'm not too clear what you are trying to do here. Do you want the values > of the variables allcum and alldhdt? > > vars() gives you a dict whose keys are varible names and values are, > well, the values. I think you are trying to write the contents of allcum > to a file with allcum in the name? > > You could do it with vars like this: > > for var in ['allcum', 'alldhdt']: > outfile=in_path+'/'+dataset+'_'+var+'.csv' > writer = csv.writer(open(outfile, "wb")) > writer.writerows(vars()[var]) > > or you could iterate a list of name, value tuples directly: > > for name, value in [('allcum', allcum), ('alldhdt', alldhdt)]: > outfile=in_path+'/'+dataset+'_'+name+'.csv' > writer = csv.writer(open(outfile, "wb")) > writer.writerows(value) > > I think I prefer the second, even with the duplication of names; it > feels more explicit to me. > > Another alternative would be to accumulate the values in a dict with > keys 'allcum' and 'alldhdt'. Then you would look up in that dict instead > of in vars(). > > HTH, > Kent > -- Configuration `````````````````````````` Plone 2.5.3-final, CMF-1.6.4, Zope (Zope 2.9.7-final, python 2.4.4, linux2), Five 1.4.1, Python 2.4.4 (#1, Jul 3 2007, 22:58:17) [GCC 4.1.1 20070105 (Red Hat 4.1.1-51)], PIL 1.1.6 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070916/e16df154/attachment.htm From kent37 at tds.net Sun Sep 16 16:08:30 2007 From: kent37 at tds.net (Kent Johnson) Date: Sun, 16 Sep 2007 10:08:30 -0400 Subject: [Tutor] how to match regular expression from right to left In-Reply-To: <57fe16f60709160701y62713254ub1b634d0c5b67f24@mail.gmail.com> References: <57fe16f60709160601se708b5fibd0abf976de40400@mail.gmail.com> <2a278ffe0709160632s53d9d1a4t3a4226b226d31073@mail.gmail.com> <57fe16f60709160701y62713254ub1b634d0c5b67f24@mail.gmail.com> Message-ID: <46ED38DE.1070809@tds.net> $B2&D6(B wrote: > yes, but I mean if I have the line like this: > > line = """38166 us::Video_Cat::Other; us::Video_Cat::Today Show; > us::VC_Supplier::bc; 1002::ms://bc.wd.net/a275/video/tdy_is.asf; > 1003::ms://bc.wd.net/a275/video/tdy_is_.fl;""" > > I want to get the part "us::MSNVideo_Cat::Other; us::MSNVideo_Cat::Today > Show; us::VC_Supplier::Msnbc;" > > but re.compile(r"(us::.*) .*(1002|1003).*$") will get the > "1002::ms://bc.wd.net/a275/video/tdy_is.asf;" included in an lazy mode. Of course, you have asked for all the text up to the end of the string. Not sure what you mean by lazy mode... If there will always be three items you could just repeat the relevant sections of the re, something like r'(us::.*?); (us::.*?); (us::.*?);' or even r'(us::Video_Cat::.*?); (us::Video_Cat::.*?); (us::VC_Supplier::.*?);' If the number of items varies then use re.findall() with (us::.*?); The non-greedy match is not strictly needed in the first case but it is in the second. Kent From alan.gauld at btinternet.com Mon Sep 17 11:53:21 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 17 Sep 2007 10:53:21 +0100 Subject: [Tutor] remove instances from a list References: <2107481c0709161658h6a7fed14y2b852ca3a4d155c@mail.gmail.com> Message-ID: <fclira$vs6$1@sea.gmane.org> "Ara Kooser" <ghashsnaga at gmail.com> wrote > Is the translation for the above line of code into pseudocode? > yeast for every yeast in the list yeasts if the yeast method > returned isAlive() Others have given you the solution. But note that you still have the terminology wrong. "... the yeast method returned isAlive()" yeast is an object and isAlive is a method of the object. The isAlive method returns a value. Thus your sentence should have said: ... the yeast.isAlive method returned True 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 Sep 17 12:00:38 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 17 Sep 2007 11:00:38 +0100 Subject: [Tutor] performance References: <185085.77554.qm@web43131.mail.sp1.yahoo.com> Message-ID: <fclj8v$1h6$1@sea.gmane.org> "Jeff Peery" <jeffpeery at yahoo.com> wrote > I am taking measurements and building up a list of objects > for each measurement. the class I created for the objects has > attributes > I also have functions within my class (I think they are properly > named 'accessors'?) that get a piece of data within the object, You don't really need these in Python. Unless they are performing some manipulation of the data its perfectly acceptable to get the data directly from the object. Having an accessor for every attribute is a fashion quirk carried over from Java which needs it for its Javabean spec. Python OOP tends to take a much more relaxed approach to attribute access. > I'm wondering what happens to my performance as I > add more accesors to my class. How are the accesors managed? Adding methods to a class does not significantly affect the objects. The methods are stored as objects in a dictionary in the class and the instances just have a reference to the class. Thus all you are doing is adding method code to the class and an extra entry to the dictionary. > will my list of objects become huge and slow as I add more > accessors? No, the dictionary lookup is nearly constant in time regardless of size. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From ricaraoz at gmail.com Mon Sep 17 12:13:30 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Mon, 17 Sep 2007 07:13:30 -0300 Subject: [Tutor] performance In-Reply-To: <4fae7dfa0709162348j574acd8frc24836297cee6763@mail.gmail.com> References: <185085.77554.qm@web43131.mail.sp1.yahoo.com> <4fae7dfa0709162347i747e10edv9399107f58d10a4b@mail.gmail.com> <4fae7dfa0709162348j574acd8frc24836297cee6763@mail.gmail.com> Message-ID: <46EE534A.1020906@bigfoot.com> Carlos Daniel Ruvalcaba Valenzuela wrote: > Don't worry too much for the accessors, I'm pretty sure it won't > degrade your performance in a noticeable way, you objects will only > grow a tiny bit by adding a function to the class, all objects share > the same in memory code and each one has it's own data, the function > for the object is just a reference for the class function, not the > memory of the function itself (I think, it would be a waste of memory > otherwise). > > However take it with a grain of salt, do your own benchmarks, you > could do a simple measure with time.time() function, or use one of the > several profiling modules for python (profile, hotshot, etc). > > Forwarded to Tutor list, I forgot it sorry! > > Regards, > Carlos Daniel Ruvalcaba Valenzuela > > On 9/16/07, Jeff Peery <jeffpeery at yahoo.com> wrote: >> Hello, >> I've got a quick question regarding performance of lists. I am taking >> measurements and building up a list of objects for each measurement. the >> class I created for the objects has attributes of time, numerical value, >> person's name who collected the sample etc. I also have functions within my >> class (I think they are properly named 'accessors'?) that get a piece of >> data within the object, for example 'self.GetSampleTime()'. I'm wondering >> what happens to my performance as I add more accesors to my class. How are >> the accesors managed? will each object in my list of objects contain the >> data for each accesor or do all the objects look to the sample module for >> the accesor? will my list of objects become huge and slow as I add more >> accessors? thanks. >> AFAIK accessors are not recommended in Python, your attributes can not be hidden anyway (only by convention). Just access or set the attributes directly : myClass.myAttribute = someValue. From eric at abrahamsen.com Mon Sep 17 07:56:49 2007 From: eric at abrahamsen.com (Eric Abrahamsen) Date: Mon, 17 Sep 2007 13:56:49 +0800 Subject: [Tutor] class awareness of variable name Message-ID: <FAB44A70-B418-415C-8C13-289A05844749@abrahamsen.com> When instantiating a class, is it possible for that instance to 'know' (via the __init__ method, I suppose) the name of the variable it's been assigned to? Thanks E From srikanth007m at gmail.com Mon Sep 17 13:15:22 2007 From: srikanth007m at gmail.com (chinni) Date: Mon, 17 Sep 2007 16:45:22 +0530 Subject: [Tutor] Xml reference Message-ID: <b5300ea90709170415g1caa96cev59aafa32a25416eb@mail.gmail.com> Hi all, Which Book is better for python parsing and reading Xml files from local machine and remote machine and also through http... Can any one Please Post the link at least ...waiting for u r Replies ..... Thanku:) -- Cheers, M.Srikanth Kumar, Phone no: +91-9866774007 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070917/b95bfb87/attachment.htm From alan.gauld at btinternet.com Mon Sep 17 13:21:26 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 17 Sep 2007 12:21:26 +0100 Subject: [Tutor] class awareness of variable name References: <FAB44A70-B418-415C-8C13-289A05844749@abrahamsen.com> Message-ID: <fclo0f$gsg$1@sea.gmane.org> "Eric Abrahamsen" <eric at abrahamsen.com> wrote > When instantiating a class, is it possible for that instance to > 'know' (via the __init__ method, I suppose) the name of the variable > it's been assigned to? You could pass it in as a string but there is little point. Recall that in Python variables are just names. You can have several variables pointing at the same object, which 'name' should the instance use? class C: pass a = C() b = a d = b L = [] L.appand(a) L.append(b) a = 42 Now we have 1 instance but 4 references to it and the original name 'a' no longer points to it!. Which name should it return? Presumably you have a reason for asking this? If you tell us what you are trying to do we might be able to come up with a more conventional solution. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From mlangford.cs03 at gtalumni.org Mon Sep 17 14:15:46 2007 From: mlangford.cs03 at gtalumni.org (Michael Langford) Date: Mon, 17 Sep 2007 08:15:46 -0400 Subject: [Tutor] Xml reference In-Reply-To: <b5300ea90709170415g1caa96cev59aafa32a25416eb@mail.gmail.com> References: <b5300ea90709170415g1caa96cev59aafa32a25416eb@mail.gmail.com> Message-ID: <82b4f5810709170515l1635883aqe1d811d7ed255bfb@mail.gmail.com> I've found Python Cookbook to be a good, modern resource for parsing as well as tricks for remote pages. Link at amazon: *http://tinyurl.com/2njsd9 --Michael Original url: http://www.amazon.com/gp/product/0596007973/102-1641864-7294551?ie=UTF8&tag=rowlab-20&linkCode=xm2&camp=1789&creativeASIN=0596007973 * On 9/17/07, chinni <srikanth007m at gmail.com> wrote: > > Hi all, > > Which Book is better for python parsing and reading Xml files from local > machine and remote machine and also through http... > Can any one Please Post the link at least ...waiting for u r Replies ..... > > Thanku:) > > -- > Cheers, > M.Srikanth Kumar, > Phone no: +91-9866774007 > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Michael Langford Phone: 404-386-0495 Consulting: http://www.TierOneDesign.com/ Entertaining: http://www.ThisIsYourCruiseDirectorSpeaking.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070917/29af74d0/attachment.htm From eric at abrahamsen.com Mon Sep 17 14:57:34 2007 From: eric at abrahamsen.com (Eric Abrahamsen) Date: Mon, 17 Sep 2007 20:57:34 +0800 Subject: [Tutor] class awareness of variable name In-Reply-To: <fclo0f$gsg$1@sea.gmane.org> References: <FAB44A70-B418-415C-8C13-289A05844749@abrahamsen.com> <fclo0f$gsg$1@sea.gmane.org> Message-ID: <F353DB6F-8EEC-4F62-A303-43AB7ADC3A31@abrahamsen.com> On Sep 17, 2007, at 7:21 PM, Alan Gauld wrote: > > "Eric Abrahamsen" <eric at abrahamsen.com> wrote > >> When instantiating a class, is it possible for that instance to >> 'know' (via the __init__ method, I suppose) the name of the variable >> it's been assigned to? > > > Presumably you have a reason for asking this? > If you tell us what you are trying to do we might be able to > come up with a more conventional solution. To be honest, I was mostly curious, as I couldn't think of a good way to do it. I was thinking of cleaner ways of giving an instance a 'name' attribute than instance_name = Class('instance_name') in which the instance_name is repeated, and could be mistyped. I know there are problems with multiple bindings, which is why I was thinking of doing it with the __init__ method, in which case you'd get the first variable name and then none other (even if it was later unbound from the original variable). In the end, though, I was mostly curious by which mechanism you could get the variable name 'inside' the class workings. How do you pass it in as a string? Thanks!, Eric From kent37 at tds.net Mon Sep 17 15:39:01 2007 From: kent37 at tds.net (Kent Johnson) Date: Mon, 17 Sep 2007 09:39:01 -0400 Subject: [Tutor] class awareness of variable name In-Reply-To: <FAB44A70-B418-415C-8C13-289A05844749@abrahamsen.com> References: <FAB44A70-B418-415C-8C13-289A05844749@abrahamsen.com> Message-ID: <46EE8375.6000301@tds.net> Eric Abrahamsen wrote: > When instantiating a class, is it possible for that instance to > 'know' (via the __init__ method, I suppose) the name of the variable > it's been assigned to? This is pretty hard. For one thing, the object will not be bound to a name until after __init__() is finished. Second, the object may not be bound to a name at all; it could be created and thrown away, or it could be added to a list, dict or other container, it could be a member of another object, it could be a temporary created as a function argument or the return value of a function... Even simple assignment has its complications. The assigned variable can be local or global. The assignment could be via tuple assignment in which case the value is inserted into a temporary tuple, then unpacked and assigned. In the very simple case of x = MyClass() you could probably use the stack frame to find the point of call and inspect the byte codes there to find the name... Kent From eric at abrahamsen.com Mon Sep 17 16:07:32 2007 From: eric at abrahamsen.com (Eric Abrahamsen) Date: Mon, 17 Sep 2007 22:07:32 +0800 Subject: [Tutor] class awareness of variable name In-Reply-To: <46EE8375.6000301@tds.net> References: <FAB44A70-B418-415C-8C13-289A05844749@abrahamsen.com> <46EE8375.6000301@tds.net> Message-ID: <E8FC821B-17E1-4EE2-9A62-EE893AC57347@abrahamsen.com> > This is pretty hard. For one thing, the object will not be bound to > a name until after __init__() is finished. Ah, that's a good thing to know... > you could probably use the stack frame to find the point of call > and inspect the byte codes there to find the name... I was afraid the answer would be something like that! I will be content with the normal way of doing things then. Thanks for the explanation. Yours, Eric From ericlake at ubuntu.com Mon Sep 17 18:44:09 2007 From: ericlake at ubuntu.com (Eric Lake) Date: Mon, 17 Sep 2007 12:44:09 -0400 Subject: [Tutor] When to use a class Message-ID: <20070917164409.GB10389@localdomain> I am still trying to understand when to use a class and when not to. All of the coding that I have done in the past (Python, Perl) has been procedural / functional. I would really like to do more OOP but I am not really sure when I need it. I have the following code. Is there any way that it would benefit from using a class? <code> #!/usr/bin/env python import string import _winreg import sys compName = sys.argv[1] x = _winreg.ConnectRegistry(compName,_winreg.HKEY_LOCAL_MACHINE) y = _winreg.OpenKey(x, r"SOFTWARE\Intel\LANDesk\VirusProtect6\CurrentVersion") avParent = _winreg.QueryValueEx(y,"Parent")[0] _winreg.CloseKey(y) print "Computer: %s \tAV Parent: %s" % (compName,avParent) </code> -- Thanks Eric Lake -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 481 bytes Desc: Digital signature Url : http://mail.python.org/pipermail/tutor/attachments/20070917/ec0c8efa/attachment-0001.pgp From mlangford.cs03 at gtalumni.org Mon Sep 17 19:32:41 2007 From: mlangford.cs03 at gtalumni.org (Michael Langford) Date: Mon, 17 Sep 2007 13:32:41 -0400 Subject: [Tutor] When to use a class In-Reply-To: <20070917164409.GB10389@localdomain> References: <20070917164409.GB10389@localdomain> Message-ID: <82b4f5810709171032ia8af3d2i9bde430763767604@mail.gmail.com> Short sections of code are not where classes shine. Classes become much more valuable when you start to get a lot of hairy details you need to pass around. For your code, for instance, you could pass in the whole registry key you want, and have out pop a RegKey object. This would be say, usable in a system where you needed to do several operations on this object. If you were accessing multiple registry keys for instance, it would probably be nice to make a RegKey class that could be created with a handy method. If you were only accessing one key one time, a simple routine will serve you well. Realms where classes are almost always used Simulations, GUI elements, business systems of any size, many parsers, especially XML and HTML parsers. Realms where they're used much less: Basic text processing, system administration tasks, simple database systems, and number crunching apps. --Michael -- Michael Langford Phone: 404-386-0495 Consulting: http://www.TierOneDesign.com/ Entertaining: http://www.ThisIsYourCruiseDirectorSpeaking.com On 9/17/07, Eric Lake <ericlake at ubuntu.com> wrote: > > I am still trying to understand when to use a class and when not to. All > of the coding that I have done in the past (Python, Perl) has been > procedural / functional. I would really like to do more OOP but I am not > really sure when I need it. > > I have the following code. Is there any way that it would benefit from > using a class? > > <code> > > #!/usr/bin/env python > > import string > import _winreg > import sys > > compName = sys.argv[1] > > x = _winreg.ConnectRegistry(compName,_winreg.HKEY_LOCAL_MACHINE) > y = _winreg.OpenKey(x, > r"SOFTWARE\Intel\LANDesk\VirusProtect6\CurrentVersion") > avParent = _winreg.QueryValueEx(y,"Parent")[0] > > _winreg.CloseKey(y) > > print "Computer: %s \tAV Parent: %s" % (compName,avParent) > > </code> > > > -- > > Thanks > Eric Lake > > -----BEGIN PGP SIGNATURE----- > Version: GnuPG v1.4.6 (GNU/Linux) > > iQEVAwUBRu6u2ZLZLpR+JU3MAQp0Dgf/cMXUpmBnVM3NPQu6b2LVwEN/L5+DG0hn > r3oyyVr56EIz04zl6fRqOk4NPkW0d0y5x2uvwWMCgvy64gyd9cHSrwCPxorCcf1j > /71QhXA0Nx44mwJK6ahCatcfimzUF1MeykOX0oxcaAP26JDtV7eF0jYjzizsEzmE > Q+2JlWzlOKrljxKL1zJLPepzubwoWFIYFmlXfYdbk2HkMCPmzPfAipEZW8WPj5xU > Fu1lGWEuODSEn/+d4X6tPNlJLOAxgL01IPPUZZSso6gfjlLDHYVPTYTEUDgZIrLD > XPuFpNT7tT8jQWZKg6OFjFS2P6/LVc02AYskXjegmEyMfNDZ27qLMw== > =9N/n > -----END PGP SIGNATURE----- > > _______________________________________________ > 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/20070917/b615fbb0/attachment.htm From alan.gauld at btinternet.com Mon Sep 17 19:54:43 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 17 Sep 2007 18:54:43 +0100 Subject: [Tutor] class awareness of variable name References: <FAB44A70-B418-415C-8C13-289A05844749@abrahamsen.com><fclo0f$gsg$1@sea.gmane.org> <F353DB6F-8EEC-4F62-A303-43AB7ADC3A31@abrahamsen.com> Message-ID: <fcmf1s$f0i$1@sea.gmane.org> "Eric Abrahamsen" <eric at abrahamsen.com> wrote > to do it. I was thinking of cleaner ways of giving an instance a > 'name' attribute than > > instance_name = Class('instance_name') The thing is that you shouldn't even try! The object can have a name and that name will be constant regardless of which variable is used to reference it. Don't try to associate variables with object identifiers, they are fundamentally different things. If you want to identify an object by its name inside a program the best way to do that is via a dictionary: objects = {} objects['foo'] = MyObject('foo') Now, no matter which other variables reference it you can always go to the dictionary and pull out a reference using the object's name. And if you want to avoid typing errors use a temp: temp = MyObject('bar') objects[temp.name] = temp And if thats too much work use a factory function: def addObject(name): objects[name] = MyObject(name) > I know there are problems with multiple bindings, Don't think of them as *problems*, just a different way of working :-) If you go with the flow rather than trying to make the flow go the way you want life is easier. -- 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 Sep 17 20:11:16 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 17 Sep 2007 19:11:16 +0100 Subject: [Tutor] When to use a class References: <20070917164409.GB10389@localdomain> Message-ID: <fcmg0u$iou$1@sea.gmane.org> "Eric Lake" <ericlake at ubuntu.com> wrote > I am still trying to understand when to use a class and when not to. > All > of the coding that I have done in the past (Python, Perl) has been > procedural / functional. I would really like to do more OOP but I am > not > really sure when I need it. You virtually never * need* it. Sometimes it makes coding simler, but you can always do without. OOP is a different way of approaching programming, it requires a different way of thinking about your program structure. Thats why established programmers tend to find it much harder to adopt OOP than beginners with no prior experience! > I have the following code. Is there any way that it would benefit > from > using a class? No, the code is too short, it is comparable to a method within a class. If you are mainly writing short snippets then its likely OOP will be overkill. If you did create a class then the registry might be a candidate. You might want to build a registry object woith friendlier method names than those exposed by the module. But for something this short there is no real advantage. Remember that objects are things. If you have a thing in your program then there is a possioble lass there. The actions you perform on that thing could be methods of the class. Some OOP gurus don't like the noun/verb approach but franlly I still find it the best starting point for people who are learning OOP. Write down a description of your program in English, underline the nouns and categorise them - people, places etc. The categories are potential classes, the instances are potential objects. Now look at the verbs associated with the objects you identified. These are potential operations of the classes. If there are no operations discount the class! In your example there is a computer and a registry. But there is nothing done to the computer, it is only a parameter to the registry, so discount it. The registry object is connected and queried. So you could write: class registry: def __init__(self, computer, key=None): ... def queryKey(key=None):... But I repeat, in your case the overhead of writing all the class code is bigger than your snuippet, so is only worth while if you would be reusing the registry object, either in the same program or in others that you write. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld <code> #!/usr/bin/env python import string You probably don;t need this, string module is pretty much redundant nowadays. import _winreg import sys compName = sys.argv[1] x = _winreg.ConnectRegistry(compName,_winreg.HKEY_LOCAL_MACHINE) y = _winreg.OpenKey(x, r"SOFTWARE\Intel\LANDesk\VirusProtect6\CurrentVersion") avParent = _winreg.QueryValueEx(y,"Parent")[0] _winreg.CloseKey(y) print "Computer: %s \tAV Parent: %s" % (compName,avParent) </code> From alan.gauld at btinternet.com Mon Sep 17 20:16:43 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 17 Sep 2007 19:16:43 +0100 Subject: [Tutor] Xml reference References: <b5300ea90709170415g1caa96cev59aafa32a25416eb@mail.gmail.com> Message-ID: <fcmgb5$k1f$1@sea.gmane.org> "chinni" <srikanth007m at gmail.com> wrote > Which Book is better for python parsing and reading Xml files from > local > machine and remote machine and also through http... A lot depends on which parser you are using. David Metz "Text Processing in Python" is a good general text on parsing, including some HTML/XML. (Aldso available in draft online) Python Network Programming has more on the networking side(surprise!) via http. But neither uses ElementTree which is one of the best XML parsers and now standrad with python. The best bet there is the developers web page.(Try Google) There is also a book dedicated to python and XML but it gets very mixed reviews and I haven't even seen it in a store. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Tue Sep 18 00:37:56 2007 From: kent37 at tds.net (Kent Johnson) Date: Mon, 17 Sep 2007 18:37:56 -0400 Subject: [Tutor] When to use a class In-Reply-To: <20070917164409.GB10389@localdomain> References: <20070917164409.GB10389@localdomain> Message-ID: <46EF01C4.9030803@tds.net> Eric Lake wrote: > I am still trying to understand when to use a class and when not to. All > of the coding that I have done in the past (Python, Perl) has been > procedural / functional. I would really like to do more OOP but I am not > really sure when I need it. My take on that question is here: http://personalpages.tds.net/~kent37/stories/00014.html Kent From sxkorean at gmail.com Tue Sep 18 01:21:09 2007 From: sxkorean at gmail.com (Andrew Nelsen) Date: Mon, 17 Sep 2007 19:21:09 -0400 Subject: [Tutor] Finding all the letters in a string? Message-ID: <a783f25a0709171621u6e630d02i9ae34e5861c682d6@mail.gmail.com> I was wondering, recently, the most expedient way to take a string with [@#$%^&*] and alpha-numeric characters [ie. "^@%#*$@*$g@)$&^@&^$F"] and place all of the letters in a string or list. I thought there could be obvious ways: A) Find all the letters, put them in a list, one by one. Something like (I'm not sure yet how I'd do it...): import string list = {} string = "@*&^$&*^@$g*(&@$*(&$@c(*&*(&c^&%&^%" for x in string: if x <is in string.letters?> list = list + [x] B) Delete all the characters in the string that don't match string.letters: No idea...strip()? Thanks, Drew -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070917/e85d0c67/attachment.htm From ericlake at ubuntu.com Tue Sep 18 01:41:49 2007 From: ericlake at ubuntu.com (Eric Lake) Date: Mon, 17 Sep 2007 19:41:49 -0400 Subject: [Tutor] Finding all the letters in a string? In-Reply-To: <a783f25a0709171621u6e630d02i9ae34e5861c682d6@mail.gmail.com> References: <a783f25a0709171621u6e630d02i9ae34e5861c682d6@mail.gmail.com> Message-ID: <20070917234149.GA25992@localdomain> On Mon, Sep 17, 2007 at 07:21:09PM -0400, Andrew Nelsen wrote: > > I was wondering, recently, the most expedient way to take a string > with [@#$%^&*] and alpha-numeric characters [ie. > "^@%#*$@*$g@)$&^@&^$F"] and place all of the letters in a string or > list. I thought there could be obvious ways: > A) Find all the letters, put them in a list, one by one. Something > like (I'm not sure yet how I'd do it...): > import string > list = {} > string = "@*&^$&*^@$g*(&@$*(&$@c(*&*(&c^&%&^%" > for x in string: > if x <is in string.letters?> > list = list + [x] > B) Delete all the characters in the string that don't match > string.letters: > No idea...strip()? > Thanks, > Drew > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor This is what I came up with for the first part of the question. #!/usr/bin/env python # -*- coding: iso-8859-15 -*- import string lst = [] chars = '@*&^$&*^@$g*(&@$*(&$@c(*&*(&c^&%&^%' for x in chars: if x in string.ascii_letters: lst.append(x) for n in lst: print n, I am sure that there is probably a better way though. -- Thanks Eric Lake -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 481 bytes Desc: Digital signature Url : http://mail.python.org/pipermail/tutor/attachments/20070917/52b78a54/attachment-0001.pgp From mlangford.cs03 at gtalumni.org Tue Sep 18 01:47:00 2007 From: mlangford.cs03 at gtalumni.org (Michael Langford) Date: Mon, 17 Sep 2007 19:47:00 -0400 Subject: [Tutor] Finding all the letters in a string? In-Reply-To: <a783f25a0709171621u6e630d02i9ae34e5861c682d6@mail.gmail.com> References: <a783f25a0709171621u6e630d02i9ae34e5861c682d6@mail.gmail.com> Message-ID: <82b4f5810709171647i67ea1cadue5dfd011b0b1c858@mail.gmail.com> At first I totally misread this.... To get the set of letters, use import string string.ascii_letters Then do what you said in your algorithm. A shorthand way to do that is filteredString = ''.join([c for c in foo if c in string.ascii_letters]) -- Michael Langford Phone: 404-386-0495 Consulting: http://www.TierOneDesign.com/ Entertaining: http://www.ThisIsYourCruiseDirectorSpeaking.com On 9/17/07, Andrew Nelsen <sxkorean at gmail.com> wrote: > > I was wondering, recently, the most expedient way to take a string with > [@#$%^&*] and alpha-numeric characters [ie. "^@%#*$@*$g@)$&^@&^$F"] and > place all of the letters in a string or list. I thought there could be > obvious ways: > > A) Find all the letters, put them in a list, one by one. Something like > (I'm not sure yet how I'd do it...): > > import string > list = {} > string = "@*&^$&*^@$g*(&@$*(&$@c(*&*(&c^&%&^%" > for x in string: > if x <is in string.letters?> > list = list + [x] > > B) Delete all the characters in the string that don't match string.letters > : > > No idea...strip()? > > Thanks, > > Drew > > _______________________________________________ > 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/20070917/72a4092e/attachment.htm From mlangford.cs03 at gtalumni.org Tue Sep 18 01:48:56 2007 From: mlangford.cs03 at gtalumni.org (Michael Langford) Date: Mon, 17 Sep 2007 19:48:56 -0400 Subject: [Tutor] Finding all the letters in a string? In-Reply-To: <82b4f5810709171647i67ea1cadue5dfd011b0b1c858@mail.gmail.com> References: <a783f25a0709171621u6e630d02i9ae34e5861c682d6@mail.gmail.com> <82b4f5810709171647i67ea1cadue5dfd011b0b1c858@mail.gmail.com> Message-ID: <82b4f5810709171648p71802e14l32d9efc632fa6450@mail.gmail.com> Not my night...the second sentence "To get the set of letters, use" should read "To get the filtered string".....time for more Coke Zero. --Michael -- Michael Langford Phone: 404-386-0495 Consulting: http://www.TierOneDesign.com/ Entertaining: http://www.ThisIsYourCruiseDirectorSpeaking.com On 9/17/07, Michael Langford <mlangford.cs03 at gtalumni.org> wrote: > > At first I totally misread this.... > > To get the set of letters, use > > import string > string.ascii_letters > > Then do what you said in your algorithm. > > A shorthand way to do that is > > filteredString = ''.join([c for c in foo if c in string.ascii_letters]) > > -- > Michael Langford > Phone: 404-386-0495 > Consulting: http://www.TierOneDesign.com/ > Entertaining: http://www.ThisIsYourCruiseDirectorSpeaking.com > > On 9/17/07, Andrew Nelsen <sxkorean at gmail.com> wrote: > > > > I was wondering, recently, the most expedient way to take a string with > > [@#$%^&*] and alpha-numeric characters [ie. "^@%#*$@*$g@)$&^@&^$F"] and > > place all of the letters in a string or list. I thought there could be > > obvious ways: > > > > A) Find all the letters, put them in a list, one by one. Something like > > (I'm not sure yet how I'd do it...): > > > > import string > > list = {} > > string = "@*&^$&*^@$g*(&@$*(&$@c(*&*(&c^&%&^%" > > for x in string: > > if x <is in string.letters?> > > list = list + [x] > > > > B) Delete all the characters in the string that don't match > > string.letters: > > > > No idea...strip()? > > > > Thanks, > > > > Drew > > > > _______________________________________________ > > 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/20070917/eefabf44/attachment.htm From ericlake at ubuntu.com Tue Sep 18 02:12:44 2007 From: ericlake at ubuntu.com (Eric Lake) Date: Mon, 17 Sep 2007 20:12:44 -0400 Subject: [Tutor] Finding all the letters in a string? In-Reply-To: <82b4f5810709171648p71802e14l32d9efc632fa6450@mail.gmail.com> References: <a783f25a0709171621u6e630d02i9ae34e5861c682d6@mail.gmail.com> <82b4f5810709171647i67ea1cadue5dfd011b0b1c858@mail.gmail.com> <82b4f5810709171648p71802e14l32d9efc632fa6450@mail.gmail.com> Message-ID: <20070918001244.GA27543@localdomain> On Mon, Sep 17, 2007 at 07:48:56PM -0400, Michael Langford wrote: > > Not my night...the second sentence "To get the set of letters, use" > should read "To get the filtered string".....time for more Coke Zero. > --Michael > On 9/17/07, Andrew Nelsen <[6] sxkorean at gmail.com> wrote: > > I was wondering, recently, the most expedient way to take a string > with [@#$%^&*] and alpha-numeric characters [ie. > "^@%#*$@*$g@)$&^@&^$F"] and place all of the letters in a string or > list. I thought there could be obvious ways: > A) Find all the letters, put them in a list, one by one. Something > like (I'm not sure yet how I'd do it...): > import string > list = {} > string = "@*&^$&*^@$g*(&@$*(&$@c(*&*(&c^&%&^%" > for x in string: > if x <is in string.letters?> > list = list + [x] > B) Delete all the characters in the string that don't match > string.letters: > No idea...strip()? > Thanks, > Drew > > _______________________________________________ I missed a part too. The original question specified alpha-numeric characters. sting.ascii.letters will only get a - z and A - Z. Would a regular expression work here with \w? -- Thanks Eric Lake -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 481 bytes Desc: Digital signature Url : http://mail.python.org/pipermail/tutor/attachments/20070917/b534a6a7/attachment.pgp From ericlake at ubuntu.com Tue Sep 18 02:20:15 2007 From: ericlake at ubuntu.com (Eric Lake) Date: Mon, 17 Sep 2007 20:20:15 -0400 Subject: [Tutor] Finding all the letters in a string? In-Reply-To: <82b4f5810709171648p71802e14l32d9efc632fa6450@mail.gmail.com> References: <a783f25a0709171621u6e630d02i9ae34e5861c682d6@mail.gmail.com> <82b4f5810709171647i67ea1cadue5dfd011b0b1c858@mail.gmail.com> <82b4f5810709171648p71802e14l32d9efc632fa6450@mail.gmail.com> Message-ID: <20070918002015.GB27543@localdomain> This seems to work to get out the alpha-numeric characters. #!/usr/bin/env python # -*- coding: iso-8859-15 -*- import re pat = re.compile('\w') lst = [] chars = '@*1&^$&*^@$g*(&@2$*(&$@c(*&3*(&c^&%4&^%' lst = pat.findall(chars) for x in lst: print x, -- Thanks Eric Lake -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 481 bytes Desc: Digital signature Url : http://mail.python.org/pipermail/tutor/attachments/20070917/e73cf93d/attachment.pgp From mlangford.cs03 at gtalumni.org Tue Sep 18 02:37:38 2007 From: mlangford.cs03 at gtalumni.org (Michael Langford) Date: Mon, 17 Sep 2007 20:37:38 -0400 Subject: [Tutor] Finding all the letters in a string? In-Reply-To: <82b4f5810709171735r7d97fa88n8df1f92751704354@mail.gmail.com> References: <a783f25a0709171621u6e630d02i9ae34e5861c682d6@mail.gmail.com> <82b4f5810709171647i67ea1cadue5dfd011b0b1c858@mail.gmail.com> <82b4f5810709171648p71802e14l32d9efc632fa6450@mail.gmail.com> <20070918002015.GB27543@localdomain> <82b4f5810709171735r7d97fa88n8df1f92751704354@mail.gmail.com> Message-ID: <82b4f5810709171737r5c6a3c9dxf8c7f08aa588ab5b@mail.gmail.com> Man...really not my night: import re def getLettersOnly( chars ) : pat = re.compile('[a-zA-Z]') return ''.join(pat.findall(chars)) if __name__ == "__main__": print getLettersOnly("afdlkjal32jro3kjlkj(*&&^%&^TUHKLJDHFKJHS(*&987") Which would produce: afdlkjaljrokjlkjTUHKLJDHFKJHS --Michael -- Michael Langford Phone: 404-386-0495 Consulting: http://www.TierOneDesign.com/ Entertaining: http://www.ThisIsYourCruiseDirectorSpeaking.com On 9/17/07, Michael Langford <mlangford.cs03 at gtalumni.org> wrote: > > The original question was asking for a list of the letters (or a string > with them). Not all the alpha-numeric characters. > > \w would leave in the numbers, which is not what he wanted. If you wanted > to base the solution off regex, then you'd need to go: > > > import re > > def getLettersOnly( chars ) : > pat = re.compile('[a-zA-Z]') > return ''.join.pat.findall(chars) > > if __name__ == "__main__": > print getLettersOnly("afdlkjal32jro3kjlkj(*&&^%&^TUHKLJDHFKJHS(*&987") > > > --Michael > > -- > Michael Langford > Phone: 404-386-0495 > Consulting: http://www.TierOneDesign.com/ > Entertaining: http://www.ThisIsYourCruiseDirectorSpeaking.com > > On 9/17/07, Eric Lake <ericlake at ubuntu.com> wrote: > > > This seems to work to get out the alpha-numeric characters. > > > > #!/usr/bin/env python > > # -*- coding: iso-8859-15 -*- > > > > import re > > > > pat = re.compile('\w') > > > > lst = [] > > > > chars = '@*1&^$&*^@$g*(&@2$*(&$@c(*&3*(&c^&%4&^%' > > > > lst = pat.findall(chars) > > for x in lst: > > print x, > > > > > > -- > > > > Thanks > > Eric Lake > > > > -----BEGIN PGP SIGNATURE----- > > Version: GnuPG v1.4.6 (GNU/Linux) > > > > iQEVAwUBRu8ZvpLZLpR+JU3MAQrcXgf9HALZxw0jcZeI1I90GO2gpj3EonMUzaag > > bNPyY6NNjai8QEv/UpnhWBsNNibZ5GsmTH419YspJvncz95eqqukjDWU2bfBX2Zv > > WZ/Mgz14W2Kjx2mYExsujGmOIahc7JNKsm8w3gtoBWrUKOBxcwOW88wgRHm/cbka > > zVehXczP4tDyOf9rjQ04nxHVxIxV5J5IisLyXwIOZXbsOtdOAsMbuow41VJy8JFZ > > 593+Ngav2a/RFjglkohwJTw9nj4sUzcU8VkDAuzdf5eoOXdAKuCLdk0dyp2CJ09w > > o4dXZ/qQb/cgvctsshad2+78f7bZyTbyub2qxM79NHiCgBZeh1ZdHg== > > =oa8G > > -----END PGP SIGNATURE----- > > > > _______________________________________________ > > 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/20070917/b3cadb8b/attachment.htm From john at fouhy.net Tue Sep 18 02:43:24 2007 From: john at fouhy.net (John Fouhy) Date: Tue, 18 Sep 2007 12:43:24 +1200 Subject: [Tutor] Finding all the letters in a string? In-Reply-To: <a783f25a0709171621u6e630d02i9ae34e5861c682d6@mail.gmail.com> References: <a783f25a0709171621u6e630d02i9ae34e5861c682d6@mail.gmail.com> Message-ID: <5e58f2e40709171743g6fbb139ata8e4152a7a2041b3@mail.gmail.com> On 18/09/2007, Andrew Nelsen <sxkorean at gmail.com> wrote: > I was wondering, recently, the most expedient way to take a string with > [@#$%^&*] and alpha-numeric characters [ie. "^@%#*$@*$g@)$&^@&^$F"] and > place all of the letters in a string or list. I thought there could be > obvious ways: > > A) Find all the letters, put them in a list, one by one. Something like (I'm > not sure yet how I'd do it...): > > import string > list = {} > string = "@*&^$&*^@$g*(&@$*(&$@c(*&*(&c^&%&^%" > for x in string: > if x <is in string.letters?> > list = list + [x] Hi Andrew, First up, you should not reuse the name 'string' like that. It will lead to problems :-) You could do this: import string keepChars = string.letters + string.digits inStr = "@*&^$&*^@$g*(&@$*(&$@c(*&*(&c^&%&^%" lst = [c for c in inStr if c in keepChars] outStr = ''.join(lst) -- John. From kent37 at tds.net Tue Sep 18 03:26:56 2007 From: kent37 at tds.net (Kent Johnson) Date: Mon, 17 Sep 2007 21:26:56 -0400 Subject: [Tutor] Finding all the letters in a string? In-Reply-To: <a783f25a0709171621u6e630d02i9ae34e5861c682d6@mail.gmail.com> References: <a783f25a0709171621u6e630d02i9ae34e5861c682d6@mail.gmail.com> Message-ID: <46EF2960.4070909@tds.net> Andrew Nelsen wrote: > I was wondering, recently, the most expedient way to take a string with > [@#$%^&*] and alpha-numeric characters [ie. "^@%#*$@*$g@)$&^@&^$F"] and > place all of the letters in a string or list. Another way to do this is to use str.translate(). This method is likely faster than the other approaches though it is more obscure and the speed difference won't matter for small strings. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/59857 Kent From rabidpoobear at gmail.com Tue Sep 18 03:39:29 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Mon, 17 Sep 2007 20:39:29 -0500 Subject: [Tutor] Finding all the letters in a string? In-Reply-To: <5e58f2e40709171743g6fbb139ata8e4152a7a2041b3@mail.gmail.com> References: <a783f25a0709171621u6e630d02i9ae34e5861c682d6@mail.gmail.com> <5e58f2e40709171743g6fbb139ata8e4152a7a2041b3@mail.gmail.com> Message-ID: <46EF2C51.9010101@gmail.com> John Fouhy wrote: > On 18/09/2007, Andrew Nelsen <sxkorean at gmail.com> wrote: > >> I was wondering, recently, the most expedient way to take a string with >> [@#$%^&*] and alpha-numeric characters [ie. "^@%#*$@*$g@)$&^@&^$F"] and >> place all of the letters in a string or list. I thought there could be >> obvious ways: >> >> A) Find all the letters, put them in a list, one by one. Something like (I'm >> not sure yet how I'd do it...): >> >> import string >> list = {} >> string = "@*&^$&*^@$g*(&@$*(&$@c(*&*(&c^&%&^%" >> for x in string: >> if x <is in string.letters?> >> list = list + [x] >> > > Hi Andrew, > > First up, you should not reuse the name 'string' like that. It will > lead to problems :-) > > You could do this: > > import string > keepChars = string.letters + string.digits > > inStr = "@*&^$&*^@$g*(&@$*(&$@c(*&*(&c^&%&^%" > lst = [c for c in inStr if c in keepChars] > outStr = ''.join(lst) > Remember how people are always saying "don't use the string module unless necessary because string objects have most of the functionality built-in now" This is another case of that. teststr = "afdlkjal32jro3kjlkj(*&&^%&^TUHKLJDHFKJHS(*&987" print ''.join([item for item in teststr if item.isalnum()]) No imports required, may be an abuse of isalnum since (I assume) this is generally intended for use on whole strings and not on single-character strings, but either way, it works. Also note isalpha() and isdigit() for checking specific items in a string. -Luke From varsha.purohit at gmail.com Tue Sep 18 04:06:47 2007 From: varsha.purohit at gmail.com (Varsha Purohit) Date: Mon, 17 Sep 2007 19:06:47 -0700 Subject: [Tutor] [tutor] Reading/Writing Ascii text file Message-ID: <c2157c790709171906i34cb546ah68ac3333bec58f8d@mail.gmail.com> Hello friends, I wanted a link or tutorial to help me understand how to read or write ascii text file in python. with and without using Numpy. If you have any example that would also help me understand better. thanks, Varsha Purohit, Graduate Student -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070917/e65ebb22/attachment.htm From sxkorean at gmail.com Tue Sep 18 05:42:37 2007 From: sxkorean at gmail.com (Andrew Nelsen) Date: Mon, 17 Sep 2007 23:42:37 -0400 Subject: [Tutor] Finding all the letters in a string? In-Reply-To: <46EF2C51.9010101@gmail.com> References: <a783f25a0709171621u6e630d02i9ae34e5861c682d6@mail.gmail.com> <5e58f2e40709171743g6fbb139ata8e4152a7a2041b3@mail.gmail.com> <46EF2C51.9010101@gmail.com> Message-ID: <a783f25a0709172042v1ada165eu1821256f11075606@mail.gmail.com> Thanks, everyone, for your help. It was a pretty narrow question because it's a pretty specific task, but only because I was guessing there was more than one way of shelling an acorn. My original idea was something a lot like: lst = [] chars = '@*&^$&*^@$g*(&@$*(&$@c(*&*(&c^&%&^%' for x in chars: if x in string.ascii_letters lst.append(x) But I was guessing there was an easier way (There was.). I'm actually working through this one site called http://www.pythonchallenge.com. Seems like a nifty way to learn a little more python. Thanks, Drew -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070917/fa47458a/attachment.htm From cspears2002 at yahoo.com Tue Sep 18 07:10:05 2007 From: cspears2002 at yahoo.com (Christopher Spears) Date: Mon, 17 Sep 2007 22:10:05 -0700 (PDT) Subject: [Tutor] catching errors in calculator script Message-ID: <15243.84421.qm@web51607.mail.re2.yahoo.com> I wrote a simple calculator script: #!/usr/bin/python env def calculator(n1, operator, n2): f1 = float(n1) f2 = float(n2) if operator == '+': return f1 + f2 elif operator == '-': return f1 - f2 elif operator == '*': return f1 * f2 elif operator == '/': return f1 / f2 elif operator == '%': return f1 % f2 elif operator == '**': return f1 ** f2 else: print "Can't perform operation: %s" % operator print "Welcome to the calculator!" print "Performs float operations" print "Enter your problem like so: 5 * 3" op = raw_input(">>> ") op_list = op.split() print calculator(op_list[0], op_list[1], op_list[2]) How do I handle an error that is caused when a character other than a number is given to the calculator as one of the operands? For example, if the letter 'g' is given to the calculator the following happens: io at io-station-1 ./chap5 134> python calculator.py Welcome to the calculator! Performs float operations Enter your problem like so: 5 * 3 >>> g * h Traceback (most recent call last): File "calculator.py", line 26, in ? print calculator(op_list[0], op_list[1], op_list[2]) File "calculator.py", line 4, in calculator f1 = float(n1) ValueError: invalid literal for float(): g "I'm the last person to pretend that I'm a radio. I'd rather go out and be a color television set." -David Bowie "Who dares wins" -British military motto "I generally know what I'm doing." -Buster Keaton From alan.gauld at btinternet.com Tue Sep 18 09:38:49 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 18 Sep 2007 08:38:49 +0100 Subject: [Tutor] [tutor] Reading/Writing Ascii text file References: <c2157c790709171906i34cb546ah68ac3333bec58f8d@mail.gmail.com> Message-ID: <fcnvb3$o8u$1@sea.gmane.org> "Varsha Purohit" <varsha.purohit at gmail.com> wrote > I wanted a link or tutorial to help me understand how to read > or write > ascii text file in python. with and without using Numpy. If you have > any > example that would also help me understand better. Almost any tutorial will show you how to read/write an ascii file. Numpy is fairly irrelevant, you just need to convert the data into a strong before writing (or from a string when reading). Look at the beginners pages on python.org for a list of tutorials. Or just go to the Handling Files topic in mine... -- 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 Sep 18 09:50:59 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 18 Sep 2007 08:50:59 +0100 Subject: [Tutor] catching errors in calculator script References: <15243.84421.qm@web51607.mail.re2.yahoo.com> Message-ID: <fco01t$qbh$1@sea.gmane.org> "Christopher Spears" <cspears2002 at yahoo.com> wrote >I wrote a simple calculator script: > > #!/usr/bin/python env > > def calculator(n1, operator, n2): > f1 = float(n1) > f2 = float(n2) You probably shouldn't do this since it forces all your results to be floats even if the two arguments are integers. Its better to get the client of the function to decide whjat typres they want to use and let the function depend on duck typing to work. > if operator == '+': > return f1 + f2 ...etc > else: > print "Can't perform operation: %s" % operator You could raise an OperatorError exception here instead of printing which would make the code more reusable (eg in a GUI). You would have to define the exception of course, but thats easy: class OperatorError(Exception): pass > > op = raw_input(">>> ") > op_list = op.split() This is the best place to convert the data and catch any errors > print calculator(op_list[0], op_list[1], op_list[2]) > File "calculator.py", line 4, in calculator > f1 = float(n1) > ValueError: invalid literal for float(): g And the type of error to catch is a ValueError. So just wrap the call to calculator (or your convertions) in a try/except try: print calculator( float(op_list[0]), op_list{1], op_list[2]) except ValueError: print "invalid values, try again' except OperatorError: print 'invalid operator, try again' Take a look at my tutorial topic on handling errors for 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 Tue Sep 18 10:04:02 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 18 Sep 2007 09:04:02 +0100 Subject: [Tutor] Finding all the letters in a string? References: <a783f25a0709171621u6e630d02i9ae34e5861c682d6@mail.gmail.com> Message-ID: <fco0qc$sl6$1@sea.gmane.org> "Andrew Nelsen" <sxkorean at gmail.com> wrote >I was wondering, recently, the most expedient way to take a string >with > [@#$%^&*] and alpha-numeric characters [ie. "^@%#*$@*$g@)$&^@&^$F"] > and > place all of the letters in a string or list. I thought there could > be > obvious ways: The most obvious way is to use the filter() function newstr = filter(lambda c: c.isalpha(), oldstr) filter filters outs values from a sequence that match the given operation. or using list comprehensions: newstr = ''.join([c for c in oldstr if c.isalpha()]) BTW, I know this wasn't real code but... > import string you shouldn't use the string module now, string objects make it nearly redundant > list = {} this defines a dictionary not a list. and the world list is a bui8lt in function, if you use it as a name you will not be able to convert things to lists! > string = "@*&^$&*^@$g*(&@$*(&$@c(*&*(&c^&%&^%" string is the name of the module you imported, if you use a name thats already in use you will hide that name, in this case you wouldn't be able to use the string module! > for x in string: > if x <is in string.letters?> > list = list + [x] This would almost work, except the append() method would probably be better than list addition. In fact its almost exactly what my list comprehension does above. > B) Delete all the characters in the string that don't match > string.letters: > > No idea...strip()? del() for a list, but you can't modify strings in place so youd need to convert to a list and then back again. The first method is better. 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 Tue Sep 18 10:08:38 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 18 Sep 2007 09:08:38 +0100 Subject: [Tutor] Finding all the letters in a string? References: <a783f25a0709171621u6e630d02i9ae34e5861c682d6@mail.gmail.com><5e58f2e40709171743g6fbb139ata8e4152a7a2041b3@mail.gmail.com><46EF2C51.9010101@gmail.com> <a783f25a0709172042v1ada165eu1821256f11075606@mail.gmail.com> Message-ID: <fco12v$tjt$1@sea.gmane.org> "Andrew Nelsen" <sxkorean at gmail.com> wrote > But I was guessing there was an easier way (There was.). I'm > actually > working through this one site called http://www.pythonchallenge.com. > Seems > like a nifty way to learn a little more python. If you are doing the challenge then take a look at the translate technique that Kent mentioned! It might ccome in handy later... Alan G. From kent37 at tds.net Tue Sep 18 12:45:59 2007 From: kent37 at tds.net (Kent Johnson) Date: Tue, 18 Sep 2007 06:45:59 -0400 Subject: [Tutor] Finding all the letters in a string? In-Reply-To: <46EF2C51.9010101@gmail.com> References: <a783f25a0709171621u6e630d02i9ae34e5861c682d6@mail.gmail.com> <5e58f2e40709171743g6fbb139ata8e4152a7a2041b3@mail.gmail.com> <46EF2C51.9010101@gmail.com> Message-ID: <46EFAC67.2060201@tds.net> Luke Paireepinart wrote: > Remember how people are always saying "don't use the string module > unless necessary because string objects have most of the functionality > built-in now" > This is another case of that. I think this advice is being a little overstated in this thread. The string module itself is not deprecated. Many functions in the string module are also available as methods of a string. These functions are deprecated. You can see a list here: http://docs.python.org/lib/node42.html There is nothing wrong with using the constants defined in the string module such as string.ascii_letters. Template strings (http://docs.python.org/lib/node40.html) were actually *added* to the string module in Python 2.4. capwords() and maketrans() are available only in the string module, not available as string methods. Kent From eike.welk at gmx.net Tue Sep 18 16:12:04 2007 From: eike.welk at gmx.net (Eike Welk) Date: Tue, 18 Sep 2007 16:12:04 +0200 Subject: [Tutor] [tutor] Reading/Writing Ascii text file In-Reply-To: <c2157c790709171906i34cb546ah68ac3333bec58f8d@mail.gmail.com> References: <c2157c790709171906i34cb546ah68ac3333bec58f8d@mail.gmail.com> Message-ID: <200709181612.05450.eike.welk@gmx.net> On Tuesday 18 September 2007 04:06, Varsha Purohit wrote: > I wanted a link or tutorial to help me understand how to read > or write ascii text file in python. with and without using Numpy. If you want to save a Numpy array as a text file, goto this web-page: http://www.scipy.org/Numpy_Example_List_With_Doc Look at: savetxt(); tofile() loadtxt(); fromfile() If you also have Scipy and Matplotlib there are even more ways to save arrays as text files: http://www.scipy.org/Cookbook/InputOutput Regards, Eike. From sanelson at gmail.com Wed Sep 19 02:09:36 2007 From: sanelson at gmail.com (Stephen Nelson-Smith) Date: Wed, 19 Sep 2007 01:09:36 +0100 Subject: [Tutor] [Slightly OT] Inheritance, Polymorphism and Encapsulation Message-ID: <b6131fdc0709181709wd6fd135i65c1dc92ff9cd711@mail.gmail.com> Hello friends, Over lunch today some colleagues discussed a question they are using as a conversation starter in some preliminary chats in our developer hiring process. The question was: "Place the following three in order: Inheritance, Polymorphism, Encapsulation." They specifically did not define in *what* order, leaving that for the answerer to decide. I responded thus: Encapsulation comes with OO - you get it for free. Polymorphism is a hugely important enabler, but this in itself is enabled by Inheritance, so I put them in this order: Inheritance, Polymorphism, Encapsulation. My colleagues felt that of the three options this was the least satisfactory, and showed a lack of understanding of OO design. One even suggested that one could have polymorphism without inheritance. I'm curious as to your opinions - answer to the question, responses to my answer, and to the feedback from my colleagues. Thanks! S. From emadnawfal at gmail.com Wed Sep 19 02:23:57 2007 From: emadnawfal at gmail.com (Emad Nawfal) Date: Tue, 18 Sep 2007 19:23:57 -0500 Subject: [Tutor] unicode problem Message-ID: <652641e90709181723m44824651h877d492ad706c42d@mail.gmail.com> *Hi All Tutors,* *I'm new and I'm trying to use unicode strings in my code (specifically Arabic), but I get this:* IDLE 1.2.1 >>> text = ur'????????' Unsupported characters in input >>> for letter in text: print letter Traceback (most recent call last): File "<pyshell#4>", line 1, in <module> for letter in text: NameError: name 'text' is not defined >>> u = u'????????' Unsupported characters in input >>> s = u'????????'.encode('utf-8') Unsupported characters in input *Can anyone please tell me how to use Arabic in my code? * -- ?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? ????????.....???? ??????? Emad Soliman Nawfal Indiana University, Bloomington http://emadnawfal.googlepages.com -------------------------------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070918/dbaba6b1/attachment.htm From witham.ian at gmail.com Wed Sep 19 02:46:53 2007 From: witham.ian at gmail.com (Ian Witham) Date: Wed, 19 Sep 2007 12:46:53 +1200 Subject: [Tutor] [Slightly OT] Inheritance, Polymorphism and Encapsulation In-Reply-To: <b6131fdc0709181709wd6fd135i65c1dc92ff9cd711@mail.gmail.com> References: <b6131fdc0709181709wd6fd135i65c1dc92ff9cd711@mail.gmail.com> Message-ID: <a04dbf4b0709181746j56129c0ds44bf1acd94abfa42@mail.gmail.com> On 9/19/07, Stephen Nelson-Smith <sanelson at gmail.com> wrote: > > > "Place the following three in order: Inheritance, Polymorphism, > Encapsulation." > > They specifically did not define in *what* order, leaving that for > the answerer to decide. > I would place them in alphabetical order. BTW, there are 6 possible orders, not 3. Ian. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070919/b9bb30ad/attachment.htm From ricaraoz at gmail.com Wed Sep 19 02:51:17 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Tue, 18 Sep 2007 21:51:17 -0300 Subject: [Tutor] [Slightly OT] Inheritance, Polymorphism and Encapsulation In-Reply-To: <b6131fdc0709181709wd6fd135i65c1dc92ff9cd711@mail.gmail.com> References: <b6131fdc0709181709wd6fd135i65c1dc92ff9cd711@mail.gmail.com> Message-ID: <46F07285.9040407@bigfoot.com> Stephen Nelson-Smith wrote: > Hello friends, > > Over lunch today some colleagues discussed a question they are using > as a conversation starter in some preliminary chats in our developer > hiring process. > > The question was: > > "Place the following three in order: Inheritance, Polymorphism, Encapsulation." > > They specifically did not define in *what* order, leaving that for > the answerer to decide. > > I responded thus: > > Encapsulation comes with OO - you get it for free. Encapsulation does not come with OO. It is something you must code in your classes. > Polymorphism is a > hugely important enabler, but this in itself is enabled by > Inheritance, so I put them in this order: Inheritance, Polymorphism, > Encapsulation. > > My colleagues felt that of the three options this was the least > satisfactory, and showed a lack of understanding of OO design. One > even suggested that one could have polymorphism without inheritance. > IMHO you can have polymorphism without inheritance. Why shouldn't you? It does NOT depend on inheritance I guess you could say it depends on namespaces defined by the classes, but not inheritance. From mlangford.cs03 at gtalumni.org Wed Sep 19 03:26:45 2007 From: mlangford.cs03 at gtalumni.org (Michael Langford) Date: Tue, 18 Sep 2007 21:26:45 -0400 Subject: [Tutor] [Slightly OT] Inheritance, Polymorphism and Encapsulation In-Reply-To: <82b4f5810709181824p5875cb4bpdaf021cc21a35353@mail.gmail.com> References: <b6131fdc0709181709wd6fd135i65c1dc92ff9cd711@mail.gmail.com> <46F07285.9040407@bigfoot.com> <82b4f5810709181824p5875cb4bpdaf021cc21a35353@mail.gmail.com> Message-ID: <82b4f5810709181826l734f1870nb5748b4c35ca41e9@mail.gmail.com> > "Place the following three in order: Inheritance, Polymorphism, Encapsulation." Inheritance: Syntactic sugar that's not really needed to make a well organized system. Often overused, especially by programmers in big companies, beginning students of programmers, green engineers, and professors. In practice hides a lot of data, often making behavior surprising, therefore harder to maintain. Can be used in limited situations to great advantage, but like cologne on car salesmen, is used in greater amounts than it should be. One should always ask, can I make a simpler system with composition. Polymorphism: The process of creating many classes which a single interface which are then all used by an object that doesn't know or need to know the type. Many people think you only get this by using inheritance and therefore use inheritance many places a simpler, less opaque, more lightweight solution will work. Most dynamically typed languages (most notably, python, ruby and smalltalk) don't even require you specify the interface explicitly to get polymorphic behavior. C++ templates can do non-explicit interface polymorphism, however in a more complicated, blindingly fast to run, blindingly slow to compile way. Encapsulation: The process of taking what shouldn't matter to the external world, and locking it behind an interface. This principle works best when put into small, specialized libraries and designed for general use, as this is the only encapsulated form that is shown to last over time. Supposedly something OO based design allows, but in reality, the coupling among classes varies in differing amounts. The module/public visibility of Java is a good compromise with classes that hides some data but share some with certain other classes. C++ has large issues for historical reasons on this front, as the implementation section of a class is largely revealed through the class definition. --Michael -- Michael Langford Phone: 404-386-0495 Consulting: http://www.TierOneDesign.com/ Entertaining: http://www.ThisIsYourCruiseDirectorSpeaking.com On 9/18/07, Ricardo Ar?oz <ricaraoz at gmail.com> wrote: > > Stephen Nelson-Smith wrote: > > Hello friends, > > > > Over lunch today some colleagues discussed a question they are using > > as a conversation starter in some preliminary chats in our developer > > hiring process. > > > > The question was: > > > > "Place the following three in order: Inheritance, Polymorphism, > Encapsulation." > > > > They specifically did not define in *what* order, leaving that for > > the answerer to decide. > > > > I responded thus: > > > > Encapsulation comes with OO - you get it for free. > > Encapsulation does not come with OO. It is something you must code in > your classes. > > > Polymorphism is a > > hugely important enabler, but this in itself is enabled by > > Inheritance, so I put them in this order: Inheritance, Polymorphism, > > Encapsulation. > > > > My colleagues felt that of the three options this was the least > > satisfactory, and showed a lack of understanding of OO design. One > > even suggested that one could have polymorphism without inheritance. > > > > IMHO you can have polymorphism without inheritance. Why shouldn't you? > It does NOT depend on inheritance I guess you could say it depends on > namespaces defined by the classes, but not inheritance. > _______________________________________________ > 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/20070918/46d00d30/attachment-0001.htm From cspears2002 at yahoo.com Wed Sep 19 03:28:35 2007 From: cspears2002 at yahoo.com (Christopher Spears) Date: Tue, 18 Sep 2007 18:28:35 -0700 (PDT) Subject: [Tutor] sales tax Message-ID: <777228.35831.qm@web51603.mail.re2.yahoo.com> I wrote a script that takes a price and a sales tax and calculates the new price. #!/usr/bin/env python def calculate_price(price, percent_tax): sales_tax = price * percent_tax new_price = price + sales_tax return new_price price = float(raw_input("Enter a price: ")) percent_tax = float(raw_input("Enter a sales tax: ")) print "%.2f" % calculate_price(price, percent_tax) Here is the script in action: io at io-station-1 ./chap5 173> python sales_tax.py Enter a price: 10.00 Enter a sales tax: .0825 10.82 I'm not convinced that the new price is completely accurate because the price without the string formating is 10.825 io at io-station-1 ./chap5 164> python sales_tax.py Enter a price: 10 Enter a sales tax: .0825 10.825000 Wouldn't the price be rounded up to 10.83 in the real world? How can I accomplish this? From mlangford.cs03 at gtalumni.org Wed Sep 19 03:34:29 2007 From: mlangford.cs03 at gtalumni.org (Michael Langford) Date: Tue, 18 Sep 2007 21:34:29 -0400 Subject: [Tutor] sales tax In-Reply-To: <777228.35831.qm@web51603.mail.re2.yahoo.com> References: <777228.35831.qm@web51603.mail.re2.yahoo.com> Message-ID: <82b4f5810709181834i31dba1dy5a1c59d42a73ec36@mail.gmail.com> This function can easily found using the google programming rule: I want a function that does 'action' Type: <Name of programming language> <action> into google Look in top 5 results. If that doesn't work, try synonyms for 'action' --Michael PS: The function you're looking for is called round. Its first param is the number to round, the seconds is how many digits past the radix point to keep. -- Michael Langford Phone: 404-386-0495 Consulting: http://www.TierOneDesign.com/ Entertaining: http://www.ThisIsYourCruiseDirectorSpeaking.com On 9/18/07, Christopher Spears <cspears2002 at yahoo.com> wrote: > > I wrote a script that takes a price and a sales tax > and calculates the new price. > > #!/usr/bin/env python > > def calculate_price(price, percent_tax): > sales_tax = price * percent_tax > new_price = price + sales_tax > return new_price > > price = float(raw_input("Enter a price: ")) > percent_tax = float(raw_input("Enter a sales tax: ")) > print "%.2f" % calculate_price(price, percent_tax) > > Here is the script in action: > io at io-station-1 ./chap5 173> python sales_tax.py > Enter a price: 10.00 > Enter a sales tax: .0825 > 10.82 > > I'm not convinced that the new price is completely > accurate because the price without the string > formating is 10.825 > > io at io-station-1 ./chap5 164> python sales_tax.py > Enter a price: 10 > Enter a sales tax: .0825 > 10.825000 > > Wouldn't the price be rounded up to 10.83 in the real > world? How can I accomplish this? > _______________________________________________ > 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/20070918/08bb3c3b/attachment.htm From orsenthil at gmail.com Wed Sep 19 03:55:52 2007 From: orsenthil at gmail.com (O.R.Senthil Kumaran) Date: Wed, 19 Sep 2007 07:25:52 +0530 Subject: [Tutor] class awareness of variable name In-Reply-To: <fcmf1s$f0i$1@sea.gmane.org> References: <F353DB6F-8EEC-4F62-A303-43AB7ADC3A31@abrahamsen.com> <fcmf1s$f0i$1@sea.gmane.org> Message-ID: <20070919015552.GB3410@gmail.com> * Alan Gauld <alan.gauld at btinternet.com> [2007-09-17 18:54:43]: > If you go with the flow rather than trying to make the flow > go the way you want life is easier. Insightful. QOTW. :-) -- O.R.Senthil Kumaran http://uthcode.sarovar.org From kent37 at tds.net Wed Sep 19 04:41:41 2007 From: kent37 at tds.net (Kent Johnson) Date: Tue, 18 Sep 2007 22:41:41 -0400 Subject: [Tutor] unicode problem In-Reply-To: <652641e90709181723m44824651h877d492ad706c42d@mail.gmail.com> References: <652641e90709181723m44824651h877d492ad706c42d@mail.gmail.com> Message-ID: <46F08C65.80700@tds.net> Emad Nawfal wrote: > *Hi All Tutors,* > *I'm new and I'm trying to use unicode strings in my code (specifically > Arabic), but I get this:* > > IDLE 1.2.1 >>>> text = ur'????????' > Unsupported characters in input This seems to be a problem with IDLE rather than Python itself. This message: http://www.thescripts.com/forum/thread543035.html suggests editing one of the IDLE files to make it support unicode. Alternately you might want to use the plain Python interpreter and a text editor that supports arabic. Kent From witham.ian at gmail.com Wed Sep 19 05:39:58 2007 From: witham.ian at gmail.com (Ian Witham) Date: Wed, 19 Sep 2007 15:39:58 +1200 Subject: [Tutor] sales tax In-Reply-To: <777228.35831.qm@web51603.mail.re2.yahoo.com> References: <777228.35831.qm@web51603.mail.re2.yahoo.com> Message-ID: <a04dbf4b0709182039r6246565du12344784d884f279@mail.gmail.com> As Michael points out, you need to explicitly use the round function, as the float formatting merely truncates anything after the second decimal place. I ran across a similar problem with the int() fuction early on. Anything after the decimal point is truncated, not rounded, leading to behavior I was not expecting. For example: int(-1.5) == -1 int(-.5) == 0 int(.5) == 0 int(1.5) == 1 Ian On 9/19/07, Christopher Spears <cspears2002 at yahoo.com> wrote: > > I wrote a script that takes a price and a sales tax > and calculates the new price. > > #!/usr/bin/env python > > def calculate_price(price, percent_tax): > sales_tax = price * percent_tax > new_price = price + sales_tax > return new_price > > price = float(raw_input("Enter a price: ")) > percent_tax = float(raw_input("Enter a sales tax: ")) > print "%.2f" % calculate_price(price, percent_tax) > > Here is the script in action: > io at io-station-1 ./chap5 173> python sales_tax.py > Enter a price: 10.00 > Enter a sales tax: .0825 > 10.82 > > I'm not convinced that the new price is completely > accurate because the price without the string > formating is 10.825 > > io at io-station-1 ./chap5 164> python sales_tax.py > Enter a price: 10 > Enter a sales tax: .0825 > 10.825000 > > Wouldn't the price be rounded up to 10.83 in the real > world? How can I accomplish this? > _______________________________________________ > 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/20070919/8ab0b1ab/attachment.htm From mlangford.cs03 at gtalumni.org Wed Sep 19 05:58:14 2007 From: mlangford.cs03 at gtalumni.org (Michael Langford) Date: Tue, 18 Sep 2007 23:58:14 -0400 Subject: [Tutor] sales tax In-Reply-To: <a04dbf4b0709182039r6246565du12344784d884f279@mail.gmail.com> References: <777228.35831.qm@web51603.mail.re2.yahoo.com> <a04dbf4b0709182039r6246565du12344784d884f279@mail.gmail.com> Message-ID: <82b4f5810709182058r28080a59tba6e0e1fd27a850c@mail.gmail.com> There is definitely a secondary understanding of math that comes from working on computers. How computers do math is quite a bit different from how you or I do it on a piece of paper. The fact that python can do arbitrary large integer arithmetic makes it quite nice for many math applications as you don't have to deal with some of the issues of other languages. Floating point numbers are different than anything you may have encountered out of computing. Their nuances are fully detailed in the wonderful "What every computer scientist should know about floating point": http://docs.sun.com/source/806-3568/ncg_goldberg.html However, the paper is a little long and quite obtuse, even though it goes through everything from a mathematical perspective. Don't feel like you need to understand it, but when you DO need to understand the true issues with floating point, that will be your guide. There is also great advantage in learning how to do fixed point calculations, especially in python, with its awesome integer type. This is especially the case for times when you need very accurate addition and subtraction, such as with large quantities of money. http://fixedpoint.sourceforge.net/ is a project that implements it. I don't seem to see fixed point numbers in the python standard libraries, but then again, I'd not be surprised if they were there. --Michael -- Michael Langford Phone: 404-386-0495 Consulting: http://www.TierOneDesign.com/ Entertaining: http://www.ThisIsYourCruiseDirectorSpeaking.com On 9/18/07, Ian Witham <witham.ian at gmail.com> wrote: > > As Michael points out, you need to explicitly use the round function, as > the float formatting merely truncates anything after the second decimal > place. > > I ran across a similar problem with the int() fuction early on. Anything > after the decimal point is truncated, not rounded, leading to behavior I was > not expecting. > > For example: > > int(-1.5) == -1 > int(-.5) == 0 > int(.5) == 0 > int(1.5) == 1 > > Ian > > > On 9/19/07, Christopher Spears < cspears2002 at yahoo.com> wrote: > > > > I wrote a script that takes a price and a sales tax > > and calculates the new price. > > > > #!/usr/bin/env python > > > > def calculate_price(price, percent_tax): > > sales_tax = price * percent_tax > > new_price = price + sales_tax > > return new_price > > > > price = float(raw_input("Enter a price: ")) > > percent_tax = float(raw_input("Enter a sales tax: ")) > > print "%.2f" % calculate_price(price, percent_tax) > > > > Here is the script in action: > > io at io-station-1 ./chap5 173> python sales_tax.py > > Enter a price: 10.00 > > Enter a sales tax: .0825 > > 10.82 > > > > I'm not convinced that the new price is completely > > accurate because the price without the string > > formating is 10.825 > > > > io at io-station-1 ./chap5 164> python sales_tax.py > > Enter a price: 10 > > Enter a sales tax: .0825 > > 10.825000 > > > > Wouldn't the price be rounded up to 10.83 in the real > > world? How can I accomplish this? > > _______________________________________________ > > 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/20070918/7216643c/attachment.htm From sanelson at gmail.com Wed Sep 19 07:51:11 2007 From: sanelson at gmail.com (Stephen Nelson-Smith) Date: Wed, 19 Sep 2007 06:51:11 +0100 Subject: [Tutor] [Slightly OT] Inheritance, Polymorphism and Encapsulation In-Reply-To: <82b4f5810709181826l734f1870nb5748b4c35ca41e9@mail.gmail.com> References: <b6131fdc0709181709wd6fd135i65c1dc92ff9cd711@mail.gmail.com> <46F07285.9040407@bigfoot.com> <82b4f5810709181824p5875cb4bpdaf021cc21a35353@mail.gmail.com> <82b4f5810709181826l734f1870nb5748b4c35ca41e9@mail.gmail.com> Message-ID: <b6131fdc0709182251v2a13f13bv485c0aeb51071c5@mail.gmail.com> Michael Langford wrote: > Inheritance: Syntactic sugar that's not really needed to make a well > organized system. Often overused, especially by programmers in big > companies, beginning students of programmers, green engineers, and > professors. In practice hides a lot of data, often making behavior > surprising, therefore harder to maintain. Can be used in limited situations > to great advantage, but like cologne on car salesmen, is used in greater > amounts than it should be. One should always ask, can I make a simpler > system with composition. Pretty much exactly what my colleague said. Having thought about it I understand this. > Polymorphism: The process of creating many classes which a single interface > which are then all used by an object that doesn't know or need to know the > type. Many people think you only get this by using inheritance and therefore > use inheritance many places a simpler, less opaque, more lightweight > solution will work. Most dynamically typed languages (most notably, python, > ruby and smalltalk) don't even require you specify the interface explicitly > to get polymorphic behavior. C++ templates can do non-explicit interface > polymorphism, however in a more complicated, blindingly fast to run, > blindingly slow to compile way. Also what my colleague said! This is the bit I had missed. Perhaps I need to rethink / reload my understanding of polymorphism. > Encapsulation: The process of taking what shouldn't matter to the external > world, and locking it behind an interface. This principle works best when > put into small, specialized libraries and designed for general use, as this > is the only encapsulated form that is shown to last over time. Supposedly > something OO based design allows, but in reality, the coupling among classes > varies in differing amounts. The module/public visibility of Java is a good > compromise with classes that hides some data but share some with certain > other classes. C++ has large issues for historical reasons on this front, as > the implementation section of a class is largely revealed through the class > definition. Interesting. And again revealing of a weakness in my understanding. I do think this is a good question for getting a sense of where a person's understanding is. I wonder how much this understanding is a pre-requistite for being a good developer... not too much I hope! > --Michael S. From alan.gauld at btinternet.com Wed Sep 19 09:07:39 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 19 Sep 2007 08:07:39 +0100 Subject: [Tutor] [Slightly OT] Inheritance, Polymorphism and Encapsulation References: <b6131fdc0709181709wd6fd135i65c1dc92ff9cd711@mail.gmail.com> Message-ID: <fcqhsl$u7t$1@sea.gmane.org> "Stephen Nelson-Smith" <sanelson at gmail.com> wrote > "Place the following three in order: Inheritance, Polymorphism, > Encapsulation." Interesting exercise! > Encapsulation comes with OO - you get it for free. It comes with OO but not for free. It is a fundamental property of OOP languages, but not all languages are OOP and trying to write OO programs in a non OOP language will very quickly show that encapsulation requires a lot of effort! > Polymorphism is a hugely important enabler, but this in itself > is enabled by Inheritance, Polymorphism is the root of OOP. It is what distinguishes true OOP from Modular or Object Based programming. But, it does NOT depend on inheritance, you can do polymorphism on several levels and in Python we use duck typing to create polymorphism without inheritance all the time. Inheritance is an implementation convenience, it saves writing extra code but that is all. > this order: Inheritance, Polymorphism, Encapsulation. I'd go for Encapsulation, Polymorphism, Inheritance. Without encapsulation you have no objects(*). Without polymorphism you have no OOP. Inheritance is convenient. (*) I use encapsulation in its original sense of binding data and functions together in a single unit of code - an object. Not in its frequently seen, but corrupted sense, of data hiding (using private/public data declatations etc) > My colleagues felt that of the three options this was the least > satisfactory, and showed a lack of understanding of OO design. That goes a bit far, the order is fairly argbitrary, but going by your reasoning I'd disagree with your choices as explained above. > even suggested that one could have polymorphism without inheritance. Absolutely true, see the OOP topic in my tutorial for an example in Python. Indeed some OOP languages do not support inheritance but do support polymorphism - Actor is one such. 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 Sep 19 09:17:21 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 19 Sep 2007 08:17:21 +0100 Subject: [Tutor] [Slightly OT] Inheritance, Polymorphism and Encapsulation References: <b6131fdc0709181709wd6fd135i65c1dc92ff9cd711@mail.gmail.com> <46F07285.9040407@bigfoot.com> Message-ID: <fcqies$vpm$1@sea.gmane.org> "Ricardo Ar?oz" <ricaraoz at gmail.com> wrote> > Encapsulation comes with OO - you get it for free. > > Encapsulation does not come with OO. It is something you must code > in > your classes. This depends on your definition of encapsulation. Many modern texts use a definition of encapsulation that relates to data hiding. Thus, making attributes private/protected etc is called encapsulation. This definition didn't start to appear till the very late 80's with the rise of C++. In the early days of OOP encapsulation was the act of binding data and functions together in a single code entity - a class(*). The early definition was a radical new idea in the 70's and 80's but with the advent of OOP languages liker C++/Java it becomes a fundamental concept so its easy to forget how important and fundamental encapsulation of data and function into a class is. It is literally the foundation of all Object Oriented and Object Based programming. And without an OOP that kind of encapsulation is very tricky to get right. Data hiding is a nice to have. Python OOP provides the original concept of encapsulation but doesn't really support the later meaning. (*)BTW Its also possible to do OOP without classes! This is not often seen nowadays but there were several OOP languages in the 70's and 80's that explored that route. Scheme is probably the best known. Its a very different kind of OOP of course but the basic concepts are all there. 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 Wed Sep 19 09:23:25 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 19 Sep 2007 08:23:25 +0100 Subject: [Tutor] [Slightly OT] Inheritance, Polymorphism and Encapsulation References: <b6131fdc0709181709wd6fd135i65c1dc92ff9cd711@mail.gmail.com><46F07285.9040407@bigfoot.com><82b4f5810709181824p5875cb4bpdaf021cc21a35353@mail.gmail.com> <82b4f5810709181826l734f1870nb5748b4c35ca41e9@mail.gmail.com> Message-ID: <fcqiq7$114$1@sea.gmane.org> "Michael Langford" <mlangford.cs03 at gtalumni.org> wrote Good stuff on inheritance and polymorphism snipped... > Encapsulation: The process of taking what shouldn't matter to > the external world, and locking it behind an interface. Actually I'd call that Abstraction. Encapsulation literally means taking things and putting them in a container - a capsule. Or in the case of OOP a class/object. > This principle works best when put into small, specialized libraries > and designed for general use, ..... But the rest I agree with :-) -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From mlangford.cs03 at gtalumni.org Wed Sep 19 09:28:16 2007 From: mlangford.cs03 at gtalumni.org (Michael Langford) Date: Wed, 19 Sep 2007 03:28:16 -0400 Subject: [Tutor] [Slightly OT] Inheritance, Polymorphism and Encapsulation In-Reply-To: <fcqies$vpm$1@sea.gmane.org> References: <b6131fdc0709181709wd6fd135i65c1dc92ff9cd711@mail.gmail.com> <46F07285.9040407@bigfoot.com> <fcqies$vpm$1@sea.gmane.org> Message-ID: <82b4f5810709190028l26c72d0u4b40b7521985eb88@mail.gmail.com> (*)BTW Its also possible to do OOP without classes! This is not often seen nowadays but there were several OOP languages in the 70's and 80's that explored that route. Scheme is probably the best known. Its a very different kind of OOP of course but the basic concepts are all there. OOP without classes is quite common still. This is how a good portion of the Linux kernel is written (I do kernel modules/porting at my day job). As far as classes go, they're largely a syntactic method for implicitly passing a data member to the correct functions that should operate on it. You can do that in pure procedural languages like C. (Its actually a very very maintainable way to write C, some studies show that it is more maintainable than equivalent projects in C++, but that has little to do with C++'s OO features and lots to do with C++ containing not just the kitchen sink but the bathroom sink and a bidet too). --Michael -- Michael Langford Phone: 404-386-0495 Consulting: http://www.TierOneDesign.com/ Entertaining: http://www.ThisIsYourCruiseDirectorSpeaking.com On 9/19/07, Alan Gauld <alan.gauld at btinternet.com> wrote: > > "Ricardo Ar?oz" <ricaraoz at gmail.com> wrote> > > > Encapsulation comes with OO - you get it for free. > > > > Encapsulation does not come with OO. It is something you must code > > in > > your classes. > > This depends on your definition of encapsulation. > Many modern texts use a definition of encapsulation that relates > to data hiding. Thus, making attributes private/protected etc is > called > encapsulation. This definition didn't start to appear till the very > late > 80's with the rise of C++. In the early days of OOP encapsulation > was the act of binding data and functions together in a single code > entity - a class(*). > > The early definition was a radical new idea in the 70's and 80's but > with the advent of OOP languages liker C++/Java it becomes a > fundamental concept so its easy to forget how important and > fundamental encapsulation of data and function into a class is. > It is literally the foundation of all Object Oriented and Object > Based programming. And without an OOP that kind of > encapsulation is very tricky to get right. Data hiding is a nice > to have. Python OOP provides the original concept of encapsulation > but doesn't really support the later meaning. > > (*)BTW Its also possible to do OOP without classes! This is not > often seen nowadays but there were several OOP languages in > the 70's and 80's that explored that route. Scheme is probably > the best known. Its a very different kind of OOP of course but the > basic concepts are all there. > > Regards, > > > -- > 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/20070919/4f9e0535/attachment.htm From alan.gauld at btinternet.com Wed Sep 19 09:25:34 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 19 Sep 2007 08:25:34 +0100 Subject: [Tutor] [Slightly OT] Inheritance, Polymorphism and Encapsulation References: <b6131fdc0709181709wd6fd135i65c1dc92ff9cd711@mail.gmail.com><46F07285.9040407@bigfoot.com><82b4f5810709181824p5875cb4bpdaf021cc21a35353@mail.gmail.com><82b4f5810709181826l734f1870nb5748b4c35ca41e9@mail.gmail.com> <b6131fdc0709182251v2a13f13bv485c0aeb51071c5@mail.gmail.com> Message-ID: <fcqiu8$1e6$1@sea.gmane.org> "Stephen Nelson-Smith" <sanelson at gmail.com> wrote > I do think this is a good question for getting a sense of where a > person's understanding is. I wonder how much this understanding is > a > pre-requistite for being a good developer... not too much I hope! To use classes/objects yuou don;t need to understand the fundamentals too much. To build OO designs you need to understand much more. To build a new OOP you must understand it intimately! -- 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 Sep 19 09:32:27 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 19 Sep 2007 08:32:27 +0100 Subject: [Tutor] sales tax References: <777228.35831.qm@web51603.mail.re2.yahoo.com> Message-ID: <fcqjb5$2jc$1@sea.gmane.org> "Christopher Spears" <cspears2002 at yahoo.com> wrote > def calculate_price(price, percent_tax): > sales_tax = price * percent_tax > new_price = price + sales_tax > return new_price > > price = float(raw_input("Enter a price: ")) > percent_tax = float(raw_input("Enter a sales tax: ")) > print "%.2f" % calculate_price(price, percent_tax) > > Here is the script in action: > io at io-station-1 ./chap5 173> python sales_tax.py > Enter a price: 10.00 > Enter a sales tax: .0825 > 10.82 > > I'm not convinced that the new price is completely > accurate because the price without the string > formating is 10.825 Of course, its just doing a multiply/divide. > Wouldn't the price be rounded up to 10.83 in the real > world? How can I accomplish this? Depends on the tax laws in your neck of the woods. In the UK you are not allowed to charge more than the tax so it would be rounded *down* to 10.82. But you should never use floats for financial calculations because they are inherently inaccurate. Its usually better to multiply sums up to integer values of pennies and then convert back to decimal at the point of display. Either that or use a BCD type module such as Python's decimal module. 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 Sep 19 09:37:48 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 19 Sep 2007 08:37:48 +0100 Subject: [Tutor] sales tax References: <777228.35831.qm@web51603.mail.re2.yahoo.com> <82b4f5810709181834i31dba1dy5a1c59d42a73ec36@mail.gmail.com> Message-ID: <fcqjl6$3fs$1@sea.gmane.org> "Michael Langford" <mlangford.cs03 at gtalumni.org> wrote > PS: The function you're looking for is called round. Its first param > is the > number to round, the seconds is how many digits past the radix point > to > keep. Caveat: Note that round will perform math style rounding - sometimes rounding up, sometimes rounding down. If you have legal retrictions that force rounding down, say, then round() will not work as required. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From mlangford.cs03 at gtalumni.org Wed Sep 19 09:51:35 2007 From: mlangford.cs03 at gtalumni.org (Michael Langford) Date: Wed, 19 Sep 2007 03:51:35 -0400 Subject: [Tutor] [Slightly OT] Inheritance, Polymorphism and Encapsulation In-Reply-To: <b6131fdc0709182251v2a13f13bv485c0aeb51071c5@mail.gmail.com> References: <b6131fdc0709181709wd6fd135i65c1dc92ff9cd711@mail.gmail.com> <46F07285.9040407@bigfoot.com> <82b4f5810709181824p5875cb4bpdaf021cc21a35353@mail.gmail.com> <82b4f5810709181826l734f1870nb5748b4c35ca41e9@mail.gmail.com> <b6131fdc0709182251v2a13f13bv485c0aeb51071c5@mail.gmail.com> Message-ID: <82b4f5810709190051i4a8f10e1qf29f45ec6d0d3140@mail.gmail.com> I do think this is a good question for getting a sense of where a person's understanding is. I wonder how much this understanding is a pre-requistite for being a good developer... not too much I hope! A good developer is a very loaded term. :o) There are a lot of good programmers who are bad developers. A lot of being a good developer is getting things done that work well enough to supply whomever is downstream from you at work. This goes way beyond programming, and is much more about being an effective human being than being good at programming. It also has to do with several things such as source control tools, ticket tracking tools, testing, debugging, and deployment as well. You will find yourself making more informed choices on things and debugging things a lot better the more of this technical programming stuff you pick up. A good compiler/interpreter book and a lot of experimentation will really open your eyes on a lot of this, as will just doing your job while constantly reading reading reading about what you are learning and doing things like talk with your co-workers at lunch about hiring tests, and participating in online discussion boards. In addition you should try doing really hard things that break or come really close to breaking the tools you use. But not too hard, you have to be able to *do* them after all. Learning how VM's and interpreters and compilers work, then understanding the concepts behind why they work that way really helps give you a framework to hang an understanding of what's going on in a program. One way to get this knowledge is to start far in the past and work forward. Another is to dive deep into something from today. I will say if you're already in the workforce and not headed back out to school, the onus will be on you to pick up more of this. Much of the conceptual stuff you won't hear at work, except occasionally overheard in a discussion assuming you already know it. You'll have to ask questions, and you'll have to read up on it afterwards, because often your co-workers won't have the whole picture either. --Michael -- Michael Langford Phone: 404-386-0495 Consulting: http://www.TierOneDesign.com/ Entertaining: http://www.ThisIsYourCruiseDirectorSpeaking.com On 9/19/07, Stephen Nelson-Smith <sanelson at gmail.com> wrote: > > Michael Langford wrote: > > > Inheritance: Syntactic sugar that's not really needed to make a well > > organized system. Often overused, especially by programmers in big > > companies, beginning students of programmers, green engineers, and > > professors. In practice hides a lot of data, often making behavior > > surprising, therefore harder to maintain. Can be used in limited > situations > > to great advantage, but like cologne on car salesmen, is used in greater > > amounts than it should be. One should always ask, can I make a simpler > > system with composition. > > Pretty much exactly what my colleague said. Having thought about it I > understand this. > > > Polymorphism: The process of creating many classes which a single > interface > > which are then all used by an object that doesn't know or need to know > the > > type. Many people think you only get this by using inheritance and > therefore > > use inheritance many places a simpler, less opaque, more lightweight > > solution will work. Most dynamically typed languages (most notably, > python, > > ruby and smalltalk) don't even require you specify the interface > explicitly > > to get polymorphic behavior. C++ templates can do non-explicit > interface > > polymorphism, however in a more complicated, blindingly fast to run, > > blindingly slow to compile way. > > Also what my colleague said! This is the bit I had missed. Perhaps I > need to rethink / reload my understanding of polymorphism. > > > Encapsulation: The process of taking what shouldn't matter to the > external > > world, and locking it behind an interface. This principle works best > when > > put into small, specialized libraries and designed for general use, as > this > > is the only encapsulated form that is shown to last over time. > Supposedly > > something OO based design allows, but in reality, the coupling among > classes > > varies in differing amounts. The module/public visibility of Java is a > good > > compromise with classes that hides some data but share some with certain > > other classes. C++ has large issues for historical reasons on this > front, as > > the implementation section of a class is largely revealed through the > class > > definition. > > Interesting. And again revealing of a weakness in my understanding. > > I do think this is a good question for getting a sense of where a > person's understanding is. I wonder how much this understanding is a > pre-requistite for being a good developer... not too much I hope! > > > --Michael > > S. > _______________________________________________ > 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/20070919/7a5be8a4/attachment.htm From alan.gauld at btinternet.com Wed Sep 19 09:52:27 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 19 Sep 2007 08:52:27 +0100 Subject: [Tutor] [Slightly OT] Inheritance, Polymorphism and Encapsulation References: <b6131fdc0709181709wd6fd135i65c1dc92ff9cd711@mail.gmail.com><46F07285.9040407@bigfoot.com> <fcqies$vpm$1@sea.gmane.org> <82b4f5810709190028l26c72d0u4b40b7521985eb88@mail.gmail.com> Message-ID: <fcqkgm$5vf$1@sea.gmane.org> "Michael Langford" <mlangford.cs03 at gtalumni.org> wrote > OOP without classes is quite common still. This is how a > good portion of the Linux kernel is written True, but as I understand it the Linux approach is to use C structs to mimic some class type behaviour. Essentially binding data and functions inside a struct. Is that not the case? What I was referring to was the lack of any kind of class structure at all, a purely prototype driven OOP style. (Somewhat like JavaScript OOP except that it's very easy to fake classes in JavaScript) My first OOP project was in pure C and used a combination of structs and a function protocol to identify objects, it was mostly modelled on ADA and had no inheritance mechanism. The concept got refined into an intenal OOP dialect of C called Cellular C (if I recall correctly) which did have a class type concept (the cell, of course!) before we eventually adopted C++. > very maintainable way to write C, some studies show > that it is more maintainable than equivalent projects > in C++, I agree, C++ - especially in its post v2.0 forms - has become a minefield of temporary objects and unexpected constructor calls. > lots to do with C++ containing not just the kitchen > sink but the bathroom sink and a bidet too). :-) All true and the reason I've mostly given up programming in C++! Indeed one of my biggest fears for Python is that I see worrying signs that people are trying to cram in every programming fad going and there is a danger that it too acquires the kind of baggage that C++ has gathered over the years. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From ksterling at mindspring.com Wed Sep 19 11:08:00 2007 From: ksterling at mindspring.com (Ken Oliver) Date: Wed, 19 Sep 2007 05:08:00 -0400 (GMT-04:00) Subject: [Tutor] sales tax Message-ID: <15911132.1190192880431.JavaMail.root@mswamui-blood.atl.sa.earthlink.net> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070919/5c97b113/attachment.htm From janos.juhasz at VELUX.com Wed Sep 19 11:10:34 2007 From: janos.juhasz at VELUX.com (=?ISO-8859-1?Q?J=E1nos_Juh=E1sz?=) Date: Wed, 19 Sep 2007 11:10:34 +0200 Subject: [Tutor] OO triangulation Message-ID: <OF1AB81E96.8AB8FF37-ONC125735B.0030CD29-C125735B.00326739@velux.com> Dear Tutors, I made an OO style triangulation based on an old C progam I made about 10 years ago. The sample is working finally. First time I made the triangulation with recursion, but I reached the recursion limit very shortly. So I changed the recursion to a queue. I am interested about your opinions about the OO style. It hasn't got too much comments, but probably readable. ################ class Triangulation: def __init__(self, points=None): self.UpdateList = [] if points: self.points = points else: self.NewPointSet() def Triangulate(self): self.triangles = [] if self.points: self.SortPoints() self.RemoveDuplicates() self.MakeSnake() self.Simplify() def SortPoints(self): self.points.sort(lambda p1,p2: cmp(p1[0], p2[0]) or cmp(p1[1], p2[1])) def RemoveDuplicates(self): newpoints = [] prevpoint = None for p in self.points: if p != prevpoint: newpoints.append(p) prevpoint = p self.points = newpoints def MakeSnake(self): for i in xrange(len(self.points)-1): a = self.points[i]; b = self.points[i+1] t1 = Triangle([None, b, a]); t2 = Triangle([None, a, b]) self.triangles.append(t1); self.triangles.append(t2) t1.neighbours[0] = t2; t2.neighbours[0] = t1 for i in xrange(len(self.points)-2): t1 = self.triangles[i*2]; t2 = self.triangles[i*2 + 1] t3 = self.triangles[i*2 + 2]; t4 = self.triangles[i*2 + 3] t1.neighbours[2] = t3; t3.neighbours[1] = t1 t2.neighbours[1] = t4; t4.neighbours[2] = t2 t1 = self.triangles[0]; t2 = self.triangles[1] t1.neighbours[1] = t2; t2.neighbours[2] = t1 t1 = self.triangles[-2]; t2 = self.triangles[-1] t1.neighbours[2] = t2; t2.neighbours[1] = t1 def Simplify(self): self.UpdateList = self.triangles[:] while self.UpdateList: NextToCheck = self.UpdateList.pop() NextToCheck.Update(self.UpdateList) def NewPointSet(self, pointnum=100): self.points = ([[random.randint(1,420), random.randint(1,380)] for x in xrange(pointnum)]) ## 0 ## TOP ## / \ ## / \ ## 2 / \ 1 ## / \ ## / \ ##1 LEFT---------RIGHT 2 ## 0 class Triangle: def __init__(self, points=[None, None, None]): self.points = points self.neighbours = [None, None, None] def CCW(self, a, b, c): ## return 2 * Triangle Area try: return (b[0] - a[0])*(c[1] - a[1]) - (b[1] - a[1])*(c[0] - a[0]) except: return 0 def InCircle(self, a, b, c, p): x21 = b[0] - a[0]; y21 = b[1] - a[1]; x23 = b[0] - c[0]; y23 = b[1] - c[1] x41 = p[0] - a[0]; y41 = p[1] - a[1]; x43 = p[0] - c[0]; y43 = p[1] - c[1] return (y41*x23+x41*y23) * (x43*x21-y43*y21) > (y43*x21+x43*y21) * (x41*x23-y41*y23); def Update(self, UpdateList): for p in self.points: if self.HaveToSwap(p): self.Swap(p) UpdateList += self.neighbours UpdateList += self.BottomTriangle(p).neighbours def HaveToSwap(self, p1): if p1 in self.points: if self.NextPoint(p1) == None: p2 = self.PrevPoint(p1) tOpp = self.BottomTriangle(p1) p3 = tOpp.PrevPoint(p2) return (self.CCW(p2,p1,p3) > 0) if self.PrevPoint(p1) == None: p2 = self.NextPoint(p1) tOpp = self.BottomTriangle(p1) p3 = tOpp.NextPoint(p2) return (self.CCW(p3,p1,p2) > 0) C = p1 A = self.PrevPoint(C) D = self.NextPoint(C) t2 = self.BottomTriangle(C) p = t2.NextPoint(D) if None in (A, C, D, p): return 0 return self.InCircle(A, C, D, p) return 0 def Swap(self, C): ## Ta2 Ta2 """ Swap a triangle pair """ ## / \ / \ D = self.NextPoint(C) ## / a2 \ / a2 \ A = self.PrevPoint(C) ## A---------B A---------B t2 = self.BottomTriangle(C) ## / | \ | \ / | / | \ B = t2.NextPoint(D) ## a1| \ t2 | a1 |self / | a1 = self.BottomTriangle(D) ## |self \ | d2 | / t2 | d2 d1 = self.BottomTriangle(A) ## \ | \ | / \ | / | / a2 = t2.BottomTriangle(D) ## C---------D C---------D d2 = t2.BottomTriangle(A) ## \ d1 / \ d1 / Ta2 = a2.NextPoint(B) ## \ / \ / Td1 = d1.NextPoint(C) ## Td1 Td1 self.points = [A, C, B]; t2.points = [D, B, C] self.neighbours = [t2, a2, a1]; t2.neighbours = [self, d1, d2] d1.SetTriangle(Td1 ,t2); a2.SetTriangle(Ta2, self) def NextPoint(self, p): return self.points[(self.points.index(p)+1)%3] def PrevPoint(self, p): return self.points[(self.points.index(p)+2)%3] def BottomTriangle(self, p): return self.neighbours[self.points.index(p)] def SetTriangle(self, p, tri): self.neighbours[self.points.index(p)] = tri import wx class DrawingFrame(wx.Frame): def __init__(self, parent, id, title, fileName=None): wx.Frame.__init__(self, parent, id, title, style = wx.DEFAULT_FRAME_STYLE | wx.WANTS_CHARS | wx.NO_FULL_REPAINT_ON_RESIZE) self.Bind(wx.EVT_PAINT, self.onPaintEvent) self.SetSizeHints(minW=250, minH=200) self.SetSize(wx.Size(450, 450)) self.SetBackgroundColour(wx.WHITE) self.CreateStatusBar() menu = wx.Menu() retri = menu.Append(-1, "100 new points", "100 new points") self.Bind(wx.EVT_MENU, self.Retriangulate100, retri) retri = menu.Append(-1, "1000 new points", "1000 new points") self.Bind(wx.EVT_MENU, self.Retriangulate1000, retri) retri = menu.Append(-1, "10000 new points", "10000 new points") self.Bind(wx.EVT_MENU, self.Retriangulate10000, retri) menuBar = wx.MenuBar() menuBar.Append(menu, "Retriangulate") self.SetMenuBar(menuBar) self.Show() def Retriangulate100(self, evt): triang.NewPointSet(100) start = time.clock() triang.Triangulate() stop = time.clock() self.Refresh() st = 'Triangulating 100 points takes %.2f seconds' % (stop-start) self.SetStatusText(st) def Retriangulate1000(self, evt): triang.NewPointSet(1000) start = time.clock() triang.Triangulate() stop = time.clock() self.Refresh() st = 'Triangulating 1000 points takes %.2f seconds' % (stop-start) self.SetStatusText(st) def Retriangulate10000(self, evt): triang.NewPointSet(10000) start = time.clock() triang.Triangulate() stop = time.clock() self.Refresh() st = 'Triangulating 10000 points takes %.2f seconds' % (stop-start) self.SetStatusText(st) def onPaintEvent(self, event): dc = wx.PaintDC(self) dc.BeginDrawing() for tri in triang.triangles: if None in tri.points: continue dc.DrawPolygon(tri.points) cx, cy = (0,0) for p in tri.points: cx += p[0]/3 cy += p[1]/3 r = ((p[0]-cx)**2 + (p[1]-cy)**2)**0.5 #dc.DrawCircle(cx, cy, 2) dc.EndDrawing() class App(wx.App): def OnInit(self): frame = DrawingFrame(None, -1, "Triangulation") self.SetTopWindow(frame) frame.Show() return 1 if __name__ == '__main__': import random import time triang = Triangulation() triang.NewPointSet(1000) triang.Triangulate() app = App(0) app.MainLoop() ############## Yours sincerely, ______________________________ J?nos Juh?sz From work at infomaniak.ch Wed Sep 19 10:23:49 2007 From: work at infomaniak.ch (cedric briner) Date: Wed, 19 Sep 2007 10:23:49 +0200 Subject: [Tutor] uncomprehension on RE Message-ID: <46F0DC95.3090208@infomaniak.ch> Hello, I do not understand the behaviour of this: import re re.search('(a)*','aaa').groups() ('a',) I was thinking that the ``*'' will operate on the group delimited by the parenthesis. And so, I was expecting this result: ('a', 'a', 'a') Is there something I'am missing ? Ced. -- Cedric BRINER Geneva - Switzerland From sanelson at gmail.com Wed Sep 19 11:26:31 2007 From: sanelson at gmail.com (Stephen Nelson-Smith) Date: Wed, 19 Sep 2007 10:26:31 +0100 Subject: [Tutor] [Slightly OT] Inheritance, Polymorphism and Encapsulation In-Reply-To: <82b4f5810709190051i4a8f10e1qf29f45ec6d0d3140@mail.gmail.com> References: <b6131fdc0709181709wd6fd135i65c1dc92ff9cd711@mail.gmail.com> <46F07285.9040407@bigfoot.com> <82b4f5810709181824p5875cb4bpdaf021cc21a35353@mail.gmail.com> <82b4f5810709181826l734f1870nb5748b4c35ca41e9@mail.gmail.com> <b6131fdc0709182251v2a13f13bv485c0aeb51071c5@mail.gmail.com> <82b4f5810709190051i4a8f10e1qf29f45ec6d0d3140@mail.gmail.com> Message-ID: <b6131fdc0709190226r41436a4cm1beb98da8f1f84ab@mail.gmail.com> On 9/19/07, Michael Langford <mlangford.cs03 at gtalumni.org> wrote: > I do think this is a good question for getting a sense of where a > person's understanding is. I wonder how much this understanding is a > pre-requistite for being a good developer... not too much I hope! > > A good developer is a very loaded term. :o) > > There are a lot of good programmers who are bad developers. A lot of being a > good developer is getting things done that work well enough to supply > whomever is downstream from you at work. Agreed - we discussed this at work yesterday when designing the interview tasks for our new recruits. On this point, I feel I score highly. > It also has to do with several things such as source control > tools, ticket tracking tools, testing, debugging, and deployment as well. Right - which is the sort of stuff a fresh-faced university student will take time to get up to speed with, > You will find yourself making more informed choices on things and debugging > things a lot better the more of this technical programming stuff you pick > up. A good compiler/interpreter book and a lot of experimentation will > really open your eyes on a lot of this, as will just doing your job while > constantly reading reading reading about what you are learning and doing > things like talk with your co-workers at lunch about hiring tests, and > participating in online discussion boards. :o) Yes - this is exactly what I feel, and try to do. I'm lucky that I work with some brilliant people. I wasn't hired as a developer - I'm a sysadmin who can also program. I've been seconded to the development team, and am loving it, but quickly realising how much I don't know! > In addition you should try doing really hard things that break or come > really close to breaking the tools you use. But not too hard, you have to be > able to *do* them after all. Learning how VM's and interpreters and > compilers work, then understanding the concepts behind why they work that > way really helps give you a framework to hang an understanding of what's > going on in a program. One way to get this knowledge is to start far in the > past and work forward. Another is to dive deep into something from today. Inspiring advice! :) > I will say if you're already in the workforce and not headed back out to > school, the onus will be on you to pick up more of this. Much of the > conceptual stuff you won't hear at work, except occasionally overheard in a > discussion assuming you already know it. You'll have to ask questions, and > you'll have to read up on it afterwards, because often your co-workers won't > have the whole picture either. Right. And I must spend more time here again. Since leaving my last job most of my programming has been in Ruby (and now PHP and SQL). I sort of fear that my head won't be able to hold it all at once, so I've neglected my Python studies! S. From kent37 at tds.net Wed Sep 19 13:08:15 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 19 Sep 2007 07:08:15 -0400 Subject: [Tutor] [Slightly OT] Inheritance, Polymorphism and Encapsulation In-Reply-To: <fcqkgm$5vf$1@sea.gmane.org> References: <b6131fdc0709181709wd6fd135i65c1dc92ff9cd711@mail.gmail.com><46F07285.9040407@bigfoot.com> <fcqies$vpm$1@sea.gmane.org> <82b4f5810709190028l26c72d0u4b40b7521985eb88@mail.gmail.com> <fcqkgm$5vf$1@sea.gmane.org> Message-ID: <46F1031F.2010005@tds.net> Alan Gauld wrote: > What I was referring to was the lack of any kind of class > structure at all, a purely prototype driven OOP style. > (Somewhat like JavaScript OOP except that it's very easy > to fake classes in JavaScript) Wikipedia has an article about prototype-based programming: http://en.wikipedia.org/wiki/Prototype-based_programming Among others, it lists JavaScript (and its variations), Lua and Self as prototype-based languages. This paper makes an interesting argument for prototype-based OOP in user-interface programming: http://waltersmith.us/wp-content/uploads/2005/12/OOPSLA95.pdf They say that in UI programming, single-use classes are often created; classes that implement a specific widget or window. In these cases the dichotomy between class and object is not useful, in fact it adds extra cognitive load to the program without providing any benefit. Prototype-based programming is a better fit for this problem domain because instanced with the desired behaviour are created directly. Kent From kent37 at tds.net Wed Sep 19 13:31:33 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 19 Sep 2007 07:31:33 -0400 Subject: [Tutor] sales tax In-Reply-To: <a04dbf4b0709182039r6246565du12344784d884f279@mail.gmail.com> References: <777228.35831.qm@web51603.mail.re2.yahoo.com> <a04dbf4b0709182039r6246565du12344784d884f279@mail.gmail.com> Message-ID: <46F10895.5070704@tds.net> Ian Witham wrote: > As Michael points out, you need to explicitly use the round function, as > the float formatting merely truncates anything after the second decimal > place. No. I don't know what algorithm it uses for rounding, but it does round: In [3]: '%.2f' % 6.6666 Out[3]: '6.67' In [4]: '%.2f' % 6.665 Out[4]: '6.67' In [5]: '%.2f' % 6.664 Out[5]: '6.66' The round() function seems to be aware of limits of representation and takes them into account. 10.825 is not exactly represented in floating point: In [8]: 10.825 Out[8]: 10.824999999999999 String formatting is literal in its rounding; 10.824999999999999 is closer to 10.82 than 10.83: In [15]: '%.2f' % 10.825 Out[15]: '10.82' round() seems to know about this: In [12]: round(10.825, 2) Out[12]: 10.83 This is not surprising after what is above, but perhaps a bit disturbing: In [13]: round(10.824999999999999, 2) Out[13]: 10.83 Kent From kent37 at tds.net Wed Sep 19 13:35:34 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 19 Sep 2007 07:35:34 -0400 Subject: [Tutor] uncomprehension on RE In-Reply-To: <46F0DC95.3090208@infomaniak.ch> References: <46F0DC95.3090208@infomaniak.ch> Message-ID: <46F10986.1090101@tds.net> cedric briner wrote: > Hello, > > I do not understand the behaviour of this: > > import re > re.search('(a)*','aaa').groups() > ('a',) > > I was thinking that the ``*'' will operate on the group delimited by the > parenthesis. And so, I was expecting this result: > ('a', 'a', 'a') > > Is there something I'am missing ? It just doesn't work that way. The returned group is the last string matched by the group: In [17]: re.search('(a.)*','azabac').groups() Out[17]: ('ac',) Use re.findall() instead: In [18]: re.findall('a.', 'azabac') Out[18]: ['az', 'ab', 'ac'] If you want overlapping matches you have to search in a loop and collect them yourself, findall() gives only non-overlapping matches. Kent From sanelson at gmail.com Wed Sep 19 14:04:52 2007 From: sanelson at gmail.com (Stephen Nelson-Smith) Date: Wed, 19 Sep 2007 13:04:52 +0100 Subject: [Tutor] uncomprehension on RE In-Reply-To: <46F0DC95.3090208@infomaniak.ch> References: <46F0DC95.3090208@infomaniak.ch> Message-ID: <b6131fdc0709190504t5560e203u72ccd1f5c3e52ef2@mail.gmail.com> On 9/19/07, cedric briner <work at infomaniak.ch> wrote: > Hello, > > I do not understand the behaviour of this: > > import re > re.search('(a)*','aaa').groups() > ('a',) > > I was thinking that the ``*'' will operate on the group delimited by the > parenthesis. And so, I was expecting this result: > ('a', 'a', 'a') > > Is there something I'am missing ? <reposting as sent to OP by default... I am sure the list used to munge addresses and things were sent to the list by default> What you are trying to do, I think, is get the * to expand to the number of times you expect your group to appear. You cannot do this. You need to specify as many groups as you want to get returned: re.search('(x)(x)(x)', 'xxx').groups() would work. In your case you have a single group that matches several times. Python simply returns one match. Consider this: >>> re.search('(.)*', 'abc').groups() ('c',) Can you see how that happens? You could do re.findall('x', 'xxx') - but I don't know what you are actually trying to do. S. From boykie.mackay at gmail.com Wed Sep 19 14:51:06 2007 From: boykie.mackay at gmail.com (Boykie Mackay) Date: Wed, 19 Sep 2007 13:51:06 +0100 Subject: [Tutor] Finding even and odd numbers Message-ID: <1190206266.7991.12.camel@apprentice-laptop> Hi guys, I have come across a bit of code to find if a group of numbers is odd or even.The code snippet is shown below: if not n&1: return false The above should return false for all even numbers,numbers being represented by n.I have tried to wrap my head around the 'not n&1' but I'm failing to understand what's going on.Could someone please explain the statement. Thanks in advance. Boyks From taserian at gmail.com Wed Sep 19 15:47:03 2007 From: taserian at gmail.com (taserian) Date: Wed, 19 Sep 2007 09:47:03 -0400 Subject: [Tutor] Finding even and odd numbers In-Reply-To: <1190206266.7991.12.camel@apprentice-laptop> References: <1190206266.7991.12.camel@apprentice-laptop> Message-ID: <70dbc4d40709190647p5a3d5daapf1f2b9abb8b63a43@mail.gmail.com> On 9/19/07, Boykie Mackay <boykie.mackay at gmail.com> wrote: > Hi guys, > > I have come across a bit of code to find if a group of numbers is odd or > even.The code snippet is shown below: > > if not n&1: > return false > > The above should return false for all even numbers,numbers being > represented by n.I have tried to wrap my head around the 'not n&1' but > I'm failing to understand what's going on.Could someone please explain > the statement. I'll respond more from a general programming point of view than as a Python expert (far from it!). You can always tell if a regular number is divisible by 10, by just looking at the last digit; if it's a zero, it is, and if it's anything else, it isn't. That's a property of the decimal (base 10) system. The above snippet is taking advantage of a similar property of binary numbers, which are base 2. What the above snippet is doing is checking to see if that last digit is a 0 or not (asking "not n&1" is equivalent to asking "n&0", since that digit can only be a 0 or 1). Since binary numbers are base 2, any binary number that ends in a 0 is divisible by 2, analogous to the decimal number example above. The technique being used to determine the value of the last digit is a bitwise-AND. It compares the binary digits in the representation of n with the binary digits in the representation of 1 on a one-to-one positional arrangement. If either number has a zero in a certain position, the result will have a zero in that position as well; if both numbers have a 1 in that position, the result will have a 1. As an example, I'll represent 4 as a binary number: 100 (4 in binary) 001 (1 in binary) --------- 000 (Result of bitwise-AND) and now using 5 as our input: 101 (5 in binary) 001 (1 in binary) -------- 001 (Result of bitwise-AND) Since 1 represented in binary is all zeroes except for the last digit, the only way to get anything different from 000 as a result is for the last digit to be 1. Hopefully this didn't confuse you anymore. Experts, feel free to chime in. Tony R. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070919/95b319ee/attachment.htm From sacharook at hotmail.co.uk Wed Sep 19 15:50:34 2007 From: sacharook at hotmail.co.uk (sacha rook) Date: Wed, 19 Sep 2007 14:50:34 +0100 Subject: [Tutor] python and wmi interface Message-ID: <BAY111-W2582EF54297590F2BA292AF3B90@phx.gbl> Hi all can anyone point me in the direction of any python docs or tutorials of interacting with the windows WMI interface ? I am not trying to do anything specific as yet just try to build up a bit of knowledge see what the possibilities are! Thanks in advance for you help :0-) S _________________________________________________________________ 100?s of Music vouchers to be won with MSN Music https://www.musicmashup.co.uk -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070919/9810eb46/attachment.htm From ewald.ertl at gmail.com Wed Sep 19 15:06:55 2007 From: ewald.ertl at gmail.com (Ewald Ertl) Date: Wed, 19 Sep 2007 15:06:55 +0200 Subject: [Tutor] Finding even and odd numbers In-Reply-To: <1190206266.7991.12.camel@apprentice-laptop> References: <1190206266.7991.12.camel@apprentice-laptop> Message-ID: <46F11EEF.7010705@gmail.com> Hi Boyks, Boykie Mackay wrote: > Hi guys, > > I have come across a bit of code to find if a group of numbers is odd or > even.The code snippet is shown below: > > if not n&1: > return false > > The above should return false for all even numbers,numbers being > represented by n.I have tried to wrap my head around the 'not n&1' but > I'm failing to understand what's going on.Could someone please explain the single '&' is a bitwise and operator. every odd number has the first bit set so <odd number>&1 returns 1. The binray representation of : 1 0001 2 0010 3 0011 4 0100 >>> 1&1 1 >>> 2&1 0 >>> 3&1 1 >>> 4&1 0 HTH Ewald From sanelson at gmail.com Wed Sep 19 15:58:15 2007 From: sanelson at gmail.com (Stephen Nelson-Smith) Date: Wed, 19 Sep 2007 14:58:15 +0100 Subject: [Tutor] Finding even and odd numbers In-Reply-To: <1190206266.7991.12.camel@apprentice-laptop> References: <1190206266.7991.12.camel@apprentice-laptop> Message-ID: <b6131fdc0709190658k16f530e7x346854692b5bc58b@mail.gmail.com> On 9/19/07, Boykie Mackay <boykie.mackay at gmail.com> wrote: > Hi guys, > > I have come across a bit of code to find if a group of numbers is odd or > even.The code snippet is shown below: > > if not n&1: > return false > > The above should return false for all even numbers,numbers being > represented by n.I have tried to wrap my head around the 'not n&1' but > I'm failing to understand what's going on.Could someone please explain > the statement. It's just a bitwise and, which will always return 1 for an odd number. S. From orsenthil at gmail.com Wed Sep 19 16:13:23 2007 From: orsenthil at gmail.com (O.R.Senthil Kumaran) Date: Wed, 19 Sep 2007 19:43:23 +0530 Subject: [Tutor] Xml reference In-Reply-To: <fcmgb5$k1f$1@sea.gmane.org> References: <b5300ea90709170415g1caa96cev59aafa32a25416eb@mail.gmail.com> <fcmgb5$k1f$1@sea.gmane.org> Message-ID: <20070919141323.GB4002@gmail.com> > > Which Book is better for python parsing and reading Xml files from > > local > > machine and remote machine and also through http... > > Python Network Programming has more on the networking > side(surprise!) via http. You mean, this one. http://www.complete.org/publications/pynet/ ? > > But neither uses ElementTree which is one of the best XML > parsers and now standrad with python. The best bet there is > the developers web page.(Try Google) > Yes, effbot.org site is too good a resource for XML Parsing stuff using python. Read the documentation and examples from effbot, you can go far with XML parsing. http://effbot.org/zone/element-index.htm#usage -- O.R.Senthil Kumaran http://uthcode.sarovar.org From kent37 at tds.net Wed Sep 19 16:27:52 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 19 Sep 2007 10:27:52 -0400 Subject: [Tutor] python and wmi interface In-Reply-To: <BAY111-W2582EF54297590F2BA292AF3B90@phx.gbl> References: <BAY111-W2582EF54297590F2BA292AF3B90@phx.gbl> Message-ID: <46F131E8.4010601@tds.net> sacha rook wrote: > Hi all > > can anyone point me in the direction of any python docs or tutorials of > interacting with the windows WMI interface ? See Tim Golden's WMI page: http://tgolden.sc.sabren.com/python/wmi.html Kent From boykie.mackay at gmail.com Wed Sep 19 16:33:12 2007 From: boykie.mackay at gmail.com (Boykie Mackay) Date: Wed, 19 Sep 2007 15:33:12 +0100 Subject: [Tutor] Finding even and odd numbers In-Reply-To: <70dbc4d40709190647p5a3d5daapf1f2b9abb8b63a43@mail.gmail.com> References: <1190206266.7991.12.camel@apprentice-laptop> <70dbc4d40709190647p5a3d5daapf1f2b9abb8b63a43@mail.gmail.com> Message-ID: <1190212392.7991.15.camel@apprentice-laptop> Thanks. The analogy to the decimal system was a big help in getting me to understand the principle. On Wed, 2007-09-19 at 09:47 -0400, taserian wrote: > On 9/19/07, Boykie Mackay <boykie.mackay at gmail.com> wrote: > Hi guys, > > I have come across a bit of code to find if a group of numbers > is odd or > even.The code snippet is shown below: > > if not n&1: > return false > > The above should return false for all even numbers,numbers > being > represented by n.I have tried to wrap my head around the 'not > n&1' but > I'm failing to understand what's going on.Could someone please > explain > the statement. > > I'll respond more from a general programming point of view than as a > Python expert (far from it!). > > You can always tell if a regular number is divisible by 10, by just > looking at the last digit; if it's a zero, it is, and if it's anything > else, it isn't. That's a property of the decimal (base 10) system. > > The above snippet is taking advantage of a similar property of binary > numbers, which are base 2. What the above snippet is doing is checking > to see if that last digit is a 0 or not (asking "not n&1" is > equivalent to asking "n&0", since that digit can only be a 0 or 1). > Since binary numbers are base 2, any binary number that ends in a 0 is > divisible by 2, analogous to the decimal number example above. > > The technique being used to determine the value of the last digit is a > bitwise-AND. It compares the binary digits in the representation of n > with the binary digits in the representation of 1 on a one-to-one > positional arrangement. If either number has a zero in a certain > position, the result will have a zero in that position as well; if > both numbers have a 1 in that position, the result will have a 1. > > As an example, I'll represent 4 as a binary number: > > 100 (4 in binary) > 001 (1 in binary) > --------- > 000 (Result of bitwise-AND) > > and now using 5 as our input: > > 101 (5 in binary) > 001 (1 in binary) > -------- > 001 (Result of bitwise-AND) > > Since 1 represented in binary is all zeroes except for the last digit, > the only way to get anything different from 000 as a result is for the > last digit to be 1. > > Hopefully this didn't confuse you anymore. Experts, feel free to chime > in. > > Tony R. > > > > > > > From jecarnell at saintfrancis.com Wed Sep 19 17:05:31 2007 From: jecarnell at saintfrancis.com (Carnell, James E) Date: Wed, 19 Sep 2007 10:05:31 -0500 Subject: [Tutor] ValueError:too many values to unpack (passing 2d array to class) Message-ID: <CEFAE560FE3E3C458A2335A1AA37A82D06763984@MAIL2W2K3.WarrenNT.SaintFrancis.Loc> Any help would greatly appreciated. Question: I am getting the following error from the validMove function: ValueError: too many values to unpack This program (currently) consists of a 2dArray and objects (represented by integers) in that array that can be moved. I am guessing that it has to do with copying a 2dArray to a local member value. I thought that it was just copying a pointer to the array and not the entire array, but I am not sure anymore. To tell the truth I have decided to change how this whole thing is done, but I really want to learn why this didn't work before I do. There are three sections - code - command line example of error - conceptual example if code doesn't make sense ======================================================================== ======= class WorldObject: def __init__(self): s = self s.curPos = [0,0] def createRandomPosition(s,arrayEnv): """takes a 2d array and returns a random position for placement of object. currentPosition contains 2 integers for column and row.""" s.curPos[0] = random.randint(0,len(arrayEnv)-1) s.curPos[1] = random.randint(0,len(arrayEnv[0])-1) return s.curPos def validMove(s,arrayEnv,newPosition): """calls to see if newPosition is inside the bounds of the 2d environment array and then if the newPosition is not a wall or something that the object can not go through (unblocked)""" s,arrayEnv = arrayEnv####### THIS MIGHT BE MY PROBLEM Is it just copying a pointer?####### s.newPos = newPosition #newPosition for example is [0,1] to go East or [-1,-1] to go NorthWest if s.insideArray(s.arrayEnv,s.newPos) and s.unblocked(s.arrayEnv,s.newPos): s.curPos[0] += s.newPos[0] s.curPos[1] += s.newPos[1] return s.curPos else: return curPos #returns the same position that was evaluated w/o changes def insideArray(s, arrayEnv,newPosition): """called by validMove to make sure I don't get an out bounds error for newPosition""" s.newPos = newPosition#so I can fit everything on one line if s.curPos[0] + s.newPos[0] < 0 or s.curPos[0] + s.newPos[0] >= len(arrayEnv[0]): return False elif s.curPos[1] + s.newPos[1] < 0 or s.curPos[1] + s.newPos[1] >= len(arrayEnv): return False else: return True def unblocked(s,arrayEnv,newPosition): """called by validMove to make sure that I am not walking through walls. For ease of explanation arrayEnv just holds integers. If the integer is >= 5 then I can't walk through it""" s.newPos = newPosition if arrayEnv[s.curPos[0] + s.newPos[0]][s.curPos[1] + s.newPos[1]] < 5: return True elif arrayEnv[s.curPos[0] + s.newPos[0]][s.curPos[1] + s.newPos[1]] >= 5: return False else: print "error in World Object unblocked function" return False ==================================COMMAND LINE ERROR=================================== >>> env = [[0,0,0],[0,0,0],[0,0,0]] >>> apple = WorldObject() >>> apple.createRandomPosition(env) [1, 2] >>> newPosition = [0,0] #not moving anywhere at all >>> apple.insideArray(env,newPosition) True >>> apple.unblocked(env,newPosition) True >>> apple.curPos [1, 2] >>> apple.validMove(env,newPosition) Traceback (most recent call last): File "<input>", line 1, in ? File "<input>", line 27, in validMove ValueError: too many values to unpack ======================CONCEPTUAL EXAMPLE IF CODE DOESN'T MAKE SENSE======================= env = [[0,0,0],[0,0,0],[0,0,0]] currentPosition = [1,1] WorldObject is represented by the number 7 env[ currentPosition[0] ][ currentPosition[1] ] = 7 env = [[0,0,0],[0,7,0],[0,0,0]] newPosition = [0,0] by adding currentPosition[0] to newPosition[0] I get the new coordinates in the env array. same with currentPosition[1] to newPosition[1] I just have to check to see if I am within the array so I don't go out of bounds, and to make sure I am not running into a wall. For example if env[0][0] is 5 (integer represents wall) then don't move James Carnell -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070919/0887e406/attachment.htm From janos.juhasz at VELUX.com Wed Sep 19 17:22:38 2007 From: janos.juhasz at VELUX.com (=?ISO-8859-1?Q?J=E1nos_Juh=E1sz?=) Date: Wed, 19 Sep 2007 17:22:38 +0200 Subject: [Tutor] python and wmi interface Message-ID: <OF05D69605.ED7AB8EE-ONC125735B.0054219F-C125735B.005477C6@velux.com> Dear sacha, >>can anyone point me in the direction of any python docs or tutorials >>of interacting with the windows WMI interface ? Scriptomatic 2.0 from Microsoft seems to be good for pythonists. https://www.microsoft.com/downloads/details.aspx?FamilyID=09dfc342-648b-4119-b7eb-783b0f7d1178&DisplayLang=en Yours sincerely, ______________________________ J?nos Juh?sz From taserian at gmail.com Wed Sep 19 17:28:33 2007 From: taserian at gmail.com (taserian) Date: Wed, 19 Sep 2007 11:28:33 -0400 Subject: [Tutor] Finding even and odd numbers In-Reply-To: <b6131fdc0709190751p20c0243am6e3a21bc3465ec2b@mail.gmail.com> References: <1190206266.7991.12.camel@apprentice-laptop> <70dbc4d40709190647p5a3d5daapf1f2b9abb8b63a43@mail.gmail.com> <b6131fdc0709190751p20c0243am6e3a21bc3465ec2b@mail.gmail.com> Message-ID: <70dbc4d40709190828o7b91b261ka953f85dd6b07ce0@mail.gmail.com> > > > The above snippet is taking advantage of a similar property of binary > > numbers, which are base 2. What the above snippet is doing is checking > to > > see if that last digit is a 0 or not (asking "not n&1" is equivalent to > > asking "n&0", since that digit can only be a 0 or 1). > > Not quite. The &1 is simply checking the least significant bit in the > word. n&0 will always give 0. not n&1 checks whether the last digit > -is- or -isn't- 1. > > S. Not at all, you mean. I was way off with that statement; I'll plead not guilty by virtue of not having had enough coffee today. <8-( (Wearing the dunce cap. . .) Tony R. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070919/d58ef525/attachment-0001.htm From kent37 at tds.net Wed Sep 19 17:43:55 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 19 Sep 2007 11:43:55 -0400 Subject: [Tutor] ValueError:too many values to unpack (passing 2d array to class) In-Reply-To: <CEFAE560FE3E3C458A2335A1AA37A82D06763984@MAIL2W2K3.WarrenNT.SaintFrancis.Loc> References: <CEFAE560FE3E3C458A2335A1AA37A82D06763984@MAIL2W2K3.WarrenNT.SaintFrancis.Loc> Message-ID: <46F143BB.7060500@tds.net> Carnell, James E wrote: > s,arrayEnv = arrayEnv####### THIS MIGHT BE MY PROBLEM Is it just > copying a pointer?####### I think you want s.arrayEnv = arrayEnv note the period where you have a comma. and yes, assignment just makes a new reference to the same object, it does not make a copy. Kent From jecarnell at saintfrancis.com Wed Sep 19 18:09:43 2007 From: jecarnell at saintfrancis.com (Carnell, James E) Date: Wed, 19 Sep 2007 11:09:43 -0500 Subject: [Tutor] Disregard Value Error:too many values to unpack Message-ID: <CEFAE560FE3E3C458A2335A1AA37A82D06763986@MAIL2W2K3.WarrenNT.SaintFrancis.Loc> The problem was pointed out by Kent """ I think you want s.arrayEnv = arrayEnv Not s,arrayEnv (comma instead of period) """ Maybe I should put time limits on myself when I am programming... After a few hours my mind starts going fruity. Maybe I should be wearing the dunce cap. Hopefully, I can put it on with putting an eye out. Well its back to apples and oranges tonight ! Thanks. James Carnell -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070919/b28cfcad/attachment.htm From boykie.mackay at gmail.com Wed Sep 19 18:22:07 2007 From: boykie.mackay at gmail.com (Boykie Mackay) Date: Wed, 19 Sep 2007 17:22:07 +0100 Subject: [Tutor] Finding prime numbers Message-ID: <1190218927.7991.25.camel@apprentice-laptop> Hi Guys, Could you please look over my code 'attached' to find and print out prime numbers between to given values.When run it it is showing inaccuracies i.e printing out '49' and '95' as prime numbers. I have been through the code but can't seem to find where I may have gone wrong.I am sure it has to do with the algorithm to find the prime numbers as the function fails it's unit test.Any help or links would be much appreciated. Thanks, Boyks From mlangford.cs03 at gtalumni.org Wed Sep 19 18:31:15 2007 From: mlangford.cs03 at gtalumni.org (Michael Langford) Date: Wed, 19 Sep 2007 12:31:15 -0400 Subject: [Tutor] Finding prime numbers In-Reply-To: <1190218927.7991.25.camel@apprentice-laptop> References: <1190218927.7991.25.camel@apprentice-laptop> Message-ID: <82b4f5810709190931u16ee0621xc6608d2bcb2fec5e@mail.gmail.com> Attachments are a bad thing to send to open mailing lists in general. In your case, the list appears to have filtered off the code. Please paste it in inline. --Michael On 9/19/07, Boykie Mackay <boykie.mackay at gmail.com> wrote: > > Hi Guys, > > Could you please look over my code 'attached' to find and print out > prime numbers between to given values.When run it it is showing > inaccuracies i.e printing out '49' and '95' as prime numbers. > > I have been through the code but can't seem to find where I may have > gone wrong.I am sure it has to do with the algorithm to find the prime > numbers as the function fails it's unit test.Any help or links would be > much appreciated. > > Thanks, > > Boyks > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Michael Langford Phone: 404-386-0495 Consulting: http://www.TierOneDesign.com/ Entertaining: http://www.ThisIsYourCruiseDirectorSpeaking.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070919/6fb49776/attachment.htm From boykie.mackay at gmail.com Wed Sep 19 18:38:49 2007 From: boykie.mackay at gmail.com (Boykie Mackay) Date: Wed, 19 Sep 2007 17:38:49 +0100 Subject: [Tutor] Finding prime numbers In-Reply-To: <82b4f5810709190931u16ee0621xc6608d2bcb2fec5e@mail.gmail.com> References: <1190218927.7991.25.camel@apprentice-laptop> <82b4f5810709190931u16ee0621xc6608d2bcb2fec5e@mail.gmail.com> Message-ID: <1190219929.7991.28.camel@apprentice-laptop> Sorry about that. I have posted the code below: #!/usr/bin/env python '''A program to generate prime numbers when given 2 numbers''' def isPrime(number): number=abs(int(number)) #1 is not considered a prime number if number<2: return False #2 is the only even prime number if number==2: return True #no even prime numbers after 2 if not number&1: return False #to find all prime numbers we need to go up to the #square root of the highest odd number for x in range(3,int(number**0.5)+1,2): if number%x==0: return False return True if __name__=='__main__': startNum=int(raw_input()) endNum=int(raw_input()) for num in range(startNum,endNum): check=isPrime(num) if check==True: print num, On Wed, 2007-09-19 at 12:31 -0400, Michael Langford wrote: > Attachments are a bad thing to send to open mailing lists in general. > > In your case, the list appears to have filtered off the code. Please > paste it in inline. > > --Michael > > On 9/19/07, Boykie Mackay <boykie.mackay at gmail.com> wrote: > Hi Guys, > > Could you please look over my code 'attached' to find and > print out > prime numbers between to given values.When run it it is > showing > inaccuracies i.e printing out '49' and '95' as prime numbers. > > I have been through the code but can't seem to find where I > may have > gone wrong.I am sure it has to do with the algorithm to find > the prime > numbers as the function fails it's unit test.Any help or links > would be > much appreciated. > > Thanks, > > Boyks > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > > -- > Michael Langford > Phone: 404-386-0495 > Consulting: http://www.TierOneDesign.com/ > Entertaining: http://www.ThisIsYourCruiseDirectorSpeaking.com From noufal at airtelbroadband.in Wed Sep 19 18:57:40 2007 From: noufal at airtelbroadband.in (Noufal Ibrahim) Date: Wed, 19 Sep 2007 22:27:40 +0530 Subject: [Tutor] Decorators and function arguments. Message-ID: <46F15504.4070301@airtelbroadband.in> Hello everyone, I have a question regarding the use of some decorators. In my program, I have functions like this def process_command_line(...): ... def run_command(...): ... def update_db(...): ... These functions are for various stages of the program. Now, I need to profile these functions (find out how long they take) and record this information in some kind of log. So I write a decorator like this def profile(stagename): def decorator(fn): def _wrapper(*args): start_time = time.time() ret = apply(fn, args) end_time = time.time() running_time = end_time - start_time print "Stage %s took %f seconds to run"%(stagename,running_time) return ret return _wrapper return decorator And the functions above get this as a decorator like so @profile("Processing command line") def process_command_line(...): ... @profile("Running command") def run_command(...): ... @profile("Updating database") def update_db(...): ... So far so good. Now the problem. With the "run_command" function, I need the profiling function to print out the name of the command as well as the stage. So instead of printing "Stage running command took 0.30 seconds to run" I need something like "Stage running command (du -sh) took 2.0 seconds to run" How I've accomplished this right now is to pass an extra optional named parameter to all the functions called "desc". The definition of wrapper inside the decorator is then changed to def _wrapper(*args,**dargs): description = dargs.get("desc","") . . . print "Stage %s (%s) took %f seconds to \ run"%(stagename,description,running_time) My question is whether this is a valid use for a decorator and whether this kind of usage is pythonic. If not, are there any better ways to do this? I need some functions in my program to be timed and the timings to be recorded into a separate database. This program acts as a wrapper for various other programs and I need information on how much time they're taking to do their work. Thanks in advance, -- ~noufal From christopher.henk at allisontransmission.com Wed Sep 19 19:01:02 2007 From: christopher.henk at allisontransmission.com (christopher.henk at allisontransmission.com) Date: Wed, 19 Sep 2007 13:01:02 -0400 Subject: [Tutor] Finding prime numbers In-Reply-To: <1190219929.7991.28.camel@apprentice-laptop> Message-ID: <OFA3470F31.15E40B92-ON8525735B.005D4499-8525735B.005D7A6A@gm.com> tutor-bounces at python.org wrote on 09/19/2007 12:38:49 PM: > Sorry about that. > > I have posted the code below: > > #!/usr/bin/env python > > '''A program to generate prime numbers when given 2 numbers''' > > def isPrime(number): > number=abs(int(number)) > #1 is not considered a prime number > if number<2: > return False > #2 is the only even prime number > if number==2: > return True > #no even prime numbers after 2 > if not number&1: > return False > #to find all prime numbers we need to go up to the > #square root of the highest odd number > for x in range(3,int(number**0.5)+1,2): > if number%x==0: > return False > return True Looks like you want to move the return True out one level of indentation. > > -- > > Michael Langford > > Phone: 404-386-0495 > > Consulting: http://www.TierOneDesign.com/ > > Entertaining: http://www.ThisIsYourCruiseDirectorSpeaking.com > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor Chris Henk Allison Transmission phone: 317.242.2569 fax: 317.242.3469 e-mail: christopher.henk at allisontransmission.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070919/91590ebc/attachment.htm From boykie.mackay at gmail.com Wed Sep 19 19:08:33 2007 From: boykie.mackay at gmail.com (Boykie Mackay) Date: Wed, 19 Sep 2007 18:08:33 +0100 Subject: [Tutor] Finding prime numbers In-Reply-To: <OFA3470F31.15E40B92-ON8525735B.005D4499-8525735B.005D7A6A@gm.com> References: <OFA3470F31.15E40B92-ON8525735B.005D4499-8525735B.005D7A6A@gm.com> Message-ID: <1190221713.7991.30.camel@apprentice-laptop> Thanks.That's solved! On Wed, 2007-09-19 at 13:01 -0400, christopher.henk at allisontransmission.com wrote: > > > tutor-bounces at python.org wrote on 09/19/2007 12:38:49 PM: > > > Sorry about that. > > > > I have posted the code below: > > > > #!/usr/bin/env python > > > > '''A program to generate prime numbers when given 2 numbers''' > > > > def isPrime(number): > > number=abs(int(number)) > > #1 is not considered a prime number > > if number<2: > > return False > > #2 is the only even prime number > > if number==2: > > return True > > #no even prime numbers after 2 > > if not number&1: > > return False > > #to find all prime numbers we need to go up to the > > #square root of the highest odd number > > for x in range(3,int(number**0.5)+1,2): > > if number%x==0: > > return False > > return True > > Looks like you want to move the return True out one level of > indentation. > > > > -- > > > Michael Langford > > > Phone: 404-386-0495 > > > Consulting: http://www.TierOneDesign.com/ > > > Entertaining: http://www.ThisIsYourCruiseDirectorSpeaking.com > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > Chris Henk > Allison Transmission > phone: 317.242.2569 > fax: 317.242.3469 > e-mail: christopher.henk at allisontransmission.com From kent37 at tds.net Wed Sep 19 19:22:34 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 19 Sep 2007 13:22:34 -0400 Subject: [Tutor] Decorators and function arguments. In-Reply-To: <46F15504.4070301@airtelbroadband.in> References: <46F15504.4070301@airtelbroadband.in> Message-ID: <46F15ADA.4030506@tds.net> Noufal Ibrahim wrote: > My question is whether this is a valid use for a decorator and whether > this kind of usage is pythonic. If not, are there any better ways to do > this? It seems like a bit of a hack to me. I guess you change the way you call run_command to include desc? You could add another parameter to profile() which says whether to include parameters (or how many parameters) in the output. Something like def profile(stagename, params=0): def decorator(fn): def _wrapper(*args): start_time = time.time() ret = apply(fn, args) end_time = time.time() running_time = end_time - start_time if params: paramStr = ' (' + ', '.join(map(repr, args[:params])) + ')' else: paramStr = '' print "Stage %s%s took %f seconds to run"%(stagename,paramStr, running_time) return ret return _wrapper return decorator Then you would say @profile("Running command", params=1) def run_command(...): Kent From noufal at airtelbroadband.in Wed Sep 19 20:22:02 2007 From: noufal at airtelbroadband.in (Noufal Ibrahim) Date: Wed, 19 Sep 2007 23:52:02 +0530 Subject: [Tutor] Decorators and function arguments. In-Reply-To: <46F15ADA.4030506@tds.net> References: <46F15504.4070301@airtelbroadband.in> <46F15ADA.4030506@tds.net> Message-ID: <46F168CA.8040002@airtelbroadband.in> Kent Johnson wrote: > Noufal Ibrahim wrote: >> My question is whether this is a valid use for a decorator and whether >> this kind of usage is pythonic. If not, are there any better ways to >> do this? > > It seems like a bit of a hack to me. I guess you change the way you call > run_command to include desc? Yes. That was the plan. I'd set some keyword arguments that would be "reserved" for the decorator rather than the function itself. > You could add another parameter to profile() which says whether to > include parameters (or how many parameters) in the output. Something like Thanks Kent. That would keep my original functions unaware that they're being "decorated". I think it's better. -- ~noufal From carroll at tjc.com Wed Sep 19 22:16:58 2007 From: carroll at tjc.com (Terry Carroll) Date: Wed, 19 Sep 2007 13:16:58 -0700 (PDT) Subject: [Tutor] Finding even and odd numbers In-Reply-To: <1190206266.7991.12.camel@apprentice-laptop> Message-ID: <Pine.LNX.4.44.0709191310090.27337-100000@violet.rahul.net> On Wed, 19 Sep 2007, Boykie Mackay wrote: > if not n&1: > return false > > The above should return false for all even numbers,numbers being > represented by n.I have tried to wrap my head around the 'not n&1' but > I'm failing to understand what's going on.Could someone please explain > the statement. Others have explained why this works, but let me rail against this code for a moment. IMHO, a bitwise operation is appropriate only when the field being operated on is a set of bits with bitwise information; for example, if the right-most bit was a flag bit of some sort, N&1 is a perfectly appropriate operation. But evenness/oddness is a property of numbers, and the code would be much easier to understand if the parameter was treated as a number, rather than as a field of bits, i.e.: >>> def isodd(n): ... return bool(n%2) ... >>> isodd(4) False >>> isodd(7) True >>> Mind you, I'll bet that the bit-checking method is slightly faster than the modulus operation in my little piece of code above. I'll also bet that, if you added up the amount of time that was saved by using the bitwise approach over the modulus approach, over all executions of the program everywhere, it probably would be a smaller amount of time than it would take for a programmmer maintaining the program to find out what that line of code is supposed to do. </soapbox> From brunson at brunson.com Wed Sep 19 22:32:23 2007 From: brunson at brunson.com (Eric Brunson) Date: Wed, 19 Sep 2007 14:32:23 -0600 Subject: [Tutor] Finding even and odd numbers In-Reply-To: <Pine.LNX.4.44.0709191310090.27337-100000@violet.rahul.net> References: <Pine.LNX.4.44.0709191310090.27337-100000@violet.rahul.net> Message-ID: <46F18757.8080102@brunson.com> >>> t = timeit.Timer( '1000%2') >>> t.timeit(1000000) 0.25893402099609375 >>> t = timeit.Timer( '1000&1') >>> t.timeit(1000000) 0.2567589282989502 It's almost insignificantly faster. However as a programmer and a mathematician, I disagree with your position that the bitwise operation is more or less readable than the modulus operation. If you wrap either in a function called "isOdd()" that's all someone has see to know what it's doing. My internal implementation of "isOdd()" should be of no consequence to someone unless they are modifying that particular piece of code, and if they're doing that, % is just as common an operation as &. However, with that said, the overhead of the function call is significantly greater than the cost of the actual operation, around four times slower: >>> t = timeit.Timer( 'isOdd(1000)', 'def isOdd(num): return num&1') >>> t.timeit(1000000) 1.1442101001739502 >>> t = timeit.Timer( 'isOdd(1000)', 'def isOdd(num): return num%2') >>> t.timeit(1000000) 1.1032519340515137 Terry Carroll wrote: > On Wed, 19 Sep 2007, Boykie Mackay wrote: > > >> if not n&1: >> return false >> >> The above should return false for all even numbers,numbers being >> represented by n.I have tried to wrap my head around the 'not n&1' but >> I'm failing to understand what's going on.Could someone please explain >> the statement. >> > > Others have explained why this works, but let me rail against this code > for a moment. IMHO, a bitwise operation is appropriate only when the > field being operated on is a set of bits with bitwise information; for > example, if the right-most bit was a flag bit of some sort, N&1 is a > perfectly appropriate operation. > > But evenness/oddness is a property of numbers, and the code would be much > easier to understand if the parameter was treated as a number, rather than > as a field of bits, i.e.: > > >>>> def isodd(n): >>>> > ... return bool(n%2) > ... > >>>> isodd(4) >>>> > False > >>>> isodd(7) >>>> > True > > > Mind you, I'll bet that the bit-checking method is slightly faster than > the modulus operation in my little piece of code above. >< > I'll also bet > that, if you added up the amount of time that was saved by using the > bitwise approach over the modulus approach, over all executions of the > program everywhere, it probably would be a smaller amount of time than it > would take for a programmmer maintaining the program to find out what that > line of code is supposed to do. > > </soapbox> > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From boykie.mackay at gmail.com Wed Sep 19 22:36:07 2007 From: boykie.mackay at gmail.com (Boykie Mackay) Date: Wed, 19 Sep 2007 21:36:07 +0100 Subject: [Tutor] How to take in 2 or more values from user on a single line (like parameters?) Message-ID: <1190234167.7991.46.camel@apprentice-laptop> Hi again, I have racked my brains and tried googling but to no avail. Is there any simple way of getting parameter input from the user? What I want to do is to type in two (or more) values on the command prompt and have a function do some work on them and return a result.For example say I had a multiplication function that I wanted to work as follows: me at computer:~/dir/project$python multiply.py me at computer:~/dir/project$10 12 [enter] me at computer:~/dir/project$120 Basically I want to start the program 'multiply.py',then be presented with a blank screen in which I enter the numbers I want multipied seperated by a space e.g 1 10 11 to give an answer of 110.I have used the raw_input() and input() functions but it seems they only take on value at a time! I suppose what I'm really asking is how to receive muliple values of input from a user on a single line? From mlangford.cs03 at gtalumni.org Wed Sep 19 22:52:14 2007 From: mlangford.cs03 at gtalumni.org (Michael Langford) Date: Wed, 19 Sep 2007 16:52:14 -0400 Subject: [Tutor] Finding even and odd numbers In-Reply-To: <Pine.LNX.4.44.0709191310090.27337-100000@violet.rahul.net> References: <1190206266.7991.12.camel@apprentice-laptop> <Pine.LNX.4.44.0709191310090.27337-100000@violet.rahul.net> Message-ID: <82b4f5810709191352q5517edc6k32e287924ec8804e@mail.gmail.com> Premature optimization is the devil. Care not which method is faster. Only optimize when the whole program is too slow and then find which area is the biggest culprit and optimize that. Computers are very very fast these days. Even embedded systems are so fast you don't understand how fast they are. Your brain just doesn't comprehend periods of time that short. It can't understand really understand *Really* how many instructions happen in a second. It just can't. That being said, I'd say the bitwise and (&) is unclear unless you're working around embedded programmers or other low level engineers or C programmers or are using it for a lot of other bit masking. I'd also go for modulus (%) because its more generalizable to divisibility tests other than powers of 2. There is no bitwise and test to see if a number is divisible by 5 for instance, at least not one you'd like to see. You're going to confusing everyone if you implement isDivBy8 with bitwise operations. --Michael On 9/19/07, Terry Carroll <carroll at tjc.com> wrote: > > On Wed, 19 Sep 2007, Boykie Mackay wrote: > > > if not n&1: > > return false > > > > The above should return false for all even numbers,numbers being > > represented by n.I have tried to wrap my head around the 'not n&1' but > > I'm failing to understand what's going on.Could someone please explain > > the statement. > > Others have explained why this works, but let me rail against this code > for a moment. IMHO, a bitwise operation is appropriate only when the > field being operated on is a set of bits with bitwise information; for > example, if the right-most bit was a flag bit of some sort, N&1 is a > perfectly appropriate operation. > > But evenness/oddness is a property of numbers, and the code would be much > easier to understand if the parameter was treated as a number, rather than > as a field of bits, i.e.: > > >>> def isodd(n): > ... return bool(n%2) > ... > >>> isodd(4) > False > >>> isodd(7) > True > >>> > > Mind you, I'll bet that the bit-checking method is slightly faster than > the modulus operation in my little piece of code above. I'll also bet > that, if you added up the amount of time that was saved by using the > bitwise approach over the modulus approach, over all executions of the > program everywhere, it probably would be a smaller amount of time than it > would take for a programmmer maintaining the program to find out what that > line of code is supposed to do. > > </soapbox> > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Michael Langford Phone: 404-386-0495 Consulting: http://www.TierOneDesign.com/ Entertaining: http://www.ThisIsYourCruiseDirectorSpeaking.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070919/08090243/attachment.htm From mlangford.cs03 at gtalumni.org Wed Sep 19 23:00:17 2007 From: mlangford.cs03 at gtalumni.org (Michael Langford) Date: Wed, 19 Sep 2007 17:00:17 -0400 Subject: [Tutor] How to take in 2 or more values from user on a single line (like parameters?) In-Reply-To: <1190234167.7991.46.camel@apprentice-laptop> References: <1190234167.7991.46.camel@apprentice-laptop> Message-ID: <82b4f5810709191400hee091b2sc7cc911ace49f698@mail.gmail.com> Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)] on wi 32 Type "help", "copyright", "credits" or "license" for more information. >>> a = raw_input("Who's yo daddy?: ") Who's yo daddy?: Bubby June >>> print a Bubby June >>> See how the variable "a" now has the whole sentence "Bubby June" in it? You can call split on "a" now and you'll get a list of words: >>> Names = a.split() >>> print Names ['Bubby','June'] >>> --Michael On 9/19/07, Boykie Mackay <boykie.mackay at gmail.com> wrote: > > Hi again, > > I have racked my brains and tried googling but to no avail. > > Is there any simple way of getting parameter input from the user? > > What I want to do is to type in two (or more) values on the command > prompt and have a function do some work on them and return a result.For > example say I had a multiplication function that I wanted to work as > follows: > > me at computer:~/dir/project$python multiply.py > me at computer:~/dir/project$10 12 [enter] > me at computer:~/dir/project$120 > > Basically I want to start the program 'multiply.py',then be presented > with a blank screen in which I enter the numbers I want multipied > seperated by a space e.g 1 10 11 to give an answer of 110.I have used > the raw_input() and input() functions but it seems they only take on > value at a time! > > I suppose what I'm really asking is how to receive muliple values of > input from a user on a single line? > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Michael Langford Phone: 404-386-0495 Consulting: http://www.TierOneDesign.com/ Entertaining: http://www.ThisIsYourCruiseDirectorSpeaking.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070919/a0160d37/attachment-0001.htm From ulrich at lavabit.com Thu Sep 20 01:00:55 2007 From: ulrich at lavabit.com (Ulrich Holtzhausen) Date: Thu, 20 Sep 2007 01:00:55 +0200 Subject: [Tutor] Income calculator Message-ID: <46F1AA27.3050603@lavabit.com> Hi there, I started out with Python about two days ago, it's my very first shot at programming and I find it quite interesting. Anyway I'll get to the point: I made a simple script that works, albeit not the shortest way I think but it works, however I would like to make it a bit more "fancy" though I'm getting an error. Below is my first script that works, the second script doesn't work, the error I get on the second script is simple, but I can't seem to figure out how to fix it, also, if there's a shorter way of doing this effectively, please help :) . File "./pyfinances.py", line 18 print "Your expected earnings for %s is %d" % (financeLogs['month'], financeLogs['total']) ^ SyntaxError: invalid syntax Basic working program: http://pastebin.com/f2f7f3cd5 Non-working program: http://pastebin.com/f4da62e57 Thanks in advance for any help contributed. From alan.gauld at btinternet.com Thu Sep 20 01:14:17 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 20 Sep 2007 00:14:17 +0100 Subject: [Tutor] How to take in 2 or more values from user on a single line(like parameters?) References: <1190234167.7991.46.camel@apprentice-laptop> Message-ID: <fcsah4$8mu$1@sea.gmane.org> "Boykie Mackay" <boykie.mackay at gmail.com> wrote > Is there any simple way of getting parameter input from the user? > > What I want to do is to type in two (or more) values on the command > prompt and have a function do some work on them and return a result. Take a look at sys.argv. And then take a look at my "talking to the user" topic in my tutorial. The last section covers use of argv to get parameters from the user. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From witham.ian at gmail.com Thu Sep 20 01:22:11 2007 From: witham.ian at gmail.com (Ian Witham) Date: Thu, 20 Sep 2007 11:22:11 +1200 Subject: [Tutor] Income calculator In-Reply-To: <46F1AA27.3050603@lavabit.com> References: <46F1AA27.3050603@lavabit.com> Message-ID: <a04dbf4b0709191622g1e62484uafe4b88f0f45eb53@mail.gmail.com> Your links aren't working for me. On 9/20/07, Ulrich Holtzhausen <ulrich at lavabit.com> wrote: > > Hi there, > > I started out with Python about two days ago, it's my very first shot at > programming and I find it quite interesting. Anyway I'll get to the point: > > I made a simple script that works, albeit not the shortest way I think > but it works, however I would like to make it a bit more "fancy" though > I'm getting an error. Below is my first script that works, the second > script doesn't work, the error I get on the second script is simple, but > I can't seem to figure out how to fix it, also, if there's a shorter way > of doing this effectively, please help :) . > > File "./pyfinances.py", line 18 > print "Your expected earnings for %s is %d" % (financeLogs['month'], > financeLogs['total']) > ^ > SyntaxError: invalid syntax > > Basic working program: http://pastebin.com/f2f7f3cd5 > Non-working program: http://pastebin.com/f4da62e57 > > Thanks in advance for any help contributed. > > _______________________________________________ > 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/20070920/fd843f82/attachment.htm From ulrich at lavabit.com Thu Sep 20 00:58:05 2007 From: ulrich at lavabit.com (Ulrich Holtzhausen) Date: Thu, 20 Sep 2007 00:58:05 +0200 Subject: [Tutor] Income calculator Message-ID: <46F1A97D.9060404@lavabit.com> -------------- next part -------------- An embedded message was scrubbed... From: Ulrich Holtzhausen <ulrich at lavabit.com> Subject: Income calculator Date: Thu, 20 Sep 2007 00:54:19 +0200 Size: 1267 Url: http://mail.python.org/pipermail/tutor/attachments/20070920/aef941d3/attachment.eml From ulrich at lavabit.com Thu Sep 20 00:54:19 2007 From: ulrich at lavabit.com (Ulrich Holtzhausen) Date: Thu, 20 Sep 2007 00:54:19 +0200 Subject: [Tutor] Income calculator Message-ID: <46F1A89B.6030306@lavabit.com> Hi there, I started out with Python about two days ago, it's my very first shot at programming and I find it quite interesting. Anyway I'll get to the point: I made a simple script that works, albeit not the shortest way I think but it works, however I would like to make it a bit more "fancy" though I'm getting an error. Below is my first script that works, the second script doesn't work, the error I get on the second script is simple, but I can't seem to figure out how to fix it, also, if there's a shorter way of doing this effectively, please help :) . File "./pyfinances.py", line 18 print "Your expected earnings for %s is %d" % (financeLogs['month'], financeLogs['total']) ^ SyntaxError: invalid syntax Basic working program: http://pastebin.com/f2f7f3cd5 Non-working program: http://pastebin.com/f4da62e57 Thanks in advance for any help contributed. From eike.welk at gmx.net Thu Sep 20 01:27:32 2007 From: eike.welk at gmx.net (Eike Welk) Date: Thu, 20 Sep 2007 01:27:32 +0200 Subject: [Tutor] Income calculator In-Reply-To: <46F1AA27.3050603@lavabit.com> References: <46F1AA27.3050603@lavabit.com> Message-ID: <200709200127.33889.eike.welk@gmx.net> On Thursday 20 September 2007 01:00, Ulrich Holtzhausen wrote: > Non-working program: http://pastebin.com/f4da62e57 There seems to be a closing bracket ')' missing at the end of line 17. In line 18 there is a bracket missing too, in the code at pastebin, but nut in the error message. So this seems to be an incomplete line at pastebin. I hope this helps, Eike. From mlangford.cs03 at gtalumni.org Thu Sep 20 01:37:11 2007 From: mlangford.cs03 at gtalumni.org (Michael Langford) Date: Wed, 19 Sep 2007 19:37:11 -0400 Subject: [Tutor] Income calculator In-Reply-To: <46F1A97D.9060404@lavabit.com> References: <46F1A97D.9060404@lavabit.com> Message-ID: <82b4f5810709191637p56082a3bq1e39f422c4f45884@mail.gmail.com> On 9/19/07, Ulrich Holtzhausen <ulrich at lavabit.com> wrote: > > > > I can't seem to figure out how to fix it, also, if there's a shorter way > of doing this effectively, please help :) . > > > Instead of a keys in a dict, you should think about making a financeRecord class to hold the data. Don't worry about methods at first, just use it to hold your data if nothing else: class financeRecord: def __init__(self): self.hourlyRate= float(raw_input("Hourly rate: ")) self.overtimeMult = float(raw_input("By which sum is your rate multiplied for overtime hours? ")) #etc financeLogs = {} myDetails = None options = raw_input((menu)) while options != 'quit': if options == 'details': myDetails = financeRecord() else #whatever else you're doing.... Unless there is some really good reason you need text keys, this is a lot more natural. --Michael -- Michael Langford Phone: 404-386-0495 Consulting: http://www.TierOneDesign.com/ Entertaining: http://www.ThisIsYourCruiseDirectorSpeaking.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070919/0a9821a1/attachment.htm From bhaaluu at gmail.com Thu Sep 20 02:16:51 2007 From: bhaaluu at gmail.com (bhaaluu) Date: Wed, 19 Sep 2007 20:16:51 -0400 Subject: [Tutor] IndexError: list index out of range Message-ID: <ea979d70709191716i5c3628edxb47ef489b24a0954@mail.gmail.com> Greetings, I'm working with Python 2.4.3 on the GNU/Linux platform. I'm currently playing with functions and stacks, and am using the "Towers of Hanoi" as a test game to play with. Note: This game is not a recursive programming exercise, it is meant to be solved by the player, manually. The game asks for a number to move, and a stack to move it to. The game starts out in this state: ========================= A [5, 4, 3, 2, 1] False B [] True C [] True ========================= Enter number and stack to move it to: 1b It seems to work fine with my test moves: 1b 2c 1c 3b 1a 2b 1b 1b 4c 1c 2a 1a 3c 1b 2c 1c 5b Which brings the game to this state: Enter number and stack to move it to: 5b 5 B A [] True B [5] False C [4, 3, 2, 1] False ========================= Then, in the second round of test moves, it bombs on the first move: Enter number and stack to move it to: 1b 1 B Traceback (most recent call last): File "funcStack.py", line 73, in ? moveNum(num,abc) File "funcStack.py", line 52, in moveNum popNum(num) File "funcStack.py", line 32, in popNum if num == stackA[-1]: IndexError: list index out of range The second round of test moves are: 1b 2a 1a 3b 1c 2b 1b 4a 1a 2c 1c 3a 1b 2a 1a 5c The third round of test moves are: 1b 2c 1c 3b 1a 2b 1b 1b 4c 1c 2a 1a 3c 1b 2c 1c Which should bring the game to this state: ========================= C [] True B [] True A [5, 4, 3, 2, 1] False ========================= Here is my Python source code: # funcStacks.py # passing parameters, returning values, pushing and popping # 2007-09-19 # b h a a l u u at g m a i l dot c o m ###################################### """ Pseudocode 1. Get the number to move and the column to move it to: 1b, 2c, etc. 2. Find the column the number is in: A, B, or C 3. Is it the last number (ie. can it be popped?) num == stackA[-1] 4. If the number can be popped, pop it! stackA.pop() 5. Else, number is buried: return an error and try again. 6. Determine if the number can be legally moved to the column requested. 7. If the column is empty, move the number: stackB.append(num) 8. If the column has a number, is it larger? stackB.append(num) 9. Else if number in column is smaller, return an error and try again. 10. Loop. """ num = 0 abc = "" EMPTY = [] stackA = [] stackB = [] stackC = [] def isEmpty(stack): if stack == EMPTY: return True else: return False def popNum(num): if num == stackA[-1]: stackA.pop() elif num == stackB[-1]: stackB.pop() elif num == stackC[-1]: stackC.pop() else: return "Error: number not available." def pushNum(num,abc): if abc == 'C': stackC.append(num) elif abc == 'B': stackB.append(num) elif abc == 'A': stackA.append(num) else: return "Move not allowed, try again." def moveNum(num,abc): popNum(num) pushNum(num,abc) return stack_status() def stack_status(): print "A",stackA, isEmpty(stackA) print "B",stackB, isEmpty(stackB) print "C",stackC, isEmpty(stackC) # main print '='*25 stackA=[5,4,3,2,1] stack_status() print '='*25 myMove = raw_input('Enter number and stack to move it to: ') while myMove != 'Q': num = int(myMove[0]) abc = str.upper(myMove[1]) print num, abc moveNum(num,abc) print '='*25 myMove = raw_input('Enter number and stack to move it to: ') Remember, I'm learning Python. I haven't studied OOP yet, so suggestions to make a class out of it won't help me much. =) -- bhaaluu at gmail dot com From mlangford.cs03 at gtalumni.org Thu Sep 20 02:22:16 2007 From: mlangford.cs03 at gtalumni.org (Michael Langford) Date: Wed, 19 Sep 2007 20:22:16 -0400 Subject: [Tutor] IndexError: list index out of range In-Reply-To: <ea979d70709191716i5c3628edxb47ef489b24a0954@mail.gmail.com> References: <ea979d70709191716i5c3628edxb47ef489b24a0954@mail.gmail.com> Message-ID: <82b4f5810709191722r21ce1f22i29e2c2504b171879@mail.gmail.com> You should check if the stack is empty before you access it: def popNum(num): if len(stackA) > 0 and num == stackA[-1]: stackA.pop() #etc --Michael -- Michael Langford Phone: 404-386-0495 Consulting: http://www.TierOneDesign.com/ Entertaining: http://www.ThisIsYourCruiseDirectorSpeaking.com On 9/19/07, bhaaluu <bhaaluu at gmail.com> wrote: > > Greetings, > I'm working with Python 2.4.3 on the GNU/Linux platform. > I'm currently playing with functions and stacks, and am > using the "Towers of Hanoi" as a test game to play with. > Note: This game is not a recursive programming exercise, > it is meant to be solved by the player, manually. > > The game asks for a number to move, and a stack to move it to. > The game starts out in this state: > ========================= > A [5, 4, 3, 2, 1] False > B [] True > C [] True > ========================= > Enter number and stack to move it to: 1b > > It seems to work fine with my test moves: > > 1b 2c 1c 3b 1a 2b 1b 1b 4c 1c 2a 1a 3c 1b 2c 1c 5b > Which brings the game to this state: > > Enter number and stack to move it to: 5b > 5 B > A [] True > B [5] False > C [4, 3, 2, 1] False > ========================= > > Then, in the second round of test moves, it bombs on the first move: > > Enter number and stack to move it to: 1b > 1 B > Traceback (most recent call last): > File "funcStack.py", line 73, in ? > moveNum(num,abc) > File "funcStack.py", line 52, in moveNum > popNum(num) > File "funcStack.py", line 32, in popNum > if num == stackA[-1]: > IndexError: list index out of range > > The second round of test moves are: > 1b 2a 1a 3b 1c 2b 1b 4a 1a 2c 1c 3a 1b 2a 1a 5c > The third round of test moves are: > 1b 2c 1c 3b 1a 2b 1b 1b 4c 1c 2a 1a 3c 1b 2c 1c > Which should bring the game to this state: > ========================= > C [] True > B [] True > A [5, 4, 3, 2, 1] False > ========================= > > Here is my Python source code: > # funcStacks.py > # passing parameters, returning values, pushing and popping > # 2007-09-19 > # b h a a l u u at g m a i l dot c o m > ###################################### > """ > Pseudocode > 1. Get the number to move and the column to move it to: 1b, 2c, etc. > 2. Find the column the number is in: A, B, or C > 3. Is it the last number (ie. can it be popped?) num == stackA[-1] > 4. If the number can be popped, pop it! stackA.pop() > 5. Else, number is buried: return an error and try again. > 6. Determine if the number can be legally moved to the column requested. > 7. If the column is empty, move the number: stackB.append(num) > 8. If the column has a number, is it larger? stackB.append(num) > 9. Else if number in column is smaller, return an error and try again. > 10. Loop. > """ > num = 0 > abc = "" > EMPTY = [] > stackA = [] > stackB = [] > stackC = [] > > def isEmpty(stack): > if stack == EMPTY: > return True > else: > return False > > def popNum(num): > if num == stackA[-1]: > stackA.pop() > elif num == stackB[-1]: > stackB.pop() > elif num == stackC[-1]: > stackC.pop() > else: > return "Error: number not available." > > def pushNum(num,abc): > if abc == 'C': > stackC.append(num) > elif abc == 'B': > stackB.append(num) > elif abc == 'A': > stackA.append(num) > else: > return "Move not allowed, try again." > > def moveNum(num,abc): > popNum(num) > pushNum(num,abc) > return stack_status() > > def stack_status(): > print "A",stackA, isEmpty(stackA) > print "B",stackB, isEmpty(stackB) > print "C",stackC, isEmpty(stackC) > > # main > print '='*25 > stackA=[5,4,3,2,1] > stack_status() > print '='*25 > > myMove = raw_input('Enter number and stack to move it to: ') > while myMove != 'Q': > num = int(myMove[0]) > abc = str.upper(myMove[1]) > print num, abc > moveNum(num,abc) > print '='*25 > myMove = raw_input('Enter number and stack to move it to: ') > > Remember, I'm learning Python. I haven't studied OOP yet, so > suggestions to make a class out of it won't help me much. =) > -- > bhaaluu at gmail dot 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/20070919/d6f90df7/attachment.htm From kent37 at tds.net Thu Sep 20 02:35:07 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 19 Sep 2007 20:35:07 -0400 Subject: [Tutor] IndexError: list index out of range In-Reply-To: <ea979d70709191716i5c3628edxb47ef489b24a0954@mail.gmail.com> References: <ea979d70709191716i5c3628edxb47ef489b24a0954@mail.gmail.com> Message-ID: <46F1C03B.9050801@tds.net> bhaaluu wrote: > def popNum(num): > if num == stackA[-1]: > stackA.pop() What happens here if stackA is empty? Kent From bhaaluu at gmail.com Thu Sep 20 02:47:19 2007 From: bhaaluu at gmail.com (bhaaluu) Date: Wed, 19 Sep 2007 20:47:19 -0400 Subject: [Tutor] IndexError: list index out of range In-Reply-To: <46F1C03B.9050801@tds.net> References: <ea979d70709191716i5c3628edxb47ef489b24a0954@mail.gmail.com> <46F1C03B.9050801@tds.net> Message-ID: <ea979d70709191747r335b6bdbt55e2a537d633aa28@mail.gmail.com> On 9/19/07, Kent Johnson <kent37 at tds.net> wrote: > bhaaluu wrote: > > > def popNum(num): > > if num == stackA[-1]: > > stackA.pop() > > What happens here if stackA is empty? > > Kent This was how I was looking for the number. It seems to me that if the list was EMPTY or didn't have the sought after number, it would look in the next list... after all, that's what it did 16 times in the first round... but now that I look back at it, stackA wasn't empty until after the 5 had been moved out of it. But the search worked even when stackB and stackC were empty. Interesting. As far as I could see, all three conditionals in popNum(num) were the same, just checking different lists. I tried Michael's suggestion and added: if len(stackA) > 0 and num == stackA[-1]: etc. to popNum(num) and that worked to continue through the second and third rounds of test values. Thank you very much! -- bhaaluu at gmail dot com From jtp at nc.rr.com Thu Sep 20 03:23:24 2007 From: jtp at nc.rr.com (James) Date: Wed, 19 Sep 2007 21:23:24 -0400 Subject: [Tutor] Threading in Python Message-ID: <F6902FC9-5B53-4C43-8C61-65E0306DAD65@nc.rr.com> Hi. :) I have a question regarding threading in Python. I'm trying to write a wrapper script in Python that will spin off multiple (lots!) of instances of an I/O benchmark/testing utility. I'm very interested in doing this in Python, but am unsure if this is a good idea. I thought I read somewhere online that because of the way Python was written, even if I spun off (forked off?) multiple instances of a program, all those child processes would be restricted to one CPU. Is this true? I'm not sure if the utility I'm forking is CPU-intensive; it may very well be. Does Python indeed have this limitation? Also, should I be using os.fork() for this kind of program? Thoughts/ideas appreciated. :) Thanks! .james From kent37 at tds.net Thu Sep 20 04:19:25 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 19 Sep 2007 22:19:25 -0400 Subject: [Tutor] Threading in Python In-Reply-To: <F6902FC9-5B53-4C43-8C61-65E0306DAD65@nc.rr.com> References: <F6902FC9-5B53-4C43-8C61-65E0306DAD65@nc.rr.com> Message-ID: <46F1D8AD.5010305@tds.net> James wrote: > Hi. :) > > I have a question regarding threading in Python. I'm trying to write > a wrapper script in Python that will spin off multiple (lots!) of > instances of an I/O benchmark/testing utility. I'm very interested > in doing this in Python, but am unsure if this is a good idea. I > thought I read somewhere online that because of the way Python was > written, even if I spun off (forked off?) multiple instances of a > program, all those child processes would be restricted to one CPU. > Is this true? Python *threads* are limited to a single CPU, or at least they will not run faster on multiple CPUs. I don't think there is any such restriction for forked processes. > I'm not sure if the utility I'm forking is CPU-intensive; it may very > well be. Does Python indeed have this limitation? I would think an I/O benchmark is more likely to be I/O bound... > Also, should I be using os.fork() for this kind of program? There is a fair amount of activity these days around making Python friendly to multi-processing. See http://wiki.python.org/moin/ParallelProcessing Kent From jtp at nc.rr.com Thu Sep 20 04:56:19 2007 From: jtp at nc.rr.com (James) Date: Wed, 19 Sep 2007 22:56:19 -0400 Subject: [Tutor] Threading in Python In-Reply-To: <46F1D8AD.5010305@tds.net> References: <F6902FC9-5B53-4C43-8C61-65E0306DAD65@nc.rr.com> <46F1D8AD.5010305@tds.net> Message-ID: <20737943-56E2-4768-9538-0EB3BE2D77F9@nc.rr.com> Thanks for the quick reply. Interesting. I'm a little overwhelmed with the different terminology (fork, spawn, thread, etc.). I'm under the impression that I'm supposed to use os.fork() or os.spawn() for something like what I'm trying to do (start multiple instances of the I/O utility from one Python script). However, from what I gather from the documentation, os.fork() is going to fork the python Python script that calls the original fork (so fork won't directly start off the programs that I need). How would I go about forking + then executing an application? Isn't this what spawn does? Or should I stick with fork + exec*? Lots to learn, I guess. ;) .james On Sep 19, 2007, at 10:19 PM, Kent Johnson wrote: > James wrote: >> Hi. :) >> I have a question regarding threading in Python. I'm trying to >> write a wrapper script in Python that will spin off multiple >> (lots!) of instances of an I/O benchmark/testing utility. I'm >> very interested in doing this in Python, but am unsure if this is >> a good idea. I thought I read somewhere online that because of >> the way Python was written, even if I spun off (forked off?) >> multiple instances of a program, all those child processes would >> be restricted to one CPU. Is this true? > > Python *threads* are limited to a single CPU, or at least they will > not run faster on multiple CPUs. I don't think there is any such > restriction for forked processes. > >> I'm not sure if the utility I'm forking is CPU-intensive; it may >> very well be. Does Python indeed have this limitation? > > I would think an I/O benchmark is more likely to be I/O bound... > >> Also, should I be using os.fork() for this kind of program? > > There is a fair amount of activity these days around making Python > friendly to multi-processing. See > http://wiki.python.org/moin/ParallelProcessing > > Kent From brunson at brunson.com Thu Sep 20 06:48:40 2007 From: brunson at brunson.com (Eric Brunson) Date: Wed, 19 Sep 2007 22:48:40 -0600 Subject: [Tutor] Threading in Python In-Reply-To: <20737943-56E2-4768-9538-0EB3BE2D77F9@nc.rr.com> References: <F6902FC9-5B53-4C43-8C61-65E0306DAD65@nc.rr.com> <46F1D8AD.5010305@tds.net> <20737943-56E2-4768-9538-0EB3BE2D77F9@nc.rr.com> Message-ID: <46F1FBA8.5020505@brunson.com> James wrote: > Thanks for the quick reply. > > Interesting. I'm a little overwhelmed with the different terminology > (fork, spawn, thread, etc.). I'm under the impression that I'm > supposed to use os.fork() or os.spawn() for something like what I'm > trying to do (start multiple instances of the I/O utility from one > Python script). > A fork is a fundamental system call in which the OS makes a nearly identical copy of the running process. I know it's a kind of *-hole thing to say, but... if you don't know why you'd want to fork your process, you probably don't need to. Forking is usually used for disassociating yourself from your parent process to become a daemon. However, it's a basic function of the system an intrinsic in many other higher level actions. One you don't mention is "exec", which is to replace your running process image with a new process image. You can do it from the shell, type "exec somebinary" and that binary replaces your shell process, so when the exec'd process exits, your session is terminated. I mention that because when you combine a fork with an exec, you get a spawn. Your parent process duplicates itself, but the child process chooses to exec another process. So the child copy of the initial process is replaced by new running binary and you have a spawned process running as a child of the first. Finally, a thread (sometimes referred to as a "lightweight process" or "lwp") is kind of like a fork, except a fork duplicates everything about the initial process (except a return code) while a thread shares state with the parent process and all its sibling threads. The interesting thing about a python thread is that it is not an OS level thread, it is a separate execution thread, but still controlled by the python interpreter. So, while a dual processor computer can choose to execute two different processes or thread simultaneously, since there's only one python interpreter (per python process) a python thread is never run concurrently with another thread in the same python process. It's more of a conceptual thing, > However, from what I gather from the documentation, os.fork() is > going to fork the python Python script that calls the original fork > (so fork won't directly start off the programs that I need). How > would I go about forking + then executing an application? Isn't this > what spawn does? Or should I stick with fork + exec*? > However, what you are trying to do, i.e. spawn multiple concurrent child processes, could actually take advantage of a multi processor system using python threads. If you created multiple threads, many of which spawned an independent subprocess, those subprocesses could be executed concurrently by different processors, while their status was still being coordinated via the python thread model. Just give it a go knowing that it is an efficient design, and drop us a line if you have more questions or any problems. Sincerely, e. > Lots to learn, I guess. ;) > Always. ;-) When you think there's nothing else to learn, you've already become obsolete. > .james > > On Sep 19, 2007, at 10:19 PM, Kent Johnson wrote: > > >> James wrote: >> >>> Hi. :) >>> I have a question regarding threading in Python. I'm trying to >>> write a wrapper script in Python that will spin off multiple >>> (lots!) of instances of an I/O benchmark/testing utility. I'm >>> very interested in doing this in Python, but am unsure if this is >>> a good idea. I thought I read somewhere online that because of >>> the way Python was written, even if I spun off (forked off?) >>> multiple instances of a program, all those child processes would >>> be restricted to one CPU. Is this true? >>> >> Python *threads* are limited to a single CPU, or at least they will >> not run faster on multiple CPUs. I don't think there is any such >> restriction for forked processes. >> >> >>> I'm not sure if the utility I'm forking is CPU-intensive; it may >>> very well be. Does Python indeed have this limitation? >>> >> I would think an I/O benchmark is more likely to be I/O bound... >> >> >>> Also, should I be using os.fork() for this kind of program? >>> >> There is a fair amount of activity these days around making Python >> friendly to multi-processing. See >> http://wiki.python.org/moin/ParallelProcessing >> >> Kent >> > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From mlangford.cs03 at gtalumni.org Thu Sep 20 07:10:01 2007 From: mlangford.cs03 at gtalumni.org (Michael Langford) Date: Thu, 20 Sep 2007 01:10:01 -0400 Subject: [Tutor] Threading in Python In-Reply-To: <F6902FC9-5B53-4C43-8C61-65E0306DAD65@nc.rr.com> References: <F6902FC9-5B53-4C43-8C61-65E0306DAD65@nc.rr.com> Message-ID: <82b4f5810709192210se5647e8ued8f1e6f74efd39b@mail.gmail.com> Python has no way to force the OS to schedule a process on a given processor (therefore you're safe). If you use multiple processes, you can get true concurrency. This is one of the reasons process based concurrency is superior to threads (*ducks from items thrown by threadophiles*). Then again, you don't have a shared memory space, so get used to using pickle if you don't have another text protocol to send data back and forth. --Michael -- Michael Langford Phone: 404-386-0495 Consulting: http://www.TierOneDesign.com/ Entertaining: http://www.ThisIsYourCruiseDirectorSpeaking.com On 9/19/07, James <jtp at nc.rr.com> wrote: > > Hi. :) > > I have a question regarding threading in Python. I'm trying to write > a wrapper script in Python that will spin off multiple (lots!) of > instances of an I/O benchmark/testing utility. I'm very interested > in doing this in Python, but am unsure if this is a good idea. I > thought I read somewhere online that because of the way Python was > written, even if I spun off (forked off?) multiple instances of a > program, all those child processes would be restricted to one CPU. > Is this true? > > I'm not sure if the utility I'm forking is CPU-intensive; it may very > well be. Does Python indeed have this limitation? > > Also, should I be using os.fork() for this kind of program? > > Thoughts/ideas appreciated. :) > > Thanks! > .james > _______________________________________________ > 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/20070920/d19937f4/attachment.htm From work at infomaniak.ch Thu Sep 20 08:12:30 2007 From: work at infomaniak.ch (cedric briner) Date: Thu, 20 Sep 2007 08:12:30 +0200 Subject: [Tutor] uncomprehension on RE In-Reply-To: <46F10986.1090101@tds.net> References: <46F0DC95.3090208@infomaniak.ch> <46F10986.1090101@tds.net> Message-ID: <46F20F4E.3040604@infomaniak.ch> Kent Johnson wrote: > cedric briner wrote: >> Hello, >> >> I do not understand the behaviour of this: >> >> import re >> re.search('(a)*','aaa').groups() >> ('a',) >> >> I was thinking that the ``*'' will operate on the group delimited by the >> parenthesis. And so, I was expecting this result: >> ('a', 'a', 'a') >> >> Is there something I'am missing ? > > It just doesn't work that way. that's sad :( > The returned group is the last string > matched by the group: > In [17]: re.search('(a.)*','azabac').groups() > Out[17]: ('ac',) Somewhere I find re really too difficult. I was never able to write an re expression rightly from the first shoot ! Happily there is kodos and redet. > Use re.findall() instead: > In [18]: re.findall('a.', 'azabac') > Out[18]: ['az', 'ab', 'ac'] that's what I found, that I've to do the job with many python steps than just one > If you want overlapping matches you have to search in a loop and collect > them yourself, findall() gives only non-overlapping matches. To let you know, I'm writing a script to generate bind9 configuration from a nis hosts table. So I was trying in a one re to catch from this: <ip> <hostname> [ <cname> ...] [# comment] e.g: 10.12.23.45 hostname1 alias1 alias2 alias3 # there is a nice comment 37.64.86.23 hostname2 35.25.89.34 hostname3 alias5 .. .. so I was wishing to write an re expresion which will do in a one step all the job ! maybe am'I expecting too much from re :) Ced. -- Cedric BRINER Geneva - Switzerland From alan.gauld at btinternet.com Thu Sep 20 09:23:11 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 20 Sep 2007 08:23:11 +0100 Subject: [Tutor] IndexError: list index out of range References: <ea979d70709191716i5c3628edxb47ef489b24a0954@mail.gmail.com><46F1C03B.9050801@tds.net> <ea979d70709191747r335b6bdbt55e2a537d633aa28@mail.gmail.com> Message-ID: <fct75q$bfv$1@sea.gmane.org> "bhaaluu" <bhaaluu at gmail.com> wrote > of it. But the search worked even when stackB > and stackC were empty. Interesting. You never checked stackB or stackC when they were empty because it always found something in a prior stack first. > I could see, all three conditionals in popNum(num) > were the same, just checking different lists. They were, and all had the same problem, you only hit it on stackA. If you had started your sequence with 1c instead of 1b and then tried 1b you would have hit the problem on the second move. Alan G. From alan.gauld at btinternet.com Thu Sep 20 09:32:45 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 20 Sep 2007 08:32:45 +0100 Subject: [Tutor] Income calculator References: <46F1A89B.6030306@lavabit.com> Message-ID: <fct7np$d7a$1@sea.gmane.org> "Ulrich Holtzhausen" <ulrich at lavabit.com> wrote First the good news, what you are doing should work. > File "./pyfinances.py", line 18 > print "Your expected earnings for %s is %d" % > (financeLogs['month'], > financeLogs['total']) > ^ > SyntaxError: invalid syntax > > Non-working program: http://pastebin.com/f4da62e57 The bad news is that the code in the error message doesn't match the code on pastebin. Which is correct? If its pastebin you are missing a closing paren. If its the error message then we need to see the real code. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From boykie.mackay at gmail.com Thu Sep 20 09:37:21 2007 From: boykie.mackay at gmail.com (Boykie Mackay) Date: Thu, 20 Sep 2007 08:37:21 +0100 Subject: [Tutor] Income calculator In-Reply-To: <a04dbf4b0709191622g1e62484uafe4b88f0f45eb53@mail.gmail.com> References: <46F1AA27.3050603@lavabit.com> <a04dbf4b0709191622g1e62484uafe4b88f0f45eb53@mail.gmail.com> Message-ID: <1190273841.7991.56.camel@apprentice-laptop> I don't know if it's any help,but the line mentioned in the error message; File "./pyfinances.py", line 18 > print "Your expected earnings for %s is %d" % > (financeLogs['month'], > financeLogs['total']) > ^ doesn't seem to be properly formatted.There should be a comma after the closing quotation marks,a closing bracket after the first variable and a % sign before the next i.e: > print "Your expected earnings for %s is %d", %(financeLogs['month']),% > financeLogs['total']) Hope above works! On Thu, 2007-09-20 at 11:22 +1200, Ian Witham wrote: > Your links aren't working for me. > > On 9/20/07, Ulrich Holtzhausen <ulrich at lavabit.com> wrote: > Hi there, > > I started out with Python about two days ago, it's my very > first shot at > programming and I find it quite interesting. Anyway I'll get > to the point: > > I made a simple script that works, albeit not the shortest way > I think > but it works, however I would like to make it a bit more > "fancy" though > I'm getting an error. Below is my first script that works, the > second > script doesn't work, the error I get on the second script is > simple, but > I can't seem to figure out how to fix it, also, if there's a > shorter way > of doing this effectively, please help :) . > > File "./pyfinances.py", line 18 > print "Your expected earnings for %s is %d" % > (financeLogs['month'], > financeLogs['total']) > ^ > SyntaxError: invalid syntax > > Basic working program: http://pastebin.com/f2f7f3cd5 > Non-working program: http://pastebin.com/f4da62e57 > > Thanks in advance for any help contributed. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From alan.gauld at btinternet.com Thu Sep 20 09:45:16 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 20 Sep 2007 08:45:16 +0100 Subject: [Tutor] Threading in Python References: <F6902FC9-5B53-4C43-8C61-65E0306DAD65@nc.rr.com> Message-ID: <fct8f8$fgb$1@sea.gmane.org> "James" <jtp at nc.rr.com> wrote > I have a question regarding threading in Python. I'm trying to > write > a wrapper script in Python that will spin off multiple (lots!) of > instances of an I/O benchmark/testing utility. Are these instances of an external program or simply instances of some python code? If its an external program and you are on *nix you may not need threading at all simply call os.system() with the program in the background. Or if you need to communicate with the program use threading and os.popen() (or the subprocess module and its Popen class) to start the utility. The utility as a separate process will be able to run on different CPUs even though the threads all run in Python interpreter on one CPU. If OTOH the utility is python code then you will need to look at using fork/exec or spawn. I touch on os.fork in my inter-process comms topic of my tutor. In your case instead of setting up a client/server you would simply run your utility functions. But forking does give you the potential to communicate results back to the parent process via a pipe... 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 Sep 20 09:50:51 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 20 Sep 2007 08:50:51 +0100 Subject: [Tutor] Income calculator References: <46F1AA27.3050603@lavabit.com><a04dbf4b0709191622g1e62484uafe4b88f0f45eb53@mail.gmail.com> <1190273841.7991.56.camel@apprentice-laptop> Message-ID: <fct8pm$gih$1@sea.gmane.org> "Boykie Mackay" <boykie.mackay at gmail.com> wrote > doesn't seem to be properly formatted.There should be a comma after > the > closing quotation marks,a closing bracket after the first variable > and a > % sign before the next i.e: > >> print "Your expected earnings for %s is %d", >> %(financeLogs['month']),% >> financeLogs['total']) > > Hope above works! Nope, this is wrong. The OP had it correct. String formatting has a string followed by a % followed by a tuple of values. Did you actually try executing the line of code you posted? What happened? Alan G. From ulrich at lavabit.com Thu Sep 20 10:16:40 2007 From: ulrich at lavabit.com (Ulrich Holtzhausen) Date: Thu, 20 Sep 2007 10:16:40 +0200 Subject: [Tutor] Income calculator In-Reply-To: <fct8pm$gih$1@sea.gmane.org> References: <46F1AA27.3050603@lavabit.com><a04dbf4b0709191622g1e62484uafe4b88f0f45eb53@mail.gmail.com> <1190273841.7991.56.camel@apprentice-laptop> <fct8pm$gih$1@sea.gmane.org> Message-ID: <46F22C68.4050300@lavabit.com> Alan Gauld wrote: > "Boykie Mackay" <boykie.mackay at gmail.com> wrote > > >> doesn't seem to be properly formatted.There should be a comma after >> the >> closing quotation marks,a closing bracket after the first variable >> and a >> % sign before the next i.e: >> >> >>> print "Your expected earnings for %s is %d", >>> %(financeLogs['month']),% >>> financeLogs['total']) >>> >> Hope above works! >> > > Nope, this is wrong. The OP had it correct. > String formatting has a string followed by a % followed by a tuple of > values. > Did you actually try executing the line of code you posted? What > happened? > > Alan G. > > Thanks all, I'm having trouble figuring out how to reply to your inputs...my first time ever I joined some mailing list tutori-ish/user-group thing :D . Thanks for all your help once again. I think I might have sent one or two e-mails to individuals instead of via the tutor. Sorry if so. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > ________________________________________________________________________________ > Shelter from rain, wind and sun is a basic human need. With your help, > deserving families can have decent places to call home. > http://lavabit.com/apps/director?ad=5 > ________________________________________________________________________________ > > From sanelson at gmail.com Thu Sep 20 10:41:34 2007 From: sanelson at gmail.com (Stephen Nelson-Smith) Date: Thu, 20 Sep 2007 09:41:34 +0100 Subject: [Tutor] uncomprehension on RE In-Reply-To: <46F20F4E.3040604@infomaniak.ch> References: <46F0DC95.3090208@infomaniak.ch> <46F10986.1090101@tds.net> <46F20F4E.3040604@infomaniak.ch> Message-ID: <b6131fdc0709200141id24d4fbtf09e937a99595e52@mail.gmail.com> On 9/20/07, cedric briner <work at infomaniak.ch> wrote: > To let you know, I'm writing a script to generate bind9 configuration > from a nis hosts table. So I was trying in a one re to catch from this: > > <ip> <hostname> [ <cname> ...] [# comment] > e.g: > 10.12.23.45 hostname1 alias1 alias2 alias3 # there is a nice comment > 37.64.86.23 hostname2 > 35.25.89.34 hostname3 alias5 I'm not sure I follow. Could you state explicitly what the input is (I think the above), and what output you want? S. From ulrich at lavabit.com Thu Sep 20 12:17:14 2007 From: ulrich at lavabit.com (Ulrich Holtzhausen) Date: Thu, 20 Sep 2007 12:17:14 +0200 Subject: [Tutor] IRC bot Message-ID: <46F248AA.5070706@lavabit.com> I recently used the existing codebase of a very very simple IRC bot of which is in one of O'Reilly's books. I modified it a bit and added the NICK properties etc. and I was able to get it to join the server and my IRC channel. However I'd like to know how can I get it to print to screen what's happening in the channel, because it only prints that it's connecting to the network and that it's connected. I want it to show the MOTD etc. of the server. Also, if anyone knows how, how can I set the /ctcp version reply in the code so that if someone requests the version it's sent? Below is the script: <<<----------------------------------------------------------------------------------------------------------------------------------->>> import socket import string HOST="irc.opera.com" PORT=6667 NICK="pyKe" IDENT="pyke" REALNAME="pyKe - KeN's Python bot." CHANNEL="#ChatterBox" readbuffer="" s=socket.socket( ) s.connect((HOST, PORT)) s.send("NICK %s\r\n" % NICK) s.send("USER %s %s +iwxb :%s\r\n" % (IDENT, HOST, REALNAME)) s.send("JOIN %s\r\n" % CHANNEL) data_received = s.recv(1024) print data_received while 1: readbuffer=readbuffer+s.recv(1024) temp=string.split(readbuffer, "\n") readbuffer=temp.pop( ) for line in temp: line=string.rstrip(line) line=string.split(line) if(line[0]=="PING"): s.send("PONG %s\r\n" % line[1]) <<<----------------------------------------------------------------------------------------------------------------------------------->>> Thanks in advance From shantanoo at gmail.com Thu Sep 20 12:24:06 2007 From: shantanoo at gmail.com (=?UTF-8?Q?=E0=A4=B6=E0=A4=82=E0=A4=A4=E0=A4=A8=E0=A5=81_(Shantanoo)?=) Date: Thu, 20 Sep 2007 15:54:06 +0530 Subject: [Tutor] IRC bot In-Reply-To: <46F248AA.5070706@lavabit.com> References: <46F248AA.5070706@lavabit.com> Message-ID: <230174700709200324v536774b3i22b0102de65737b7@mail.gmail.com> On 9/20/07, Ulrich Holtzhausen <ulrich at lavabit.com> wrote: > I recently used the existing codebase of a very very simple IRC bot of > which is in one of O'Reilly's books. I modified it a bit and added the > NICK properties etc. and I was able to get it to join the server and my > IRC channel. However I'd like to know how can I get it to print to > screen what's happening in the channel, because it only prints that it's > connecting to the network and that it's connected. I want it to show the > MOTD etc. of the server. > > Also, if anyone knows how, how can I set the /ctcp version reply in the > code so that if someone requests the version it's sent? Below is the script: > > <<<----------------------------------------------------------------------------------------------------------------------------------->>> > import socket > import string > > HOST="irc.opera.com" > PORT=6667 > NICK="pyKe" > IDENT="pyke" > REALNAME="pyKe - KeN's Python bot." > CHANNEL="#ChatterBox" > readbuffer="" > > s=socket.socket( ) > s.connect((HOST, PORT)) > s.send("NICK %s\r\n" % NICK) > s.send("USER %s %s +iwxb :%s\r\n" % (IDENT, HOST, REALNAME)) > s.send("JOIN %s\r\n" % CHANNEL) > data_received = s.recv(1024) > print data_received > > while 1: > readbuffer=readbuffer+s.recv(1024) > temp=string.split(readbuffer, "\n") > readbuffer=temp.pop( ) > > for line in temp: > line=string.rstrip(line) > line=string.split(line) > > if(line[0]=="PING"): > s.send("PONG %s\r\n" % line[1]) > <<<----------------------------------------------------------------------------------------------------------------------------------->>> > > Thanks in advance Instead of writing your own code for the bot, I would suggest using supybot (http://supybot.com/). regards, shantanoo From ulrich at lavabit.com Thu Sep 20 12:34:55 2007 From: ulrich at lavabit.com (Ulrich Holtzhausen) Date: Thu, 20 Sep 2007 12:34:55 +0200 Subject: [Tutor] IRC bot In-Reply-To: <230174700709200324v536774b3i22b0102de65737b7@mail.gmail.com> References: <46F248AA.5070706@lavabit.com> <230174700709200324v536774b3i22b0102de65737b7@mail.gmail.com> Message-ID: <46F24CCF.9050703@lavabit.com> ????? (Shantanoo) wrote: > Instead of writing your own code for the bot, I would suggest using > supybot (http://supybot.com/). > > regards, > shantanoo > Hey, thank you for the suggestion. I do know about supybot and phenny, both are python bots. I want to get experience in some IRC parameters and socks programming + I want to write it all from scratch. I'm not sure how the modules work on the others. I'm still very new to this as this is only my third day with python. From boykie.mackay at gmail.com Thu Sep 20 12:56:19 2007 From: boykie.mackay at gmail.com (Boykie Mackay) Date: Thu, 20 Sep 2007 11:56:19 +0100 Subject: [Tutor] Income calculator In-Reply-To: <fct8pm$gih$1@sea.gmane.org> References: <46F1AA27.3050603@lavabit.com> <a04dbf4b0709191622g1e62484uafe4b88f0f45eb53@mail.gmail.com> <1190273841.7991.56.camel@apprentice-laptop> <fct8pm$gih$1@sea.gmane.org> Message-ID: <1190285779.7991.70.camel@apprentice-laptop> I have tried the code and it does give a syntax error.Another lesson for me I guess.I should test code before posting,unless I'm sure of my post. The problem was with the brackets in lines 17/18.I got the code running but I don't think the 'quit' function works as it should. Being a novice I think it would be something for me to come back to later. On Thu, 2007-09-20 at 08:50 +0100, Alan Gauld wrote: > "Boykie Mackay" <boykie.mackay at gmail.com> wrote > > > doesn't seem to be properly formatted.There should be a comma after > > the > > closing quotation marks,a closing bracket after the first variable > > and a > > % sign before the next i.e: > > > >> print "Your expected earnings for %s is %d", > >> %(financeLogs['month']),% > >> financeLogs['total']) > > > > Hope above works! > > Nope, this is wrong. The OP had it correct. > String formatting has a string followed by a % followed by a tuple of > values. > Did you actually try executing the line of code you posted? What > happened? > > Alan G. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From alan.gauld at btinternet.com Thu Sep 20 13:10:25 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 20 Sep 2007 12:10:25 +0100 Subject: [Tutor] Income calculator References: <46F1AA27.3050603@lavabit.com><a04dbf4b0709191622g1e62484uafe4b88f0f45eb53@mail.gmail.com><1190273841.7991.56.camel@apprentice-laptop><fct8pm$gih$1@sea.gmane.org> <1190285779.7991.70.camel@apprentice-laptop> Message-ID: <fctkfs$mp1$1@sea.gmane.org> "Boykie Mackay" <boykie.mackay at gmail.com> wrote >I have tried the code and it does give a syntax error.Another lesson >for > me I guess.I should test code before posting,unless I'm sure of my > post. It's a good idea, but don't worry about it. I've been caught out a few times myself. Alan G From rabidpoobear at gmail.com Thu Sep 20 13:42:43 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Thu, 20 Sep 2007 06:42:43 -0500 Subject: [Tutor] IRC bot In-Reply-To: <46F24CCF.9050703@lavabit.com> References: <46F248AA.5070706@lavabit.com> <230174700709200324v536774b3i22b0102de65737b7@mail.gmail.com> <46F24CCF.9050703@lavabit.com> Message-ID: <46F25CB3.9060001@gmail.com> Ulrich Holtzhausen wrote: > ????? (Shantanoo) wrote: > >> Instead of writing your own code for the bot, I would suggest using >> supybot (http://supybot.com/). >> >> regards, >> shantanoo >> >> > Hey, thank you for the suggestion. I do know about supybot and phenny, > both are python bots. I want to get experience in some IRC parameters > and socks programming + I want to write it all from scratch. I'm not > sure how the modules work on the others. I'm still very new to this as > this is only my third day with python. > Just read all incoming messages on the socket and dump them to an output file. Then go look at it and figure out what you're receiving and how you can parse it. IRC commands are generally pretty easy to parse. Once you figure out the structure, you should be able to send stuff to the server in the same structure (using an online reference to find the commands and their corresponding arguments.) If you don't feel like following this approach, I can just give you some code that listens to the IRC server and echoes everything. But that somehow seems less fun. -Luke From rabidpoobear at gmail.com Thu Sep 20 13:46:50 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Thu, 20 Sep 2007 06:46:50 -0500 Subject: [Tutor] OO triangulation In-Reply-To: <OF1AB81E96.8AB8FF37-ONC125735B.0030CD29-C125735B.00326739@velux.com> References: <OF1AB81E96.8AB8FF37-ONC125735B.0030CD29-C125735B.00326739@velux.com> Message-ID: <46F25DAA.1030706@gmail.com> J?nos Juh?sz wrote: > Dear Tutors, > > I made an OO style triangulation based on an old C progam I made about 10 > years ago. > The sample is working finally. > First time I made the triangulation with recursion, but I reached the > recursion limit very shortly. > So I changed the recursion to a queue. > > I am interested about your opinions about the OO style. > It hasn't got too much comments, but probably readable. > [snip some code] > > def Swap(self, C): ## Ta2 Ta2 > """ Swap a triangle pair """ ## / \ / > \ > D = self.NextPoint(C) ## / a2 \ / > a2 \ > A = self.PrevPoint(C) ## A---------B > A---------B > t2 = self.BottomTriangle(C) ## / | \ | \ / | > / | \ > B = t2.NextPoint(D) ## a1| \ t2 | a1 > |self / | > a1 = self.BottomTriangle(D) ## |self \ | d2 | > / t2 | d2 > d1 = self.BottomTriangle(A) ## \ | \ | / \ | > / | / > a2 = t2.BottomTriangle(D) ## C---------D > C---------D > d2 = t2.BottomTriangle(A) ## \ d1 / \ > d1 / > Ta2 = a2.NextPoint(B) ## \ / \ > / > Td1 = d1.NextPoint(C) ## Td1 Td1 > As you can see, your code is not very readable. Please post large sections of code as attachments in the future. This is probably the main reason you've gotten no replies. -Luke From bhaaluu at gmail.com Thu Sep 20 13:49:02 2007 From: bhaaluu at gmail.com (bhaaluu) Date: Thu, 20 Sep 2007 07:49:02 -0400 Subject: [Tutor] IndexError: list index out of range In-Reply-To: <fct75q$bfv$1@sea.gmane.org> References: <ea979d70709191716i5c3628edxb47ef489b24a0954@mail.gmail.com> <46F1C03B.9050801@tds.net> <ea979d70709191747r335b6bdbt55e2a537d633aa28@mail.gmail.com> <fct75q$bfv$1@sea.gmane.org> Message-ID: <ea979d70709200449o7e8622aftee03bee44e202ba4@mail.gmail.com> On 9/20/07, Alan Gauld <alan.gauld at btinternet.com> wrote: > "bhaaluu" <bhaaluu at gmail.com> wrote > > > of it. But the search worked even when stackB > > and stackC were empty. Interesting. > > You never checked stackB or stackC when they were > empty because it always found something in a prior > stack first. > > > I could see, all three conditionals in popNum(num) > > were the same, just checking different lists. > > They were, and all had the same problem, > you only hit it on stackA. > > If you had started your sequence with 1c instead > of 1b and then tried 1b you would have hit the problem > on the second move. That's right! =) After Michael suggested a fix, I went back and started the game with the list at stackC filled, and worked from C to A and the same thing happened. So Michael's fix worked fine for *that* problem. Now I'm working on checking if a move is "legal" or not. Rules: Only one number may be moved at a time. A larger number may not be put on top of a smaller number. Tonight, I'm giving a presentation ("Introduction to Python") to my local Linux Users Group (LUG). I will be telling everyone about the great Tutors on this fantastic mailing list. This list is surely one of the best 'features' about Python. =) > > Alan G. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > Anyway, even though I was somewhat braindead by the end of the day... Here is the current iteration of the funky funcStacks.py proggie: It still needs a lot of work, but it is a FUN way to learn stuff. # funcStacks.py # passing parameters, returning values, pushing and popping # 2007-09-19 # b h a a l u u at g m a i l dot c o m ###################################### """ Pseudocode 1. Get the number to move and the column to move it to: 1b, 2c, etc. 2. Find the column the number is in: A, B, or C 3. Is it the last number (ie. can it be popped?) num == stackA[-1] 4. If the number can be popped, pop it! stackA.pop() 5. Else, number is buried: return an error and try again. 6. Determine if the number can be legally moved to the column requested. 7. If the column is empty, move the number: stackB.append(num) 8. If the column has a number, is it larger? stackB.append(num) 9. Else if number in column is smaller, return an error and try again. 10. Loop. Test game 1: 1b 2c 1c 3b 1a 2b 1b 4c 1c 2a 1a 3c 1b 2c 1c 5b 1b 2a 1a 3b 1c 2b 1b 4a 1a 2c 1c 3a 1b 2a 1a 5c 1b 2c 1c 3b 1a 2b 1b 4c 1c 2a 1a 3c 1b 2c 1c 0 Test game 2: 1c 2b 1b 3c 1a 2c 1c 4b 1b 2a 1a 3b 1c 2b 1b 5c 1a 2c 1c 3a 1b 2a 1a 4c 1c 2b 1b 3c 1a 2c 1c 0 """ num = 0 abc = "" EMPTY = [] stackA = [] stackB = [] stackC = [] def isEmpty(stack): if stack == EMPTY: return True else: return False def isLegal(num,abc): if abc == 'C': if stackC == EMPTY or num < stackC[-1]: return True else: return False elif abc == 'B': if stackB == EMPTY or num < stackB[-1]: return True else: return False elif abc == 'A': if stackA == EMPTY or num < stackA[-1]: return True else: return False def popNum(num): if len(stackA) > 0 and num == stackA[-1]: stackA.pop() elif len(stackB) > 0 and num == stackB[-1]: stackB.pop() elif len (stackC) > 0 and num == stackC[-1]: stackC.pop() else: return "Error: number not available." def pushNum(num,abc): if abc == 'C' and isLegal(num,abc): stackC.append(num) elif abc == 'B' and isLegal(num,abc): stackB.append(num) elif abc == 'A' and isLegal(num,abc): stackA.append(num) else: return 'Error' def moveNum(num,abc): popNum(num) pushNum(num,abc) return stack_status() def stack_status(): print "A",stackA, isEmpty(stackA) print "B",stackB, isEmpty(stackB) print "C",stackC, isEmpty(stackC) return # main print '='*25 stackA=[5,4,3,2,1] stack_status() print '='*25 myMove = raw_input('Enter number and stack to move it to: ') while myMove != '0': num = int(myMove[0]) abc = str.upper(myMove[1]) print num, abc, isLegal(num,abc) moveNum(num,abc) print '='*25 myMove = raw_input('Enter number and stack to move it to: ') # end funcStacks.py Happy Programming! -- bhaaluu at gmail dot com From rabidpoobear at gmail.com Thu Sep 20 13:52:05 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Thu, 20 Sep 2007 06:52:05 -0500 Subject: [Tutor] uncomprehension on RE In-Reply-To: <b6131fdc0709190504t5560e203u72ccd1f5c3e52ef2@mail.gmail.com> References: <46F0DC95.3090208@infomaniak.ch> <b6131fdc0709190504t5560e203u72ccd1f5c3e52ef2@mail.gmail.com> Message-ID: <46F25EE5.5010706@gmail.com> Stephen Nelson-Smith wrote: > On 9/19/07, cedric briner <work at infomaniak.ch> wrote: > >> Hello, >> >> I do not understand the behaviour of this: >> >> import re >> re.search('(a)*','aaa').groups() >> ('a',) >> >> I was thinking that the ``*'' will operate on the group delimited by the >> parenthesis. And so, I was expecting this result: >> ('a', 'a', 'a') >> >> Is there something I'am missing ? >> > > <reposting as sent to OP by default... I am sure the list used to > munge addresses and things were sent to the list by default> > The "reply-to-all" or "reply-list" or "reply-group" functions should do what you want. We'll not get into the semantics of why the list doesn't munge. It's an unproductive discussion that the admins don't like. -Luke From bhaaluu at gmail.com Thu Sep 20 14:05:19 2007 From: bhaaluu at gmail.com (bhaaluu) Date: Thu, 20 Sep 2007 08:05:19 -0400 Subject: [Tutor] Income calculator In-Reply-To: <fctkfs$mp1$1@sea.gmane.org> References: <46F1AA27.3050603@lavabit.com> <a04dbf4b0709191622g1e62484uafe4b88f0f45eb53@mail.gmail.com> <1190273841.7991.56.camel@apprentice-laptop> <fct8pm$gih$1@sea.gmane.org> <1190285779.7991.70.camel@apprentice-laptop> <fctkfs$mp1$1@sea.gmane.org> Message-ID: <ea979d70709200505t5803186dr36d369349ab3ca3b@mail.gmail.com> On 9/20/07, Alan Gauld <alan.gauld at btinternet.com> wrote: > > "Boykie Mackay" <boykie.mackay at gmail.com> wrote > > >I have tried the code and it does give a syntax error.Another lesson > >for > > me I guess.I should test code before posting,unless I'm sure of my > > post. > > It's a good idea, but don't worry about it. I've been caught out a few > times myself. > > Alan G > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > I've tested the following with Python 2.4 running on GNU/Linux, and it seems to work fine. I believe I had to add a closing parens somewhere, and also added another input at the bottom so it would loop again so I could type 'quit' or 'details'. #!/usr/bin/env python # This is pyFinances v0.2 menu = """ To use this program, type 'details' to enter your details and 'quit' to quit the program. """ financeLogs = {} options = raw_input((menu)) while options != 'quit': if options == 'details': financeLogs['n_rate'] = float(raw_input("Hourly rate: ")) financeLogs['o_rate'] = float(raw_input("By which sum is your rate multiplied for overtime hours? ")) financeLogs['n_hours'] = float(raw_input("Normal hours to work: ")) financeLogs['o_hours'] = float(raw_input("Overtime hours to work: ")) financeLogs['month'] = raw_input("For which month are you due payment? ") financeLogs['rates'] = financeLogs['n_rate'] * financeLogs['o_rate'] financeLogs['total'] = (financeLogs['n_rate']) * (financeLogs['n_hours']) + (financeLogs['o_rate'] * financeLogs['o_hours']) print "Your expected earnings for %s is %d" % (financeLogs['month'], financeLogs['total']) options = raw_input((menu)) Now he needs to add a way to save the details to a file, and open the file to edit the details. If I'm not mistaken, since the details are in dictionary form, a 'pickle' is called for? =) -- bhaaluu at gmail dot com From ulrich at lavabit.com Thu Sep 20 14:11:18 2007 From: ulrich at lavabit.com (Ulrich Holtzhausen) Date: Thu, 20 Sep 2007 14:11:18 +0200 Subject: [Tutor] IRC bot In-Reply-To: <46F25CB3.9060001@gmail.com> References: <46F248AA.5070706@lavabit.com> <230174700709200324v536774b3i22b0102de65737b7@mail.gmail.com> <46F24CCF.9050703@lavabit.com> <46F25CB3.9060001@gmail.com> Message-ID: <46F26366.9020701@lavabit.com> Hey, Well I have the following: data_received = s.recv(1024) print data_received That only prints this when the bot connects: ''':irc.opera.com NOTICE AUTH :*** Looking up your hostname...''' Nothing else, so I am not sure whether it would actually save anything other than that if I chose to have it save do a file. I will try that though. Maybe there is some other way of doing this? > Just read all incoming messages on the socket and dump them to an > output file. Then go look at it and figure out what you're receiving > and how you can parse it. > IRC commands are generally pretty easy to parse. > Once you figure out the structure, you should be able to send stuff to > the server in the same structure (using an online reference to find > the commands and their corresponding arguments.) > If you don't feel like following this approach, I can just give you > some code that listens to the IRC server and echoes everything. > But that somehow seems less fun. > -Luke From kent37 at tds.net Thu Sep 20 14:21:22 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 20 Sep 2007 08:21:22 -0400 Subject: [Tutor] Threading in Python In-Reply-To: <46F1FBA8.5020505@brunson.com> References: <F6902FC9-5B53-4C43-8C61-65E0306DAD65@nc.rr.com> <46F1D8AD.5010305@tds.net> <20737943-56E2-4768-9538-0EB3BE2D77F9@nc.rr.com> <46F1FBA8.5020505@brunson.com> Message-ID: <46F265C2.4080806@tds.net> Eric Brunson wrote: > I mention that because when you combine a fork with an exec, you get a > spawn. Your parent process duplicates itself, but the child process > chooses to exec another process. So the child copy of the initial > process is replaced by new running binary and you have a spawned process > running as a child of the first. The subprocess module provides another way to do this. > The interesting thing about a python thread is that it is not an OS > level thread, Not true; Python threads are OS threads. > it is a separate execution thread, but still controlled by > the python interpreter. Yes, it is running the interpreter. > So, while a dual processor computer can choose > to execute two different processes or thread simultaneously, since > there's only one python interpreter (per python process) a python thread > is never run concurrently with another thread in the same python > process. It's more of a conceptual thing, The interpreter will never execute Python code in two threads at the same time. But if one thread is blocked for I/O or sleep() another thread will run, and it is possible for one thread to be running C code in an extension while another thread is running Python code in the interpreter. Kent From ulrich at lavabit.com Thu Sep 20 14:25:42 2007 From: ulrich at lavabit.com (Ulrich Holtzhausen) Date: Thu, 20 Sep 2007 14:25:42 +0200 Subject: [Tutor] Income calculator In-Reply-To: <1190285779.7991.70.camel@apprentice-laptop> References: <46F1AA27.3050603@lavabit.com> <a04dbf4b0709191622g1e62484uafe4b88f0f45eb53@mail.gmail.com> <1190273841.7991.56.camel@apprentice-laptop> <fct8pm$gih$1@sea.gmane.org> <1190285779.7991.70.camel@apprentice-laptop> Message-ID: <46F266C6.5080204@lavabit.com> Boykie Mackay wrote: > I have tried the code and it does give a syntax error.Another lesson for > me I guess.I should test code before posting,unless I'm sure of my post. > > The problem was with the brackets in lines 17/18.I got the code running > but I don't think the 'quit' function works as it should. > > Being a novice I think it would be something for me to come back to > later. > On Thu, 2007-09-20 at 08:50 +0100, Alan Gauld wrote: > Yes, the quit function does not work, I will see what I can do about that and also there seems to be some calculation errors, well the script runs but it calculates the wrong results, but that can be fixed easily I believe. From kent37 at tds.net Thu Sep 20 14:24:22 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 20 Sep 2007 08:24:22 -0400 Subject: [Tutor] IRC bot In-Reply-To: <46F248AA.5070706@lavabit.com> References: <46F248AA.5070706@lavabit.com> Message-ID: <46F26676.6060500@tds.net> Ulrich Holtzhausen wrote: > I recently used the existing codebase of a very very simple IRC bot of > which is in one of O'Reilly's books. I modified it a bit and added the > NICK properties etc. and I was able to get it to join the server and my > IRC channel. However I'd like to know how can I get it to print to > screen what's happening in the channel, because it only prints that it's > connecting to the network and that it's connected. I want it to show the > MOTD etc. of the server. > while 1: > readbuffer=readbuffer+s.recv(1024) > temp=string.split(readbuffer, "\n") > readbuffer=temp.pop( ) > > for line in temp: I think you want print line here. Kent From bhaaluu at gmail.com Thu Sep 20 14:25:34 2007 From: bhaaluu at gmail.com (bhaaluu) Date: Thu, 20 Sep 2007 08:25:34 -0400 Subject: [Tutor] OO triangulation In-Reply-To: <46F25DAA.1030706@gmail.com> References: <OF1AB81E96.8AB8FF37-ONC125735B.0030CD29-C125735B.00326739@velux.com> <46F25DAA.1030706@gmail.com> Message-ID: <ea979d70709200525p2f72e938lac228047dd304afc@mail.gmail.com> Greetings, I'm running Python 2.4 on a GNU/Linux system. Actually, I was able to get this code to work after only a few edits that had to do with line wrap, nothing more. The code works fine, and although I don't understand what it is displaying, the display is rather interesting. On my 1GHz CPU, the 100 point retriangularization takes 0.29 seconds. The 1000 point retriangulation takes 4.62 seconds, and the 10000 pointer takes 99.04 seconds. The display looks like a bad spider web! =) Retriangulate! -- bhaaluu at gmail dot com On 9/20/07, Luke Paireepinart <rabidpoobear at gmail.com> wrote: > J?nos Juh?sz wrote: > > Dear Tutors, > > > > I made an OO style triangulation based on an old C progam I made about 10 > > years ago. > > The sample is working finally. > > First time I made the triangulation with recursion, but I reached the > > recursion limit very shortly. > > So I changed the recursion to a queue. > > > > I am interested about your opinions about the OO style. > > It hasn't got too much comments, but probably readable. > > [snip some code] > > > > def Swap(self, C): ## Ta2 Ta2 > > """ Swap a triangle pair """ ## / \ / > > \ > > D = self.NextPoint(C) ## / a2 \ / > > a2 \ > > A = self.PrevPoint(C) ## A---------B > > A---------B > > t2 = self.BottomTriangle(C) ## / | \ | \ / | > > / | \ > > B = t2.NextPoint(D) ## a1| \ t2 | a1 > > |self / | > > a1 = self.BottomTriangle(D) ## |self \ | d2 | > > / t2 | d2 > > d1 = self.BottomTriangle(A) ## \ | \ | / \ | > > / | / > > a2 = t2.BottomTriangle(D) ## C---------D > > C---------D > > d2 = t2.BottomTriangle(A) ## \ d1 / \ > > d1 / > > Ta2 = a2.NextPoint(B) ## \ / \ > > / > > Td1 = d1.NextPoint(C) ## Td1 Td1 > > > As you can see, your code is not very readable. > Please post large sections of code as attachments in the future. > This is probably the main reason you've gotten no replies. > -Luke > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Thu Sep 20 14:39:34 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 20 Sep 2007 08:39:34 -0400 Subject: [Tutor] uncomprehension on RE In-Reply-To: <46F20F4E.3040604@infomaniak.ch> References: <46F0DC95.3090208@infomaniak.ch> <46F10986.1090101@tds.net> <46F20F4E.3040604@infomaniak.ch> Message-ID: <46F26A06.4030300@tds.net> cedric briner wrote: > To let you know, I'm writing a script to generate bind9 configuration > from a nis hosts table. So I was trying in a one re to catch from this: > > <ip> <hostname> [ <cname> ...] [# comment] > e.g: > 10.12.23.45 hostname1 alias1 alias2 alias3 # there is a nice comment > 37.64.86.23 hostname2 > 35.25.89.34 hostname3 alias5 > .. .. > > > so I was wishing to write an re expresion which will do in a one step > all the job ! maybe am'I expecting too much from re :) You can use an re to get the four primary fields, then use split() to break up the aliases. Try this: import re data = '''10.12.23.45 hostname1 alias1 alias2 alias3 # there is a nice comment 37.64.86.23 hostname2 35.25.89.34 hostname3 alias5 '''.splitlines() for line in data: match = re.search(r'^(\S+)\s+(\S+)([^#]*)(#.*)?$', line) if match: ip, host, aliases, comment = match.group(1, 2, 3, 4) print 'ip:', ip print 'host:', host if aliases: aliases = aliases.strip().split() for alias in aliases: print 'alias:', alias if comment: print comment print Kent From rabidpoobear at gmail.com Thu Sep 20 14:44:33 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Thu, 20 Sep 2007 07:44:33 -0500 Subject: [Tutor] IRC bot In-Reply-To: <46F26366.9020701@lavabit.com> References: <46F248AA.5070706@lavabit.com> <230174700709200324v536774b3i22b0102de65737b7@mail.gmail.com> <46F24CCF.9050703@lavabit.com> <46F25CB3.9060001@gmail.com> <46F26366.9020701@lavabit.com> Message-ID: <46F26B31.3040200@gmail.com> Ulrich Holtzhausen wrote: > Hey, > > Well I have the following: > > data_received = s.recv(1024) > print data_received > > That only prints this when the bot connects: > > ''':irc.opera.com NOTICE AUTH :*** Looking up your hostname...''' > > Nothing else, so I am not sure whether it would actually save anything > other than that if I chose to have it save do a file. I will try that > though. Maybe there is some other way of doing this? I made an IRC bot based on this same file when I was first starting Python, too. So forgive the code for any readability issues it may have. Basically what it does is monitors private messages for "themes" or "quit" if it gets "themes" it replies with a bunch of themes. The bot was for pyweek a few years ago. Anyway, you could just as easily monitor for a ctcp request. See if the code makes any sense. I'd give more help, but I'm in extremely busy right now. Freenode doesn't let you send private messages if you don't identify yourself, but it's simple to create a password. Just do a /msg NickServ register password SO make sure you register your bot prior to using this, or you won't be able to send private messages. -Luke -------------- next part -------------- A non-text attachment was scrubbed... Name: irclist.py Type: text/x-python Size: 3753 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20070920/41354542/attachment-0001.py From alan.gauld at btinternet.com Thu Sep 20 14:52:30 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 20 Sep 2007 13:52:30 +0100 Subject: [Tutor] Income calculator References: <46F1AA27.3050603@lavabit.com><a04dbf4b0709191622g1e62484uafe4b88f0f45eb53@mail.gmail.com><1190273841.7991.56.camel@apprentice-laptop><fct8pm$gih$1@sea.gmane.org><1190285779.7991.70.camel@apprentice-laptop><fctkfs$mp1$1@sea.gmane.org> <ea979d70709200505t5803186dr36d369349ab3ca3b@mail.gmail.com> Message-ID: <fctqf9$cf3$1@sea.gmane.org> "bhaaluu" <bhaaluu at gmail.com> wrote > Now he needs to add a way to save the details to a file, and open > the file to edit the details. If I'm not mistaken, since the details > are > in dictionary form, a 'pickle' is called for? =) I think you are thinking of a shelve which looks a lot like a dictionary on file. A pickle can dsave any kind of object not just dictionaries. Shelve uses pickle to store its values. Alan G. From rabidpoobear at gmail.com Thu Sep 20 15:05:33 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Thu, 20 Sep 2007 08:05:33 -0500 Subject: [Tutor] Finding prime numbers In-Reply-To: <82b4f5810709190931u16ee0621xc6608d2bcb2fec5e@mail.gmail.com> References: <1190218927.7991.25.camel@apprentice-laptop> <82b4f5810709190931u16ee0621xc6608d2bcb2fec5e@mail.gmail.com> Message-ID: <46F2701D.9050803@gmail.com> Michael Langford wrote: > Attachments are a bad thing to send to open mailing lists in general. Perhaps in general they are, but specifically, I'd prefer code that's decently long to be attached or pastebinned. e-mail clients and servers are often unfriendly on code. That's the point of attachments. Differentiating between data and text, so the various middlemen can manipulate the text however they feel without affecting the 'payload', as it were. P.S. every single e-mail I've ever gotten from you has come with an attachment. It's called part 1.2.txt and contains """ _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor """ Based on this observation alone, I'd have to say I don't think the tutor list minds attachments. > > In your case, the list appears to have filtered off the code. Please > paste it in inline. I think it's more likely he just forgot to attach it. I've been on this list for 2 years and I've never heard of problems with attachments not going through. It's not inherently less intrusive to paste the code inline, and it has unpleasant side-effects in certain situations. Most e-mail clients that I'm aware of are set to, by default, inline the code at the end of the e-mail as you're viewing it anyway. -Luke From rabidpoobear at gmail.com Thu Sep 20 15:07:23 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Thu, 20 Sep 2007 08:07:23 -0500 Subject: [Tutor] OO triangulation In-Reply-To: <ea979d70709200525p2f72e938lac228047dd304afc@mail.gmail.com> References: <OF1AB81E96.8AB8FF37-ONC125735B.0030CD29-C125735B.00326739@velux.com> <46F25DAA.1030706@gmail.com> <ea979d70709200525p2f72e938lac228047dd304afc@mail.gmail.com> Message-ID: <46F2708B.60106@gmail.com> bhaaluu wrote: > Greetings, > > I'm running Python 2.4 on a GNU/Linux system. > Actually, I was able to get this code to work after only a few > edits that had to do with line wrap, nothing more. Other people are less willing to do this than you are :) It's really the OP's prerogative to make messages posted to the list as easy as possible to be reviewed. And attaching the file rather than posting it inline is an extremely simple improvement and increase in convenience. Perhaps I only speak for myself, but I have a bit of a priority queue in my head, weighted to ease of testing and how much I understand about the topic already, so I'm more likely to help people who 1) post well-formatted code I can run directly, 2) post something I know a decent bit about, or both. -Luke > The code > works fine, and although I don't understand what it is displaying, > the display is rather interesting. On my 1GHz CPU, the 100 point > retriangularization takes 0.29 seconds. The 1000 point retriangulation > takes 4.62 seconds, and the 10000 pointer takes 99.04 seconds. > The display looks like a bad spider web! =) > > Retriangulate! > From janos.juhasz at VELUX.com Thu Sep 20 15:46:19 2007 From: janos.juhasz at VELUX.com (=?ISO-8859-1?Q?J=E1nos_Juh=E1sz?=) Date: Thu, 20 Sep 2007 15:46:19 +0200 Subject: [Tutor] OO triangulation with attacment Message-ID: <OF1AB81E96.8AB8FF37-ONC125735B.0030CD29-C125735C.004BA743@velux.com> Dear Tutors, I made an OO style triangulation based on an old C progam I made about 10 years ago. This makes Delaunay triangualtion over a point cloud in 2D. http://en.wikipedia.org/wiki/Delaunay_triangulation The sample is working finally. First time I made the triangulation with recursion, but I reached the recursion limit very shortly. So I changed the recursion to a queue. I am interested about your opinions about the OO style I made in it. It hasn't got too much comments, but probably readable. I hope you can test the code easily. I think it has got some interesting programing solutions. Yours sincerely, ______________________________ J?nos Juh?sz -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070920/71b9bb9f/attachment.htm -------------- next part -------------- A non-text attachment was scrubbed... Name: triangle.py Type: application/octet-stream Size: 8756 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20070920/71b9bb9f/attachment.obj From ulrich at lavabit.com Thu Sep 20 20:34:29 2007 From: ulrich at lavabit.com (Ulrich Holtzhausen) Date: Thu, 20 Sep 2007 20:34:29 +0200 Subject: [Tutor] IRC bot In-Reply-To: <46F26676.6060500@tds.net> References: <46F248AA.5070706@lavabit.com> <46F26676.6060500@tds.net> Message-ID: <46F2BD35.7080506@lavabit.com> Thank you Kent. That worked for the output and I'm able to understand the IRC commands and syntaxes much better now. From rob.andrews at gmail.com Thu Sep 20 21:22:19 2007 From: rob.andrews at gmail.com (Rob Andrews) Date: Thu, 20 Sep 2007 14:22:19 -0500 Subject: [Tutor] how to specify working directory from within python app? Message-ID: <8d757d2e0709201222n38fafd1aka2368004021830e0@mail.gmail.com> I've got a weekly project here in which I have to take a somewhat arbitrary number of input files, create working directories in which to process each of them, and call other programs from within the scope of those directories. The source files are in a directory named 'orig' under the project root directory. Output of my program is placed in directories nested two-deep under the job root in different branches. Once my data is in those other directories, I have to call certain other 3rd-party programs to act on the data in various ways. Those 3rd-party programs are typically called from a Windows command prompt, and only from within the directory in which the data is found. For example: C:\MyProject\BrandA\ProductB>3rdPartyApp.bat projectConfig.cfg (where "MyProject" is the project root, "BrandA" is a subdirectory, and "ProductB" is another subdirectory nested one level deeper) How might I best go about calling these 3rd-party apps? On this project, the directories are created dynamically, and there can be quite a few. -Rob A. From kent37 at tds.net Thu Sep 20 21:40:54 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 20 Sep 2007 15:40:54 -0400 Subject: [Tutor] how to specify working directory from within python app? In-Reply-To: <8d757d2e0709201222n38fafd1aka2368004021830e0@mail.gmail.com> References: <8d757d2e0709201222n38fafd1aka2368004021830e0@mail.gmail.com> Message-ID: <46F2CCC6.8040801@tds.net> Rob Andrews wrote: > I've got a weekly project here in which I have to take a somewhat > arbitrary number of input files, create working directories in which > to process each of them, and call other programs from within the scope > of those directories. Use subprocess.call() to run the external program and supply the working directory path in the cwd parameter. Kent From alan.gauld at btinternet.com Thu Sep 20 22:35:24 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 20 Sep 2007 21:35:24 +0100 Subject: [Tutor] how to specify working directory from within python app? References: <8d757d2e0709201222n38fafd1aka2368004021830e0@mail.gmail.com> Message-ID: <fculj8$3pn$1@sea.gmane.org> "Rob Andrews" <rob.andrews at gmail.com> wrote > I've got a weekly project here in which I have to take a somewhat > arbitrary number of input files, create working directories in which > to process each of them, and call other programs from within the > scope > of those directories. > > The source files are in a directory named 'orig' under the project > root directory. Output of my program is placed in directories nested > two-deep under the job root in different branches. You might be able to use the os.walk() function to derive the list of directories and change ionto them using os.chdir() > Once my data is in those other directories, I have to call certain > other 3rd-party programs to act on the data in various ways. A job for the subprocess module. > How might I best go about calling these 3rd-party apps? On this > project, the directories are created dynamically, and there can be > quite a few. You can create directories and traverse them and so forth using the os, os.path and glob modules depending on exactly how you want to go about things. Most of these things are covered in my Working with the OS topic in my tutorial. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From rob.andrews at gmail.com Thu Sep 20 23:25:12 2007 From: rob.andrews at gmail.com (Rob Andrews) Date: Thu, 20 Sep 2007 16:25:12 -0500 Subject: [Tutor] how to specify working directory from within python app? In-Reply-To: <46F2CCC6.8040801@tds.net> References: <8d757d2e0709201222n38fafd1aka2368004021830e0@mail.gmail.com> <46F2CCC6.8040801@tds.net> Message-ID: <8d757d2e0709201425y347322e1hd3bef64386db5098@mail.gmail.com> Thanks (to Alan, as well). I had a wild suspicion that there would be a fairly standard solution to this one. I've just never had to really look into it before. On 9/20/07, Kent Johnson <kent37 at tds.net> wrote: > Rob Andrews wrote: > > I've got a weekly project here in which I have to take a somewhat > > arbitrary number of input files, create working directories in which > > to process each of them, and call other programs from within the scope > > of those directories. > > Use subprocess.call() to run the external program and supply the working > directory path in the cwd parameter. > > Kent > -- Libertarian Party of Mississippi: http://mslp.org From zero2188 at hotmail.com Thu Sep 20 23:45:47 2007 From: zero2188 at hotmail.com (david lazaro) Date: Thu, 20 Sep 2007 17:45:47 -0400 Subject: [Tutor] (no subject) Message-ID: <BAY135-W248EF6E638969192482457CEBA0@phx.gbl> hi, im relatively new to this, im on chapter 2 of the python book and its asking me to print version 2.0 of "Game over" by using keyboard art, but when i draw out "over" is comes up half cut off, any reasons why that would happen? _________________________________________________________________ More photos; more messages; more whatever ? Get MORE with Windows Live? Hotmail?. NOW with 5GB storage. http://imagine-windowslive.com/hotmail/?locale=en-us&ocid=TXT_TAGHM_migration_HM_mini_5G_0907 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070920/06cbb8c3/attachment.htm From kent37 at tds.net Fri Sep 21 00:02:16 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 20 Sep 2007 18:02:16 -0400 Subject: [Tutor] Game over In-Reply-To: <BAY135-W248EF6E638969192482457CEBA0@phx.gbl> References: <BAY135-W248EF6E638969192482457CEBA0@phx.gbl> Message-ID: <46F2EDE8.80707@tds.net> david lazaro wrote: > hi, im relatively new to this, im on chapter 2 of the python book and > its asking me to print version 2.0 of "Game over" by using keyboard art, > but when i draw out "over" is comes up half cut off, any reasons why > that would happen? Welcome! Some tips for getting help on this list: - use a meaningful subject line - if you have a question about a book, tell us the name of the book - if you have a question about a program, show us the program; you can include short programs directly in your email - if you get an error message, copy and paste the entire error message, including the traceback, into your email. Kent From witham.ian at gmail.com Fri Sep 21 00:08:37 2007 From: witham.ian at gmail.com (Ian Witham) Date: Fri, 21 Sep 2007 10:08:37 +1200 Subject: [Tutor] (no subject) In-Reply-To: <BAY135-W248EF6E638969192482457CEBA0@phx.gbl> References: <BAY135-W248EF6E638969192482457CEBA0@phx.gbl> Message-ID: <a04dbf4b0709201508m307d9bb7uc4ff92a1ddc05fed@mail.gmail.com> On 9/21/07, david lazaro <zero2188 at hotmail.com> wrote: > > hi, im relatively new to this, im on chapter 2 of the python book and its > asking me to print version 2.0 of "Game over" by using keyboard art, but > when i draw out "over" is comes up half cut off, any reasons why that would > happen? > Please describe the problem in more detail. I have no idea which Python book you are referring to, or what the exercise involves. It could be helpful to show us the code you have written so far. Ian -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070921/d1491387/attachment.htm From alan.gauld at btinternet.com Fri Sep 21 00:17:12 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 20 Sep 2007 23:17:12 +0100 Subject: [Tutor] (no subject) References: <BAY135-W248EF6E638969192482457CEBA0@phx.gbl> Message-ID: <fcuri4$oi7$1@sea.gmane.org> "david lazaro" <zero2188 at hotmail.com> wrote > hi, im relatively new to this, Welcome to the tutor list. > im on chapter 2 of the python book Which one? There are dozens of python books! > and its asking me to print version 2.0 of "Game over" > by using keyboard art, Hint, Use a triple quoted string to create the message. And make sure your output display is using a fixed width font! > but when i draw out "over" is comes up half cut off, > any reasons why that would happen? Without seeing your code we can only guess. When posting to the list try to be as specific as possible. Describe what you are trying to do and what exactly happens - sample data helps. If there are error messages send the full message in your mail. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From zero2188 at hotmail.com Fri Sep 21 00:35:04 2007 From: zero2188 at hotmail.com (david lazaro) Date: Thu, 20 Sep 2007 18:35:04 -0400 Subject: [Tutor] (no subject) Message-ID: <BAY135-W14376FA108E06530FE8CAACEBA0@phx.gbl> the book is called "Python Programming, Second Edition for the absolute beginner". im using the triple quotes in the beginning and end. im sending an attachment of what its coming out as. the actual program should say Game Over, but its cutting Over in half. _________________________________________________________________ Capture your memories in an online journal! http://www.reallivemoms.com?ocid=TXT_TAGHM&loc=us -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070920/b487321b/attachment.htm -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: Game Over 2.0.py Url: http://mail.python.org/pipermail/tutor/attachments/20070920/b487321b/attachment.txt From witham.ian at gmail.com Fri Sep 21 00:57:10 2007 From: witham.ian at gmail.com (Ian Witham) Date: Fri, 21 Sep 2007 10:57:10 +1200 Subject: [Tutor] (no subject) In-Reply-To: <BAY135-W14376FA108E06530FE8CAACEBA0@phx.gbl> References: <BAY135-W14376FA108E06530FE8CAACEBA0@phx.gbl> Message-ID: <a04dbf4b0709201557p7bf235cdi5a0d527473f6b169@mail.gmail.com> On 9/21/07, david lazaro <zero2188 at hotmail.com> wrote: > > the book is called "Python Programming, Second Edition for the absolute > beginner". im using the triple quotes in the beginning and end. im sending > an attachment of what its coming out as. the actual program should say Game > Over, but its cutting Over in half. > > ------------------------------ > Make your little one a shining star! Shine on!<http://www.reallivemoms.com?ocid=TXT_TAGHM&loc=us> > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > The backslash (\) is an escape character and should be used with care. One option would be to escape the backslash itself by using a double backslash (\\), but in your case the best solution would bw to put an "r" before the first triple quote. This denotes a 'raw' string in which escape characters are ignored. eg. r"""Ignore the \n escape characters in this sting""" Ian -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070921/d1a95c71/attachment-0001.htm From alan.gauld at btinternet.com Fri Sep 21 01:01:24 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 21 Sep 2007 00:01:24 +0100 Subject: [Tutor] (no subject) References: <BAY135-W14376FA108E06530FE8CAACEBA0@phx.gbl> Message-ID: <fcuu50$vo8$1@sea.gmane.org> "david lazaro" <zero2188 at hotmail.com> wrote > should say Game Over, but its cutting Over in half. As you know backslashes signal a line continuation. To put a literal backslash in a string you need to double it:@ print 'here is a \\' Or put an r in front of the quotes: print r'here is a \ too' HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From work at infomaniak.ch Fri Sep 21 08:54:33 2007 From: work at infomaniak.ch (cedric briner) Date: Fri, 21 Sep 2007 08:54:33 +0200 Subject: [Tutor] uncomprehension on RE In-Reply-To: <46F26A06.4030300@tds.net> References: <46F0DC95.3090208@infomaniak.ch> <46F10986.1090101@tds.net> <46F20F4E.3040604@infomaniak.ch> <46F26A06.4030300@tds.net> Message-ID: <46F36AA9.6040906@infomaniak.ch> Kent Johnson wrote: > cedric briner wrote: >> To let you know, I'm writing a script to generate bind9 configuration >> from a nis hosts table. So I was trying in a one re to catch from this: >> >> <ip> <hostname> [ <cname> ...] [# comment] >> e.g: >> 10.12.23.45 hostname1 alias1 alias2 alias3 # there is a nice comment >> 37.64.86.23 hostname2 >> 35.25.89.34 hostname3 alias5 >> .. .. >> >> >> so I was wishing to write an re expresion which will do in a one step >> all the job ! maybe am'I expecting too much from re :) > > You can use an re to get the four primary fields, then use split() to > break up the aliases. Try this: > > import re > data = '''10.12.23.45 hostname1 alias1 alias2 alias3 # there is a nice > comment > 37.64.86.23 hostname2 > 35.25.89.34 hostname3 alias5 > '''.splitlines() > > for line in data: > match = re.search(r'^(\S+)\s+(\S+)([^#]*)(#.*)?$', line) > if match: > ip, host, aliases, comment = match.group(1, 2, 3, 4) > print 'ip:', ip > print 'host:', host > if aliases: > aliases = aliases.strip().split() > for alias in aliases: > print 'alias:', alias > if comment: > print comment > print I had done that before writing my first email. I knew how to do this in few python steps. But some how I was expecting RE beeing able to do this in an one shoot. Thanks for your precious help. Ced. > > Kent > -- Cedric BRINER Geneva - Switzerland From work at infomaniak.ch Fri Sep 21 08:56:32 2007 From: work at infomaniak.ch (cedric briner) Date: Fri, 21 Sep 2007 08:56:32 +0200 Subject: [Tutor] uncomprehension on RE In-Reply-To: <b6131fdc0709200141id24d4fbtf09e937a99595e52@mail.gmail.com> References: <46F0DC95.3090208@infomaniak.ch> <46F10986.1090101@tds.net> <46F20F4E.3040604@infomaniak.ch> <b6131fdc0709200141id24d4fbtf09e937a99595e52@mail.gmail.com> Message-ID: <46F36B20.5060501@infomaniak.ch> Stephen Nelson-Smith wrote: > On 9/20/07, cedric briner <work at infomaniak.ch> wrote: > >> To let you know, I'm writing a script to generate bind9 configuration >> from a nis hosts table. So I was trying in a one re to catch from this: >> >> <ip> <hostname> [ <cname> ...] [# comment] >> e.g: >> 10.12.23.45 hostname1 alias1 alias2 alias3 # there is a nice comment >> 37.64.86.23 hostname2 >> 35.25.89.34 hostname3 alias5 > > I'm not sure I follow. Could you state explicitly what the input is > (I think the above), and what output you want? > > S. > the input is 10.12.23.45 hostname1 alias1 alias2 alias3 # there is a nice comment 37.64.86.23 hostname2 35.25.89.34 hostname3 alias5 the ouput is <ip> <hostname> [ <cname> ...] [# <comment>] -- Cedric BRINER Geneva - Switzerland From boykie.mackay at gmail.com Fri Sep 21 10:41:27 2007 From: boykie.mackay at gmail.com (Boykie Mackay) Date: Fri, 21 Sep 2007 09:41:27 +0100 Subject: [Tutor] Optimisation of prime number program (cont. from finding prime numbers) Message-ID: <1190364088.6221.19.camel@apprentice-laptop> Ok,I have learnt how to generate prime numbers and how to 'split' input.The above was to help me solve the second 'SPOJ' challenge,PRIME1.The challenge can be found at <https://www.spoj.pl/problems/classical/sort=0,start=0> I have written my solution and tested it and it works fine,but unfortunately it is times out when tested by 'SPOJ'.I don't know whether it times out because it is inherently slow or because a certain condition takes it into endless loops.I think it is simply because it needs further optimisation.I have researched as much as I could but can't find any way to improve the speed of the program (problem with being a newbie is you don't know what you don't know!) Could you please look at the program (attached) and advise possible optimisations or point me to possible resources that would help solve this challenge. Thanks, Boyks -------------- next part -------------- A non-text attachment was scrubbed... Name: prime1.py Type: text/x-python Size: 1453 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20070921/922bd058/attachment.py From kent37 at tds.net Fri Sep 21 14:12:46 2007 From: kent37 at tds.net (Kent Johnson) Date: Fri, 21 Sep 2007 08:12:46 -0400 Subject: [Tutor] Optimisation of prime number program (cont. from finding prime numbers) In-Reply-To: <1190364088.6221.19.camel@apprentice-laptop> References: <1190364088.6221.19.camel@apprentice-laptop> Message-ID: <46F3B53E.8080808@tds.net> Boykie Mackay wrote: > Ok,I have learnt how to generate prime numbers and how to 'split' > input.The above was to help me solve the second 'SPOJ' > challenge,PRIME1.The challenge can be found at > <https://www.spoj.pl/problems/classical/sort=0,start=0> > > I have written my solution and tested it and it works fine,but > unfortunately it is times out when tested by 'SPOJ'.I don't know whether > it times out because it is inherently slow or because a certain > condition takes it into endless loops.I think it is simply because it > needs further optimisation.I have researched as much as I could but > can't find any way to improve the speed of the program (problem with > being a newbie is you don't know what you don't know!) Computing prime numbers is an area where picking a good algorithm is important. This page might help: http://en.wikipedia.org/wiki/Prime_number#Location_of_prime_numbers Depending on what ranges your program is working with, a sieve algorithm might be faster than checking each number individually. Python is not very fast at raw arithmetic. The top 20 submissions to this problem are in C and C++ and have times <= 0.03. The top Python program has a time of .41, so you are starting out at a disadvantage. If SPOJ allows you to use psyco then do so, that will make a big difference. http://psyco.sourceforge.net/ Kent From brunson at brunson.com Fri Sep 21 18:25:42 2007 From: brunson at brunson.com (Eric Brunson) Date: Fri, 21 Sep 2007 10:25:42 -0600 Subject: [Tutor] Optimisation of prime number program (cont. from finding prime numbers) In-Reply-To: <1190364088.6221.19.camel@apprentice-laptop> References: <1190364088.6221.19.camel@apprentice-laptop> Message-ID: <46F3F086.6040506@brunson.com> Boykie Mackay wrote: > Ok,I have learnt how to generate prime numbers and how to 'split' > input.The above was to help me solve the second 'SPOJ' > challenge,PRIME1.The challenge can be found at > <https://www.spoj.pl/problems/classical/sort=0,start=0> > > I have written my solution and tested it and it works fine,but > unfortunately it is times out when tested by 'SPOJ'.I don't know whether > it times out because it is inherently slow or because a certain > condition takes it into endless loops.I think it is simply because it > needs further optimisation.I have researched as much as I could but > can't find any way to improve the speed of the program (problem with > being a newbie is you don't know what you don't know!) > One optimization, and this is only good for printing a list of primes, is that you only need to test a number's divisibility by all *primes* less than the square root of the number. By keeping a list of the primes already calculated, I saw a 3 times increase in speed counting all the prime numbers between 2 and one million: # test all numbers below sqrt(n) ebrunsonlx(~)$ time python primes.py 78498 primes below 1000000 real 0m14.496s user 0m14.367s sys 0m0.127s # keeping a list of primes ebrunsonlx(~)$ time python primes.py 78498 primes below 1000000 real 0m5.570s user 0m5.551s sys 0m0.017s Here's the code I used: primes = [] def isPrime1( n ): s = n**.5 for d in xrange( 2, int(s)+1 ): if not n%d: return False return True def isPrime2( n ): global primes s = n**.5 for d in primes: if d>s: break if not n%d: return False primes.append( n ) return True That's just the most obvious optimization. I'd like to compare to the performance of Sieve of Eratosthanes, but I don't feel like coding it. > Could you please look at the program (attached) and advise possible > optimisations or point me to possible resources that would help solve > this challenge. > > Thanks, > > Boyks > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From kalle.svensson at gmail.com Fri Sep 21 20:14:08 2007 From: kalle.svensson at gmail.com (Kalle Svensson) Date: Fri, 21 Sep 2007 20:14:08 +0200 Subject: [Tutor] Fwd: Optimisation of prime number program (cont. from finding prime numbers) In-Reply-To: <9584033b0709211112u133681c3ge8ccfa28a31f2544@mail.gmail.com> References: <1190364088.6221.19.camel@apprentice-laptop> <9584033b0709211112u133681c3ge8ccfa28a31f2544@mail.gmail.com> Message-ID: <9584033b0709211114l24fe70e3w6b131268226c3e15@mail.gmail.com> Oops, forgot to send to the list. Hi! On 9/21/07, Boykie Mackay <boykie.mackay at gmail.com> wrote: > Ok,I have learnt how to generate prime numbers and how to 'split' > input.The above was to help me solve the second 'SPOJ' > challenge,PRIME1.The challenge can be found at > <https://www.spoj.pl/problems/classical/sort=0,start=0> ... > Could you please look at the program (attached) and advise possible > optimisations or point me to possible resources that would help solve > this challenge. Interesting problem! I've been experimenting a bit with it, but I'm not anywhere near the runtimes shown in the judge system... It definitely needs some kind of clever algorithm. My first thought was to use the sieve of Erastothenes (http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes) to generate the primes up front, but the maximum value of n is far too large. After that, I tried a combination: generate the primes up to sqrt(max N) and then divide larger numbers by those primes. If written in C, this runs fast enough (0.7 seconds on my laptop for a larger test case) but my Python implementation of the same algorithm still takes too long (about 7.5 seconds for the same test). I'd be very interested in hearing about how to write a Python program for this problem that can handle for example the input 1 999900000 1000000000 in less than a second. Regards, Kalle From tinoloc at gmail.com Fri Sep 21 21:03:28 2007 From: tinoloc at gmail.com (Tino Dai) Date: Fri, 21 Sep 2007 15:03:28 -0400 Subject: [Tutor] Quick question Message-ID: <e033edfb0709211203t1d6002e1q86f3de123e5b17b9@mail.gmail.com> Is there a more pythonic way of doing this: if queuePacket.has_key('procSeq') and \ queuePacket.has_key('opacSeq') and \ queuePacket.has_key('keySeq') and \ len(queuePacket['procSeq']) == 0 and \ len(queuePacket['opacSeq']) == 0 and \ len(queuePacket['keySeq']) == 0: ? -Thanks, Tino -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070921/48429efb/attachment.htm From mlangford.cs03 at gtalumni.org Fri Sep 21 21:12:25 2007 From: mlangford.cs03 at gtalumni.org (Michael Langford) Date: Fri, 21 Sep 2007 15:12:25 -0400 Subject: [Tutor] Quick question In-Reply-To: <e033edfb0709211203t1d6002e1q86f3de123e5b17b9@mail.gmail.com> References: <e033edfb0709211203t1d6002e1q86f3de123e5b17b9@mail.gmail.com> Message-ID: <82b4f5810709211212o2f8ec9l311481fef67606b1@mail.gmail.com> Use the .get method of the dict to return a nonzero value (say None or -1) when it can't find an item. That will half your test cases. Example of .get below: --Michael >>> foo = {} >>> foo['d']=0 >>> foo['a']=1 >>> if(foo.get('a',1)==0 and foo.get('q',1)==0): print foo ... else: print "adsflkj" ... adsflkj >>> foo['q'] = 0 >>> if(foo.get('a',1)==0 and foo.get('q',1)==0): print foo ... else: print "adsflkj" ... adsflkj >>> foo['a'] = 0 >>> if(foo.get('a',1)==0 and foo.get('q',1)==0): print foo ... else: print "adsflkj" ... {'a': 0, 'q': 0, 'd': 0} >>> -- Michael Langford Phone: 404-386-0495 Consulting: http://www.TierOneDesign.com/ Entertaining: http://www.ThisIsYourCruiseDirectorSpeaking.com On 9/21/07, Tino Dai <tinoloc at gmail.com> wrote: > > Is there a more pythonic way of doing this: > > if queuePacket.has_key('procSeq') and \ > queuePacket.has_key('opacSeq') and \ > queuePacket.has_key('keySeq') and \ > len(queuePacket['procSeq']) == 0 and \ > len(queuePacket['opacSeq']) == 0 and \ > len(queuePacket['keySeq']) == 0: > > > ? > > -Thanks, > Tino > > > _______________________________________________ > 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/20070921/5da42e1f/attachment.htm From kent37 at tds.net Fri Sep 21 21:23:28 2007 From: kent37 at tds.net (Kent Johnson) Date: Fri, 21 Sep 2007 15:23:28 -0400 Subject: [Tutor] Quick question In-Reply-To: <e033edfb0709211203t1d6002e1q86f3de123e5b17b9@mail.gmail.com> References: <e033edfb0709211203t1d6002e1q86f3de123e5b17b9@mail.gmail.com> Message-ID: <46F41A30.2030909@tds.net> Tino Dai wrote: > Is there a more pythonic way of doing this: > > if queuePacket.has_key('procSeq') and \ > queuePacket.has_key('opacSeq') and \ > queuePacket.has_key('keySeq') and \ > len(queuePacket['procSeq']) == 0 and \ > len(queuePacket['opacSeq']) == 0 and \ > len(queuePacket['keySeq']) == 0: 'procSeq' in queuePacket is a little better. You could put all the tests in a loop with all(): if all( (key in queuePacket and len(queuePacket[key]) == 0) for key in ('procSeq', 'opaqSeq', 'keySeq')): You could replace the test with something like len(queuePacket.get(key, 'xxx'))==0 which I think is equivalent though maybe a bit obscure... Kent From brunson at brunson.com Fri Sep 21 21:39:18 2007 From: brunson at brunson.com (Eric Brunson) Date: Fri, 21 Sep 2007 13:39:18 -0600 Subject: [Tutor] Quick question In-Reply-To: <e033edfb0709211203t1d6002e1q86f3de123e5b17b9@mail.gmail.com> References: <e033edfb0709211203t1d6002e1q86f3de123e5b17b9@mail.gmail.com> Message-ID: <46F41DE6.3040105@brunson.com> There are quite a few ways to do what you want. Here's are a few variations on a theme: try: if not any( ( len(queuePacket['procSeq']), len(queuePacket['opacSeq']), len(queuePacket['keySeq']) ) ): # Do your stuff here do_stuff() except KeyError: pass Or, using a generator: try: if not any( len(queuePacket[key]) for key in ( 'procSeq', 'opacSeq', 'keySeq' ) ): # Do your stuff here do_stuff() except KeyError: pass Or, using a list comprehension: try: if not [ 1 for key in ( 'procSeq', 'opacSeq', 'keySeq' ) if len(queuePacket[key]) != 0 ] ): # Do your stuff here do_stuff() except KeyError: pass Tino Dai wrote: > Is there a more pythonic way of doing this: > > if queuePacket.has_key('procSeq') and \ > queuePacket.has_key('opacSeq') and \ > queuePacket.has_key('keySeq') and \ > len(queuePacket['procSeq']) == 0 and \ > len(queuePacket['opacSeq']) == 0 and \ > len(queuePacket['keySeq']) == 0: > > > ? > > -Thanks, > Tino > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From malaclypse2 at gmail.com Fri Sep 21 21:44:33 2007 From: malaclypse2 at gmail.com (Jerry Hill) Date: Fri, 21 Sep 2007 15:44:33 -0400 Subject: [Tutor] Quick question In-Reply-To: <e033edfb0709211203t1d6002e1q86f3de123e5b17b9@mail.gmail.com> References: <e033edfb0709211203t1d6002e1q86f3de123e5b17b9@mail.gmail.com> Message-ID: <16651e80709211244q31e80202vb83f5e07582c68cc@mail.gmail.com> On 9/21/07, Tino Dai <tinoloc at gmail.com> wrote: > Is there a more pythonic way of doing this: > > if queuePacket.has_key('procSeq') and \ > queuePacket.has_key('opacSeq') and \ > queuePacket.has_key('keySeq') and \ > len(queuePacket['procSeq']) == 0 and \ > len(queuePacket['opacSeq']) == 0 and \ > len(queuePacket['keySeq']) == 0: Assuming we're talking about Python 2.5 or greater I find the following pretty readable: all(queuePacket.has_key(k) for k in ('procSeq', 'opacSeq', 'keySeq')) and \ all(len(queuePacket[k])==0 for k in ('procSeq', 'opacSeq', 'keySeq')) If you're not familiar with how those work, they use generator expressions, which are very similar to list comprehensions. See PEP 289 [1] for more information on generator expressions, and either the tutorial [2] or PEP 202 [3] for more on list comprehensions. 1: http://www.python.org/dev/peps/pep-0289/ 2: http://docs.python.org/tut/node7.html#SECTION007140000000000000000 3: http://www.python.org/dev/peps/pep-0202/ -- Jerry From ricaraoz at gmail.com Sat Sep 22 13:50:38 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Sat, 22 Sep 2007 08:50:38 -0300 Subject: [Tutor] Counting method calls Message-ID: <46F5018E.30802@bigfoot.com> Hi, I'm trying to count method calls. Tried this but... >>>> class MyList(list): > ... def __init__(self): > ... self.calls = 0 > ... def __getattr__(self, name): > ... self.calls += 1 > ... return list.__getattribute__(self, name) > >>>> a = MyList() >>>> a > [] >>>> a.append(1) >>>> a > [1] >>>> a.calls > 88 >>>> a.append(3) >>>> a.calls > 88 >>>> a.sort() >>>> a > [1, 3] >>>> a.calls > 176 It's doing some strange things with self.calls. I've also tried : >>>> class MyList(list): > ... def __init__(self): > ... self.calls = 0 > ... def __getattribute__(self, name): # Here's the change > ... self.calls += 1 > ... return list.__getattribute__(self, name) > >>>> a = MyList() >>>> a > [] >>>> a.append(1) File "<input>", line 5, in __getattribute__ File "<input>", line 5, in __getattribute__ .... snipped ..... File "<input>", line 5, in __getattribute__ File "<input>", line 5, in __getattribute__ RuntimeError: maximum recursion depth exceeded Any idea what's going on in both tries? And how can I intercept method calls without defining all of list's methods. Thanks From kent37 at tds.net Sat Sep 22 14:34:33 2007 From: kent37 at tds.net (Kent Johnson) Date: Sat, 22 Sep 2007 08:34:33 -0400 Subject: [Tutor] Counting method calls In-Reply-To: <46F5018E.30802@bigfoot.com> References: <46F5018E.30802@bigfoot.com> Message-ID: <46F50BD9.2000305@tds.net> Ricardo Ar?oz wrote: > Hi, I'm trying to count method calls. Tried this but... >>>>> class MyList(list): >> ... def __init__(self): >> ... self.calls = 0 should call list.__init__(self) here. >> ... def __getattr__(self, name): >> ... self.calls += 1 >> ... return list.__getattribute__(self, name) >> >>>>> a = MyList() >>>>> a >> [] >>>>> a.append(1) >>>>> a >> [1] >>>>> a.calls >> 88 >>>>> a.append(3) >>>>> a.calls >> 88 >>>>> a.sort() >>>>> a >> [1, 3] >>>>> a.calls >> 176 > > It's doing some strange things with self.calls. What version of Python are you using? When I try this program it prints 0 0 0 Note that __getattr__() is only called when normal attribute access *fails*, so I would not expect this to work. > I've also tried : > >>>>> class MyList(list): >> ... def __init__(self): >> ... self.calls = 0 >> ... def __getattribute__(self, name): # Here's the change >> ... self.calls += 1 >> ... return list.__getattribute__(self, name) >> >>>>> a = MyList() >>>>> a >> [] >>>>> a.append(1) > File "<input>", line 5, in __getattribute__ > File "<input>", line 5, in __getattribute__ > .... snipped ..... > File "<input>", line 5, in __getattribute__ > File "<input>", line 5, in __getattribute__ > RuntimeError: maximum recursion depth exceeded > > Any idea what's going on in both tries? And how can I intercept method > calls without defining all of list's methods. The problem here is that __getattribute__() is called for *all* attribute access including getting the value of self.calls to increment it. So __getattribute__() calls itself without end which is the recipe for a stack overflow. If you change getattribute() to this it is closer to what you want: def __getattribute__(self, name): self.calls = list.__getattribute__(self, 'calls') + 1 return list.__getattribute__(self, name) For me this prints 2 4 6 with your sequence of operations. More problems - this counts *any* attribute access, not just callables. You could change it to get the attribute and only count it if callable(value) is true. But it also counts calls to implementation methods which is probably not what you want - if list.sort() calls three other methods, do you want a count of 4 for a call to sort()? And it counts failed attribute access; that is easy to fix by incrementing calls after the call to list.__getattribute__(). A different approach is to use delegation rather than inheritance to access the list functions. Write __getattr__() to delegate to a list attribute: class MyList(object): def __init__(self): self._list = list() self.calls = 0 def __getattr__(self, name): value = getattr(self._list, name) if callable(value): self.calls += 1 return value I think this does what you want. Notice that it doesn't have anything special to do with lists, either, except instantiating a list. It can be turned into a general-purpose counting wrapper by passing the instance to be counted to the constructor: class CallCounter(object): def __init__(self, delegate): self._delegate = delegate self.calls = 0 def __getattr__(self, name): value = getattr(self._delegate, name) if callable(value): self.calls += 1 return value a = CallCounter(list()) etc. Kent From ricaraoz at gmail.com Sat Sep 22 15:24:06 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Sat, 22 Sep 2007 10:24:06 -0300 Subject: [Tutor] Counting method calls In-Reply-To: <46F50BD9.2000305@tds.net> References: <46F5018E.30802@bigfoot.com> <46F50BD9.2000305@tds.net> Message-ID: <46F51776.10401@bigfoot.com> Kent Johnson wrote: > Ricardo Ar?oz wrote: >> Hi, I'm trying to count method calls. Tried this but... >>>>>> class MyList(list): >>> ... def __init__(self): >>> ... self.calls = 0 > > should call list.__init__(self) here. Foolish me. > >>> ... def __getattr__(self, name): >>> ... self.calls += 1 >>> ... return list.__getattribute__(self, name) >>> >>>>>> a = MyList() >>>>>> a >>> [] >>>>>> a.append(1) >>>>>> a >>> [1] >>>>>> a.calls >>> 88 >>>>>> a.append(3) >>>>>> a.calls >>> 88 >>>>>> a.sort() >>>>>> a >>> [1, 3] >>>>>> a.calls >>> 176 >> >> It's doing some strange things with self.calls. > > What version of Python are you using? When I try this program it prints Py 0.9.5 Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)] on win32 I thought it might be you were trying the class with the list init call but I tried it and works the same way. Was using PyAlaMode, tried it using IDLE and it works like yours, probably a bug of PyAlaMode. > 0 > 0 > 0 > > Note that __getattr__() is only called when normal attribute access > *fails*, so I would not expect this to work. > >> I've also tried : >> >>>>>> class MyList(list): >>> ... def __init__(self): >>> ... self.calls = 0 >>> ... def __getattribute__(self, name): # Here's the change >>> ... self.calls += 1 >>> ... return list.__getattribute__(self, name) >>> >>>>>> a = MyList() >>>>>> a >>> [] >>>>>> a.append(1) >> File "<input>", line 5, in __getattribute__ >> File "<input>", line 5, in __getattribute__ >> .... snipped ..... >> File "<input>", line 5, in __getattribute__ >> File "<input>", line 5, in __getattribute__ >> RuntimeError: maximum recursion depth exceeded >> >> Any idea what's going on in both tries? And how can I intercept method >> calls without defining all of list's methods. > > The problem here is that __getattribute__() is called for *all* > attribute access including getting the value of self.calls to increment > it. So __getattribute__() calls itself without end which is the recipe > for a stack overflow. Yes, that was my conclusion too. > > If you change getattribute() to this it is closer to what you want: > > def __getattribute__(self, name): > self.calls = list.__getattribute__(self, 'calls') + 1 > return list.__getattribute__(self, name) > Aaarghh! I was looking for the problem in the 'return' line and skipped the 'self.calls' line. Thanks. > For me this prints > 2 > 4 > 6 > > with your sequence of operations. > > More problems - this counts *any* attribute access, not just callables. > You could change it to get the attribute and only count it if > callable(value) is true. But it also counts calls to implementation > methods which is probably not what you want - if list.sort() calls three > other methods, do you want a count of 4 for a call to sort()? And it > counts failed attribute access; that is easy to fix by incrementing > calls after the call to list.__getattribute__(). > > A different approach is to use delegation rather than inheritance to > access the list functions. Write __getattr__() to delegate to a list > attribute: > > class MyList(object): > def __init__(self): > self._list = list() > self.calls = 0 > def __getattr__(self, name): > value = getattr(self._list, name) > if callable(value): > self.calls += 1 > return value > > I think this does what you want. Notice that it doesn't have anything > special to do with lists, either, except instantiating a list. It can be > turned into a general-purpose counting wrapper by passing the instance > to be counted to the constructor: > > class CallCounter(object): > def __init__(self, delegate): > self._delegate = delegate > self.calls = 0 > def __getattr__(self, name): > value = getattr(self._delegate, name) > if callable(value): > self.calls += 1 > return value > > a = CallCounter(list()) > Yes, this would be exactly what I was looking for. As you can imagine it's use was not really to count method calls but to add functionality before or after the calls at will. Sadly : >>> a = CallCounter(list()) >>> a.append(1) >>> a.calls 2 >>> a.append(2) >>> a.append(3) >>> a.calls 5 >>> a[3] Traceback (most recent call last): File "<pyshell#15>", line 1, in <module> a[3] TypeError: 'CallCounter' object is unindexable >>> print a <__main__.CallCounter object at 0x00C54170> So my purpose of wrapping a class in an existing module in a transparent manner is thwarted. Any ideas? (yes, I know I should be doing my own thinking, I'll do it in the afternoon after I've finished my chores :) ) BTW I've seen some recipes, one for adding a logger to a class which could be adapted to my requirement, but they are way over my head and I like to keep code simple and understandable (by me ;c) ). From ricaraoz at gmail.com Sat Sep 22 15:25:14 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Sat, 22 Sep 2007 10:25:14 -0300 Subject: [Tutor] Counting method calls In-Reply-To: <46F50BD9.2000305@tds.net> References: <46F5018E.30802@bigfoot.com> <46F50BD9.2000305@tds.net> Message-ID: <46F517BA.30606@bigfoot.com> Kent Johnson wrote: > Ricardo Ar?oz wrote: >> Hi, I'm trying to count method calls. Tried this but... >>>>>> class MyList(list): >>> ... def __init__(self): >>> ... self.calls = 0 ... snipped ..... > I think this does what you want. Notice that it doesn't have anything > special to do with lists, either, except instantiating a list. It can be > turned into a general-purpose counting wrapper by passing the instance > to be counted to the constructor: > > class CallCounter(object): > def __init__(self, delegate): > self._delegate = delegate > self.calls = 0 > def __getattr__(self, name): > value = getattr(self._delegate, name) > if callable(value): > self.calls += 1 > return value > > a = CallCounter(list()) > > etc. > > Kent > Thanks Kent! From tinoloc at gmail.com Sat Sep 22 18:42:08 2007 From: tinoloc at gmail.com (Tino Dai) Date: Sat, 22 Sep 2007 12:42:08 -0400 Subject: [Tutor] Quick question In-Reply-To: <16651e80709211244q31e80202vb83f5e07582c68cc@mail.gmail.com> References: <e033edfb0709211203t1d6002e1q86f3de123e5b17b9@mail.gmail.com> <16651e80709211244q31e80202vb83f5e07582c68cc@mail.gmail.com> Message-ID: <e033edfb0709220942g5559ff9bhb6d0cb5bd79c95d5@mail.gmail.com> On 9/21/07, Jerry Hill <malaclypse2 at gmail.com> wrote: > > On 9/21/07, Tino Dai <tinoloc at gmail.com> wrote: > > Is there a more pythonic way of doing this: > > > > if queuePacket.has_key('procSeq') and \ > > queuePacket.has_key('opacSeq') and \ > > queuePacket.has_key('keySeq') and \ > > len(queuePacket['procSeq']) == 0 and \ > > len(queuePacket['opacSeq']) == 0 and \ > > len(queuePacket['keySeq']) == 0: > > Assuming we're talking about Python 2.5 or greater I find the > following pretty readable: > > all(queuePacket.has_key(k) for k in ('procSeq', 'opacSeq', 'keySeq')) and > \ > all(len(queuePacket[k])==0 for k in ('procSeq', 'opacSeq', 'keySeq')) You can do that in Python?!?!!! That kicks major a......well, this is a family list. Thanks for that. I really had no idea that you could do that kind of syntax structure. Now, I have a bunch of code that I can go and make a lot shorter and more readable Thanks, Tino -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070922/42d3510d/attachment.htm From kent37 at tds.net Sat Sep 22 18:46:37 2007 From: kent37 at tds.net (Kent Johnson) Date: Sat, 22 Sep 2007 12:46:37 -0400 Subject: [Tutor] Counting method calls In-Reply-To: <46F51776.10401@bigfoot.com> References: <46F5018E.30802@bigfoot.com> <46F50BD9.2000305@tds.net> <46F51776.10401@bigfoot.com> Message-ID: <46F546ED.30102@tds.net> Ricardo Ar?oz wrote: > Kent Johnson wrote: >> What version of Python are you using? When I try this program it prints > > Py 0.9.5 > Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit > (Intel)] on win32 > > I thought it might be you were trying the class with the list init call > but I tried it and works the same way. > Was using PyAlaMode, tried it using IDLE and it works like yours, > probably a bug of PyAlaMode. My guess is PyAlaMode is trying to introspect the objects in some way and that is causing the extra access (to non-existent attributes). >> class CallCounter(object): >> def __init__(self, delegate): >> self._delegate = delegate >> self.calls = 0 >> def __getattr__(self, name): >> value = getattr(self._delegate, name) >> if callable(value): >> self.calls += 1 >> return value >> >> a = CallCounter(list()) > > Sadly : >>>> a = CallCounter(list()) >>>> a.append(1) >>>> a.calls > 2 >>>> a.append(2) >>>> a.append(3) >>>> a.calls > 5 >>>> a[3] > > Traceback (most recent call last): > File "<pyshell#15>", line 1, in <module> > a[3] > TypeError: 'CallCounter' object is unindexable Hmm. The problem is that new-style classes don't look up special methods on instances, just in the class itself. There is some discussion here, it looks a bit ugly: http://groups.google.com/group/comp.lang.python/browse_thread/thread/c5bb6496970b5c5a?hl=en&tvc=2 Alex Martelli's second response proposes a solution that overrides __new__() to create a custom class for each wrapper. There might be some help here too, I haven't read it closely: http://tinyurl.com/25lx5t The code works if CallCounter is an old-style class. Kent From kent37 at tds.net Sat Sep 22 19:18:13 2007 From: kent37 at tds.net (Kent Johnson) Date: Sat, 22 Sep 2007 13:18:13 -0400 Subject: [Tutor] Counting method calls In-Reply-To: <46F546ED.30102@tds.net> References: <46F5018E.30802@bigfoot.com> <46F50BD9.2000305@tds.net> <46F51776.10401@bigfoot.com> <46F546ED.30102@tds.net> Message-ID: <46F54E55.4080300@tds.net> One more reference: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/252151 This appears as recipe 6.6 in the second edition of the printed cookbook. Kent From ricaraoz at gmail.com Sat Sep 22 20:37:28 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Sat, 22 Sep 2007 15:37:28 -0300 Subject: [Tutor] Counting method calls In-Reply-To: <46F54E55.4080300@tds.net> References: <46F5018E.30802@bigfoot.com> <46F50BD9.2000305@tds.net> <46F51776.10401@bigfoot.com> <46F546ED.30102@tds.net> <46F54E55.4080300@tds.net> Message-ID: <46F560E8.5040609@bigfoot.com> Kent Johnson wrote: > One more reference: > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/252151 > > This appears as recipe 6.6 in the second edition of the printed cookbook. > > Kent Thanks Kent. I guess I got into deep waters. It's a shame though that you can not do this in a simple manner, considering python simplifies so many other chores. To continue with your useful class : class CallCounter: def __init__(self, delegate): self._delegate = delegate self.calls = 0 def __getattr__(self, name): value = getattr(self._delegate, name) if callable(value): self.calls = getattr(self, 'calls') + 1 print 'name:', name, 'calls:',getattr(self,'calls') return value >>> a = CallCounter(list()) >>> a name: __repr__ calls: 1 [] >>> a name: __repr__ calls: 2 [] >>> name: append calls: 3 ########## a.append(3) name: append calls: 4 The line marked with ########## appeared as I was typing a.append so I guess IDLE is accessing the class as I write the command in order to display those little windows with available options. As for PyAlaMode, it exhibits a much weirder behavior, I think I'll stop using it. Cheers From jtp at nc.rr.com Sat Sep 22 22:18:27 2007 From: jtp at nc.rr.com (James) Date: Sat, 22 Sep 2007 16:18:27 -0400 Subject: [Tutor] Capturing ctrl-c Message-ID: <3F791A15-5273-46EA-A83F-E09EE574760F@nc.rr.com> Hi. :) I'm whipping up a program in Python and am having to deal with a user potentially hitting ctrl-c at any point in the program. I'd like my Python program to wrap up cleanly when it receives this signal. I did some Googling and read that Python throws a KeyboardInterrupt error. What's the best way to run a specific "cleanup" function at *any* time the interrupt is received, regardless of where the program is in execution? Most of the stuff I've read involves try-except blocks. This makes sense to me if I want to protect a specific function or area of the code from being interrupted by ctrl-c, but I'm not sure what kind of structure my program must have to catch the exception at any point during execution. Thoughts/ideas appreciated. :) Thanks! .james From mlangford.cs03 at gtalumni.org Sat Sep 22 22:31:32 2007 From: mlangford.cs03 at gtalumni.org (Michael Langford) Date: Sat, 22 Sep 2007 16:31:32 -0400 Subject: [Tutor] Capturing ctrl-c In-Reply-To: <3F791A15-5273-46EA-A83F-E09EE574760F@nc.rr.com> References: <3F791A15-5273-46EA-A83F-E09EE574760F@nc.rr.com> Message-ID: <82b4f5810709221331n1cbc730g4c1015a2a62179cf@mail.gmail.com> When I do real applications with exception based languages, I almost always wrap the main function with a try/except block to allow me to gracefully shut down. In the case of python, this means 1> Use the main method 2> wrap its execution in a try catch: import mymodule def do_stuff(): pass def graceful_cleanup() pass if "__main__" == __name__: try: do_stuff() except: graceful_cleanup() --Michael -- Michael Langford Phone: 404-386-0495 Consulting: http://www.TierOneDesign.com/ Entertaining: http://www.ThisIsYourCruiseDirectorSpeaking.com On 9/22/07, James <jtp at nc.rr.com> wrote: > > Hi. :) > > I'm whipping up a program in Python and am having to deal with a user > potentially hitting ctrl-c at any point in the program. I'd like my > Python program to wrap up cleanly when it receives this signal. > > I did some Googling and read that Python throws a KeyboardInterrupt > error. What's the best way to run a specific "cleanup" function at > *any* time the interrupt is received, regardless of where the program > is in execution? > > Most of the stuff I've read involves try-except blocks. This makes > sense to me if I want to protect a specific function or area of the > code from being interrupted by ctrl-c, but I'm not sure what kind of > structure my program must have to catch the exception at any point > during execution. > > Thoughts/ideas appreciated. :) > > Thanks! > .james > _______________________________________________ > 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/20070922/6173b1bf/attachment.htm From hunter92383 at gmail.com Sun Sep 23 03:59:35 2007 From: hunter92383 at gmail.com (elis aeris) Date: Sun, 23 Sep 2007 09:59:35 +0800 Subject: [Tutor] scite with python 2.51 Message-ID: <674d5ce60709221859o682c9341p5bf8e4e9eba336ad@mail.gmail.com> how do I set up scite editor with python so that I can click check syntax and compile from the editor? From emadnawfal at gmail.com Sun Sep 23 15:24:06 2007 From: emadnawfal at gmail.com (Emad Nawfal) Date: Sun, 23 Sep 2007 08:24:06 -0500 Subject: [Tutor] unicode problem In-Reply-To: <46F08C65.80700@tds.net> References: <652641e90709181723m44824651h877d492ad706c42d@mail.gmail.com> <46F08C65.80700@tds.net> Message-ID: <652641e90709230624n209d8267p4bae03caae977953@mail.gmail.com> Hi Tutors, I've just realized that i forgot to thank Kent Johnson for his advise on Unicode. Thank you kent. Best, Emad On 9/18/07, Kent Johnson <kent37 at tds.net> wrote: > > Emad Nawfal wrote: > > *Hi All Tutors,* > > *I'm new and I'm trying to use unicode strings in my code (specifically > > Arabic), but I get this:* > > > > IDLE 1.2.1 > >>>> text = ur'????????' > > Unsupported characters in input > > This seems to be a problem with IDLE rather than Python itself. This > message: > http://www.thescripts.com/forum/thread543035.html > > suggests editing one of the IDLE files to make it support unicode. > Alternately you might want to use the plain Python interpreter and a > text editor that supports arabic. > > Kent > -- ?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? ????????.....???? ??????? Emad Soliman Nawfal Indiana University, Bloomington http://emadnawfal.googlepages.com -------------------------------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070923/b686446b/attachment.htm From lordvader at gmail.com Sun Sep 23 17:12:56 2007 From: lordvader at gmail.com (lordvader at gmail.com) Date: Sun, 23 Sep 2007 08:12:56 -0700 Subject: [Tutor] scite with python 2.51 Message-ID: <434140620709230812n367cfa34m84375166f91ec14a@mail.gmail.com> > how do I set up scite editor with python so that I can click check > syntax and compile from the editor? You just need to setup your environment's PATH so that it knows where to find python. This probably means you need to add "C:/python25" to your path. Once you do this, restart scite, and it you will automatically be able to check syntax / compile (ctrl-1) or execute (F3) your python code. In case you don't know how to change your system's PATH variable... On windows: http://www.computerhope.com/issues/ch000549.htm On linux: http://www.linuxheadquarters.com/howto/basic/path.shtml -Fred From dave6502 at googlemail.com Sun Sep 23 18:31:52 2007 From: dave6502 at googlemail.com (dave selby) Date: Sun, 23 Sep 2007 17:31:52 +0100 Subject: [Tutor] pythons xf86misc documentation ? Message-ID: <f52017b60709230931o4a13c87fg893a611e423972b6@mail.gmail.com> Can anyone tell me where the documentation for pythons xf86misc module is, ie what methods are avalible ? Many thanks Dave -- Please avoid sending me Word or PowerPoint attachments. See http://www.gnu.org/philosophy/no-word-attachments.html From macsareback at mac.com Sun Sep 23 19:15:42 2007 From: macsareback at mac.com (Daniel Kavic) Date: Sun, 23 Sep 2007 13:15:42 -0400 Subject: [Tutor] Counting method calls In-Reply-To: <46F546ED.30102@tds.net> References: <46F5018E.30802@bigfoot.com> <46F50BD9.2000305@tds.net> <46F51776.10401@bigfoot.com> <46F546ED.30102@tds.net> Message-ID: <6FEC3918-611D-457F-9F8C-A34450B35B66@mac.com> Ok I have been a multimedia major for a few years now. I have tried javascript and that was bad, Java is just too difficult, so I joined this mailing list a while back. I have been frustrated because I just don't get entirely how OOProgramming works and how to actually write the stuff correctly. I have a hard time programming and I wish I could be better at knowing at least one language. I need a really good book or something to explain this to me. I am not the best in math On Sep 22, 2007, at 12:46 PM, Kent Johnson wrote: > Ricardo Ar?oz wrote: >> Kent Johnson wrote: > >>> What version of Python are you using? When I try this program it >>> prints >> >> Py 0.9.5 >> Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit >> (Intel)] on win32 >> >> I thought it might be you were trying the class with the list init >> call >> but I tried it and works the same way. >> Was using PyAlaMode, tried it using IDLE and it works like yours, >> probably a bug of PyAlaMode. > > My guess is PyAlaMode is trying to introspect the objects in some way > and that is causing the extra access (to non-existent attributes). > >>> class CallCounter(object): >>> def __init__(self, delegate): >>> self._delegate = delegate >>> self.calls = 0 >>> def __getattr__(self, name): >>> value = getattr(self._delegate, name) >>> if callable(value): >>> self.calls += 1 >>> return value >>> >>> a = CallCounter(list()) >> >> Sadly : >>>>> a = CallCounter(list()) >>>>> a.append(1) >>>>> a.calls >> 2 >>>>> a.append(2) >>>>> a.append(3) >>>>> a.calls >> 5 >>>>> a[3] >> >> Traceback (most recent call last): >> File "<pyshell#15>", line 1, in <module> >> a[3] >> TypeError: 'CallCounter' object is unindexable > > Hmm. The problem is that new-style classes don't look up special > methods > on instances, just in the class itself. > > There is some discussion here, it looks a bit ugly: > http://groups.google.com/group/comp.lang.python/browse_thread/ > thread/c5bb6496970b5c5a?hl=en&tvc=2 > Alex Martelli's second response proposes a solution that overrides > __new__() to create a custom class for each wrapper. > > There might be some help here too, I haven't read it closely: > http://tinyurl.com/25lx5t > > The code works if CallCounter is an old-style class. > > Kent > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From mlangford.cs03 at gtalumni.org Sun Sep 23 19:59:56 2007 From: mlangford.cs03 at gtalumni.org (Michael Langford) Date: Sun, 23 Sep 2007 13:59:56 -0400 Subject: [Tutor] Learning a Language Message-ID: <82b4f5810709231059y2280bd45wff518c3f7104d8ac@mail.gmail.com> First off, please don't pick a random message and reply to it. Please send an email directly to tutor at python.org if you have a new conversation topic. Some people's mail readers group emails together by what email you hit reply on, so it will put your email with messages it doesn't really belong with. That said: You're in luck, python is PERFECT for you. Javascript is quite a bit harder than python to do, especially for many sorts of project. I'd also say python has a lower barrier to entry than Java as well. I'm primarily a programmer, so I used Dive into Python to get started (4 years ago). Now this is a short PDF for programmers on python, but its still a good, short intro to people who aren't. http://www.diveintopython.org I've also went through some of "Learning Python". A new edition is coming out in about 10 days, and I'd suggest you'd get it and go through the exercises. Don't read them, actually type them in (don't copy and paste), and then fiddle with them to do something different with them. My wife (who does marketing for a living, and doesn't program except for the occasional VBA script) is starting this book (using the old one until the new one comes in): http://snipurl.com/learningpython Another approach, one that I use from time to time to pick up a topic, is to snarf down the course exercises of a college course that is posted on the web. For instance, Georgia Tech's intro to programming course is on the web for all to see at: http://www-static.cc.gatech.edu/classes/AY2008/cs1301_fall/homework.html It may be easier to go through a past semester (as it will have all the homeworks up there for you to do): http://www-static.cc.gatech.edu/classes/AY2007/cs1301_spring/ One nice thing about going through the course work is that they're trying to teach programming, and just happen to be using python. That approach means you'll get the most important, general skills out of it. (That course or harder ones is required for all undergrads at that institution, so I expect you'll be able to do its coursework). --Michael -- Michael Langford Phone: 404-386-0495 Consulting: http://www.TierOneDesign.com/ Entertaining: http://www.ThisIsYourCruiseDirectorSpeaking.com On 9/23/07, Daniel Kavic <macsareback at mac.com> wrote: > > Ok I have been a multimedia major for a few years now. I have tried > javascript and that was bad, Java is just too difficult, so I joined > this mailing list a while back. I have been frustrated because I just > don't get entirely how OOProgramming works and how to actually write > the stuff correctly. I have a hard time programming and I wish I > could be better at knowing at least one language. I need a really > good book or something to explain this to me. I am not the best in math > On Sep 22, 2007, at 12:46 PM, Kent Johnson wrote: > > > Ricardo Ar?oz wrote: > >> Kent Johnson wrote: > > > >>> What version of Python are you using? When I try this program it > >>> prints > >> > >> Py 0.9.5 > >> Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit > >> (Intel)] on win32 > >> > >> I thought it might be you were trying the class with the list init > >> call > >> but I tried it and works the same way. > >> Was using PyAlaMode, tried it using IDLE and it works like yours, > >> probably a bug of PyAlaMode. > > > > My guess is PyAlaMode is trying to introspect the objects in some way > > and that is causing the extra access (to non-existent attributes). > > > >>> class CallCounter(object): > >>> def __init__(self, delegate): > >>> self._delegate = delegate > >>> self.calls = 0 > >>> def __getattr__(self, name): > >>> value = getattr(self._delegate, name) > >>> if callable(value): > >>> self.calls += 1 > >>> return value > >>> > >>> a = CallCounter(list()) > >> > >> Sadly : > >>>>> a = CallCounter(list()) > >>>>> a.append(1) > >>>>> a.calls > >> 2 > >>>>> a.append(2) > >>>>> a.append(3) > >>>>> a.calls > >> 5 > >>>>> a[3] > >> > >> Traceback (most recent call last): > >> File "<pyshell#15>", line 1, in <module> > >> a[3] > >> TypeError: 'CallCounter' object is unindexable > > > > Hmm. The problem is that new-style classes don't look up special > > methods > > on instances, just in the class itself. > > > > There is some discussion here, it looks a bit ugly: > > http://groups.google.com/group/comp.lang.python/browse_thread/ > > thread/c5bb6496970b5c5a?hl=en&tvc=2 > > Alex Martelli's second response proposes a solution that overrides > > __new__() to create a custom class for each wrapper. > > > > There might be some help here too, I haven't read it closely: > > http://tinyurl.com/25lx5t > > > > The code works if CallCounter is an old-style class. > > > > 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 > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070923/df106d08/attachment.htm From rabidpoobear at gmail.com Sun Sep 23 23:08:25 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sun, 23 Sep 2007 16:08:25 -0500 Subject: [Tutor] Advice for a Multimedia Major [was: Counting method calls] In-Reply-To: <6FEC3918-611D-457F-9F8C-A34450B35B66@mac.com> References: <46F5018E.30802@bigfoot.com> <46F50BD9.2000305@tds.net> <46F51776.10401@bigfoot.com> <46F546ED.30102@tds.net> <6FEC3918-611D-457F-9F8C-A34450B35B66@mac.com> Message-ID: <46F6D5C9.4030000@gmail.com> Daniel Kavic wrote: > Ok I have been a multimedia major for a few years now. I have tried > javascript and that was bad, Java is just too difficult, so I joined > this mailing list a while back. I have been frustrated because I just > don't get entirely how OOProgramming works and how to actually write > the stuff correctly. I have a hard time programming and I wish I > could be better at knowing at least one language. I need a really > good book or something to explain this to me. I am not the best in math So if you want some recommendations, make your own thread. Don't post in another, unrelated thread. -Luke From boykie.mackay at gmail.com Mon Sep 24 00:08:32 2007 From: boykie.mackay at gmail.com (Boykie Mackay) Date: Sun, 23 Sep 2007 23:08:32 +0100 Subject: [Tutor] Learning a Language In-Reply-To: <82b4f5810709231059y2280bd45wff518c3f7104d8ac@mail.gmail.com> References: <82b4f5810709231059y2280bd45wff518c3f7104d8ac@mail.gmail.com> Message-ID: <1190585312.9600.14.camel@apprentice-laptop> You could also try the showmedo videos at: http://showmedo.com/videos/python I started with Java and am still learning Java but after just a few days of learning python I knew more about programming in python than I knew about in Java.I have also found it helpful trying out some of the challenges such as those at: http://www.pythonchallenge.com/ http://www.spoj.pl/ If you select a problem you can research using the google and the resources mentioned and try to find a solution.I have found it difficult to learn by just reading a book and prefer having a problem at hand,then using the book or other resources to try and solve the problem. Hope the above helps. The videos are simple clear and will have you programming in no time! On Sun, 2007-09-23 at 13:59 -0400, Michael Langford wrote: > First off, please don't pick a random message and reply to it. Please > send an email directly to tutor at python.org if you have a new > conversation topic. Some people's mail readers group emails together > by what email you hit reply on, so it will put your email with > messages it doesn't really belong with. > > That said: You're in luck, python is PERFECT for you. Javascript is > quite a bit harder than python to do, especially for many sorts of > project. I'd also say python has a lower barrier to entry than Java as > well. > > I'm primarily a programmer, so I used Dive into Python to get started > (4 years ago). Now this is a short PDF for programmers on python, but > its still a good, short intro to people who aren't. > http://www.diveintopython.org > > I've also went through some of "Learning Python". A new edition is > coming out in about 10 days, and I'd suggest you'd get it and go > through the exercises. Don't read them, actually type them in (don't > copy and paste), and then fiddle with them to do something different > with them. My wife (who does marketing for a living, and doesn't > program except for the occasional VBA script) is starting this book > (using the old one until the new one comes in): > http://snipurl.com/learningpython > > Another approach, one that I use from time to time to pick up a topic, > is to snarf down the course exercises of a college course that is > posted on the web. For instance, Georgia Tech's intro to programming > course is on the web for all to see at: > http://www-static.cc.gatech.edu/classes/AY2008/cs1301_fall/homework.html > > It may be easier to go through a past semester (as it will have all > the homeworks up there for you to do): > http://www-static.cc.gatech.edu/classes/AY2007/cs1301_spring/ > > One nice thing about going through the course work is that they're > trying to teach programming, and just happen to be using python. That > approach means you'll get the most important, general skills out of > it. (That course or harder ones is required for all undergrads at that > institution, so I expect you'll be able to do its coursework). > > --Michael > > -- > Michael Langford > Phone: 404-386-0495 > Consulting: http://www.TierOneDesign.com/ > Entertaining: http://www.ThisIsYourCruiseDirectorSpeaking.com > > On 9/23/07, Daniel Kavic <macsareback at mac.com> wrote: > Ok I have been a multimedia major for a few years now. I have > tried > javascript and that was bad, Java is just too difficult, so I > joined > this mailing list a while back. I have been frustrated because > I just > don't get entirely how OOProgramming works and how to actually > write > the stuff correctly. I have a hard time programming and I wish > I > could be better at knowing at least one language. I need a > really > good book or something to explain this to me. I am not the > best in math > On Sep 22, 2007, at 12:46 PM, Kent Johnson wrote: > > > Ricardo Ar?oz wrote: > >> Kent Johnson wrote: > > > >>> What version of Python are you using? When I try this > program it > >>> prints > >> > >> Py 0.9.5 > >> Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 > 32 bit > >> (Intel)] on win32 > >> > >> I thought it might be you were trying the class with the > list init > >> call > >> but I tried it and works the same way. > >> Was using PyAlaMode, tried it using IDLE and it works like > yours, > >> probably a bug of PyAlaMode. > > > > My guess is PyAlaMode is trying to introspect the objects in > some way > > and that is causing the extra access (to non-existent > attributes). > > > >>> class CallCounter(object): > >>> def __init__(self, delegate): > >>> self._delegate = delegate > >>> self.calls = 0 > >>> def __getattr__(self, name): > >>> value = getattr(self._delegate, name) > >>> if callable(value): > >>> self.calls += 1 > >>> return value > >>> > >>> a = CallCounter(list()) > >> > >> Sadly : > >>>>> a = CallCounter(list()) > >>>>> a.append(1) > >>>>> a.calls > >> 2 > >>>>> a.append(2) > >>>>> a.append(3) > >>>>> a.calls > >> 5 > >>>>> a[3] > >> > >> Traceback (most recent call last): > >> File "<pyshell#15>", line 1, in <module> > >> a[3] > >> TypeError: 'CallCounter' object is unindexable > > > > Hmm. The problem is that new-style classes don't look up > special > > methods > > on instances, just in the class itself. > > > > There is some discussion here, it looks a bit ugly: > > > http://groups.google.com/group/comp.lang.python/browse_thread/ > > thread/c5bb6496970b5c5a?hl=en&tvc=2 > > Alex Martelli's second response proposes a solution that > overrides > > __new__() to create a custom class for each wrapper. > > > > There might be some help here too, I haven't read it > closely: > > http://tinyurl.com/25lx5t > > > > The code works if CallCounter is an old-style class. > > > > 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 From balderas at whtvcable.com Mon Sep 24 00:18:28 2007 From: balderas at whtvcable.com (Chris) Date: Sun, 23 Sep 2007 15:18:28 -0700 Subject: [Tutor] python problem - help!! Message-ID: <!&!AAAAAAAAAAAYAAAAAAAAAHICkgQi6MVHrTCR8dizOffCgAAAEAAAACo8wKm6WoJChw7k2+7rOAMBAAAAAA==@whtvcable.com> I need your help! I have this problem that I can?t seem to figure out. Can you help? The problem is listed below, and below it is my code that I have so far. ---------------------------------------------------------------------------- -------------------- Two hockey teams play eight times during the regular season. Team A wins five times and Team B wins the other three times. They meet in the playoffs in a best of seven series. Write a program that estimates the chances of Team B winning the series. A sample run of the program might look like this: . Are team B's chances better in a 1 game "series", a 3 game series, a 5 game series, or a 7 game series? What would team B's chances of winning a 51 game series be? ---------------------------------------------------------------------------- ------------------- import random SERIES = 1000 game = 0 series = 0 while series < SERIES: teamA = random.randint (1,8) teamB = random.randint (1,8) teams = teamA + teamB if random.randint(1,8) >= 5: 'Team A' = team else: 'Team B' = team game = game + 1 series = series + 1 print 'In %2d simulated series %2d won %2d ' % (SERIES,team,game) print 'so I estimate there is a',(game / 10.00),'% chance they will win the series.' No virus found in this outgoing message. Checked by AVG Free Edition. Version: 7.5.487 / Virus Database: 269.13.25/1018 - Release Date: 9/19/2007 3:59 PM -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070923/1f3bbfdd/attachment.htm -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: image/gif Size: 3680 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20070923/1f3bbfdd/attachment.gif From kent37 at tds.net Mon Sep 24 02:15:34 2007 From: kent37 at tds.net (Kent Johnson) Date: Sun, 23 Sep 2007 20:15:34 -0400 Subject: [Tutor] Counting method calls In-Reply-To: <46F560E8.5040609@bigfoot.com> References: <46F5018E.30802@bigfoot.com> <46F50BD9.2000305@tds.net> <46F51776.10401@bigfoot.com> <46F546ED.30102@tds.net> <46F54E55.4080300@tds.net> <46F560E8.5040609@bigfoot.com> Message-ID: <46F701A6.9090905@tds.net> Ricardo Ar?oz wrote: > Kent Johnson wrote: >> One more reference: >> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/252151 >> >> This appears as recipe 6.6 in the second edition of the printed cookbook. >> >> Kent > > Thanks Kent. I guess I got into deep waters. > It's a shame though that you can not do this in a simple manner, > considering python simplifies so many other chores. I agree, also because it is so easy to do with old-style classes. The root of the problem seems to be that new-style classes do not use the normal attribute lookup mechanism to find special methods when they are being invoked by the interpreter *as* special methods. For example, when executing a[0], __getattribute__() is not called on the class of a or its metaclass. Instead the predefined slot for __getitem__ is accessed; if it is empty then indexing is not allowed. Here is a demonstration that __getattribute__() is not called on the class or the metaclass when __getitem__() is accessed as a special method: In [4]: class ShowMeta(type): ...: def __getattribute__(self, name): ...: print 'ShowMeta:', name ...: return type.__getattribute__(self, name) ...: ...: In [5]: class Show(object): ...: def __getattribute__(self, name): ...: print 'Show:', name ...: return object.__getattribute__(self, name) ...: __metaclass__ = ShowMeta ...: ...: In [6]: a=Show() In [7]: a[1] ------------------------------------------------------------ Traceback (most recent call last): File "<ipython console>", line 1, in <module> <type 'exceptions.TypeError'>: 'Show' object is unindexable Notice that neither __getattribute__() is called. OTOH if __getitem__() is accessed as a normal attribute then Show.__getattribute__() *is* called: In [9]: a.__getitem__(0) Show: __getitem__ ------------------------------------------------------------ Traceback (most recent call last): File "<ipython console>", line 1, in <module> File "<ipython console>", line 4, in __getattribute__ <type 'exceptions.AttributeError'>: 'Show' object has no attribute '__getitem__' The only way to put something in the __getitem__ slot to assign to cls.__getitem__. That is why the cookbook recipe copies methods from the delegate into the proxy. It seems unfortunate that the recipe requires knowing which special methods you want to delegate. Maybe an approach like the one here http://groups.google.com/group/comp.lang.python/msg/f4bf020fd94d631a of delegating all special methods with a list of exceptions would work better. Kent From ricaraoz at gmail.com Mon Sep 24 03:13:51 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Sun, 23 Sep 2007 22:13:51 -0300 Subject: [Tutor] Counting method calls In-Reply-To: <46F701A6.9090905@tds.net> References: <46F5018E.30802@bigfoot.com> <46F50BD9.2000305@tds.net> <46F51776.10401@bigfoot.com> <46F546ED.30102@tds.net> <46F54E55.4080300@tds.net> <46F560E8.5040609@bigfoot.com> <46F701A6.9090905@tds.net> Message-ID: <46F70F4F.9010405@bigfoot.com> Kent Johnson wrote: > Ricardo Ar?oz wrote: >> Kent Johnson wrote: >>> One more reference: >>> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/252151 >>> >>> This appears as recipe 6.6 in the second edition of the printed >>> cookbook. >>> >>> Kent >> >> Thanks Kent. I guess I got into deep waters. >> It's a shame though that you can not do this in a simple manner, >> considering python simplifies so many other chores. > > I agree, also because it is so easy to do with old-style classes. > > The root of the problem seems to be that new-style classes do not use > the normal attribute lookup mechanism to find special methods when they > are being invoked by the interpreter *as* special methods. For example, > when executing a[0], __getattribute__() is not called on the class of a > or its metaclass. Instead the predefined slot for __getitem__ is > accessed; if it is empty then indexing is not allowed. > > Here is a demonstration that __getattribute__() is not called on the > class or the metaclass when __getitem__() is accessed as a special method: > > In [4]: class ShowMeta(type): > ...: def __getattribute__(self, name): > ...: print 'ShowMeta:', name > ...: return type.__getattribute__(self, name) > ...: > ...: > In [5]: class Show(object): > ...: def __getattribute__(self, name): > ...: print 'Show:', name > ...: return object.__getattribute__(self, name) > ...: __metaclass__ = ShowMeta > ...: > ...: > In [6]: a=Show() > In [7]: a[1] > ------------------------------------------------------------ > Traceback (most recent call last): > File "<ipython console>", line 1, in <module> > <type 'exceptions.TypeError'>: 'Show' object is unindexable > > Notice that neither __getattribute__() is called. OTOH if __getitem__() > is accessed as a normal attribute then Show.__getattribute__() *is* called: > > In [9]: a.__getitem__(0) > Show: __getitem__ > ------------------------------------------------------------ > Traceback (most recent call last): > File "<ipython console>", line 1, in <module> > File "<ipython console>", line 4, in __getattribute__ > <type 'exceptions.AttributeError'>: 'Show' object has no attribute > '__getitem__' > > The only way to put something in the __getitem__ slot to assign to > cls.__getitem__. That is why the cookbook recipe copies methods from the > delegate into the proxy. It seems unfortunate that the recipe requires > knowing which special methods you want to delegate. Maybe an approach > like the one here > http://groups.google.com/group/comp.lang.python/msg/f4bf020fd94d631a > of delegating all special methods with a list of exceptions would work > better. > > Kent > Anyway, if you have to know the innards of the language to be able to do it then it is not good. If nothing else it is against encapsulation. An application writer should not need to know those things in order to accomplish a simple concept as intercepting all methods. I think I'll stay with old style classes for this, the code is simpler and easy to understand what you are doing. From lavendula6654 at yahoo.com Mon Sep 24 03:31:31 2007 From: lavendula6654 at yahoo.com (Elaine) Date: Sun, 23 Sep 2007 18:31:31 -0700 (PDT) Subject: [Tutor] Python course at Foothill College Message-ID: <483045.67325.qm@web31713.mail.mud.yahoo.com> If you would like to learn Python, Foothill College in Los Altos Hills California is offering a course starting this Wednesday evening, 26 Sept. The course is designed for students who are already familiar with some type of programming. Here is the course description: CIS 68K "INTRODUCTION TO PYTHON PROGRAMMING" 5 Units This course will introduce students to the Python language and environment. Four hours lecture, four hours terminal time. Advisory: CIS 15A or 27A, and CIS 68A. 2182 CIS -068K-01 LEC6:00PM- 9:50 Wednesdays - HAIGHT Middlefield Campus, Room I5. Course fee, $4. If you would like to sign up for the class, it would be very helpful if you would register beforehand by going to: http://www.foothill.fhda.edu/reg/index.php If you have questions, you can contact the instructor at: haightElaine at foothill.edu ____________________________________________________________________________________ Be a better Heartthrob. Get better relationship answers from someone who knows. Yahoo! Answers - Check it out. http://answers.yahoo.com/dir/?link=list&sid=396545433 From rabidpoobear at gmail.com Mon Sep 24 06:38:08 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sun, 23 Sep 2007 23:38:08 -0500 Subject: [Tutor] python problem - help!! In-Reply-To: <!&!AAAAAAAAAAAYAAAAAAAAAHICkgQi6MVHrTCR8dizOffCgAAAEAAAACo8wKm6WoJChw7k2+7rOAMBAAAAAA==@whtvcable.com> References: <!&!AAAAAAAAAAAYAAAAAAAAAHICkgQi6MVHrTCR8dizOffCgAAAEAAAACo8wKm6WoJChw7k2+7rOAMBAAAAAA==@whtvcable.com> Message-ID: <46F73F30.9060804@gmail.com> Chris wrote: > > I need your help! > > > > I have this problem that I can?t seem to figure out. Can you help? > The problem is listed below, and below it is my code that I have so far. > What results / errors are you getting, how are they different from the results you want to get? -Luke From rabidpoobear at gmail.com Mon Sep 24 06:52:01 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sun, 23 Sep 2007 23:52:01 -0500 Subject: [Tutor] [Fwd: Re: python problem - help!!] Message-ID: <46F74271.9090802@gmail.com> Chris wrote: > If I sent you the problem can you build it so I know what it is suppose to > look like? I've spend too much time it, and made it worse...all I know is > that it does not produce the wanted results and is missing a loop... > It looks like a homework problem, so we can't just give you an answer, we can only provide guidance. > The worse part is that I did not find anything that can help me among the > hundreds of websites I visited... > If you give us more indication of what problems you're having we can better assist you. Please in the future reply to the list and not directly to me. Use the "reply all" button, or "reply to group" button, to do this. If such a button is not available in your mail client, carbon-copy (cc) a copy of the message to tutor at python.org You'll have much more luck finding an answer if you ask the whole list rather than a specific person. -Luke -------------- next part -------------- An embedded message was scrubbed... From: "Chris" <balderas at whtvcable.com> Subject: RE: [Tutor] python problem - help!! Date: Sun, 23 Sep 2007 21:43:20 -0700 Size: 3493 Url: http://mail.python.org/pipermail/tutor/attachments/20070923/9c0032b4/attachment.eml From balderas at whtvcable.com Mon Sep 24 06:59:20 2007 From: balderas at whtvcable.com (Chris) Date: Sun, 23 Sep 2007 21:59:20 -0700 Subject: [Tutor] [Fwd: Re: python problem - help!!] In-Reply-To: <46F74271.9090802@gmail.com> References: <46F74271.9090802@gmail.com> Message-ID: <!&!AAAAAAAAAAAYAAAAAAAAAHICkgQi6MVHrTCR8dizOffCgAAAEAAAANxKWupaTJVMv2KNx/wEK4oBAAAAAA==@whtvcable.com> It's not a homework problem it is a practice problem to figure out how to code, to be able to do the assignments... Chris wrote: > If I sent you the problem can you build it so I know what it is suppose to > look like? I've spend too much time it, and made it worse...all I know is > that it does not produce the wanted results and is missing a loop... > > The worse part is that I did not find anything that can help me among the > hundreds of websites I visited... No virus found in this incoming message. Checked by AVG Free Edition. Version: 7.5.487 / Virus Database: 269.13.25/1018 - Release Date: 9/19/2007 3:59 PM No virus found in this outgoing message. Checked by AVG Free Edition. Version: 7.5.487 / Virus Database: 269.13.25/1018 - Release Date: 9/19/2007 3:59 PM From bhaaluu at gmail.com Mon Sep 24 10:58:31 2007 From: bhaaluu at gmail.com (bhaaluu) Date: Mon, 24 Sep 2007 04:58:31 -0400 Subject: [Tutor] [Fwd: Re: python problem - help!!] In-Reply-To: <!&!AAAAAAAAAAAYAAAAAAAAAHICkgQi6MVHrTCR8dizOffCgAAAEAAAANxKWupaTJVMv2KNx/wEK4oBAAAAAA==@whtvcable.com> References: <46F74271.9090802@gmail.com> <!&!AAAAAAAAAAAYAAAAAAAAAHICkgQi6MVHrTCR8dizOffCgAAAEAAAANxKWupaTJVMv2KNx/wEK4oBAAAAAA==@whtvcable.com> Message-ID: <ea979d70709240158p4443c9b4vda1281746116fdb9@mail.gmail.com> Greetings, I ran the code sample you sent and found a couple of errors that wouldn't let the code run. The first error has to do with variable assignment. When you assign a variable, it is usually on the left and what you want to assign to it is on the right. See Lines 25,29. The second error has to do with the first error in a way. See Line 41. '%d' is a placeholder for an integer. '%2d' ? '%s' is a placeholder for a string. What "type" is the variable 'team'? (Hint: print type(team)) '%.2f' is a placeholder for a float displaying two places to the right of decimal point. Example: testvar = 10.012345 print 'testvar: %.2f' % testvar Output: testvar: 10.01 print 'testvar: %.2f' % testvar Output: testvar: 10.0123 As far as the maths in your program? I can't say. Perhaps if you get the program running, you can figure them out? Debugging tips: A cheap debugger that can be used as you create your program can be as simple as the following: variable = value # assign a variable a value print variable # display the value print type(variable) # display the variable 'type' raw_input() # breakpoint: (Pause. Press <Enter> to Continue...) -- bhaaluu at gmail dot com On 9/24/07, Chris <balderas at whtvcable.com> wrote: > It's not a homework problem it is a practice problem to figure out how to > code, to be able to do the assignments... > > > Chris wrote: > > If I sent you the problem can you build it so I know what it is suppose to > > look like? I've spend too much time it, and made it worse...all I know is > > that it does not produce the wanted results and is missing a loop... > > > > The worse part is that I did not find anything that can help me among the > > hundreds of websites I visited... > > No virus found in this incoming message. > Checked by AVG Free Edition. > Version: 7.5.487 / Virus Database: 269.13.25/1018 - Release Date: 9/19/2007 > 3:59 PM > > > > No virus found in this outgoing message. > Checked by AVG Free Edition. > Version: 7.5.487 / Virus Database: 269.13.25/1018 - Release Date: 9/19/2007 > 3:59 PM > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From bhaaluu at gmail.com Mon Sep 24 11:01:31 2007 From: bhaaluu at gmail.com (bhaaluu) Date: Mon, 24 Sep 2007 05:01:31 -0400 Subject: [Tutor] [Fwd: Re: python problem - help!!] In-Reply-To: <ea979d70709240158p4443c9b4vda1281746116fdb9@mail.gmail.com> References: <46F74271.9090802@gmail.com> <!&!AAAAAAAAAAAYAAAAAAAAAHICkgQi6MVHrTCR8dizOffCgAAAEAAAANxKWupaTJVMv2KNx/wEK4oBAAAAAA==@whtvcable.com> <ea979d70709240158p4443c9b4vda1281746116fdb9@mail.gmail.com> Message-ID: <ea979d70709240201t356ebfb2mc9fb47762a310e97@mail.gmail.com> > print 'testvar: %.2f' % testvar > Output: > testvar: 10.0123 Should be: print 'testvar: %.4f' % testvar Output: testvar: 10.0123 -- bhaaluu at gmail dot com On 9/24/07, bhaaluu <bhaaluu at gmail.com> wrote: > Greetings, > > I ran the code sample you sent and found a couple of errors > that wouldn't let the code run. > > The first error has to do with variable assignment. > When you assign a variable, it is usually on the left and > what you want to assign to it is on the right. See Lines 25,29. > > The second error has to do with the first error in a way. > See Line 41. '%d' is a placeholder for an integer. '%2d' ? > '%s' is a placeholder for a string. > What "type" is the variable 'team'? > (Hint: print type(team)) > > '%.2f' is a placeholder for a float displaying > two places to the right of decimal point. > Example: > testvar = 10.012345 > print 'testvar: %.2f' % testvar > Output: > testvar: 10.01 > print 'testvar: %.2f' % testvar > Output: > testvar: 10.0123 > > As far as the maths in your program? I can't say. > Perhaps if you get the program running, you can figure them out? > > Debugging tips: > A cheap debugger that can be used > as you create your program can > be as simple as the following: > > variable = value # assign a variable a value > print variable # display the value > print type(variable) # display the variable 'type' > raw_input() # breakpoint: (Pause. Press <Enter> to Continue...) > > -- > bhaaluu at gmail dot com > > On 9/24/07, Chris <balderas at whtvcable.com> wrote: > > It's not a homework problem it is a practice problem to figure out how to > > code, to be able to do the assignments... > > > > > > Chris wrote: > > > If I sent you the problem can you build it so I know what it is suppose to > > > look like? I've spend too much time it, and made it worse...all I know is > > > that it does not produce the wanted results and is missing a loop... > > > > > > The worse part is that I did not find anything that can help me among the > > > hundreds of websites I visited... > > > > No virus found in this incoming message. > > Checked by AVG Free Edition. > > Version: 7.5.487 / Virus Database: 269.13.25/1018 - Release Date: 9/19/2007 > > 3:59 PM > > > > > > > > No virus found in this outgoing message. > > Checked by AVG Free Edition. > > Version: 7.5.487 / Virus Database: 269.13.25/1018 - Release Date: 9/19/2007 > > 3:59 PM > > > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > From bediluwolde at yahoo.com Mon Sep 24 11:53:31 2007 From: bediluwolde at yahoo.com (bedilu woldemariam) Date: Mon, 24 Sep 2007 02:53:31 -0700 (PDT) Subject: [Tutor] tutor_request Message-ID: <333248.59381.qm@web42106.mail.mud.yahoo.com> help! --------------------------------- Luggage? GPS? Comic books? Check out fitting gifts for grads at Yahoo! Search. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070924/03e14365/attachment.htm From rabidpoobear at gmail.com Mon Sep 24 12:40:51 2007 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Mon, 24 Sep 2007 05:40:51 -0500 Subject: [Tutor] tutor_request Message-ID: <46F79433.1090404@gmail.com> oops, forgot to send this to tutor as well. And I'm the one always complaining about direct e-mails :) Luke Paireepinart wrote: > bedilu woldemariam wrote: >> help! > here, take this: > > > > > > > Hope that helped, > -Luke > -------------- next part -------------- An embedded message was scrubbed... From: Luke Paireepinart <rabidpoobear at gmail.com> Subject: Re: [Tutor] tutor_request Date: Mon, 24 Sep 2007 05:39:25 -0500 Size: 625 Url: http://mail.python.org/pipermail/tutor/attachments/20070924/2f5b2d9a/attachment.eml From kent37 at tds.net Mon Sep 24 12:48:04 2007 From: kent37 at tds.net (Kent Johnson) Date: Mon, 24 Sep 2007 06:48:04 -0400 Subject: [Tutor] python problem - help!! In-Reply-To: <!&!AAAAAAAAAAAYAAAAAAAAAHICkgQi6MVHrTCR8dizOffCgAAAEAAAACo8wKm6WoJChw7k2+7rOAMBAAAAAA==@whtvcable.com> References: <!&!AAAAAAAAAAAYAAAAAAAAAHICkgQi6MVHrTCR8dizOffCgAAAEAAAACo8wKm6WoJChw7k2+7rOAMBAAAAAA==@whtvcable.com> Message-ID: <46F795E4.7030802@tds.net> Chris wrote: > I need your help! > > > > I have this problem that I can?t seem to figure out. Can you help? The > problem is listed below, and below it is my code that I have so far. This looks like a homework problem. We can help you understand Python but we won't give you the answer. > if random.randint(1,8) >= 5: > > 'Team A' = team > > else: > > 'Team B' = team Your assignment statements are backwards here, it should be team = 'Team A' etc. Kent From jason.massey at gmail.com Mon Sep 24 14:11:48 2007 From: jason.massey at gmail.com (Jason Massey) Date: Mon, 24 Sep 2007 07:11:48 -0500 Subject: [Tutor] Capturing ctrl-c In-Reply-To: <82b4f5810709221331n1cbc730g4c1015a2a62179cf@mail.gmail.com> References: <3F791A15-5273-46EA-A83F-E09EE574760F@nc.rr.com> <82b4f5810709221331n1cbc730g4c1015a2a62179cf@mail.gmail.com> Message-ID: <7e3eab2c0709240511g456b0c89mad6274c42dfa1d6d@mail.gmail.com> Interesting. As Michael suggested this works, mostly: from time import sleep def loop(): x = 0 while 1: print "x:",x x += 1 sleep(0.5) if __name__ == "__main__": while 1: try: loop() except KeyboardInterrupt: print "Nope, not going to stop." Ctrl-C is ignored. But on Win XP, at least, Ctrl-Break still exits the program. On 9/22/07, Michael Langford <mlangford.cs03 at gtalumni.org> wrote: > > When I do real applications with exception based languages, I almost > always wrap the main function with a try/except block to allow me to > gracefully shut down. > > In the case of python, this means 1> Use the main method 2> wrap its > execution in a try catch: > > import mymodule > > def do_stuff(): > pass > > def graceful_cleanup() > pass > > if "__main__" == __name__: > try: > do_stuff() > except: > graceful_cleanup() > > --Michael > > -- > Michael Langford > Phone: 404-386-0495 > Consulting: http://www.TierOneDesign.com/ > Entertaining: http://www.ThisIsYourCruiseDirectorSpeaking.com > > On 9/22/07, James <jtp at nc.rr.com> wrote: > > > > Hi. :) > > > > I'm whipping up a program in Python and am having to deal with a user > > potentially hitting ctrl-c at any point in the program. I'd like my > > Python program to wrap up cleanly when it receives this signal. > > > > I did some Googling and read that Python throws a KeyboardInterrupt > > error. What's the best way to run a specific "cleanup" function at > > *any* time the interrupt is received, regardless of where the program > > is in execution? > > > > Most of the stuff I've read involves try-except blocks. This makes > > sense to me if I want to protect a specific function or area of the > > code from being interrupted by ctrl-c, but I'm not sure what kind of > > structure my program must have to catch the exception at any point > > during execution. > > > > Thoughts/ideas appreciated. :) > > > > Thanks! > > .james > > _______________________________________________ > > 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/20070924/c914802f/attachment.htm From noufal at airtelbroadband.in Mon Sep 24 19:01:28 2007 From: noufal at airtelbroadband.in (Noufal Ibrahim) Date: Mon, 24 Sep 2007 22:31:28 +0530 Subject: [Tutor] pythons xf86misc documentation ? In-Reply-To: <f52017b60709230931o4a13c87fg893a611e423972b6@mail.gmail.com> References: <f52017b60709230931o4a13c87fg893a611e423972b6@mail.gmail.com> Message-ID: <46F7ED68.1010104@airtelbroadband.in> dave selby wrote: > Can anyone tell me where the documentation for pythons xf86misc module > is, ie what methods are avalible ? I've not used this module you mention myself but if it's got docstrings and inline documentation, you can get help by importing the module and then doing a help(xf86misc) at the python interpreter prompt. You can also run a local pydoc server if you prefer clickable HTML documentation. Peace. -- ~noufal From dos.fool at gmail.com Tue Sep 25 00:35:01 2007 From: dos.fool at gmail.com (max baseman) Date: Mon, 24 Sep 2007 16:35:01 -0600 Subject: [Tutor] quick question Message-ID: <C23DE468-5CDC-4887-8335-08193D13A0AC@gmail.com> hello just a quickie today :) how is python with patters or finding a rule for something ie: in out tables for example how hard would it be to write a program that take's a input of a in out table and finds the rule ex: in out 10 23 5 13 1 5 0 3 the rule is in*2+3 if possible do you know any tutorials that would help thanks From cspears2002 at yahoo.com Tue Sep 25 02:37:21 2007 From: cspears2002 at yahoo.com (Christopher Spears) Date: Mon, 24 Sep 2007 17:37:21 -0700 (PDT) Subject: [Tutor] largest and smallest numbers Message-ID: <730562.77936.qm@web51603.mail.re2.yahoo.com> One of the exercises from Core Python Programmng (2nd Edition) asks me to determine the largest and smallest integers, float, and complex numbers my system can handle. Using python.org and Google, I have discovered my system's largest and smallest ingtegers: >>> import sys >>> sys.maxint 2147483647 >>> -sys.maxint - 1 -2147483648 How can I find the largest float and complex numbers? From carroll at tjc.com Tue Sep 25 02:48:24 2007 From: carroll at tjc.com (Terry Carroll) Date: Mon, 24 Sep 2007 17:48:24 -0700 (PDT) Subject: [Tutor] quick question In-Reply-To: <C23DE468-5CDC-4887-8335-08193D13A0AC@gmail.com> Message-ID: <Pine.LNX.4.44.0709241747080.12833-100000@violet.rahul.net> On Mon, 24 Sep 2007, max baseman wrote: > for example how hard would it be to write a program that take's a > input of a in out table and finds the rule > > ex: > > in out > 10 23 > 5 13 > 1 5 > 0 3 > > the rule is in*2+3 This is called linear regression. A search for "Python Linear Regression" should help you out. Some sample code is at http://www.answermysearches.com/how-to-do-a-simple-linear-regression-in-python/124/ From witham.ian at gmail.com Tue Sep 25 02:55:35 2007 From: witham.ian at gmail.com (Ian Witham) Date: Tue, 25 Sep 2007 12:55:35 +1200 Subject: [Tutor] Need help speeding up algorithm. Message-ID: <a04dbf4b0709241755m439d6c9n497fe48ae7c1b550@mail.gmail.com> Hello, I am attempting to do this <https://www.spoj.pl/problems/FCTRL/> project for the Sphere Online Judge. I think my program is getting the right answer, however it exceeds the 6s time limit on the judge machine. Here is my code: ############ import sys testnums = [] tests = int(sys.stdin.readline()) for count in xrange(tests): testnums.append(int(sys.stdin.readline())) for d in testnums: maxer = int(d ** .2) + 1 g = sum(d / (5 ** x) for x in xrange(1, maxer)) sys.stdout.write('%d\n' % g) ############ Any ideas on how to speed this up? Also, if anyone is familiar with the Online Judge system, am I correct in gathering all of the input first and then providing the output? Or should I be providing output after each input? Any help appreciated, Ian. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070925/2d0a6ef1/attachment-0001.htm From carroll at tjc.com Tue Sep 25 03:01:45 2007 From: carroll at tjc.com (Terry Carroll) Date: Mon, 24 Sep 2007 18:01:45 -0700 (PDT) Subject: [Tutor] largest and smallest numbers In-Reply-To: <730562.77936.qm@web51603.mail.re2.yahoo.com> Message-ID: <Pine.LNX.4.44.0709241754500.12833-100000@violet.rahul.net> On Mon, 24 Sep 2007, Christopher Spears wrote: > How can I find the largest float and complex numbers? That's an interesting question.. I just tried this: x = 2.0 while True: x = x*2 print x if repr(x) == "1.#INF": break to just keep doubling X until Python began representing it as infinity. My output: 4.0 8.0 16.0 32.0 64.0 128.0 . . . 137438953472.0 274877906944.0 549755813888.0 1.09951162778e+012 2.19902325555e+012 4.3980465111e+012 . . . 2.24711641858e+307 4.49423283716e+307 8.98846567431e+307 1.#INF So I'd say, the answer is somewhere between 8.98846567431e+307 and double that. On complex numbers, I'm not so sure. My math is rusty. Is there a concept of "greater than" or "largest" in complex numbers on different axis? Which is larger, 4+2i or 2+4i? >>> complex(4,2) (4+2j) >>> complex(2,4) (2+4j) >>> complex(4,2) > complex(2,4) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: no ordering relation is defined for complex numbers From kent37 at tds.net Tue Sep 25 04:10:24 2007 From: kent37 at tds.net (Kent Johnson) Date: Mon, 24 Sep 2007 22:10:24 -0400 Subject: [Tutor] largest and smallest numbers In-Reply-To: <730562.77936.qm@web51603.mail.re2.yahoo.com> References: <730562.77936.qm@web51603.mail.re2.yahoo.com> Message-ID: <46F86E10.90507@tds.net> Christopher Spears wrote: > How can I find the largest float and complex numbers? I don't know how to do this in standard Python. Here are some answers that use Numeric and numpy: http://groups.google.com/group/comp.lang.python/msg/fa7a761411ced62b http://www.thescripts.com/forum/post2028282-8.html Here is the numpy solution on my machine: In [1]: from numpy import * In [2]: print finfo(float32) Machine parameters for <type 'numpy.float32'> --------------------------------------------------------------------- precision= 6 resolution= 1.0000000e-06 machep= -23 eps= 1.1920929e-07 negep = -24 epsneg= 5.9604645e-08 minexp= -126 tiny= 1.1754944e-38 maxexp= 128 max= 3.4028235e+38 nexp = 8 min= -max --------------------------------------------------------------------- Kent From balderas at whtvcable.com Tue Sep 25 06:50:00 2007 From: balderas at whtvcable.com (Chris) Date: Mon, 24 Sep 2007 21:50:00 -0700 Subject: [Tutor] python problem In-Reply-To: <mailman.3553.1190681774.2656.tutor@python.org> References: <mailman.3553.1190681774.2656.tutor@python.org> Message-ID: <!&!AAAAAAAAAAAYAAAAAAAAAHICkgQi6MVHrTCR8dizOffCgAAAEAAAAMkyk9iBJ8RLn5YK2RLm8JcBAAAAAA==@whtvcable.com> I have this GUESSING GAME code found below: --------------------- import random number = random.randint(1, 101) print "I've thought of a number between 1 and 100." print "Try and guess it!" print guess = input( "What's your guess? ") while guess != number: if guess > number: print "Your guess is too high." else: #elif guess < number: print "Your guess is too low." guess = input( "What's your next guess? " ) print "Congratulations! You guessed the number." ---------------------------------------------------- What do I have to do to the code so that the Guessing Game that tries to guess a number the user has thought of. (Make sure it can tell if the user tries to cheat, e.g. by changing the number during the game?? I hope you can help! Chris No virus found in this outgoing message. Checked by AVG Free Edition. Version: 7.5.487 / Virus Database: 269.13.25/1018 - Release Date: 9/19/2007 3:59 PM -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070924/8639b1f4/attachment.htm From mlangford.cs03 at gtalumni.org Tue Sep 25 06:56:22 2007 From: mlangford.cs03 at gtalumni.org (Michael Langford) Date: Tue, 25 Sep 2007 00:56:22 -0400 Subject: [Tutor] python problem In-Reply-To: <!&!AAAAAAAAAAAYAAAAAAAAAHICkgQi6MVHrTCR8dizOffCgAAAEAAAAMkyk9iBJ8RLn5YK2RLm8JcBAAAAAA==@whtvcable.com> References: <mailman.3553.1190681774.2656.tutor@python.org> <!&!AAAAAAAAAAAYAAAAAAAAAHICkgQi6MVHrTCR8dizOffCgAAAEAAAAMkyk9iBJ8RLn5YK2RLm8JcBAAAAAA==@whtvcable.com> Message-ID: <82b4f5810709242156q70ce988fob7a74e48524cb192@mail.gmail.com> Look here. Do this: http://en.wikipedia.org/wiki/Binary_search -- Michael Langford Phone: 404-386-0495 Consulting: http://www.TierOneDesign.com/ Entertaining: http://www.ThisIsYourCruiseDirectorSpeaking.com On 9/25/07, Chris <balderas at whtvcable.com> wrote: > > **** > > ***I have this**** GUESSING GAME code found below:***** > > --------------------- > > import random > > number = random.randint(1, 101) > > print "I've thought of a number between 1 and 100." > > print "Try and guess it!" > > print > > guess = input( "What's your guess? ") > > while guess != number: > > if guess > number: > > print "Your guess is too high." > > else: #elif guess < number: > > print "Your guess is too low." > > guess = input( "What's your next guess? " ) > > > > print "Congratulations! You guessed the number." > > ---------------------------------------------------- > > *******What do I have to******** do to the code so that******** the > Guessing Game******** that tries to guess a number the user has thought > of. (Make sure it can tell if the user tries to cheat, e.g. by changing > the number during the game********??* > > *I hope you can help!* > > *Chris***** > > No virus found in this outgoing message. > Checked by AVG Free Edition. > Version: 7.5.487 / Virus Database: 269.13.25/1018 - Release Date: > 9/19/2007 3:59 PM > > > _______________________________________________ > 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/20070925/482a1f69/attachment.htm From carroll at tjc.com Tue Sep 25 07:26:35 2007 From: carroll at tjc.com (Terry Carroll) Date: Mon, 24 Sep 2007 22:26:35 -0700 (PDT) Subject: [Tutor] Need help speeding up algorithm. In-Reply-To: <a04dbf4b0709241755m439d6c9n497fe48ae7c1b550@mail.gmail.com> Message-ID: <Pine.LNX.4.44.0709242207380.22457-100000@violet.rahul.net> On Tue, 25 Sep 2007, Ian Witham wrote: > I am attempting to do this <https://www.spoj.pl/problems/FCTRL/> project for > the Sphere Online Judge. (Summary of the problem: for a given integer N, determine the number of trailing zeroes in N! For example, for N=10, N! = 3628800, so the number of trailing zeroes is 2.) > for d in testnums: > maxer = int(d ** .2) + 1 > g = sum(d / (5 ** x) for x in xrange(1, maxer)) > sys.stdout.write('%d\n' % g) > > ############ > > Any ideas on how to speed this up? I think you're on the right track, but it can actually be much less computationally intensive. The track I think you're on is that each trailing zero means that the factorial, if factored out, had both a 2 and 5 among its factors (because 2x5 is 10, and the only way of getting 10). Furthermore, because there are so many 2s, it's really about counting the number of times 5 is multiplied in. For example, in 10!, you have two occurances of 5: at 5 itself, and at 10 (2x5). For 30!, you'd have fives at 5, 10, 15, 20, 25, and 30, which at first glance is 6; but since the 25 is actually 5x5, it counts for two, for a total of 7. And, sure enough 20! is 265252859812191058636308480000000, with 7 trailing zeoes. So, an approach might be: 1. Integer-divide N by 5. That gives the number of times it's divisible by 5. 2. Integer-divide N by 5*5, i.e., 25; That gives the number of times it's also divisible by 25. 3. Integer-divide N by 5*5*5, i.e, 125. That gives the number of times it's also divided by 125 4. through whatever: keep doing this. You can stop when the result of the integer division is zero. If you add up all the counts you got in the previous steps, you now have a number that tells you, if you were to have actually calculated N!, and then factored it, the number of times 5 would have been a factor. And since for each one of these there's at least one 2, you happen to also have the count of how many times N! was multipled by 2*5, or 10, which is also the number of trailing zeroes. I just tried this approach out, using the values given at that web page, and it works both quickly and accurately: if __name__ == "__main__": sampleinput = [3, 60, 100, 1024, 23456, 8735373] sampleoutput = [0, 14, 24, 253, 5861, 2183837] actualoutput = [] for n in sampleinput: actualoutput.append(numfaczeroes(n)) assert actualoutput == sampleoutput print actualoutput C:\test\FCTRL>fctrl.py [0, 14, 24, 253, 5861, 2183837] I'll leave the coding of the numfaczeroes function as an exercise. From witham.ian at gmail.com Tue Sep 25 08:40:01 2007 From: witham.ian at gmail.com (Ian Witham) Date: Tue, 25 Sep 2007 18:40:01 +1200 Subject: [Tutor] Need help speeding up algorithm. In-Reply-To: <Pine.LNX.4.44.0709242207380.22457-100000@violet.rahul.net> References: <a04dbf4b0709241755m439d6c9n497fe48ae7c1b550@mail.gmail.com> <Pine.LNX.4.44.0709242207380.22457-100000@violet.rahul.net> Message-ID: <a04dbf4b0709242340i783c02eei61a8138820a6490a@mail.gmail.com> On 9/25/07, Terry Carroll <carroll at tjc.com> wrote: > > On Tue, 25 Sep 2007, Ian Witham wrote: > > > I am attempting to do this <https://www.spoj.pl/problems/FCTRL/> project > for > > the Sphere Online Judge. > > (Summary of the problem: for a given integer N, determine the number of > trailing zeroes in N! For example, for N=10, N! = 3628800, so the number > of trailing zeroes is 2.) > > > for d in testnums: > > maxer = int(d ** .2) + 1 > > g = sum(d / (5 ** x) for x in xrange(1, maxer)) > > sys.stdout.write('%d\n' % g) > > > > ############ > > > > Any ideas on how to speed this up? > > I think you're on the right track, but it can actually be much less > computationally intensive. > > The track I think you're on is that each trailing zero means that the > factorial, if factored out, had both a 2 and 5 among its factors (because > 2x5 is 10, and the only way of getting 10). Furthermore, because there > are so many 2s, it's really about counting the number of times 5 is > multiplied in. > > For example, in 10!, you have two occurances of 5: at 5 itself, and at 10 > (2x5). For 30!, you'd have fives at 5, 10, 15, 20, 25, and 30, which at > first glance is 6; but since the 25 is actually 5x5, it counts for two, > for a total of 7. And, sure enough 20! is > 265252859812191058636308480000000, with 7 trailing zeoes. > > So, an approach might be: > > 1. Integer-divide N by 5. That gives the number of times it's divisible > by 5. > 2. Integer-divide N by 5*5, i.e., 25; That gives the number of times it's > also divisible by 25. > 3. Integer-divide N by 5*5*5, i.e, 125. That gives the number of times > it's also divided by 125 > 4. through whatever: keep doing this. You can stop when the result of the > integer division is zero. The problem with my program was the "through whatever". As I was using a list comprehension I wasn't sure how to make the calculations stop when the result of integer division == 0. My method was to work out the maximum exponent of 5 that I would fit within the test number. (This is the value I called "maxer") However... my math was off. int(d ** (1 / 5.0) != int(math.log(d, 5)) Once I fixed this, the program ran fast enough to be accepted. Thanks for the advice, Ian. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070925/cc8f9953/attachment-0001.htm From john at fouhy.net Tue Sep 25 10:35:58 2007 From: john at fouhy.net (John Fouhy) Date: Tue, 25 Sep 2007 20:35:58 +1200 Subject: [Tutor] largest and smallest numbers In-Reply-To: <Pine.LNX.4.44.0709241754500.12833-100000@violet.rahul.net> References: <730562.77936.qm@web51603.mail.re2.yahoo.com> <Pine.LNX.4.44.0709241754500.12833-100000@violet.rahul.net> Message-ID: <5e58f2e40709250135o62a245d4nac0d9685e69245ac@mail.gmail.com> You've got upper and lower bounds - maybe you could do a binary search to find the max exactly? It should only take the same number of steps again... On 9/25/07, Terry Carroll <carroll at tjc.com> wrote: > On Mon, 24 Sep 2007, Christopher Spears wrote: > > > How can I find the largest float and complex numbers? > > That's an interesting question.. > > I just tried this: > > x = 2.0 > while True: > x = x*2 > print x > if repr(x) == "1.#INF": break > > to just keep doubling X until Python began representing it as infinity. > My output: > > 4.0 > 8.0 > 16.0 > 32.0 > 64.0 > 128.0 > . . . > 137438953472.0 > 274877906944.0 > 549755813888.0 > 1.09951162778e+012 > 2.19902325555e+012 > 4.3980465111e+012 > . . . > 2.24711641858e+307 > 4.49423283716e+307 > 8.98846567431e+307 > 1.#INF > > So I'd say, the answer is somewhere between 8.98846567431e+307 and double > that. > > On complex numbers, I'm not so sure. My math is rusty. Is there a concept > of "greater than" or "largest" in complex numbers on different axis? > Which is larger, 4+2i or 2+4i? > > >>> complex(4,2) > (4+2j) > >>> complex(2,4) > (2+4j) > >>> complex(4,2) > complex(2,4) > Traceback (most recent call last): > File "<stdin>", line 1, in <module> > TypeError: no ordering relation is defined for complex numbers > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From bhaaluu at gmail.com Tue Sep 25 13:36:30 2007 From: bhaaluu at gmail.com (bhaaluu) Date: Tue, 25 Sep 2007 07:36:30 -0400 Subject: [Tutor] python problem In-Reply-To: <!&!AAAAAAAAAAAYAAAAAAAAAHICkgQi6MVHrTCR8dizOffCgAAAEAAAAMkyk9iBJ8RLn5YK2RLm8JcBAAAAAA==@whtvcable.com> References: <mailman.3553.1190681774.2656.tutor@python.org> <!&!AAAAAAAAAAAYAAAAAAAAAHICkgQi6MVHrTCR8dizOffCgAAAEAAAAMkyk9iBJ8RLn5YK2RLm8JcBAAAAAA==@whtvcable.com> Message-ID: <ea979d70709250436n582870a0s2795c5cb13233ae2@mail.gmail.com> On 9/25/07, Chris <balderas at whtvcable.com> wrote: > I have this GUESSING GAME code found below: > --------------------- > import random > number = random.randint(1, 101) > print "I've thought of a number between 1 and 100." > print "Try and guess it!" > print > guess = input( "What's your guess? ") > while guess != number: > if guess > number: > print "Your guess is too high." > else: #elif guess < number: > print "Your guess is too low." > guess = input( "What's your next guess? " ) > print "Congratulations! You guessed the number." > ---------------------------------------------------- > What do I have to do to the code so that the Guessing Game that tries to > guess a number the user has thought of. (Make sure it can tell if the user > tries to cheat, e.g. by changing the number during the game?? > > I hope you can help! > Chris I hope so too. You can have the user enter the "secret number" at the beginning of the game, and the computer can check it's guess against the secret number. If the computer's guess is higher than the number, the user can reply with "<" or "Lower". If the computer's guess is lower than the secret number, the user can give the computer the hint of ">" or "Higher", whatever. But since the secret number is stored in a variable at the beginning of the game, the user can't 'cheat' by changing the number the computer is trying to guess, in the middle of the game. Just have a test that checks the computer's guess against the number stored in the secret number variable. I recently ran across this problem while working through the Chapter 3 Challenges in Michael Dawson's _Programming Python for the Absolute Beginner, Second Edition_. Challenge #4 : Here's a bigger challenge. Write the pseudocode for a program where the player and the computer trade places in the number guessing game. That is, the player picks a random number between 1 and 100 that the computer has to guess. Before you start, think about how you guess. If all goes well, try coding the game. So my question for you, is: Where is your pseudocode? The challenge is to plan the game beforehand using pseudocode. Have you thought about how you guess when you play the Guess-A-Number game? Show us your pseudocode for the game. -- bhaaluu at gmail dot com From jecarnell at saintfrancis.com Tue Sep 25 15:15:59 2007 From: jecarnell at saintfrancis.com (Carnell, James E) Date: Tue, 25 Sep 2007 08:15:59 -0500 Subject: [Tutor] Need help speeding up algorithm. (Terry Carroll) In-Reply-To: <mailman.3603.1190702404.2656.tutor@python.org> Message-ID: <CEFAE560FE3E3C458A2335A1AA37A82D06763998@MAIL2W2K3.WarrenNT.SaintFrancis.Loc> Terry, I liked your answer! From carroll at tjc.com Tue Sep 25 17:17:06 2007 From: carroll at tjc.com (Terry Carroll) Date: Tue, 25 Sep 2007 08:17:06 -0700 (PDT) Subject: [Tutor] largest and smallest numbers In-Reply-To: <5e58f2e40709250135o62a245d4nac0d9685e69245ac@mail.gmail.com> Message-ID: <Pine.LNX.4.44.0709250816440.31475-100000@violet.rahul.net> On Tue, 25 Sep 2007, John Fouhy wrote: > You've got upper and lower bounds - maybe you could do a binary search > to find the max exactly? It should only take the same number of steps > again... I thought of that; and then I thought I'd rather go home and have dinner. From linpeiheng at 163.com Tue Sep 25 17:05:23 2007 From: linpeiheng at 163.com (=?gb2312?B?wdbF4Lrj?=) Date: Tue, 25 Sep 2007 23:05:23 +0800 Subject: [Tutor] largest and smallest numbers (Linpeiheng) Message-ID: <46F9273E.079B0F.06246@m5-86.163.com> On Mon, 24 Sep 2007, Terry Carroll write: >My math is rusty. Is there a concept of "greater than" >or "largest" in complex numbers on different axis? Which >is larger, 4+2i or 2+4i? In fact, complex numbers can not compare directly. People always compare complex numbers with their 'model'. For example, sqrt(a**2 + b**2) is the 'model' of a+bi. From carroll at tjc.com Tue Sep 25 17:33:31 2007 From: carroll at tjc.com (Terry Carroll) Date: Tue, 25 Sep 2007 08:33:31 -0700 (PDT) Subject: [Tutor] Need help speeding up algorithm. In-Reply-To: <a04dbf4b0709242340i783c02eei61a8138820a6490a@mail.gmail.com> Message-ID: <Pine.LNX.4.44.0709250817120.31475-100000@violet.rahul.net> On Tue, 25 Sep 2007, Ian Witham wrote: > As I was using a list comprehension I wasn't sure how to make the > calculations stop when the result of integer division == 0. I don't see how to do that, either. Someone on this list (sorry, I forget who) once suggested that the list comprehension should support a "while" predicate, similar to the "if" filter. Such a predicate would not just filter the generated list, but actually stop its computation. I think that would be a great idea, and this is a good use case why. Absent that capability, your only alternatives that I see are either 1) use the if-filter to filter out the list entries beyond those needed; or 2) force the programmer to work backwards to figure out when that while-condition would be hit, and bake that into something like a range (as you did). The downside of #1 is the computational expense: you generate a lot of potential list enties, just to throw them away. The downside of #2 is that it's programmer-intensive, wasting programmer time, and prone ro errors, as you discovered. Now that you've solved your code, here's the function I came up with. As I said, it resists implimentation as a list comprehension: def numfaczeroes(n): """ return the count of trailing zeroes from n! e.g., 10! = 3628800; count of trailing zeros = 2 """ exponent = 1 fivecount = 0 while (n//(5**exponent)) > 0: fivecount += n//(5**exponent) exponent += 1 return fivecount But what I like about is is that the only math is integer division and addition (and all the addition is simple incrementation). No use of logarithms, not even any multiplication (which is just perverse, when you think about the fact that it's analyzing factorials, which are pure multiplication). From kent37 at tds.net Tue Sep 25 18:06:36 2007 From: kent37 at tds.net (Kent Johnson) Date: Tue, 25 Sep 2007 12:06:36 -0400 Subject: [Tutor] Need help speeding up algorithm. In-Reply-To: <Pine.LNX.4.44.0709250817120.31475-100000@violet.rahul.net> References: <Pine.LNX.4.44.0709250817120.31475-100000@violet.rahul.net> Message-ID: <46F9320C.4070704@tds.net> Terry Carroll wrote: > On Tue, 25 Sep 2007, Ian Witham wrote: > >> As I was using a list comprehension I wasn't sure how to make the >> calculations stop when the result of integer division == 0. > > I don't see how to do that, either. Someone on this list (sorry, I forget > who) once suggested that the list comprehension should support a "while" > predicate, similar to the "if" filter. Such a predicate would not just > filter the generated list, but actually stop its computation. Take a look at itertools.takewhile() > Now that you've solved your code, here's the function I came up with. As > I said, it resists implimentation as a list comprehension: > > def numfaczeroes(n): > """ > return the count of trailing zeroes from n! > e.g., 10! = 3628800; count of trailing zeros = 2 > """ > exponent = 1 > fivecount = 0 > while (n//(5**exponent)) > 0: > fivecount += n//(5**exponent) > exponent += 1 > return fivecount Here is a version using takewhile() and a generator expression: from itertools import count, takewhile def numfaczeroes2(n): def while_(e): return n//(5**e) > 0 return sum(n//(5**exponent) for exponent in takewhile(while_, count(1))) It is quite a bit slower, though; probably because of the extra function call introduced for while_(): from timeit import Timer print min(Timer('for i in range(1, 101): numfaczeroes(i)', setup='from __main__ import numfaczeroes').repeat(number=1000)) print min(Timer('for i in range(1, 101): numfaczeroes2(i)', setup='from __main__ import numfaczeroes2').repeat(number=1000)) prints: 0.14363694191 0.412271022797 You could also encapsulate the condition in a generator function: def numfaczeroes3(n): def gen(n): e = 1 while (n//(5**e)) > 0: yield e e += 1 return sum(n//(5**exponent) for exponent in gen(n)) This is faster than numfaczeroes2 but still not as fast as the original. Kent From timmichelsen at gmx-topmail.de Tue Sep 25 18:25:09 2007 From: timmichelsen at gmx-topmail.de (Tim) Date: Tue, 25 Sep 2007 16:25:09 +0000 (UTC) Subject: [Tutor] data type conversion for print statement Message-ID: <loom.20070925T161525-373@post.gmane.org> Hello, I have a print statement where I use concatenation of variables with "+" to avoid extra whitespaces. The variables are mixed (float/int). How can I convert them all to strings to have a clean print statement? example print str(var1)+"and this "+str(var2)+"needs to check "+str(var3) how can I convert var1, var2, var3 all at once? This would avoid errors because of mixed data types. BTW, why does a statment like print var1, var2 automatically add spaces between the variables? Thanks in advance for your help. Timmie From tktucker at gmail.com Tue Sep 25 18:49:22 2007 From: tktucker at gmail.com (Tom Tucker) Date: Tue, 25 Sep 2007 12:49:22 -0400 Subject: [Tutor] data type conversion for print statement In-Reply-To: <loom.20070925T161525-373@post.gmane.org> References: <loom.20070925T161525-373@post.gmane.org> Message-ID: <2a278ffe0709250949k7127978ej36e1d5afc68b8818@mail.gmail.com> Excerpt from an email Danny Yoo sent to me and the list in 2005. I had the same question. ;-) Hi Tom, The 'print' statement is hardcoded to add a space between elements. print is meant to make output easy, at the cost of control. If we need more fine-grained control over output, we may want to take a look at the sys.stdout object; it's a file object that corresponds to the output we send to the user. ####### >>> import sys >>> sys.stdout <open file '<stdout>', mode 'w' at 0x2a060> ####### As a file object, we can use the methods that files provide: http://www.python.org/doc/lib/bltin-file-objects.html But the one we'll probably want is 'write()': the write() method of a file object lets us send content out, without any adulteration: ###### >>> import sys >>> for i in range(5): ... sys.stdout.write('hello' + str(i)) ... hello0hello1hello2hello3hello4 ###### We might have to be a little bit more careful with write(), because unlike the print statement, the write() method isn't magical, and won't automatically try to coerse objects to strings. The code above shows that we str() each number, and for good reason. If we try without it, we'll get a TypeError: ###### >>> sys.stdout.write(42) Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: argument 1 must be string or read-only character buffer, not int ###### So it just means we'll have to be more aware about the type of a value when we use write(). For some more information, see: http://www.python.org/doc/tut/node9.html#SECTION009200000000000000000 http://www.python.org/doc/tut/node9.html#SECTION009100000000000000000 Please feel free to ask more questions. Good luck! On 9/25/07, Tim <timmichelsen at gmx-topmail.de> wrote: > > Hello, > I have a print statement where I use concatenation of variables with "+" > to > avoid extra whitespaces. The variables are mixed (float/int). > > How can I convert them all to strings to have a clean print statement? > > example > print str(var1)+"and this "+str(var2)+"needs to check "+str(var3) > > how can I convert var1, var2, var3 all at once? > > This would avoid errors because of mixed data types. > > BTW, why does a statment like > print var1, var2 > automatically add spaces between the variables? > > Thanks in advance for your help. > > Timmie > > _______________________________________________ > 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/20070925/e3c6d99e/attachment-0001.htm From kent37 at tds.net Tue Sep 25 19:03:36 2007 From: kent37 at tds.net (Kent Johnson) Date: Tue, 25 Sep 2007 13:03:36 -0400 Subject: [Tutor] data type conversion for print statement In-Reply-To: <loom.20070925T161525-373@post.gmane.org> References: <loom.20070925T161525-373@post.gmane.org> Message-ID: <46F93F68.8060504@tds.net> Tim wrote: > Hello, > I have a print statement where I use concatenation of variables with "+" to > avoid extra whitespaces. The variables are mixed (float/int). > > How can I convert them all to strings to have a clean print statement? > > example > print str(var1)+"and this "+str(var2)+"needs to check "+str(var3) > > how can I convert var1, var2, var3 all at once? Use string formatting: print '%sand this %s needs to check %s' % (var1, var2, var3) The %s format calls str() for its parameter. > BTW, why does a statment like > print var1, var2 > automatically add spaces between the variables? Because it is convenient. Use string formatting to get closer control. Kent From Mike.Hansen at atmel.com Tue Sep 25 20:27:17 2007 From: Mike.Hansen at atmel.com (Hansen, Mike) Date: Tue, 25 Sep 2007 12:27:17 -0600 Subject: [Tutor] Take if offline Message-ID: <7941B2693F32294AAF16C26B679A258D0D805E@csomb01.corp.atmel.com> Anytime someone posts in HTML, or posts without a subject, or accidentally hijacks a thread, or top-posts, or writes in caps, a couple of posters pop up and complain. Rather than posting to the entire list, I think it'd be best if you send your complaint directly to the "offending" user. I'd prefer to read about Python not read lessons in net/mail-list etiquette. Thanks, Mike From D3IBZ at hotmail.com Tue Sep 25 20:32:37 2007 From: D3IBZ at hotmail.com (Darren Williams) Date: Tue, 25 Sep 2007 14:32:37 -0400 Subject: [Tutor] Take if offline References: <7941B2693F32294AAF16C26B679A258D0D805E@csomb01.corp.atmel.com> Message-ID: <BAY138-DAV3273634C285CCC19D1951E9B70@phx.gbl> So by your own rules, you should have sent that to the offending user(s). ----- Original Message ----- From: "Hansen, Mike" <Mike.Hansen at atmel.com> To: "python tutor" <tutor at python.org> Sent: Tuesday, September 25, 2007 2:27 PM Subject: [Tutor] Take if offline > Anytime someone posts in HTML, or posts without a subject, or > accidentally > hijacks a thread, or top-posts, or writes in caps, a couple of posters > pop up > and complain. Rather than posting to the entire list, I think it'd be > best if > you send your complaint directly to the "offending" user. I'd prefer to > read > about Python not read lessons in net/mail-list etiquette. > > Thanks, > > Mike > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From noufal at airtelbroadband.in Tue Sep 25 20:33:55 2007 From: noufal at airtelbroadband.in (Noufal Ibrahim) Date: Wed, 26 Sep 2007 00:03:55 +0530 Subject: [Tutor] largest and smallest numbers (Linpeiheng) In-Reply-To: <46F9273E.079B0F.06246@m5-86.163.com> References: <46F9273E.079B0F.06246@m5-86.163.com> Message-ID: <46F95493.9020907@airtelbroadband.in> ??? wrote: > On Mon, 24 Sep 2007, Terry Carroll write: > >> My math is rusty. Is there a concept of "greater than" >> or "largest" in complex numbers on different axis? Which >> is larger, 4+2i or 2+4i? > > In fact, complex numbers can not compare directly. People always compare complex numbers with their 'model'. For example, sqrt(a**2 + b**2) is the 'model' of a+bi. i think you mean "modulus". Also, you can get it directly. The abs builtin does it for you. >>> foo = 3+4j >>> print abs(foo) I don't think there is a direct way to the get the argument. You'd have to use arctan for that. -- ~noufal From kent37 at tds.net Tue Sep 25 20:56:10 2007 From: kent37 at tds.net (Kent Johnson) Date: Tue, 25 Sep 2007 14:56:10 -0400 Subject: [Tutor] Take if offline In-Reply-To: <7941B2693F32294AAF16C26B679A258D0D805E@csomb01.corp.atmel.com> References: <7941B2693F32294AAF16C26B679A258D0D805E@csomb01.corp.atmel.com> Message-ID: <46F959CA.9080806@tds.net> Hansen, Mike wrote: > Anytime someone posts in HTML, or posts without a subject, or > accidentally > hijacks a thread, or top-posts, or writes in caps, a couple of posters > pop up > and complain. Rather than posting to the entire list, I think it'd be > best if > you send your complaint directly to the "offending" user. I'd prefer to > read > about Python not read lessons in net/mail-list etiquette. Hmmm. So instead, whenever someone complains about netiquette on-list we should post on-list complaining about it? I'm not sure that improves the situation any, especially if it sparks a discussion. Perhaps you should email your suggestion privately to the offending parties. :-) I definitely think this list is about how to be part of the Python community, as well as how to program in Python. Knowing how to participate in a mailing list is part of that. Maybe you could just skip those posts, there are not that many of them. Kent From noufal at airtelbroadband.in Tue Sep 25 21:02:11 2007 From: noufal at airtelbroadband.in (Noufal Ibrahim) Date: Wed, 26 Sep 2007 00:32:11 +0530 Subject: [Tutor] data type conversion for print statement In-Reply-To: <loom.20070925T161525-373@post.gmane.org> References: <loom.20070925T161525-373@post.gmane.org> Message-ID: <46F95B33.3010008@airtelbroadband.in> Tim wrote: > Hello, > I have a print statement where I use concatenation of variables with "+" to > avoid extra whitespaces. The variables are mixed (float/int). > > How can I convert them all to strings to have a clean print statement? > > example > print str(var1)+"and this "+str(var2)+"needs to check "+str(var3) Well, if they're all ints or floats, you could do something like print "%fand this %fneeds to check %f"%(val1,val2,val3) but you'll get decimal points for everything. I suppose you could also do but it's a little less readable print "%sand this %sneeds to check %s"%tuple([str(x) for x in (val1,val2,val3)]) Both don't look very pythonic to me though. :( -- ~noufal From mlangford.cs03 at gtalumni.org Tue Sep 25 21:02:48 2007 From: mlangford.cs03 at gtalumni.org (Michael Langford) Date: Tue, 25 Sep 2007 15:02:48 -0400 Subject: [Tutor] Take if offline In-Reply-To: <46F959CA.9080806@tds.net> References: <7941B2693F32294AAF16C26B679A258D0D805E@csomb01.corp.atmel.com> <46F959CA.9080806@tds.net> Message-ID: <82b4f5810709251202y4924204bw2f79f97a1f44c09@mail.gmail.com> I agree with Kent... -- Michael Langford Phone: 404-386-0495 Consulting: http://www.TierOneDesign.com/ Entertaining: http://www.ThisIsYourCruiseDirectorSpeaking.com On 9/25/07, Kent Johnson <kent37 at tds.net> wrote: > > Hansen, Mike wrote: > > Anytime someone posts in HTML, or posts without a subject, or > > accidentally > > hijacks a thread, or top-posts, or writes in caps, a couple of posters > > pop up > > and complain. Rather than posting to the entire list, I think it'd be > > best if > > you send your complaint directly to the "offending" user. I'd prefer to > > read > > about Python not read lessons in net/mail-list etiquette. > > Hmmm. So instead, whenever someone complains about netiquette on-list we > should post on-list complaining about it? I'm not sure that improves the > situation any, especially if it sparks a discussion. Perhaps you should > email your suggestion privately to the offending parties. :-) > > I definitely think this list is about how to be part of the Python > community, as well as how to program in Python. Knowing how to > participate in a mailing list is part of that. Maybe you could just skip > those posts, there are not that many of them. > > 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/20070925/9558d05d/attachment.htm From kent37 at tds.net Tue Sep 25 21:12:16 2007 From: kent37 at tds.net (Kent Johnson) Date: Tue, 25 Sep 2007 15:12:16 -0400 Subject: [Tutor] data type conversion for print statement In-Reply-To: <46F95B33.3010008@airtelbroadband.in> References: <loom.20070925T161525-373@post.gmane.org> <46F95B33.3010008@airtelbroadband.in> Message-ID: <46F95D90.8020901@tds.net> Noufal Ibrahim wrote: > I suppose you could also do but it's a little less readable > print "%sand this %sneeds to check %s"%tuple([str(x) for x in > (val1,val2,val3)]) The %s formatter takes care of the string conversion, the list comprehension is not needed. Just use print "%sand this %sneeds to check %s" % (val1,val2,val3) From D3IBZ at hotmail.com Tue Sep 25 21:39:07 2007 From: D3IBZ at hotmail.com (Darren Williams) Date: Tue, 25 Sep 2007 15:39:07 -0400 Subject: [Tutor] Take if offline References: <7941B2693F32294AAF16C26B679A258D0D805E@csomb01.corp.atmel.com> <BAY138-DAV3273634C285CCC19D1951E9B70@phx.gbl> <2dc0c81b0709251206h9809e8el2be346455713ad80@mail.gmail.com> Message-ID: <BAY138-DAV734253628BF365AE4DCA0E9B70@phx.gbl> All jokes aside now (glad you took it that way Mike). Maybe I havn't gave the tutor enough attention, but I have never witnessed someone jump down anothers throat because they posted in all caps, didn't enter a subject etc... etc... The one time I have seen an argument (well heated debate) was about a subject entitled 'Losing the expressiveness of C' (or something similar), which I found pretty interesting. ----- Original Message ----- From: "Shawn Milochik" <Shawn at Milochik.com> To: "Darren Williams" <D3IBZ at hotmail.com> Sent: Tuesday, September 25, 2007 3:06 PM Subject: Re: [Tutor] Take if offline > No, not really. He had to give everyone the rule once. Otherwise, he'd > have to do it a hundred times a day, and monitor every single post to > find out who he had to inform. He'd end up doing not much else with > his life, and would flee to a monastery and give up coding forever. > You wouldn't want that to happen, would you? > > > > On 9/25/07, Darren Williams <D3IBZ at hotmail.com> wrote: >> So by your own rules, you should have sent that to the offending user(s). >> >> ----- Original Message ----- >> From: "Hansen, Mike" <Mike.Hansen at atmel.com> >> To: "python tutor" <tutor at python.org> >> Sent: Tuesday, September 25, 2007 2:27 PM >> Subject: [Tutor] Take if offline >> >> >> > Anytime someone posts in HTML, or posts without a subject, or >> > accidentally >> > hijacks a thread, or top-posts, or writes in caps, a couple of posters >> > pop up >> > and complain. Rather than posting to the entire list, I think it'd be >> > best if >> > you send your complaint directly to the "offending" user. I'd prefer to >> > read >> > about Python not read lessons in net/mail-list etiquette. >> > >> > Thanks, >> > >> > Mike >> > _______________________________________________ >> > 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 >> > > > -- > Please read: > http://milocast.com/2007/07/31/this-i-believe/ > From witham.ian at gmail.com Tue Sep 25 23:30:22 2007 From: witham.ian at gmail.com (Ian Witham) Date: Wed, 26 Sep 2007 09:30:22 +1200 Subject: [Tutor] Need help speeding up algorithm. In-Reply-To: <46F9320C.4070704@tds.net> References: <Pine.LNX.4.44.0709250817120.31475-100000@violet.rahul.net> <46F9320C.4070704@tds.net> Message-ID: <a04dbf4b0709251430p621d833q6697194f22bf6506@mail.gmail.com> > > > from itertools import count, takewhile > > def numfaczeroes2(n): > def while_(e): > return n//(5**e) > 0 > return sum(n//(5**exponent) for exponent in takewhile(while_, > count(1))) > > > It is quite a bit slower, though; probably because of the extra function > call introduced for while_(): > I sped this up slightly by using a lambda function instead of while_(), but not by much. My solution still took over 5 seconds on the Sphere Judge machine. The top Python solution takes around 0.6 seconds! While I haven't submitted Terry's solution, my Timer comparisons suggest that it would take around 1.5 seconds to process the data. This doesn't take into account any time used inputting and outputting the test data. If anyone knows the 0.6 second solution feel free to share! Ian. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070926/f40b963c/attachment-0001.htm From carroll at tjc.com Wed Sep 26 00:00:15 2007 From: carroll at tjc.com (Terry Carroll) Date: Tue, 25 Sep 2007 15:00:15 -0700 (PDT) Subject: [Tutor] Need help speeding up algorithm. In-Reply-To: <a04dbf4b0709251430p621d833q6697194f22bf6506@mail.gmail.com> Message-ID: <Pine.LNX.4.44.0709251459190.1301-100000@violet.rahul.net> On Wed, 26 Sep 2007, Ian Witham wrote: > My solution still took over 5 seconds on the Sphere Judge machine. How much data are they throwing at you? For the sample data they provide on the website, your first "slow" solution finished on my machine almost instantaneously. From witham.ian at gmail.com Wed Sep 26 00:17:38 2007 From: witham.ian at gmail.com (Ian Witham) Date: Wed, 26 Sep 2007 10:17:38 +1200 Subject: [Tutor] Need help speeding up algorithm. In-Reply-To: <Pine.LNX.4.44.0709251459190.1301-100000@violet.rahul.net> References: <a04dbf4b0709251430p621d833q6697194f22bf6506@mail.gmail.com> <Pine.LNX.4.44.0709251459190.1301-100000@violet.rahul.net> Message-ID: <a04dbf4b0709251517v3408e907j45f54fd546aeb17@mail.gmail.com> On 9/26/07, Terry Carroll <carroll at tjc.com> wrote: > > On Wed, 26 Sep 2007, Ian Witham wrote: > > > My solution still took over 5 seconds on the Sphere Judge machine. > > How much data are they throwing at you? For the sample data they provide > on the website, your first "slow" solution finished on my machine almost > instantaneously. Approximately 100000 numbers in the range 1 <= N <= 1000000000, and they run your solution on a Pentium III 700MHz. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070926/f4220564/attachment.htm From witham.ian at gmail.com Wed Sep 26 01:06:31 2007 From: witham.ian at gmail.com (Ian Witham) Date: Wed, 26 Sep 2007 11:06:31 +1200 Subject: [Tutor] Need help speeding up algorithm. In-Reply-To: <Pine.LNX.4.44.0709250817120.31475-100000@violet.rahul.net> References: <a04dbf4b0709242340i783c02eei61a8138820a6490a@mail.gmail.com> <Pine.LNX.4.44.0709250817120.31475-100000@violet.rahul.net> Message-ID: <a04dbf4b0709251606t1a11304n7c4b8ef7ae7df41b@mail.gmail.com> On 9/26/07, Terry Carroll <carroll at tjc.com> wrote: > > On Tue, 25 Sep 2007, Ian Witham wrote: > > def numfaczeroes(n): > """ > return the count of trailing zeroes from n! > e.g., 10! = 3628800; count of trailing zeros = 2 > """ > exponent = 1 > fivecount = 0 > while (n//(5**exponent)) > 0: > fivecount += n//(5**exponent) > exponent += 1 > return fivecount > I've come up with a couple of improvements to your function First I moved the (n//(5**exponent)) out of the while definition as it was being evaluated twice for each iteration: def numfaczeroes(n): """ return the count of trailing zeroes from n! e.g., 10! = 3628800; count of trailing zeros = 2 """ exponent = 1 fivecount = 0 count = (n//(5**exponent)) while count > 0: fivecount += count exponent += 1 count = (n//(5**exponent)) return fivecount This shaved about 10% off the run time. Then I got rid of the (n//(5**exponent)) altogether: def numfaczeroes(n): """ return the count of trailing zeroes from n! e.g., 10! = 3628800; count of trailing zeros = 2 """ fivecount = 0 count = n//5 while count > 0: fivecount += count count /= 5 return fivecount This shaved a further 40% off the run time! In practice, the Sphere Judge still takes 3 seconds to execute. So perhaps there is another bottleneck in my program -- maybe the input/output? Interestingly, print runs faster than sys.stout.write, but input() is far slower than sys.stdin.readline import sys for test in range(int(sys.stdin.readline())): n = int(sys.stdin.readline()) fivecount = 0 count = n/5 while count > 0: fivecount += count count /= 5 print fivecount -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070926/de1c3016/attachment.htm From jeffpeery at yahoo.com Wed Sep 26 01:37:15 2007 From: jeffpeery at yahoo.com (Jeff Peery) Date: Tue, 25 Sep 2007 16:37:15 -0700 (PDT) Subject: [Tutor] pickle question In-Reply-To: <a04dbf4b0709251606t1a11304n7c4b8ef7ae7df41b@mail.gmail.com> Message-ID: <766685.71408.qm@web43131.mail.sp1.yahoo.com> hello, I have a question about the pickler. I'm using it to save objects in a program of mine that I can later reload to use. I was wondering how the pickle works and how it references the class module when I unpickle the pickled objects. for example I save some objects using the pickler, then I continue to develop my program so the class module is changed and additional attributes and methods are added. What happens now when I unpickle the pickled data and try to operate on it using the new methods and new attributes? here's an example if I didn't explain myself well... I create a class of data called 'var' class var: def __init__(self): self.data = numpy.array([1,2,3,4]) self.color = 'blue' def operate(self): return self.data+1 now create the instance: myVariable = var() I then pickle it to some file. and now I continue to develop my class module: class var: def __init__(self): self.data = numpy.array([1,2,3,4]) self.color = 'blue' self.name = 'bob' def operate(self): return self.data+1 def GetName(self): return self.name So now I unpickle my object from before using my new program. and I use MyVar.GetName(). does this work? If not, how do people usually handle this type of problem? or do they not use the pickler to save program data? big thanks! Jeff --------------------------------- Fussy? Opinionated? Impossible to please? Perfect. Join Yahoo!'s user panel and lay it on us. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070925/6e3f4f71/attachment.htm From orsenthil at gmail.com Wed Sep 26 02:36:08 2007 From: orsenthil at gmail.com (O.R.Senthil Kumaran) Date: Wed, 26 Sep 2007 06:06:08 +0530 Subject: [Tutor] data type conversion for print statement In-Reply-To: <2a278ffe0709250949k7127978ej36e1d5afc68b8818@mail.gmail.com> References: <loom.20070925T161525-373@post.gmane.org> <2a278ffe0709250949k7127978ej36e1d5afc68b8818@mail.gmail.com> Message-ID: <20070926003608.GD3428@gmail.com> > > The 'print' statement is hardcoded to add a space between elements. > print is meant to make output easy, at the cost of control. Well, that was a good example. I had prepared Notes for myself also along the same lines. print and softspace in python In python, whenever you use >>>print statement it will append a newline by default. If you don't want newline to be appended, you got use a comma at the end (>>>print 10,) When, you have a list of characters and want them to be printed together a string using a for loop, there was observation that no matter what there was space coming between the characters. No split or join methods helped. >>>list1=['a','b','c'] >>>for e in list1: print e, a b c >>># Without whitespace it will look like. >>>print "abc" abc The language reference says that print is designed to output a space before any object. And some search goes to find and that is controlled by softspace attribute of sys.stdout. Way to print without leading space is using sys.stdout.write() >>>import sys >>>for e in list1: sys.stdout.write(e) abc Reference manual says: A space is written before each object is (converted and) written, unless the output system believes it is positioned at the beginning of a line. This is the case (1) when no characters have yet been written to standard output, (2) when the last character written to standard output is "\n", or (3) when the last write operation on standard output was not a print statement. (In some cases it may be functional to write an empty string to standard output for this reason.) Not getting the last part as how you will write a empty string and use print not appending blank space in a single line http://phoe6.livejournal.com/50886.html -- O.R.Senthil Kumaran http://uthcode.sarovar.org From fiyawerx at gmail.com Wed Sep 26 02:44:31 2007 From: fiyawerx at gmail.com (Fiyawerx) Date: Tue, 25 Sep 2007 20:44:31 -0400 Subject: [Tutor] Take if offline In-Reply-To: <BAY138-DAV734253628BF365AE4DCA0E9B70@phx.gbl> References: <7941B2693F32294AAF16C26B679A258D0D805E@csomb01.corp.atmel.com> <BAY138-DAV3273634C285CCC19D1951E9B70@phx.gbl> <2dc0c81b0709251206h9809e8el2be346455713ad80@mail.gmail.com> <BAY138-DAV734253628BF365AE4DCA0E9B70@phx.gbl> Message-ID: <1b31ae500709251744k3e89f8e3qb24bb8e13f2534df@mail.gmail.com> It also seems, for people like me, I've learned a lot of 'what not to do' by seeing peoples replies to others posts telling them.. well, what not to do. If all these were taken 'off list' you'd have a whole lot more people doing bad things because they wouldn't have seen yet not to do it, not to mention a whole lot more people having to send 'off-list' complaints to people, due to the same reason. On 9/25/07, Darren Williams <D3IBZ at hotmail.com> wrote: > > All jokes aside now (glad you took it that way Mike). Maybe I havn't gave > the tutor enough attention, but I have never witnessed someone jump down > anothers throat because they posted in all caps, didn't enter a subject > etc... etc... The one time I have seen an argument (well heated debate) > was > about a subject entitled 'Losing the expressiveness of C' (or something > similar), which I found pretty interesting. > > ----- Original Message ----- > From: "Shawn Milochik" <Shawn at Milochik.com> > To: "Darren Williams" <D3IBZ at hotmail.com> > Sent: Tuesday, September 25, 2007 3:06 PM > Subject: Re: [Tutor] Take if offline > > > > No, not really. He had to give everyone the rule once. Otherwise, he'd > > have to do it a hundred times a day, and monitor every single post to > > find out who he had to inform. He'd end up doing not much else with > > his life, and would flee to a monastery and give up coding forever. > > You wouldn't want that to happen, would you? > > > > > > > > On 9/25/07, Darren Williams <D3IBZ at hotmail.com> wrote: > >> So by your own rules, you should have sent that to the offending > user(s). > >> > >> ----- Original Message ----- > >> From: "Hansen, Mike" <Mike.Hansen at atmel.com> > >> To: "python tutor" <tutor at python.org> > >> Sent: Tuesday, September 25, 2007 2:27 PM > >> Subject: [Tutor] Take if offline > >> > >> > >> > Anytime someone posts in HTML, or posts without a subject, or > >> > accidentally > >> > hijacks a thread, or top-posts, or writes in caps, a couple of > posters > >> > pop up > >> > and complain. Rather than posting to the entire list, I think it'd be > >> > best if > >> > you send your complaint directly to the "offending" user. I'd prefer > to > >> > read > >> > about Python not read lessons in net/mail-list etiquette. > >> > > >> > Thanks, > >> > > >> > Mike > >> > _______________________________________________ > >> > 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 > >> > > > > > > -- > > Please read: > > http://milocast.com/2007/07/31/this-i-believe/ > > > > _______________________________________________ > 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/20070925/92edffae/attachment-0001.htm From Mike.Hansen at atmel.com Wed Sep 26 03:03:24 2007 From: Mike.Hansen at atmel.com (Hansen, Mike) Date: Tue, 25 Sep 2007 19:03:24 -0600 Subject: [Tutor] Take if offline In-Reply-To: <1b31ae500709251744k3e89f8e3qb24bb8e13f2534df@mail.gmail.com> References: <7941B2693F32294AAF16C26B679A258D0D805E@csomb01.corp.atmel.com><BAY138-DAV3273634C285CCC19D1951E9B70@phx.gbl><2dc0c81b0709251206h9809e8el2be346455713ad80@mail.gmail.com><BAY138-DAV734253628BF365AE4DCA0E9B70@phx.gbl> <1b31ae500709251744k3e89f8e3qb24bb8e13f2534df@mail.gmail.com> Message-ID: <7941B2693F32294AAF16C26B679A258D0D808C@csomb01.corp.atmel.com> aaaahhhhh!!! You posted in HTML and top posted! OH NO! I top-posted too! """ runs away screaming and bouncing off the walls like Daffy Duck """ _____ From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf Of Fiyawerx Sent: Tuesday, September 25, 2007 6:45 PM To: Darren Williams Cc: tutor at python.org; Shawn Milochik Subject: Re: [Tutor] Take if offline It also seems, for people like me, I've learned a lot of 'what not to do' by seeing peoples replies to others posts telling them.. well, what not to do. If all these were taken 'off list' you'd have a whole lot more people doing bad things because they wouldn't have seen yet not to do it, not to mention a whole lot more people having to send 'off-list' complaints to people, due to the same reason. On 9/25/07, Darren Williams <HYPERLINK "mailto:D3IBZ at hotmail.com"D3IBZ at hotmail.com> wrote: All jokes aside now (glad you took it that way Mike). Maybe I havn't gave the tutor enough attention, but I have never witnessed someone jump down anothers throat because they posted in all caps, didn't enter a subject etc... etc... The one time I have seen an argument (well heated debate) was about a subject entitled 'Losing the expressiveness of C' (or something similar), which I found pretty interesting. ----- Original Message ----- From: "Shawn Milochik" <HYPERLINK "mailto:Shawn at Milochik.com"Shawn at Milochik.com> To: "Darren Williams" <HYPERLINK "mailto:D3IBZ at hotmail.com"D3IBZ at hotmail.com> Sent: Tuesday, September 25, 2007 3:06 PM Subject: Re: [Tutor] Take if offline > No, not really. He had to give everyone the rule once. Otherwise, he'd > have to do it a hundred times a day, and monitor every single post to > find out who he had to inform. He'd end up doing not much else with > his life, and would flee to a monastery and give up coding forever. > You wouldn't want that to happen, would you? > > > > On 9/25/07, Darren Williams <HYPERLINK "mailto:D3IBZ at hotmail.com" D3IBZ at hotmail.com> wrote: >> So by your own rules, you should have sent that to the offending user(s). >> >> ----- Original Message ----- >> From: "Hansen, Mike" <HYPERLINK "mailto:Mike.Hansen at atmel.com" Mike.Hansen at atmel.com> >> To: "python tutor" <HYPERLINK "mailto:tutor at python.org"tutor at python.org> >> Sent: Tuesday, September 25, 2007 2:27 PM >> Subject: [Tutor] Take if offline >> >> >> > Anytime someone posts in HTML, or posts without a subject, or >> > accidentally >> > hijacks a thread, or top-posts, or writes in caps, a couple of posters >> > pop up >> > and complain. Rather than posting to the entire list, I think it'd be >> > best if >> > you send your complaint directly to the "offending" user. I'd prefer to >> > read >> > about Python not read lessons in net/mail-list etiquette. >> > >> > Thanks, >> > >> > Mike >> > _______________________________________________ >> > Tutor maillist - HYPERLINK "mailto:Tutor at python.org"Tutor at python.org >> > http://mail.python.org/mailman/listinfo/tutor >> > >> _______________________________________________ >> Tutor maillist - HYPERLINK "mailto:Tutor at python.org"Tutor at python.org >> HYPERLINK "http://mail.python.org/mailman/listinfo/tutor"http://mail.python.org/ma ilman/listinfo/tutor >> > > > -- > Please read: > http://milocast.com/2007/07/31/this-i-believe/ > _______________________________________________ Tutor maillist - HYPERLINK "mailto:Tutor at python.org"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/20070925/1840fdeb/attachment.htm From cspears2002 at yahoo.com Wed Sep 26 04:07:16 2007 From: cspears2002 at yahoo.com (Christopher Spears) Date: Tue, 25 Sep 2007 19:07:16 -0700 (PDT) Subject: [Tutor] home_finance.py Message-ID: <559604.13351.qm@web51602.mail.re2.yahoo.com> I'm working on a problem in Chapter 5 of Core Python Programming(2nd Edition). I am supposed to write a script that take an opening balance and a monthly payment from the user. The script then displays the balance and payments like so: Enter opening balance: 100 Enter monthly payment: 16.13 Amount Remaining Pymnt# Paid Balance 0 0.00 100.00 1 16.13 83.87 2 16.13 67.74 3 16.13 51.61 4 16.13 35.48 5 16.13 19.35 6 16.13 3.22 7 3.22 0.00 Here is what I have written so far: #!/usr/bin/env python balance = float(raw_input("Enter opening balance: ")) payment = float(raw_input("Enter monthly payment: ")) print "\tAmount\tRemaining" print "Pymnt#\tPaid\tBalance" payment_num = 0 print "%d\t%.2f\t%.2f" % (payment_num,0,balance) while balance >= 0: payment_num = payment_num + 1 if balance > 0: balance = balance - payment print "%d\t%.2f\t%.2f" % (payment_num,payment,balance) else: payment = balance balance = balance - payment print "%d\t%.2f\t%.2f" % (payment_num,payment,balance) This is what my script displays: Enter opening balance: 100 Enter monthly payment: 16.13 Amount Remaining Pymnt# Paid Balance 0 0.00 100.00 1 16.13 83.87 2 16.13 67.74 3 16.13 51.61 4 16.13 35.48 5 16.13 19.35 6 16.13 3.22 7 16.13 -12.91 I'm not sure how to solve this problem. Apparently, trying to catch the remaining balance when it becomes negative doesn't work! From balderas at whtvcable.com Wed Sep 26 04:16:35 2007 From: balderas at whtvcable.com (Chris) Date: Tue, 25 Sep 2007 19:16:35 -0700 Subject: [Tutor] python problem In-Reply-To: <ea979d70709250436n582870a0s2795c5cb13233ae2@mail.gmail.com> References: <mailman.3553.1190681774.2656.tutor@python.org> <!&!AAAAAAAAAAAYAAAAAAAAAHICkgQi6MVHrTCR8dizOffCgAAAEAAAAMkyk9iBJ8RLn5YK2RLm8JcBAAAAAA==@whtvcable.com> <ea979d70709250436n582870a0s2795c5cb13233ae2@mail.gmail.com> Message-ID: <!&!AAAAAAAAAAAYAAAAAAAAAHICkgQi6MVHrTCR8dizOffCgAAAEAAAADW0DfjaCctGiMgss+5ipe4BAAAAAA==@whtvcable.com> Ok, in this case the guessing game is design to guess the number (0-100) that the user holds in his head. I assume that Python off the bat Python gives a first guess. Example: I guess 50 #(using the split range) Depending on the user # Python asks: Press 1 if I am high. Press 2 if I am low. Press 3 if I got it. Throughout the guessing Python should use the split range method. Python should also be able to tell the user if he or she is cheating....and you wonder why I need help...yikes! Pseudo code: Guess the number from the user using 1,2,3 keys Ask the user if # is high, low, or dead on. Print 'you got it' when Python gets it. As you can see I need help. I've given you the pseudo code. Chris -----Original Message----- From: bhaaluu [mailto:bhaaluu at gmail.com] Sent: Tuesday, September 25, 2007 4:37 AM To: Chris Cc: tutor at python.org Subject: Re: [Tutor] python problem On 9/25/07, Chris <balderas at whtvcable.com> wrote: > I have this GUESSING GAME code found below: > --------------------- > import random > number = random.randint(1, 101) > print "I've thought of a number between 1 and 100." > print "Try and guess it!" > print > guess = input( "What's your guess? ") > while guess != number: > if guess > number: > print "Your guess is too high." > else: #elif guess < number: > print "Your guess is too low." > guess = input( "What's your next guess? " ) > print "Congratulations! You guessed the number." > ---------------------------------------------------- > What do I have to do to the code so that the Guessing Game that tries to > guess a number the user has thought of. (Make sure it can tell if the user > tries to cheat, e.g. by changing the number during the game?? > > I hope you can help! No virus found in this outgoing message. Checked by AVG Free Edition. Version: 7.5.487 / Virus Database: 269.13.25/1018 - Release Date: 9/19/2007 3:59 PM From kent37 at tds.net Wed Sep 26 04:28:05 2007 From: kent37 at tds.net (Kent Johnson) Date: Tue, 25 Sep 2007 22:28:05 -0400 Subject: [Tutor] pickle question In-Reply-To: <766685.71408.qm@web43131.mail.sp1.yahoo.com> References: <766685.71408.qm@web43131.mail.sp1.yahoo.com> Message-ID: <46F9C3B5.8080209@tds.net> Jeff Peery wrote: > hello, > > I have a question about the pickler. I'm using it to save objects in a > program of mine that I can later reload to use. I was wondering how the > pickle works and how it references the class module when I unpickle the > pickled objects. for example I save some objects using the pickler, then > I continue to develop my program so the class module is changed and > additional attributes and methods are added. What happens now when I > unpickle the pickled data and try to operate on it using the new methods > and new attributes? The pickle docs suggest that the way to handle this is to write your own __setstate__() method and possibly to include a version number in the object or write one with a __getstate__() method. In your example, I think you could have something like this (not tested): def __setstate__(self, d): if 'name' not in d: d['name'] = 'bob' # some appropriate default for old pickles self.__dict__.update(d) Every time you change the class data, add a bit of conversion code to __setstate__(). If you just keep accreting converters to the end of __setstate__(), it will be able to upgrade any version of pickle. Kent PS Please don't start a new thread by replying to another thread, create a new message. Those of use who use threaded mail readers will appreciate it. PPS Mike Hansen please ignore the previous PS ;-) From kent37 at tds.net Wed Sep 26 04:32:15 2007 From: kent37 at tds.net (Kent Johnson) Date: Tue, 25 Sep 2007 22:32:15 -0400 Subject: [Tutor] python problem In-Reply-To: <!&!AAAAAAAAAAAYAAAAAAAAAHICkgQi6MVHrTCR8dizOffCgAAAEAAAADW0DfjaCctGiMgss+5ipe4BAAAAAA==@whtvcable.com> References: <mailman.3553.1190681774.2656.tutor@python.org> <!&!AAAAAAAAAAAYAAAAAAAAAHICkgQi6MVHrTCR8dizOffCgAAAEAAAAMkyk9iBJ8RLn5YK2RLm8JcBAAAAAA==@whtvcable.com> <ea979d70709250436n582870a0s2795c5cb13233ae2@mail.gmail.com> <!&!AAAAAAAAAAAYAAAAAAAAAHICkgQi6MVHrTCR8dizOffCgAAAEAAAADW0DfjaCctGiMgss+5ipe4BAAAAAA==@whtvcable.com> Message-ID: <46F9C4AF.9080309@tds.net> Chris wrote: > Guess the number from the user using 1,2,3 keys > Ask the user if # is high, low, or dead on. > Print 'you got it' when Python gets it. > > As you can see I need help. I've given you the pseudo code. OK, how about some real code? If we write the program for you that won't help you learn. What have you tried so far? Which parts of the pseudocode do you know how to code? Which parts do you need help with? Kent From balderas at whtvcable.com Wed Sep 26 04:49:52 2007 From: balderas at whtvcable.com (Chris) Date: Tue, 25 Sep 2007 19:49:52 -0700 Subject: [Tutor] python problem In-Reply-To: <46F9C4AF.9080309@tds.net> References: <mailman.3553.1190681774.2656.tutor@python.org> <!&!AAAAAAAAAAAYAAAAAAAAAHICkgQi6MVHrTCR8dizOffCgAAAEAAAAMkyk9iBJ8RLn5YK2RLm8JcBAAAAAA==@whtvcable.com> <ea979d70709250436n582870a0s2795c5cb13233ae2@mail.gmail.com> <!&!AAAAAAAAAAAYAAAAAAAAAHICkgQi6MVHrTCR8dizOffCgAAAEAAAADW0DfjaCctGiMgss+5ipe4BAAAAAA==@whtvcable.com> <46F9C4AF.9080309@tds.net> Message-ID: <!&!AAAAAAAAAAAYAAAAAAAAAHICkgQi6MVHrTCR8dizOffCgAAAEAAAAF/EqAec6QNJiEltTYB6Z9gBAAAAAA==@whtvcable.com> Ok as I see it, it's should go like this: Print 'Think of a number between 1 and 100, and let me guess it' Type1 = input ('Type 1 if I am high') Type2 = input ('Type 2 if I am low') Type3 = input ('Type 3 if I am dead on') I can't seem to get the guts of it. I assume that there are 3 if statements and a while statement. guess While x != If guess I get lost right around here...help! import random > number = random.randint(1, 101) > print "I've thought of a number between 1 and 100." > print "Try and guess it!" > print > guess = input( "What's your guess? ") > while guess != number: > if guess > number: > print "Your guess is too high." > else: #elif guess < number: > print "Your guess is too low." > guess = input( "What's your next guess? " ) print > "Congratulations! You guessed the number." -----Original Message----- From: Kent Johnson [mailto:kent37 at tds.net] Sent: Tuesday, September 25, 2007 7:32 PM To: Chris Cc: tutor at python.org Subject: Re: [Tutor] python problem Chris wrote: > Guess the number from the user using 1,2,3 keys > Ask the user if # is high, low, or dead on. > Print 'you got it' when Python gets it. > > As you can see I need help. I've given you the pseudo code. OK, how about some real code? If we write the program for you that won't help you learn. What have you tried so far? Which parts of the pseudocode do you know how to code? Which parts do you need help with? Kent No virus found in this incoming message. Checked by AVG Free Edition. Version: 7.5.487 / Virus Database: 269.13.25/1018 - Release Date: 9/19/2007 3:59 PM No virus found in this outgoing message. Checked by AVG Free Edition. Version: 7.5.487 / Virus Database: 269.13.25/1018 - Release Date: 9/19/2007 3:59 PM From witham.ian at gmail.com Wed Sep 26 04:56:50 2007 From: witham.ian at gmail.com (Ian Witham) Date: Wed, 26 Sep 2007 14:56:50 +1200 Subject: [Tutor] home_finance.py In-Reply-To: <559604.13351.qm@web51602.mail.re2.yahoo.com> References: <559604.13351.qm@web51602.mail.re2.yahoo.com> Message-ID: <a04dbf4b0709251956j3e1b630er572a94fee9ca5205@mail.gmail.com> On 9/26/07, Christopher Spears <cspears2002 at yahoo.com> wrote: > > I'm working on a problem in Chapter 5 of Core Python > Programming(2nd Edition). I am supposed to write a > script that take an opening balance and a monthly > payment from the user. The script then displays the > balance and payments like so: > > > Enter opening balance: 100 > Enter monthly payment: 16.13 > Amount Remaining > Pymnt# Paid Balance > 0 0.00 100.00 > 1 16.13 83.87 > 2 16.13 67.74 > 3 16.13 51.61 > 4 16.13 35.48 > 5 16.13 19.35 > 6 16.13 3.22 > 7 3.22 0.00 > > Here is what I have written so far: > > #!/usr/bin/env python > > balance = float(raw_input("Enter opening balance: ")) > payment = float(raw_input("Enter monthly payment: ")) > > print "\tAmount\tRemaining" > print "Pymnt#\tPaid\tBalance" > > payment_num = 0 > print "%d\t%.2f\t%.2f" % (payment_num,0,balance) > > while balance >= 0: > payment_num = payment_num + 1 > if balance > 0: You have: if balance > 0: You should be checking whether the remaining balance is greater than the payment amount, not whether it is greater than 0. This is probably just a typo as it looks like you're on the right track. Ian -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070926/5c4cb42f/attachment.htm From hobo.online at gmail.com Wed Sep 26 08:07:12 2007 From: hobo.online at gmail.com (Armand Nell) Date: Wed, 26 Sep 2007 08:07:12 +0200 Subject: [Tutor] New to Python and Linux Message-ID: <4febe39e0709252307j651009e8m51a5667367491f16@mail.gmail.com> Hi I am new to python programming and also the linux enviroment most of my skills are windows based and programming skills is visual basics. I decided that it would be a great start and new direction for me to learn python and at the same time linux. However I have already run into a wall, and any help would be appreciated even if you can direct me where to find the info or 'turor'. I am running Fedoracore 7 and Python 2.5 In windows, if i write a program in Python and save it I then can simply double click the icon and the program will execute in a console window. Now under Fedoracore I write my program in gedit save it in my \home\(username)\python directory, when I double click it, it opens up agian in gedit. Now true it is maybe a simple error from me but mostly it is me that don't know how to work with python on linux. I would like to know how do I test(run) the programs I write under fedoracore? Simple yet challanging for me, Your patience and wisdom on this subject will be greatly appreciated. Regards Digitalhobo -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070926/f31d005a/attachment.htm From mlangford.cs03 at gtalumni.org Wed Sep 26 08:22:26 2007 From: mlangford.cs03 at gtalumni.org (Michael Langford) Date: Wed, 26 Sep 2007 02:22:26 -0400 Subject: [Tutor] New to Python and Linux In-Reply-To: <4febe39e0709252307j651009e8m51a5667367491f16@mail.gmail.com> References: <4febe39e0709252307j651009e8m51a5667367491f16@mail.gmail.com> Message-ID: <82b4f5810709252322p37e89f94ga8706d86ea487474@mail.gmail.com> Somewhere in the start menu, you'll be able to open a terminal. It might be called GTerm, Gnome Term, xterm, or any number of things with "term" in the name. Once you've done that, you need to see if python is in your path. Do that by typing python in the terminal. If you enter the python shell, you're in luck.exit out (Ctrl-Z return, probably), If not, you need to install/find python and add it to your path by typing export PATHTOPY=/usr/bin/python #I don't know where python is for you...this is just a guess export PATH=$PATH:$PYTHTOPY If you google bashrc, you'll learn how to make it so you don't have to type this every time. Now, you should be able to type "cd python" in a terminal you broght up. This will change into the python directory you said you made in your home dir. Now type "ls". That should show you a list of files in the directory. If there is a python file there, say, named foo.py, then you'd type python foo.py to run the application. You can also set python up as the default app when you click a .py ext file. I dislike this, then again, on windows, that's exactly how I have it setup (while not in windows). To change this to match the windows behavior, you need to right click on the .py file, and pray that you see an "Open with" option. If you don't, ask for help on a Gnome mailing list :o). If you do see the Open with option, select it, then select "other", then using the folder on the command line, browse to your python executable. I don't know where it is. If you open up a terminal and type: which python that *may* show you where it is. -- Michael Langford Phone: 404-386-0495 Consulting: http://www.TierOneDesign.com/ Entertaining: http://www.ThisIsYourCruiseDirectorSpeaking.com On 9/26/07, Armand Nell <hobo.online at gmail.com> wrote: > > Hi > > I am new to python programming and also the linux enviroment most of my skills are windows based and programming skills is visual basics. I decided that it would be a great start and new direction for me to learn python and at the same time linux. However I have already run into a wall, and any help would be appreciated even if you can direct me where to find the info or 'turor'. > > I am running Fedoracore 7 and Python 2.5 > > In windows, if i write a program in Python and save it I then can simply double click the icon and the program will execute in a console window. Now under Fedoracore I write my program in gedit save it in my \home\(username)\python directory, when I double click it, it opens up agian in gedit. Now true it is maybe a simple error from me but mostly it is me that don't know how to work with python on linux. > > I would like to know how do I test(run) the programs I write under fedoracore? > > Simple yet challanging for me, > > Your patience and wisdom on this subject will be greatly appreciated. > > Regards > > Digitalhobo > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From json.barnes at gmail.com Wed Sep 26 08:49:18 2007 From: json.barnes at gmail.com (Jason M Barnes) Date: Wed, 26 Sep 2007 02:49:18 -0400 Subject: [Tutor] New to Python and Linux In-Reply-To: <82b4f5810709252322p37e89f94ga8706d86ea487474@mail.gmail.com> References: <4febe39e0709252307j651009e8m51a5667367491f16@mail.gmail.com> <82b4f5810709252322p37e89f94ga8706d86ea487474@mail.gmail.com> Message-ID: <833263a00709252349l746052f7na2a571d9e8ef83d9@mail.gmail.com> Hi, Another way to execute your program is to open up your file with gedit, and on the very first line type (sans quotes) "#!/usr/bin/env python" by itself and save it. Then, go to the terminal like Michael said, and cd into the directory with your file. Type "chmod 0700 your-program.py" at the prompt. This allows you to execute your program without invoking python first. That way when you are cd'ed into the directory that contains your program, you can type "./your-program.py" at the prompt, and it should run. If you're going to switch to linux, then you'll need to learn how to make the most of your CLI. I'd suggest googling for tutorials on the linux command line. Jason From kalle.svensson at gmail.com Wed Sep 26 09:01:31 2007 From: kalle.svensson at gmail.com (Kalle Svensson) Date: Wed, 26 Sep 2007 09:01:31 +0200 Subject: [Tutor] Optimisation of prime number program (cont. from finding prime numbers) In-Reply-To: <9584033b0709211112u133681c3ge8ccfa28a31f2544@mail.gmail.com> References: <1190364088.6221.19.camel@apprentice-laptop> <9584033b0709211112u133681c3ge8ccfa28a31f2544@mail.gmail.com> Message-ID: <9584033b0709260001g359c18aah61b0769e41eaf789@mail.gmail.com> Hi! Just a followup on this: On 9/21/07, Kalle Svensson <kalle.svensson at gmail.com> wrote: > Hi! > > On 9/21/07, Boykie Mackay <boykie.mackay at gmail.com> wrote: > > Ok,I have learnt how to generate prime numbers and how to 'split' > > input.The above was to help me solve the second 'SPOJ' > > challenge,PRIME1.The challenge can be found at > > <https://www.spoj.pl/problems/classical/sort=0,start=0> > ... > > Could you please look at the program (attached) and advise possible > > optimisations or point me to possible resources that would help solve > > this challenge. > > Interesting problem! I've been experimenting a bit with it, but I'm > not anywhere near the runtimes shown in the judge system... After quite a bit of experimentation, I finally managed to write a program that was accepted by the judge system. It's a C++ implementation of the deterministic Miller-Rabin algorithm. My Python implementation of the same algorithm is still too slow, though. Has anyone managed to write a fast enough Python program? The problem: https://www.spoj.pl/problems/PRIME1/ Miller-Rabin: http://en.wikipedia.org/wiki/Miller-Rabin_primality_test Regards, Kalle From andreas at kostyrka.org Wed Sep 26 09:27:47 2007 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Wed, 26 Sep 2007 09:27:47 +0200 Subject: [Tutor] New to Python and Linux In-Reply-To: <833263a00709252349l746052f7na2a571d9e8ef83d9@mail.gmail.com> References: <4febe39e0709252307j651009e8m51a5667367491f16@mail.gmail.com> <82b4f5810709252322p37e89f94ga8706d86ea487474@mail.gmail.com> <833263a00709252349l746052f7na2a571d9e8ef83d9@mail.gmail.com> Message-ID: <46FA09F3.8070002@kostyrka.org> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Well, chmod 0700 is usually not want you want: a) 0700 gives only read/write/execute rights to the user. Technically for historical reason permissions can be written as an octal number, with the first digit being optional, encoding stuff like setuid/setgid permissions. The last 3 digits code permissions for user, group and other, one octal digit each. 4 is read, 2 is write and 1 is execute. We aware that on directories execute permission allows you to access/search the directory, while read allows you to "read" (==list) the directory. So a typical permission for scripts would be 755 (read/exec for all, write on top of that for the owner), or 775 (on distributions that give each user their own primary group). b) Specifying permissions as octal numbers is not really necessary nowadays (and has not been necessary for over a decade, at least on Linux): chmod a+x => add eXecute rights to All. chmod u=rwx,og=rx => set 755 Andreas Jason M Barnes wrote: > Hi, > > Another way to execute your program is to open up your file with > gedit, and on the very first line type (sans quotes) "#!/usr/bin/env > python" by itself and save it. Then, go to the terminal like Michael > said, and cd into the directory with your file. Type "chmod 0700 > your-program.py" at the prompt. This allows you to execute your > program without invoking python first. That way when you are cd'ed > into the directory that contains your program, you can type > "./your-program.py" at the prompt, and it should run. > > If you're going to switch to linux, then you'll need to learn how to > make the most of your CLI. I'd suggest googling for tutorials on the > linux command line. > > Jason > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.2 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFG+gnyHJdudm4KnO0RAgyXAJ9YGKU2OU9p2pnG4YyS15ZLwzj8vACfRAQD H7jawyovWfkd9fEm36MfBBs= =FquY -----END PGP SIGNATURE----- From sli1que at yahoo.com Wed Sep 26 11:01:59 2007 From: sli1que at yahoo.com (Eric Walker) Date: Wed, 26 Sep 2007 02:01:59 -0700 (PDT) Subject: [Tutor] home_finance.py In-Reply-To: <559604.13351.qm@web51602.mail.re2.yahoo.com> Message-ID: <550027.75432.qm@web60121.mail.yahoo.com> I think you need to check to see if the remaining amount is less than the payment amount. Eric... Christopher Spears <cspears2002 at yahoo.com> wrote: I'm working on a problem in Chapter 5 of Core Python Programming(2nd Edition). I am supposed to write a script that take an opening balance and a monthly payment from the user. The script then displays the balance and payments like so: Enter opening balance: 100 Enter monthly payment: 16.13 Amount Remaining Pymnt# Paid Balance 0 0.00 100.00 1 16.13 83.87 2 16.13 67.74 3 16.13 51.61 4 16.13 35.48 5 16.13 19.35 6 16.13 3.22 7 3.22 0.00 Here is what I have written so far: #!/usr/bin/env python balance = float(raw_input("Enter opening balance: ")) payment = float(raw_input("Enter monthly payment: ")) print "\tAmount\tRemaining" print "Pymnt#\tPaid\tBalance" payment_num = 0 print "%d\t%.2f\t%.2f" % (payment_num,0,balance) while balance >= 0: payment_num = payment_num + 1 if balance > 0: balance = balance - payment print "%d\t%.2f\t%.2f" % (payment_num,payment,balance) else: payment = balance balance = balance - payment print "%d\t%.2f\t%.2f" % (payment_num,payment,balance) This is what my script displays: Enter opening balance: 100 Enter monthly payment: 16.13 Amount Remaining Pymnt# Paid Balance 0 0.00 100.00 1 16.13 83.87 2 16.13 67.74 3 16.13 51.61 4 16.13 35.48 5 16.13 19.35 6 16.13 3.22 7 16.13 -12.91 I'm not sure how to solve this problem. Apparently, trying to catch the remaining balance when it becomes negative doesn't work! _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor --------------------------------- Luggage? GPS? Comic books? Check out fitting gifts for grads at Yahoo! Search. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070926/b81653d0/attachment-0001.htm From nelsonkusuma at yahoo.com Wed Sep 26 12:11:38 2007 From: nelsonkusuma at yahoo.com (Nelson Kusuma) Date: Wed, 26 Sep 2007 03:11:38 -0700 (PDT) Subject: [Tutor] copy files + directory tree via ftp Message-ID: <284807.47739.qm@web32611.mail.mud.yahoo.com> Hello I have a problem when copy files and directory tree in ftp, scripts in here only copy one file: from ftplib import FTP rootList = [] session = FTP() session.connect('workstation', port=21) session.login(user='saiki', passwd='saiki') session.retrlines('LIST', rootList.append) f=open('D:/PARAMS.LST','rb') session.storbinary('STOR '+"af", f, 1024) f.close() session.close() f anyone has any ideas I would appreciate it. Thank you Nelson ____________________________________________________________________________________ Take the Internet to Go: Yahoo!Go puts the Internet in your pocket: mail, news, photos & more. http://mobile.yahoo.com/go?refer=1GNXIC From kent37 at tds.net Wed Sep 26 12:49:42 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 26 Sep 2007 06:49:42 -0400 Subject: [Tutor] Optimisation of prime number program (cont. from finding prime numbers) In-Reply-To: <9584033b0709260001g359c18aah61b0769e41eaf789@mail.gmail.com> References: <1190364088.6221.19.camel@apprentice-laptop> <9584033b0709211112u133681c3ge8ccfa28a31f2544@mail.gmail.com> <9584033b0709260001g359c18aah61b0769e41eaf789@mail.gmail.com> Message-ID: <46FA3946.1040702@tds.net> Kalle Svensson wrote: > After quite a bit of experimentation, I finally managed to write a > program that was accepted by the judge system. It's a C++ > implementation of the deterministic Miller-Rabin algorithm. My Python > implementation of the same algorithm is still too slow, though. Has > anyone managed to write a fast enough Python program? Have you tried using psyco? Have you seen this thread? It has some very interesting ideas about speeding up the sieve algorithm. (Uncle Timmy is Tim Peters who still has one of the fastest Python solutions.) https://www.spoj.pl/forum/viewtopic.php?t=3226 Kent From kent37 at tds.net Wed Sep 26 13:00:24 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 26 Sep 2007 07:00:24 -0400 Subject: [Tutor] copy files + directory tree via ftp In-Reply-To: <284807.47739.qm@web32611.mail.mud.yahoo.com> References: <284807.47739.qm@web32611.mail.mud.yahoo.com> Message-ID: <46FA3BC8.8040104@tds.net> Nelson Kusuma wrote: > Hello > > I have a problem when copy files and directory tree in > ftp, scripts in here only copy one file: To transfer an entire directory with ftplib you will have to read the local directory with os.listdir() and loop to send the files. There are a few higher-level modules written on top of ftplib that might be helpful directly or as examples: http://pypi.python.org/pypi/ftputil/2.2.3 (site is down at the moment) http://www.nedbatchelder.com/code/modules/ftpupload.html Kent From ricaraoz at gmail.com Wed Sep 26 13:30:34 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Wed, 26 Sep 2007 08:30:34 -0300 Subject: [Tutor] home_finance.py In-Reply-To: <550027.75432.qm@web60121.mail.yahoo.com> References: <550027.75432.qm@web60121.mail.yahoo.com> Message-ID: <46FA42DA.4080001@bigfoot.com> Eric Walker wrote: > I think you need to check to see if the remaining amount is less than > the payment amount. > > Eric... Or just subtract the minimum between the remaining amount and the payment amount. See below > > */Christopher Spears <cspears2002 at yahoo.com>/* wrote: > > I'm working on a problem in Chapter 5 of Core Python > Programming(2nd Edition). I am supposed to write a > script that take an opening balance and a monthly > payment from the user. The script then displays the > balance and payments like so: > > > Enter opening balance: 100 > Enter monthly payment: 16.13 > Amount Remaining > Pymnt# Paid Balance > 0 0.00 100.00 > 1 16.13 83.87 > 2 16.13 67.74 > 3 16.13 51.61 > 4 16.13 35.48 > 5 16.13 19.35 > 6 16.13 3.22 > 7 3.22 0.00 > > Here is what I have written so far: > > #!/usr/bin/env python > > balance = float(raw_input("Enter opening balance: ")) > payment = float(raw_input("Enter monthly payment: ")) > > print "\tAmount\tRemaining" > print "Pymnt#\tPaid\tBalance" > > payment_num = 0 > print "%d\t%.2f\t%.2f" % (payment_num,0,balance) > > while balance >= 0: > payment_num = payment_num + 1 > if balance > 0: > balance = balance - payment Instead of this ^^^ line you should have : balance = balance - min(balance, payment) And I guess that would be it. > print "%d\t%.2f\t%.2f" % > (payment_num,payment,balance) > else: > payment = balance > balance = balance - payment > print "%d\t%.2f\t%.2f" % > (payment_num,payment,balance) > > This is what my script displays: > > Enter opening balance: 100 > Enter monthly payment: 16.13 > Amount Remaining > Pymnt# Paid Balance > 0 0.00 100.00 > 1 16.13 83.87 > 2 16.13 67.74 > 3 16.13 51.61 > 4 16.13 35.48 > 5 16.13 19.35 > 6 16.13 3.22 > 7 16.13 -12.91 > > I'm not sure how to solve this problem. Apparently, > trying to catch the remaining balance when it becomes > negative doesn't work! > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > ------------------------------------------------------------------------ > Luggage? GPS? Comic books? > Check out fitting gifts for grads > <http://us.rd.yahoo.com/evt=48249/*http://search.yahoo.com/search?fr=oni_on_mail&p=graduation+gifts&cs=bz> > at Yahoo! Search. > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From bhaaluu at gmail.com Wed Sep 26 14:12:40 2007 From: bhaaluu at gmail.com (bhaaluu) Date: Wed, 26 Sep 2007 08:12:40 -0400 Subject: [Tutor] python problem In-Reply-To: <!&!AAAAAAAAAAAYAAAAAAAAAHICkgQi6MVHrTCR8dizOffCgAAAEAAAAF/EqAec6QNJiEltTYB6Z9gBAAAAAA==@whtvcable.com> References: <mailman.3553.1190681774.2656.tutor@python.org> <!&!AAAAAAAAAAAYAAAAAAAAAHICkgQi6MVHrTCR8dizOffCgAAAEAAAAMkyk9iBJ8RLn5YK2RLm8JcBAAAAAA==@whtvcable.com> <ea979d70709250436n582870a0s2795c5cb13233ae2@mail.gmail.com> <!&!AAAAAAAAAAAYAAAAAAAAAHICkgQi6MVHrTCR8dizOffCgAAAEAAAADW0DfjaCctGiMgss+5ipe4BAAAAAA==@whtvcable.com> <46F9C4AF.9080309@tds.net> <!&!AAAAAAAAAAAYAAAAAAAAAHICkgQi6MVHrTCR8dizOffCgAAAEAAAAF/EqAec6QNJiEltTYB6Z9gBAAAAAA==@whtvcable.com> Message-ID: <ea979d70709260512ke43baaan8e34fdfda2f948ef@mail.gmail.com> Greetings Chris, On 9/25/07, Chris <balderas at whtvcable.com> wrote: > > Ok as I see it, it's should go like this: > > Print 'Think of a number between 1 and 100, and let me guess it' > > Type1 = input ('Type 1 if I am high') > Type2 = input ('Type 2 if I am low') > Type3 = input ('Type 3 if I am dead on') > > I can't seem to get the guts of it. I assume that there are 3 if statements > and a while statement. > > guess > > While x != > If guess > > > > I get lost right around here...help! Thunk! er, Think! =) Play the guess-a-number game, and jot down exactly what YOU do to make a guess. Prompt:> Think of a number between 1 and 100. Got it? Prompt:> Okay, now I, the Great Computer, will guess the number... Prompt:> Is the number 51? Prompt:> 0=Correct, 1=Lower, 2=Higher: _ The range is 1 to 100. Let's say you think of the number 37. At he prompt, you type 1 because the number is Lower than 51. (or whatever scheme you decide to use.) If you were playing against the computer, and the computer told you to guess Lower, what would you do? Would you guess 50? 49? 10? 1? How do you guess when you're playing the game? How do you narrow it down? Figure it out. So, now you think you can outsmart the computer half-way through the game by thinking of a different number, say 38.... Pretty sneaky! That's like palming the pea in a shell game. Granted, the Great Computer, isn't very smart... but it IS an idiot savant. It can remember tons of information that you've forgotten as irrelevant just seconds ago. So what the Great Computer has been doing, while guessing, is keeping track of the bounds it can guess between, from the hints you've been providing [0,1,2, whatever] and maybe even a list of all its guesses that were not correct. And in a split second, it can compare all that stuff. Chris, what constraints are you working under? How many Python 'tools' (keywords, methods, etc.) do you have to solve the problem with? Input? [raw_inpu(), input(), ...], Output? [print, ...], Selection? [if, elif, else, ...] Iteration? [for, while, ...]. You also have to consider what you have to work with so far. -- b h a a l u u at g m a i l dot c o m http://www.geocities.com/ek.bhaaluu/index.html > import random > > number = random.randint(1, 101) > > print "I've thought of a number between 1 and 100." > > print "Try and guess it!" > > print > > guess = input( "What's your guess? ") > > while guess != number: > > if guess > number: > > print "Your guess is too high." > > else: #elif guess < number: > > print "Your guess is too low." > > guess = input( "What's your next guess? " ) print > > "Congratulations! You guessed the number." > -----Original Message----- > From: Kent Johnson [mailto:kent37 at tds.net] > Sent: Tuesday, September 25, 2007 7:32 PM > To: Chris > Cc: tutor at python.org > Subject: Re: [Tutor] python problem > > Chris wrote: > > > Guess the number from the user using 1,2,3 keys > > Ask the user if # is high, low, or dead on. > > Print 'you got it' when Python gets it. > > > > As you can see I need help. I've given you the pseudo code. > > OK, how about some real code? If we write the program for you that won't > help you learn. What have you tried so far? Which parts of the > pseudocode do you know how to code? Which parts do you need help with? > > Kent > > > > > No virus found in this incoming message. > Checked by AVG Free Edition. > Version: 7.5.487 / Virus Database: 269.13.25/1018 - Release Date: 9/19/2007 > 3:59 PM > > > No virus found in this outgoing message. > Checked by AVG Free Edition. > Version: 7.5.487 / Virus Database: 269.13.25/1018 - Release Date: 9/19/2007 > 3:59 PM > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Wed Sep 26 14:14:37 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 26 Sep 2007 08:14:37 -0400 Subject: [Tutor] python problem In-Reply-To: <!&!AAAAAAAAAAAYAAAAAAAAAHICkgQi6MVHrTCR8dizOffCgAAAEAAAAF/EqAec6QNJiEltTYB6Z9gBAAAAAA==@whtvcable.com> References: <mailman.3553.1190681774.2656.tutor@python.org> <!&!AAAAAAAAAAAYAAAAAAAAAHICkgQi6MVHrTCR8dizOffCgAAAEAAAAMkyk9iBJ8RLn5YK2RLm8JcBAAAAAA==@whtvcable.com> <ea979d70709250436n582870a0s2795c5cb13233ae2@mail.gmail.com> <!&!AAAAAAAAAAAYAAAAAAAAAHICkgQi6MVHrTCR8dizOffCgAAAEAAAADW0DfjaCctGiMgss+5ipe4BAAAAAA==@whtvcable.com> <46F9C4AF.9080309@tds.net> <!&!AAAAAAAAAAAYAAAAAAAAAHICkgQi6MVHrTCR8dizOffCgAAAEAAAAF/EqAec6QNJiEltTYB6Z9gBAAAAAA==@whtvcable.com> Message-ID: <46FA4D2D.5090301@tds.net> Chris wrote: > Ok as I see it, it's should go like this: > > Print 'Think of a number between 1 and 100, and let me guess it' > > Type1 = input ('Type 1 if I am high') > Type2 = input ('Type 2 if I am low') > Type3 = input ('Type 3 if I am dead on') This will ask for three different inputs which is not what you want. Can you modify it to ask for input just once? > > I can't seem to get the guts of it. I assume that there are 3 if statements > and a while statement. That sounds about right. > > guess > > While x != > If guess OK, you have some of the pieces. Maybe it would help to write a more detailed pseudocode. I think it might be: ask the user to pick a number wait for the user to pick a number pick a starting guess loop: tell the user my guess ask if the guess is correct if the guess is correct congratulate myself quit if the guess is too high pick a lower guess if the guess is too low pick a higher guess Can you turn this into code? Kent From bhaaluu at gmail.com Wed Sep 26 15:06:07 2007 From: bhaaluu at gmail.com (bhaaluu) Date: Wed, 26 Sep 2007 09:06:07 -0400 Subject: [Tutor] New to Python and Linux In-Reply-To: <4febe39e0709252307j651009e8m51a5667367491f16@mail.gmail.com> References: <4febe39e0709252307j651009e8m51a5667367491f16@mail.gmail.com> Message-ID: <ea979d70709260606m523d8765i5c23b16c27e25710@mail.gmail.com> Greetings, I don't know how to do ms-windows, but I use GNU/Linux on a daily basis. There is a nice IDE (Integrated Development Environment) for Python called IDLE. It is available for ms-windows, GNU/Linux, and maybe another OS as well. There is information about IDLE at Python.Org. I'd suggest that you Check It Out. If it isn't already installed on your FedoraCore distro, you'll have to download it. http://www.python.org/idle/ IDLE has a shell, an editor, a debugger, and all sorts of bells and whistles. What you'll find out about GNU/Linux is: it isn't very difficult at all..... you're just unfamiliar with it. The unfamiliarity makes it seem difficult. =) It's actually easier to use than ms-windows, once you become familiar with it, much easier. You should see me trying to do anything on a ms-windows computer... it seems so braindead to me, I flop around like a fish out of water because I'm not familiar with it. Okay, enuff of that. (That was my version of encouragement. =) I use vim. vim is "vi improved". vi (pronounced "vee-eye") is the 'vi'sual editor. There is some version of vi on just about every *nix box out there. vi has been around since almost the very beginning of creation. (the beginning of creation is counted from 1970-01-01 or thereabouts... The vi editor was developed starting around 1976 by Bill Joy, who was then a graduate student at the University of California at Berkeley. ... ) So, why vim, and not an easier editor, like pico or nano, or a swiss-army-editor like emacs, or a GUI editor like Gedit, or Nedit, or Kate, or Kwrite? pico and nano are extremely limited. Yeah, they're easy: too easy! You can't really do anything serious with them. Your favorite GUI editor might not be available. I once watched a couple of guys who were thrown out of X to a console, trying to edit a config file to get X going, using vi. They didn't have their favorite GUI editor, and they were completely lost. It was hilarious to watch them. I let them suffer for a few minutes before offering suggestions. Too funny! 8^D emacs? I won't go there... it's like dicussing religion, or something. There are Python bindings for emacs, which will allow you to run it like an IDE. vim is ubiquitous, powerful, and very, very sexy. That last part was to make you curious enough to try it. Do you have vim on your fedoracore? Maybe. I always have to download it with a new install of my distro. nvi is the default version of vi with a new install of my distro. vim. Open a terminal and type: which vim If you get something like: /usr/bin/vim then you're in business. Otherwise, you'll have to grab it and install it. Once you have it, you start it by typing vim at the prompt. Once in vim, press Shift-colon ( : ) help :help To exit vim, press Shift-colon q :q (you may have to do it a couple of times, if you're in help) vim comes with an interactive tutorial called: vimtutor Just type: vimtutor at the prompt to start it. It has enough stuff in it to get you started. Once you've started, you can pick up more advanced stuff as you need it. Now the part you've been waiting for! To make vim a Python IDE, copy/paste this file into your home directory: " .vimrc " " Created by Jeff Elkner 23 January 2006 " Last modified 2 February 2006 " " Turn on syntax highlighting and autoindenting syntax enable filetype indent on " set autoindent width to 4 spaces (see " http://www.vim.org/tips/tip.php?tip_id=83) set nu set et set sw=4 set smarttab " Bind <f2> key to running the python interpreter on the currently active " file. (curtesy of Steve Howell from email dated 1 Feb 2006). map <f2> :w\|!python %<cr> Now edit your Python code in an editor that has line numbers (my addition to the original file, found at: http://www.ibiblio.org/obp/pyBiblio/tips/elkner/vim4python.php ) syntax highlighting, auto-indent, AND, just press the F2 function key to run the code from the editor (no quitting the editor, running the code, starting the editor....). Here is an interesting and helpful Visual vi tutorial: http://www.viemu.com/a_vi_vim_graphical_cheat_sheet_tutorial.html Finally, from the same site: "Why, oh WHY, do those #?@! nutheads use vi?" http://www.viemu.com/a-why-vi-vim.html What fun, eh? ;-) -- b h a a l u u at g m a i l dot c o m http://www.geocities.com/ek.bhaaluu/index.html On 9/26/07, Armand Nell <hobo.online at gmail.com> wrote: > Hi > > I am new to python programming and also the linux enviroment most of my > skills are windows based and programming skills is visual basics. I decided > that it would be a great start and new direction for me to learn python and > at the same time linux. However I have already run into a wall, and any help > would be appreciated even if you can direct me where to find the info or > 'turor'. > > I am running Fedoracore 7 and Python 2.5 > > In windows, if i write a program in Python and save it I then can simply > double click the icon and the program will execute in a console window. Now > under Fedoracore I write my program in gedit save it in my > \home\(username)\python directory, when I double click it, it opens up agian > in gedit. Now true it is maybe a simple error from me but mostly it is me > that don't know how to work with python on linux. > > I would like to know how do I test(run) the programs I write under > fedoracore? > > Simple yet challanging for me, > > Your patience and wisdom on this subject will be greatly appreciated. > > Regards > > Digitalhobo > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From emadnawfal at gmail.com Wed Sep 26 13:43:21 2007 From: emadnawfal at gmail.com (Emad Nawfal) Date: Wed, 26 Sep 2007 06:43:21 -0500 Subject: [Tutor] indexing question Message-ID: <652641e90709260443y75cddf79jae7c1f24e1d0268@mail.gmail.com> Hi Tutors, Is there a way to get the index of every occurence of a certain element in a list. listname.index(element) gives me the index of the first occurence. For example: >>> t = 'we are we are we we we'.split() >>> t ['we', 'are', 'we', 'are', 'we', 'we', 'we'] >>> for word in t: if word =='we': t.index(word) 0 0 0 0 0 Now I want the index of each 'we' in t. I want the result to be 0, 2, 4, 5, 6 How can I do that? Thank you in anticipation? -- ?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? ????????.....???? ??????? Emad Soliman Nawfal Indiana University, Bloomington http://emadnawfal.googlepages.com -------------------------------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070926/a8f6fefb/attachment-0001.htm From kent37 at tds.net Wed Sep 26 15:35:24 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 26 Sep 2007 09:35:24 -0400 Subject: [Tutor] indexing question In-Reply-To: <652641e90709260443y75cddf79jae7c1f24e1d0268@mail.gmail.com> References: <652641e90709260443y75cddf79jae7c1f24e1d0268@mail.gmail.com> Message-ID: <46FA601C.5080401@tds.net> Emad Nawfal wrote: > Hi Tutors, > Is there a way to get the index of every occurence of a certain element > in a list. listname.index(element) gives me the index of the first > occurence. For example: > > >>> t = 'we are we are we we we'.split() > Now I want the index of each 'we' in t. I want the result to be 0, 2, 4, > 5, 6 In [1]: t = 'we are we are we we we'.split() In [2]: [i for i, x in enumerate(t) if x=='we'] Out[2]: [0, 2, 4, 5, 6] Or, IMO a bit awkward but you could do this: In [3]: [i for i in range(len(t)) if t[i]=='we'] Out[3]: [0, 2, 4, 5, 6] In [4]: filter(lambda i: t[i]=='we', range(len(t))) Out[4]: [0, 2, 4, 5, 6] Kent From linpeiheng at 163.com Wed Sep 26 16:15:40 2007 From: linpeiheng at 163.com (=?gb2312?B?wdbF4Lrj?=) Date: Wed, 26 Sep 2007 22:15:40 +0800 Subject: [Tutor] Re: New to Python and Linux Message-ID: <46FA6D1F.065A5B.11422@m5-82.163.com> Hi Armand, I suggest you learn Linux command line first. It is the basic skill in Linux world, like double-click in Windows. If you know how to run a program in Windows with double-click, you will understand how to run most program in Windows. If you know how to run a program with command line, you will understand how to run most program in Linux. Linux command line may be some more difficult than double-click, but it is worthy. You can learn Linux command line from here: http://linuxcommand.org From linpeiheng at 163.com Wed Sep 26 18:06:44 2007 From: linpeiheng at 163.com (=?GB2312?B?wdbF4Lrj?=) Date: Thu, 27 Sep 2007 00:06:44 +0800 Subject: [Tutor] Re: New to Python and Linux Message-ID: <46FA8394.065F3E.11422@m5-82.163.com> Hi Armand, I suggest you learn Linux command line first. It is the basic skill in Linux world, like double-click in Windows. If you know how to run a program in Windows with double-click, you will understand how to run most program in Windows. If you know how to run a program with command line, you will understand how to run most program in Linux. Linux command line may be some more difficult than double-click, but it is worthy. You can learn Linux command line from here: http://linuxcommand.org From Owojaiye.Babajide at diageo.com Wed Sep 26 17:57:09 2007 From: Owojaiye.Babajide at diageo.com (Babajide, Owojaiye) Date: Wed, 26 Sep 2007 16:57:09 +0100 Subject: [Tutor] Python for animation Message-ID: <6C7CAD10D9BD4C4D843DE6B213D78E7606CFD371@DCBVMSG004B.guww.net> Hi all, I'm looking for a tutorial PDF file of Python that is dedicated to animation and special effects,can ahyone help?If you can please forward to the following address: babajideowojaiye at yahoo.com Owojaiye.babajide at diageo.com THANKS ________________________________________________________________________ This email and any files transmitted with it are confidential and intended solely for the use of the individual or entity to which they are addressed. If you have received this email in error please notify the Diageo Servicedesk on +44 (0) 131 319 6000 This footnote also confirms that this email has been scanned for all viruses by the Messagelabs SkyScan service. http://www.diageo.com ________________________________________________________________________ -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070926/1671bf4b/attachment.htm From lufangwen at gmail.com Wed Sep 26 19:07:50 2007 From: lufangwen at gmail.com (Fangwen Lu) Date: Wed, 26 Sep 2007 10:07:50 -0700 Subject: [Tutor] questions about tuples Message-ID: <4e7ea3b40709261007g15fe6e3al5ad3ab48c09e181b@mail.gmail.com> Dear all- I want to do some loops. Each loop will generate a tuple. Eventually I want to put tuples together in a higher level of tuple. Do you know how to do this? Say a=(1,2,3), b=(4,3,2),c=(9,5,6). I want to get a tuple as ((1,2,3), (4,3,2),(9,5,6)). If there are just 2 tuples, I can write x=a and then x=(x,b). But for 3 tuples or more, I will get something like (((1,2,3), (4,3,2)),(9,5,6)). Thanks. Fangwen -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070926/877357e9/attachment.htm From lufangwen at gmail.com Wed Sep 26 19:17:11 2007 From: lufangwen at gmail.com (Fangwen Lu) Date: Wed, 26 Sep 2007 10:17:11 -0700 Subject: [Tutor] print array Message-ID: <4e7ea3b40709261017jb88d9ffi2e3fcfefcfecf35a@mail.gmail.com> Dear all- Let a=(3,4,7), b=[3,4,7]. If I type print '%d + %d = %d' %(a) I get 3 + 4 = 7 But if I type print '%d + %d = %d' %(b), I get errors. If there is a way for doing this kind of type dirrectly from array. Thank you! Fangwen -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070926/993f8477/attachment.htm From lufangwen at gmail.com Wed Sep 26 19:11:56 2007 From: lufangwen at gmail.com (Fangwen Lu) Date: Wed, 26 Sep 2007 10:11:56 -0700 Subject: [Tutor] how to convert array into tuple Message-ID: <4e7ea3b40709261011u1e0911dax926860a8aeaf446d@mail.gmail.com> Dear all- If I have an array array([1, 2, 3, 4, 5, 6]), and I want to get ((1,2),(3,4),(5,6)). What should I do? Thank you! Fangwen -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070926/b8b22f29/attachment.htm From ricaraoz at gmail.com Wed Sep 26 20:31:13 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Wed, 26 Sep 2007 15:31:13 -0300 Subject: [Tutor] questions about tuples In-Reply-To: <4e7ea3b40709261007g15fe6e3al5ad3ab48c09e181b@mail.gmail.com> References: <4e7ea3b40709261007g15fe6e3al5ad3ab48c09e181b@mail.gmail.com> Message-ID: <46FAA571.7050204@bigfoot.com> Fangwen Lu wrote: > Dear all- > > I want to do some loops. Each loop will generate a tuple. Eventually I > want to put tuples together in a higher level of tuple. Do you know how > to do this? > > Say a=(1,2,3), b=(4,3,2),c=(9,5,6). I want to get a tuple as ((1,2,3), > (4,3,2),(9,5,6)). > > If there are just 2 tuples, I can write x=a and then x=(x,b). But for 3 > tuples or more, I will get something like (((1,2,3), (4,3,2)),(9,5,6)). > > Thanks. > > Fangwen > >>> a = (1,2,3) >>> b = (4,5,6) >>> c = (7,8,9) >>> x = (a,b,c) >>> x ((1, 2, 3), (4, 5, 6), (7, 8, 9)) Or : >>> x = [] >>> x.append(a) >>> x.append(b) >>> x.append(c) >>> tuple(x) ((1, 2, 3), (4, 5, 6), (7, 8, 9)) HTH From brunson at brunson.com Wed Sep 26 20:32:45 2007 From: brunson at brunson.com (Eric Brunson) Date: Wed, 26 Sep 2007 12:32:45 -0600 Subject: [Tutor] print array In-Reply-To: <4e7ea3b40709261017jb88d9ffi2e3fcfefcfecf35a@mail.gmail.com> References: <4e7ea3b40709261017jb88d9ffi2e3fcfefcfecf35a@mail.gmail.com> Message-ID: <46FAA5CD.1010603@brunson.com> Fangwen Lu wrote: > Dear all- > > Let a=(3,4,7), b=[3,4,7]. > If I type > print '%d + %d = %d' %(a) > I get > 3 + 4 = 7 > > But if I type print '%d + %d = %d' %(b), I get errors. > > If there is a way for doing this kind of type dirrectly from array. No, but it's trivial to convert an array to a tuple: >>> b=[3,4,7] >>> print '%d + %d = %d' % tuple(b) 3 + 4 = 7 > > Thank you! > > Fangwen > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From brunson at brunson.com Wed Sep 26 20:36:18 2007 From: brunson at brunson.com (Eric Brunson) Date: Wed, 26 Sep 2007 12:36:18 -0600 Subject: [Tutor] questions about tuples In-Reply-To: <4e7ea3b40709261007g15fe6e3al5ad3ab48c09e181b@mail.gmail.com> References: <4e7ea3b40709261007g15fe6e3al5ad3ab48c09e181b@mail.gmail.com> Message-ID: <46FAA6A2.2020400@brunson.com> Fangwen Lu wrote: > Dear all- > > I want to do some loops. Each loop will generate a tuple. Eventually I > want to put tuples together in a higher level of tuple. Do you know > how to do this? > > Say a=(1,2,3), b=(4,3,2),c=(9,5,6). I want to get a tuple as ((1,2,3), > (4,3,2),(9,5,6)). > > If there are just 2 tuples, I can write x=a and then x=(x,b). But for > 3 tuples or more, I will get something like (((1,2,3), (4,3,2)),(9,5,6)). >>> a=(1,2,3) >>> b=(4,3,2) >>> c=(9,5,6) >>> x = (a,b,c) >>> print x ((1, 2, 3), (4, 3, 2), (9, 5, 6)) Or: >>> x = [] >>> x.append(a) >>> x.append(b) >>> x.append(c) >>> print x [(1, 2, 3), (4, 3, 2), (9, 5, 6)] >>> x = tuple(x) >>> print x ((1, 2, 3), (4, 3, 2), (9, 5, 6)) You can't use append() on a tuple, because a tuple is, by design, immutable. > > Thanks. > > Fangwen > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From ricaraoz at gmail.com Wed Sep 26 20:39:09 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Wed, 26 Sep 2007 15:39:09 -0300 Subject: [Tutor] how to convert array into tuple In-Reply-To: <4e7ea3b40709261011u1e0911dax926860a8aeaf446d@mail.gmail.com> References: <4e7ea3b40709261011u1e0911dax926860a8aeaf446d@mail.gmail.com> Message-ID: <46FAA74D.4010700@bigfoot.com> Fangwen Lu wrote: > Dear all- > > If I have an array array([1, 2, 3, 4, 5, 6]), and I want to get > ((1,2),(3,4),(5,6)). What should I do? > tuple([j for (i,j) in enumerate(zip(x, x[1:])) if i % 2 == 0]) From ricaraoz at gmail.com Wed Sep 26 20:40:46 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Wed, 26 Sep 2007 15:40:46 -0300 Subject: [Tutor] print array In-Reply-To: <4e7ea3b40709261017jb88d9ffi2e3fcfefcfecf35a@mail.gmail.com> References: <4e7ea3b40709261017jb88d9ffi2e3fcfefcfecf35a@mail.gmail.com> Message-ID: <46FAA7AE.4080602@bigfoot.com> Fangwen Lu wrote: > Dear all- > > Let a=(3,4,7), b=[3,4,7]. > If I type > print '%d + %d = %d' %(a) > I get > 3 + 4 = 7 > > But if I type print '%d + %d = %d' %(b), I get errors. > > If there is a way for doing this kind of type dirrectly from array. > print '%d + %d = %d' % tuple(b) From brunson at brunson.com Wed Sep 26 20:40:43 2007 From: brunson at brunson.com (Eric Brunson) Date: Wed, 26 Sep 2007 12:40:43 -0600 Subject: [Tutor] how to convert array into tuple In-Reply-To: <4e7ea3b40709261011u1e0911dax926860a8aeaf446d@mail.gmail.com> References: <4e7ea3b40709261011u1e0911dax926860a8aeaf446d@mail.gmail.com> Message-ID: <46FAA7AB.6030803@brunson.com> Fangwen Lu wrote: > Dear all- > > If I have an array array([1, 2, 3, 4, 5, 6]), and I want to get > ((1,2),(3,4),(5,6)). What should I do? First, you read some documentation and tutorials on the language, then you iterate over the list and build tuples out of the elements. > > Thank you! > > Fangwen > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From balderas at whtvcable.com Wed Sep 26 20:58:00 2007 From: balderas at whtvcable.com (Chris) Date: Wed, 26 Sep 2007 11:58:00 -0700 Subject: [Tutor] python problem In-Reply-To: <ea979d70709260512ke43baaan8e34fdfda2f948ef@mail.gmail.com> References: <mailman.3553.1190681774.2656.tutor@python.org> <!&!AAAAAAAAAAAYAAAAAAAAAHICkgQi6MVHrTCR8dizOffCgAAAEAAAAMkyk9iBJ8RLn5YK2RLm8JcBAAAAAA==@whtvcable.com> <ea979d70709250436n582870a0s2795c5cb13233ae2@mail.gmail.com> <!&!AAAAAAAAAAAYAAAAAAAAAHICkgQi6MVHrTCR8dizOffCgAAAEAAAADW0DfjaCctGiMgss+5ipe4BAAAAAA==@whtvcable.com> <46F9C4AF.9080309@tds.net> <!&!AAAAAAAAAAAYAAAAAAAAAHICkgQi6MVHrTCR8dizOffCgAAAEAAAAF/EqAec6QNJiEltTYB6Z9gBAAAAAA==@whtvcable.com> <ea979d70709260512ke43baaan8e34fdfda2f948ef@mail.gmail.com> Message-ID: <!&!AAAAAAAAAAAYAAAAAAAAAHICkgQi6MVHrTCR8dizOffCgAAAEAAAABJpKaSRYx9MjetW9a2/VR8BAAAAAA==@whtvcable.com> Here some more work: guess = 0 Print ?Pick a number between 0 and 100? While guess != ________ : print ?My first guess is ?, guess print ?Is my guess correct?? if guess = = type3 print ?I got it!? if guess > _______: pick lower # if guess <_______ : pick higher # that?s all I can do right now? the mechanism that I can?t figure out is how to show in code form how the computer goes to the next guess using the split range... ie. if the first guess is 50, the second guess would be taken from the 50-100 (50/2 = 25 + 50 = 75) second guess would be 75 if the number is too high. If the number falls below 50, then the split range is 25, ect? -----Original Message----- From: bhaaluu [mailto:bhaaluu at gmail.com] Sent: Wednesday, September 26, 2007 5:13 AM To: Chris Cc: tutor at python.org Subject: Re: [Tutor] python problem Greetings Chris, On 9/25/07, Chris <balderas at whtvcable.com> wrote: > > Ok as I see it, it's should go like this: > > Print 'Think of a number between 1 and 100, and let me guess it' > > Type1 = input ('Type 1 if I am high') > Type2 = input ('Type 2 if I am low') > Type3 = input ('Type 3 if I am dead on') > > I can't seem to get the guts of it. I assume that there are 3 if statements > and a while statement. > > guess > > While x != > If guess > > > > I get lost right around here...help! Thunk! er, Think! =) Play the guess-a-number game, and jot down exactly what YOU do to make a guess. Prompt:> Think of a number between 1 and 100. Got it? Prompt:> Okay, now I, the Great Computer, will guess the number... Prompt:> Is the number 51? Prompt:> 0=Correct, 1=Lower, 2=Higher: _ The range is 1 to 100. Let's say you think of the number 37. At he prompt, you type 1 because the number is Lower than 51. (or whatever scheme you decide to use.) If you were playing against the computer, and the computer told you to guess Lower, what would you do? Would you guess 50? 49? 10? 1? How do you guess when you're playing the game? How do you narrow it down? Figure it out. So, now you think you can outsmart the computer half-way through the game by thinking of a different number, say 38.... Pretty sneaky! That's like palming the pea in a shell game. Granted, the Great Computer, isn't very smart... but it IS an idiot savant. It can remember tons of information that you've forgotten as irrelevant just seconds ago. So what the Great Computer has been doing, while guessing, is keeping track of the bounds it can guess between, from the hints you've been providing [0,1,2, whatever] and maybe even a list of all its guesses that were not correct. And in a split second, it can compare all that stuff. Chris, what constraints are you working under? How many Python 'tools' (keywords, methods, etc.) do you have to solve the problem with? Input? [raw_inpu(), input(), ...], Output? [print, ...], Selection? [if, elif, else, ...] Iteration? [for, while, ...]. You also have to consider what you have to work with so far. -- b h a a l u u at g m a i l dot c o m http://www.geocities.com/ek.bhaaluu/index.html No virus found in this outgoing message. Checked by AVG Free Edition. Version: 7.5.487 / Virus Database: 269.13.25/1018 - Release Date: 9/19/2007 3:59 PM -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070926/a211be32/attachment.htm From ulrich at lavabit.com Wed Sep 26 21:47:27 2007 From: ulrich at lavabit.com (Ulrich Holtzhausen) Date: Wed, 26 Sep 2007 21:47:27 +0200 Subject: [Tutor] Where can I find simple python scripts to edit and play around? Message-ID: <46FAB74F.4020906@lavabit.com> Well I guess the subject/topic here describes it all. I am looking for a nice collection of SIMPLE python scripts, IE: How to manipulate files, text, how to create a bot, how to work with socks...making a server/client, converting decimal to binary etc. etc. etc. Example scripts since I am having a difficulty creating these myself since I am struggling to adapt to using creativity at the moment. I know that creativity is everything in programming. I just lack some experience + knowledge (examples) of how things are done. If someone knows of some sites or collections of these kinds of things from where I can view/download code from (possible) real world example applications/scripts that would be great. I want to modify and play around and read/interpret/understand what I'm struggling to conjour. Thanks for any help and/or suggestions :) From bhaaluu at gmail.com Wed Sep 26 22:07:28 2007 From: bhaaluu at gmail.com (bhaaluu) Date: Wed, 26 Sep 2007 16:07:28 -0400 Subject: [Tutor] Where can I find simple python scripts to edit and play around? In-Reply-To: <46FAB74F.4020906@lavabit.com> References: <46FAB74F.4020906@lavabit.com> Message-ID: <ea979d70709261307r2134d21dia4f2eb5d61783069@mail.gmail.com> http://examples.oreilly.com/python3/ http://aspn.activestate.com/ASPN/Cookbook/Python/ http://examples.oreilly.com/twistedadn/ http://www.vex.net/parnassus/ I guess you could start with those and see what you can find? -- b h a a l u u at g m a i l dot c o m http://www.geocities.com/ek.bhaaluu/index.html On 9/26/07, Ulrich Holtzhausen <ulrich at lavabit.com> wrote: > Well I guess the subject/topic here describes it all. I am looking for a > nice collection of SIMPLE python scripts, IE: How to manipulate files, > text, how to create a bot, how to work with socks...making a > server/client, converting decimal to binary etc. etc. etc. Example > scripts since I am having a difficulty creating these myself since I am > struggling to adapt to using creativity at the moment. I know that > creativity is everything in programming. I just lack some experience + > knowledge (examples) of how things are done. If someone knows of some > sites or collections of these kinds of things from where I can > view/download code from (possible) real world example > applications/scripts that would be great. I want to modify and play > around and read/interpret/understand what I'm struggling to conjour. > > Thanks for any help and/or suggestions :) > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From sxkorean at gmail.com Wed Sep 26 22:07:29 2007 From: sxkorean at gmail.com (Andrew Nelsen) Date: Wed, 26 Sep 2007 16:07:29 -0400 Subject: [Tutor] Where can I find simple python scripts to edit and play around? In-Reply-To: <46FAB74F.4020906@lavabit.com> References: <46FAB74F.4020906@lavabit.com> Message-ID: <a783f25a0709261307k54dac89aib12fe74aa3ef6c4e@mail.gmail.com> On 9/26/07, Ulrich Holtzhausen <ulrich at lavabit.com> wrote: > > Well I guess the subject/topic here describes it all. I am looking for a > nice collection of SIMPLE python scripts, IE: How to manipulate files, > text, how to create a bot, how to work with socks...making a > server/client, converting decimal to binary etc. etc. etc. Example > scripts since I am having a difficulty creating these myself since I am > struggling to adapt to using creativity at the moment. I know that > creativity is everything in programming. I just lack some experience + > knowledge (examples) of how things are done. If someone knows of some > sites or collections of these kinds of things from where I can > view/download code from (possible) real world example > applications/scripts that would be great. I want to modify and play > around and read/interpret/understand what I'm struggling to conjour. > > Thanks for any help and/or suggestions :) Check out this site: http://www.uselesspython.com It has some pretty nifty stuff on there, but a lot of it is kinda old. Just my two cents - I'm pretty new as well. - Drew -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070926/016803d3/attachment-0001.htm From kent37 at tds.net Wed Sep 26 22:18:29 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 26 Sep 2007 16:18:29 -0400 Subject: [Tutor] Where can I find simple python scripts to edit and play around? In-Reply-To: <46FAB74F.4020906@lavabit.com> References: <46FAB74F.4020906@lavabit.com> Message-ID: <46FABE95.5010506@tds.net> Ulrich Holtzhausen wrote: > Well I guess the subject/topic here describes it all. I am looking for a > nice collection of SIMPLE python scripts, http://aspn.activestate.com/ASPN/Cookbook/Python as well as the printed version already referenced. http://diveintopython.org/ has fairly long examples http://www.amazon.com/Python-Phrasebook-Developers-Library-Dayley/dp/0672329107 Kent From nephish at gmail.com Wed Sep 26 23:24:23 2007 From: nephish at gmail.com (shawn bright) Date: Wed, 26 Sep 2007 16:24:23 -0500 Subject: [Tutor] do i have to import modules at the start of a file? Message-ID: <384c93600709261424g17e1a1d5j14fb5fdc1363cc35@mail.gmail.com> lo there all, i have a gui program that imports a few modules that i don't need if i am using the program remotely. The program has an admin interface and thread interface, only the admin interface is needed when i am using the program from a remote computer. all of my modules are imported at the start of the file, and not initiated till a certain button is clicked on the GUI, could i put those import statements in the button click event? thanks shawn -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070926/849ea8d2/attachment.htm From kent37 at tds.net Wed Sep 26 23:52:35 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 26 Sep 2007 17:52:35 -0400 Subject: [Tutor] do i have to import modules at the start of a file? In-Reply-To: <384c93600709261424g17e1a1d5j14fb5fdc1363cc35@mail.gmail.com> References: <384c93600709261424g17e1a1d5j14fb5fdc1363cc35@mail.gmail.com> Message-ID: <46FAD4A3.4030905@tds.net> shawn bright wrote: > lo there all, > > i have a gui program that imports a few modules that i don't need if i > am using the program remotely. > The program has an admin interface and thread interface, only the admin > interface is needed when > i am using the program from a remote computer. > > all of my modules are imported at the start of the file, and not > initiated till a certain button is clicked on the GUI, could i put those > import statements in the button click event? Yes but why do you want to? The reasons I know for doing this: - the import takes a long time or a lot of memory and you don't want to incur the cost unless you need it - the imported module may not be available always and you want the rest of the importing module still to be usable Kent From balderas at whtvcable.com Thu Sep 27 03:46:14 2007 From: balderas at whtvcable.com (Chris) Date: Wed, 26 Sep 2007 18:46:14 -0700 Subject: [Tutor] still need help.. In-Reply-To: <mailman.3880.1190837254.2656.tutor@python.org> References: <mailman.3880.1190837254.2656.tutor@python.org> Message-ID: <!&!AAAAAAAAAAAYAAAAAAAAAHICkgQi6MVHrTCR8dizOffCgAAAEAAAACbaZbC8zw9Dv3HRt+qMAUEBAAAAAA==@whtvcable.com> Here some more work: guess = 0 Print ?Pick a number between 0 and 100? While guess != ________ : print ?My first guess is ?, guess print ?Is my guess correct?? if guess = = type3 print ?I got it!? if guess > _______: pick lower # if guess <_______ : pick higher # that?s all I can do right now? the mechanism that I can?t figure out is how to show in code form how the computer goes to the next guess using the split range... ie. if the first guess is 50, the second guess would be taken from the 50-100 (50/2 = 25 + 50 = 75) second guess would be 75 if the number is too high. If the number falls below 50, then the split range is 25, ect? Internal Virus Database is out-of-date. Checked by AVG Free Edition. Version: 7.5.487 / Virus Database: 269.13.25/1018 - Release Date: 9/19/2007 3:59 PM From kent37 at tds.net Thu Sep 27 04:07:19 2007 From: kent37 at tds.net (Kent Johnson) Date: Wed, 26 Sep 2007 22:07:19 -0400 Subject: [Tutor] still need help.. In-Reply-To: <!&!AAAAAAAAAAAYAAAAAAAAAHICkgQi6MVHrTCR8dizOffCgAAAEAAAACbaZbC8zw9Dv3HRt+qMAUEBAAAAAA==@whtvcable.com> References: <mailman.3880.1190837254.2656.tutor@python.org> <!&!AAAAAAAAAAAYAAAAAAAAAHICkgQi6MVHrTCR8dizOffCgAAAEAAAACbaZbC8zw9Dv3HRt+qMAUEBAAAAAA==@whtvcable.com> Message-ID: <46FB1057.1040202@tds.net> Chris wrote: > > Here some more work: > > > guess = 0 > > Print ?Pick a number between 0 and 100? > > > While guess != ________ : > print ?My first guess is ?, guess > print ?Is my guess correct?? > if guess = = type3 > print ?I got it!? > if guess > _______: > pick lower # > if guess <_______ : > pick higher # > > that?s all I can do right now? > > the mechanism that I can?t figure out is how to show in code form how the > computer goes to the next guess using the split range... ie. if the first > guess is 50, the second guess would be taken from the 50-100 (50/2 = 25 + 50 > = 75) second guess would be 75 if the number is too high. If the number > falls below 50, then the split range is 25, ect? What I would do is keep a variable delta that gets added to or subtracted from the current guess, depending on whether the guess is too high or too low. Each time through the loop, make delta smaller by dividing by two unless delta is already down to 1. Are you reading Python Programming for the absolute beginner? This problem is exercise 4 for chapter 3 in my copy. Have you tried exercises 1-3? They are not so hard as this one. Kent From balderas at whtvcable.com Thu Sep 27 04:50:25 2007 From: balderas at whtvcable.com (Chris) Date: Wed, 26 Sep 2007 19:50:25 -0700 Subject: [Tutor] i am stuck... In-Reply-To: <46FB1057.1040202@tds.net> References: <mailman.3880.1190837254.2656.tutor@python.org> <!&!AAAAAAAAAAAYAAAAAAAAAHICkgQi6MVHrTCR8dizOffCgAAAEAAAACbaZbC8zw9Dv3HRt+qMAUEBAAAAAA==@whtvcable.com> <46FB1057.1040202@tds.net> Message-ID: <!&!AAAAAAAAAAAYAAAAAAAAAHICkgQi6MVHrTCR8dizOffCgAAAEAAAALGvbX11NPxKnIaiUsrzYQMBAAAAAA==@whtvcable.com> I don't know what to do at this point. I do not have the book, but will get it just to have... Can anyone help me? > Here some more work: > > > guess = 0 > > Print ?Pick a number between 0 and 100? > > > While guess != ________ : > print ?My first guess is ?, guess > print ?Is my guess correct?? > if guess = = type3 > print ?I got it!? > if guess > _______: > pick lower # > if guess <_______ : > pick higher # > > that?s all I can do right now? > > the mechanism that I can?t figure out is how to show in code form how the > computer goes to the next guess using the split range... ie. if the first > guess is 50, the second guess would be taken from the 50-100 (50/2 = 25 + 50 = 75) second guess would be 75 if the number is too high. If the number > falls below 50, then the split range is 25, ect? Internal Virus Database is out-of-date. Checked by AVG Free Edition. Version: 7.5.487 / Virus Database: 269.13.25/1018 - Release Date: 9/19/2007 3:59 PM From witham.ian at gmail.com Thu Sep 27 06:15:47 2007 From: witham.ian at gmail.com (Ian Witham) Date: Thu, 27 Sep 2007 16:15:47 +1200 Subject: [Tutor] i am stuck... In-Reply-To: <!&!AAAAAAAAAAAYAAAAAAAAAHICkgQi6MVHrTCR8dizOffCgAAAEAAAALGvbX11NPxKnIaiUsrzYQMBAAAAAA==@whtvcable.com> References: <mailman.3880.1190837254.2656.tutor@python.org> <!&!AAAAAAAAAAAYAAAAAAAAAHICkgQi6MVHrTCR8dizOffCgAAAEAAAACbaZbC8zw9Dv3HRt+qMAUEBAAAAAA==@whtvcable.com> <46FB1057.1040202@tds.net> <!&!AAAAAAAAAAAYAAAAAAAAAHICkgQi6MVHrTCR8dizOffCgAAAEAAAALGvbX11NPxKnIaiUsrzYQMBAAAAAA==@whtvcable.com> Message-ID: <a04dbf4b0709262115k3dc28658h4a46c330303a1184@mail.gmail.com> On 9/27/07, Chris <balderas at whtvcable.com> wrote: > > I don't know what to do at this point. I do not have the book, but will > get > it just to have... > > Can anyone help me? > > > Here some more work: > > > > > > guess = 0 > > > > Print ?Pick a number between 0 and 100? > > > > > > While guess != ________ : > > print ?My first guess is ?, guess > > print ?Is my guess correct?? > > if guess = = type3 > > print ?I got it!? > > if guess > _______: > > pick lower # > > if guess <_______ : > > pick higher # > > > > that?s all I can do right now? > > > > the mechanism that I can?t figure out is how to show in code form how > the > > computer goes to the next guess using the split range... ie. if the > first > > guess is 50, the second guess would be taken from the 50-100 (50/2 = 25 > + > 50 = 75) second guess would be 75 if the number is too high. If the > number > > falls below 50, then the split range is 25, ect? Try having these 3 variables: top, the top number that the secret number might be. bottom, the lowest number that the secret number might be. guess, the current guess. if the guess is too high, then the value for guess should become your new 'top': if guess > secret_number: top = guess If the guess is too low, do the opposite. 'bottom' should now be set to guess Now create a new value for guess using your new values for top and bottom, and guess again. Ian. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070927/41fa3e99/attachment.htm From witham.ian at gmail.com Thu Sep 27 07:05:25 2007 From: witham.ian at gmail.com (Ian Witham) Date: Thu, 27 Sep 2007 17:05:25 +1200 Subject: [Tutor] i am stuck... In-Reply-To: <a04dbf4b0709262115k3dc28658h4a46c330303a1184@mail.gmail.com> References: <mailman.3880.1190837254.2656.tutor@python.org> <!&!AAAAAAAAAAAYAAAAAAAAAHICkgQi6MVHrTCR8dizOffCgAAAEAAAACbaZbC8zw9Dv3HRt+qMAUEBAAAAAA==@whtvcable.com> <46FB1057.1040202@tds.net> <!&!AAAAAAAAAAAYAAAAAAAAAHICkgQi6MVHrTCR8dizOffCgAAAEAAAALGvbX11NPxKnIaiUsrzYQMBAAAAAA==@whtvcable.com> <a04dbf4b0709262115k3dc28658h4a46c330303a1184@mail.gmail.com> Message-ID: <a04dbf4b0709262205w307f7503w598bbb9ce53cdf3b@mail.gmail.com> On 9/27/07, Ian Witham <witham.ian at gmail.com> wrote: > > On 9/27/07, Chris <balderas at whtvcable.com> wrote: > > > > I don't know what to do at this point. I do not have the book, but will > > get > > it just to have... > > > > Can anyone help me? > > > > > Here some more work: > > > > > > > > > guess = 0 > > > > > > Print ?Pick a number between 0 and 100? > > > > > > > > > While guess != ________ : > > > print ?My first guess is ?, guess > > > print ?Is my guess correct?? > > > if guess = = type3 > > > print ?I got it!? > > > if guess > _______: > > > pick lower # > > > if guess <_______ : > > > pick higher # > > > > > > that?s all I can do right now? > > > > > > the mechanism that I can?t figure out is how to show in code form how > > the > > > computer goes to the next guess using the split range... ie. if the > > first > > > guess is 50, the second guess would be taken from the 50-100 (50/2 = > > 25 + > > 50 = 75) second guess would be 75 if the number is too high. If the > > number > > > falls below 50, then the split range is 25, ect? > > > > Try having these 3 variables: > > top, the top number that the secret number might be. > bottom, the lowest number that the secret number might be. > guess, the current guess. > > if the guess is too high, then the value for guess should become your new > 'top': > if guess > secret_number: > top = guess > > If the guess is too low, do the opposite. 'bottom' should now be set to > guess > > Now create a new value for guess using your new values for top and bottom, > and guess again. > > Ian. > Some Pseudocode might help: secret_number = something bottom = 1 top = 101 guess = 50 while guess != secret number: print "My guess is: ___" if guess too low: print "That guess is too low." bottom = guess if guess too high: print "That guess is too high." top = guess guess = make a new guess, halfway between top and bottom print "I have guessed your number, it is ____" Ian -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070927/b85e661a/attachment-0001.htm From aditya.n.lal at gmail.com Thu Sep 27 09:36:17 2007 From: aditya.n.lal at gmail.com (Aditya Lal) Date: Thu, 27 Sep 2007 13:06:17 +0530 Subject: [Tutor] How to speed up input/string parsing ... Message-ID: <5df213700709270036p1a354dd9m9aeacb72b8caf9f1@mail.gmail.com> Hi !! I was trying to solve SPOJ (www.spoj.pl) problems - ADDREV (add reversed numbers). My solution clocked 0.58 seconds in SPOJ's computer as compared to best time of 0.28. Interestingly my program spends 50% of its total execution time in reading/parsing the input. Following is the sample input/output. The actual data set contains ~ 10,000 numbers. Sample input: 3 --> indicates the # of lines to follow 24 1 --> 2 numbers separated by a space 4358 754 305 794 Sample output: 34 --> reverse of sum of reverse of both numbers 1998 1 I wrote the following code - def rev(n) : m = 0 while n > 0 : m = m*10 + n%10 n = n/10 return m def solve(line) : nums = line.split(' ') a = int(nums[0]) b = int(nums[1]) return rev( rev(a) + rev(b) ) if __name__ == '__main__' : N = int(sys.stdin.readline()) lines = sys.stdin.readlines() for i in xrange(N) : print solve(lines[i]) My Question : How do I improve the input reading or string parsing ? I know there should be a better way because the best program (at cost of memory) performs > 50% faster than mine. So he must have done something to improve input processing. Thanks Aditya -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070927/981585af/attachment.htm From kent37 at tds.net Thu Sep 27 12:38:30 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 27 Sep 2007 06:38:30 -0400 Subject: [Tutor] How to speed up input/string parsing ... In-Reply-To: <5df213700709270036p1a354dd9m9aeacb72b8caf9f1@mail.gmail.com> References: <5df213700709270036p1a354dd9m9aeacb72b8caf9f1@mail.gmail.com> Message-ID: <46FB8826.6030507@tds.net> Aditya Lal wrote: > def rev(n) : > m = 0 > while n > 0 : > m = m*10 + n%10 > n = n/10 > return m I would try reversing the numbers as strings. s[::-1] will reverse a string s. > How do I improve the input reading or string parsing ? I know there > should be a better way because the best program (at cost of memory) > performs > 50% faster than mine. So he must have done something to > improve input processing. The programs that use a lot of memory are using psyco. Kent From kent37 at tds.net Thu Sep 27 12:41:06 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 27 Sep 2007 06:41:06 -0400 Subject: [Tutor] ftp inside function In-Reply-To: <281948.44703.qm@web32612.mail.mud.yahoo.com> References: <281948.44703.qm@web32612.mail.mud.yahoo.com> Message-ID: <46FB88C2.2010100@tds.net> Nelson Kusuma wrote: > Dear Kent > > Thanks Kent, i made loop function to create directory > tree, and for the first login, i also want to make > inside function : > > def exeFtp(): > session=ftplib.FTP('myWorkstation','tes', 'tes') > direc="d:\TES" > direcFtp(direc) #function to create directory > session.close() > but this function can't execute although i can execute > one buy one in GUI but not in that function, Is there > any something wrong? Thanks What happens when you run the program? Please copy and paste the exact error message you get, including the traceback, into your email. My guess is that you have to pass session as a parameter to direcFtp. Kent PS Please use Reply All to reply to the list. From nephish at gmail.com Thu Sep 27 15:23:44 2007 From: nephish at gmail.com (shawn bright) Date: Thu, 27 Sep 2007 08:23:44 -0500 Subject: [Tutor] do i have to import modules at the start of a file? In-Reply-To: <46FAD4A3.4030905@tds.net> References: <384c93600709261424g17e1a1d5j14fb5fdc1363cc35@mail.gmail.com> <46FAD4A3.4030905@tds.net> Message-ID: <384c93600709270623k10c5b825o3e996b4f62b9c403@mail.gmail.com> It's the second one, not all the modules will be available on the portable version. But the threads that require those modules will not be necessary on the portable version. I want to be able to go to any linux computer with GTK and mysqldb installed and check out my stuff from svn and run the admin part of the program. But the main computer at work that takes data in will need the modules to run the threads. thanks for your help on this shawn On 9/26/07, Kent Johnson <kent37 at tds.net> wrote: > > shawn bright wrote: > > lo there all, > > > > i have a gui program that imports a few modules that i don't need if i > > am using the program remotely. > > The program has an admin interface and thread interface, only the admin > > interface is needed when > > i am using the program from a remote computer. > > > > all of my modules are imported at the start of the file, and not > > initiated till a certain button is clicked on the GUI, could i put those > > import statements in the button click event? > > Yes but why do you want to? The reasons I know for doing this: > - the import takes a long time or a lot of memory and you don't want to > incur the cost unless you need it > - the imported module may not be available always and you want the rest > of the importing module still to be usable > > Kent > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070927/50f9dcb0/attachment.htm From mlangford.cs03 at gtalumni.org Thu Sep 27 15:27:07 2007 From: mlangford.cs03 at gtalumni.org (Michael Langford) Date: Thu, 27 Sep 2007 09:27:07 -0400 Subject: [Tutor] do i have to import modules at the start of a file? In-Reply-To: <384c93600709270623k10c5b825o3e996b4f62b9c403@mail.gmail.com> References: <384c93600709261424g17e1a1d5j14fb5fdc1363cc35@mail.gmail.com> <46FAD4A3.4030905@tds.net> <384c93600709270623k10c5b825o3e996b4f62b9c403@mail.gmail.com> Message-ID: <82b4f5810709270627r26c83693n6191ccbf28987eab@mail.gmail.com> In your particular situation, I've often used the "One Library, two executable" pattern. Put all the common functionality into one python module. Have one python file who's main brings up a GUI and one who brings up the admin cli interface, both of which that import the main library that does all the common things. --Michael On 9/27/07, shawn bright <nephish at gmail.com> wrote: > It's the second one, not all the modules will be available on the portable > version. But the threads that require those modules will not be necessary on > the portable version. I want to be able to go to any linux computer with GTK > and mysqldb installed and check out my stuff from svn and run the admin part > of the program. But the main computer at work that takes data in will need > the modules to run the threads. > > thanks for your help on this > > shawn > > > On 9/26/07, Kent Johnson <kent37 at tds.net> wrote: > > shawn bright wrote: > > > lo there all, > > > > > > i have a gui program that imports a few modules that i don't need if i > > > am using the program remotely. > > > The program has an admin interface and thread interface, only the admin > > > interface is needed when > > > i am using the program from a remote computer. > > > > > > all of my modules are imported at the start of the file, and not > > > initiated till a certain button is clicked on the GUI, could i put those > > > import statements in the button click event? > > > > Yes but why do you want to? The reasons I know for doing this: > > - the import takes a long time or a lot of memory and you don't want to > > incur the cost unless you need it > > - the imported module may not be available always and you want the rest > > of the importing module still to be usable > > > > Kent > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Michael Langford Phone: 404-386-0495 Consulting: http://www.TierOneDesign.com/ Entertaining: http://www.ThisIsYourCruiseDirectorSpeaking.com From rikard.bosnjakovic at gmail.com Thu Sep 27 18:41:11 2007 From: rikard.bosnjakovic at gmail.com (Rikard Bosnjakovic) Date: Thu, 27 Sep 2007 18:41:11 +0200 Subject: [Tutor] questions about tuples In-Reply-To: <46FAA6A2.2020400@brunson.com> References: <4e7ea3b40709261007g15fe6e3al5ad3ab48c09e181b@mail.gmail.com> <46FAA6A2.2020400@brunson.com> Message-ID: <d9e88eaf0709270941u75fe1752i65ad77f210b7b129@mail.gmail.com> On 26/09/2007, Eric Brunson <brunson at brunson.com> wrote: > You can't use append() on a tuple, because a tuple is, by design, immutable. Yes, and that's why he appends to a list, then converts the list to a tuple. -- - Rikard - http://bos.hack.org/cv/ From paulino1 at sapo.pt Thu Sep 27 18:48:14 2007 From: paulino1 at sapo.pt (paulino1 at sapo.pt) Date: Thu, 27 Sep 2007 17:48:14 +0100 Subject: [Tutor] exec sintax error or bug? Message-ID: <20070927174814.ej6t4ub00o44wo88@w6.mail.sapo.pt> Hello! Why doesn't the second code snipet, work like the first? >>> for i in range(5): ... if i == 3 : continue ... print i, ... 0 1 2 4 >>> exp = "if i == 3 : continue" >>> for i in range(5): ... exec( exp ) ... print i, ... Traceback (most recent call last): File "<input>", line 2, in <module> File "<string>", line 1 SyntaxError: 'continue' not properly in loop (<string>, line 1) I have other examples os exp = "if <some condition> : do this" that work as expected when called by exec(exp) So i think the problem is not about "continue" but about "exec". >>> exp2 = 'if i == 2 : print 2**2' >>> for i in range(5): ... exec( exp2 ) ... print i, ... 0 1 4 2 3 4 From kent37 at tds.net Thu Sep 27 19:59:46 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 27 Sep 2007 13:59:46 -0400 Subject: [Tutor] exec sintax error or bug? In-Reply-To: <20070927174814.ej6t4ub00o44wo88@w6.mail.sapo.pt> References: <20070927174814.ej6t4ub00o44wo88@w6.mail.sapo.pt> Message-ID: <46FBEF92.4050903@tds.net> paulino1 at sapo.pt wrote: > Hello! > > Why doesn't the second code snipet, work like the first? > >>>> for i in range(5): > ... if i == 3 : continue > ... print i, > ... > 0 1 2 4 > >>>> exp = "if i == 3 : continue" >>>> for i in range(5): > ... exec( exp ) > ... print i, > ... > Traceback (most recent call last): > File "<input>", line 2, in <module> > File "<string>", line 1 > SyntaxError: 'continue' not properly in loop (<string>, line 1) I think the code you pass to exec must be syntactically correct on its own. It is parsed as if it were in a file by itself, then executed in the local scope. Kent From noufal at airtelbroadband.in Thu Sep 27 20:44:08 2007 From: noufal at airtelbroadband.in (Noufal Ibrahim) Date: Fri, 28 Sep 2007 00:14:08 +0530 Subject: [Tutor] how to convert array into tuple In-Reply-To: <4e7ea3b40709261011u1e0911dax926860a8aeaf446d@mail.gmail.com> References: <4e7ea3b40709261011u1e0911dax926860a8aeaf446d@mail.gmail.com> Message-ID: <46FBF9F8.1000002@airtelbroadband.in> Fangwen Lu wrote: > Dear all- > > If I have an array array([1, 2, 3, 4, 5, 6]), and I want to get > ((1,2),(3,4),(5,6)). What should I do? This seems to work although I'd like comments from the more experienced Pythonistas out there. >>> foo [1, 2, 3, 4, 5, 6, 7, 8, 9] >>> [(foo[i],foo[i+1]) for i in range(0,len(foo)-2,2)] [(1, 2), (3, 4), (5, 6), (7, 8)] >>> Peace. -- ~noufal From kent37 at tds.net Thu Sep 27 21:05:50 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 27 Sep 2007 15:05:50 -0400 Subject: [Tutor] how to convert array into tuple In-Reply-To: <46FBF9F8.1000002@airtelbroadband.in> References: <4e7ea3b40709261011u1e0911dax926860a8aeaf446d@mail.gmail.com> <46FBF9F8.1000002@airtelbroadband.in> Message-ID: <46FBFF0E.1060209@tds.net> Noufal Ibrahim wrote: > This seems to work although I'd like comments from the more experienced > Pythonistas out there. > > >>> foo > [1, 2, 3, 4, 5, 6, 7, 8, 9] > >>> [(foo[i],foo[i+1]) for i in range(0,len(foo)-2,2)] > [(1, 2), (3, 4), (5, 6), (7, 8)] This problem is a perennial favorite on comp.lang.python and in the cookbook, which I take to mean that there is no clear best solution. You can see some alternatives here http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/425044 and in the links at the bottom of that page. One question is what to do with partial groups at the end; your version truncates the original list. Kent From aditya.n.lal at gmail.com Thu Sep 27 21:40:20 2007 From: aditya.n.lal at gmail.com (Aditya Lal) Date: Fri, 28 Sep 2007 01:10:20 +0530 Subject: [Tutor] How to speed up input/string parsing ... In-Reply-To: <46FB8826.6030507@tds.net> References: <5df213700709270036p1a354dd9m9aeacb72b8caf9f1@mail.gmail.com> <46FB8826.6030507@tds.net> Message-ID: <5df213700709271240t59c3eb2cx318b0407fea998f1@mail.gmail.com> Hello Kent, I tried finding solution with using only strings but unfortunately reversing a number has some interesting issues - For example: take following two numbers - 002000 002000 though the final answer is 4 - arriving at it using string is stripping '0' from both left and right of both numbers. I thought it was far easier to convert it into an integer and reverse. Anyway I wasn't aware of string reversal shortcut - [::-1] ... thanx :) Following code performs in 0.50 seconds : import sys def rev(n) : m = 0 while n > 0 : r = n%10 m = m*10 + r n = n/10 return m def solve(line) : nums = line.split(' ') a = int(nums[0].strip('0')[::-1]) b = int(nums[1].strip('0')[::-1]) return rev( a + b ) if __name__ == '__main__' : N = int(sys.stdin.readline()) lines = sys.stdin.readlines() for i in xrange(N) : print solve(lines[i]) I will start working on psyco ... though not sure what is it ? Thanks again Kent. Cheers Aditya On 9/27/07, Kent Johnson <kent37 at tds.net> wrote: > > Aditya Lal wrote: > > > def rev(n) : > > m = 0 > > while n > 0 : > > m = m*10 + n%10 > > n = n/10 > > return m > > I would try reversing the numbers as strings. s[::-1] will reverse a > string s. > > > How do I improve the input reading or string parsing ? I know there > > should be a better way because the best program (at cost of memory) > > performs > 50% faster than mine. So he must have done something to > > improve input processing. > > The programs that use a lot of memory are using psyco. > > Kent > -- Aditya -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070928/4d89ca42/attachment-0001.htm From kent37 at tds.net Thu Sep 27 21:48:32 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 27 Sep 2007 15:48:32 -0400 Subject: [Tutor] How to speed up input/string parsing ... In-Reply-To: <5df213700709271240t59c3eb2cx318b0407fea998f1@mail.gmail.com> References: <5df213700709270036p1a354dd9m9aeacb72b8caf9f1@mail.gmail.com> <46FB8826.6030507@tds.net> <5df213700709271240t59c3eb2cx318b0407fea998f1@mail.gmail.com> Message-ID: <46FC0910.1040700@tds.net> Aditya Lal wrote: > I will start working on psyco ... though not sure what is it ? Google is your friend. Kent From bhaaluu at gmail.com Thu Sep 27 21:50:59 2007 From: bhaaluu at gmail.com (bhaaluu) Date: Thu, 27 Sep 2007 15:50:59 -0400 Subject: [Tutor] how to convert array into tuple In-Reply-To: <46FBFF0E.1060209@tds.net> References: <4e7ea3b40709261011u1e0911dax926860a8aeaf446d@mail.gmail.com> <46FBF9F8.1000002@airtelbroadband.in> <46FBFF0E.1060209@tds.net> Message-ID: <ea979d70709271250h13a4e437wf656170d68a2456e@mail.gmail.com> Can you explain how this works? How would this be written in a "conventional" way? >>> foo = [1,2,3,4,5,6] >>> [(foo[i],foo[i+1]) for i in range(0,len(foo),2)] [(1, 2), (3, 4), (5, 6)] >>> foo = [1,2,3,4,5,6,7,8,9] >>> [(foo[i],foo[i+1]) for i in range(0,len(foo)-4,2)] [(1, 2), (3, 4), (5, 6)] Also, what kinds of ways might this be used? -- b h a a l u u at g m a i l dot c o m http://www.geocities.com/ek.bhaaluu/index.html On 9/27/07, Kent Johnson <kent37 at tds.net> wrote: > Noufal Ibrahim wrote: > > > This seems to work although I'd like comments from the more experienced > > Pythonistas out there. > > > > >>> foo > > [1, 2, 3, 4, 5, 6, 7, 8, 9] > > >>> [(foo[i],foo[i+1]) for i in range(0,len(foo)-2,2)] > > [(1, 2), (3, 4), (5, 6), (7, 8)] > > This problem is a perennial favorite on comp.lang.python and in the > cookbook, which I take to mean that there is no clear best solution. You > can see some alternatives here > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/425044 > > and in the links at the bottom of that page. > > One question is what to do with partial groups at the end; your version > truncates the original list. > > Kent > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From gtxy20 at gmail.com Thu Sep 27 23:09:45 2007 From: gtxy20 at gmail.com (GTXY20) Date: Thu, 27 Sep 2007 17:09:45 -0400 Subject: [Tutor] How to adjust a text file... Message-ID: <39cb7e5d0709271409if7b01edo988af0f35888fcf3@mail.gmail.com> Hi, I have a CSV file as follows: ID Products 1 a b c d 1 a e 2 a b c 2 a 3 b c 3 a 4 d 5 a d I am trying to write a script that will take the CSV file and output another text file as follows: ID Products 1 a 1 b 1 c 1 d 1 a 1 e etc.. for all of the ID's essentially I need to create a single instance for products for each ID - currently the products are separated by a space. I am thinking I need a for loop that will search on the space as a delimiter... -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070927/2de654d4/attachment.htm From witham.ian at gmail.com Thu Sep 27 23:31:26 2007 From: witham.ian at gmail.com (Ian Witham) Date: Fri, 28 Sep 2007 09:31:26 +1200 Subject: [Tutor] How to speed up input/string parsing ... In-Reply-To: <5df213700709271240t59c3eb2cx318b0407fea998f1@mail.gmail.com> References: <5df213700709270036p1a354dd9m9aeacb72b8caf9f1@mail.gmail.com> <46FB8826.6030507@tds.net> <5df213700709271240t59c3eb2cx318b0407fea998f1@mail.gmail.com> Message-ID: <a04dbf4b0709271431h5f36741bk5dba9e3dffb409e4@mail.gmail.com> Check the SPOJ Python forums, the process is explained there. It's all about adding two lines of code at the beginning of your script. But I can't recall which two. Ian. On 9/28/07, Aditya Lal <aditya.n.lal at gmail.com> wrote: > > Hello Kent, > I tried finding solution with using only strings but unfortunately > reversing a number has some interesting issues - For example: take following > two numbers - > 002000 002000 > > though the final answer is 4 - arriving at it using string is stripping > '0' from both left and right of both numbers. I thought it was far easier to > convert it into an integer and reverse. Anyway I wasn't aware of string > reversal shortcut - [::-1] ... thanx :) > > Following code performs in 0.50 seconds : > > import sys > > def rev(n) : > m = 0 > while n > 0 : > r = n%10 > m = m*10 + r > n = n/10 > return m > > def solve(line) : > nums = line.split (' ') > a = int(nums[0].strip('0')[::-1]) > b = int(nums[1].strip('0')[::-1]) > return rev( a + b ) > > if __name__ == '__main__' : > N = int(sys.stdin.readline()) > lines = sys.stdin.readlines() > for i in xrange(N) : > print solve(lines[i]) > > > I will start working on psyco ... though not sure what is it ? > > Thanks again Kent. > > Cheers > Aditya > > On 9/27/07, Kent Johnson < kent37 at tds.net> wrote: > > > > Aditya Lal wrote: > > > > > def rev(n) : > > > m = 0 > > > while n > 0 : > > > m = m*10 + n%10 > > > n = n/10 > > > return m > > > > I would try reversing the numbers as strings. s[::-1] will reverse a > > string s. > > > > > How do I improve the input reading or string parsing ? I know there > > > should be a better way because the best program (at cost of memory) > > > performs > 50% faster than mine. So he must have done something to > > > improve input processing. > > > > The programs that use a lot of memory are using psyco. > > > > Kent > > > > > > -- > Aditya > > _______________________________________________ > 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/20070928/76a7064d/attachment.htm From witham.ian at gmail.com Thu Sep 27 23:43:23 2007 From: witham.ian at gmail.com (Ian Witham) Date: Fri, 28 Sep 2007 09:43:23 +1200 Subject: [Tutor] How to adjust a text file... In-Reply-To: <39cb7e5d0709271409if7b01edo988af0f35888fcf3@mail.gmail.com> References: <39cb7e5d0709271409if7b01edo988af0f35888fcf3@mail.gmail.com> Message-ID: <a04dbf4b0709271443k3af07beek2add32a746d5e2e8@mail.gmail.com> > > > I am trying to write a script that will take the CSV file and output > another text file as follows: > > ID Products > 1 a > 1 b > 1 c > 1 d > 1 a > 1 e > > etc.. for all of the ID's essentially I need to create a single instance > for products for each ID - currently the products are separated by a space. > I am thinking I need a for loop that will search on the space as a > delimiter... > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > If your goal is to separate 'a b c d' using space as a delimiter, just use 'a b c d'.split() This returns ['a', 'b', 'c', 'd'] Ian. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070928/68e1054b/attachment.htm From witham.ian at gmail.com Fri Sep 28 00:17:04 2007 From: witham.ian at gmail.com (Ian Witham) Date: Fri, 28 Sep 2007 10:17:04 +1200 Subject: [Tutor] exec sintax error or bug? In-Reply-To: <46FBEF92.4050903@tds.net> References: <20070927174814.ej6t4ub00o44wo88@w6.mail.sapo.pt> <46FBEF92.4050903@tds.net> Message-ID: <a04dbf4b0709271517s67e16309rb165ac5150839400@mail.gmail.com> What version of Python arre you running Paulino? When I run your second snippet on 2.5 I get an error: >>> exp = "if i == 3 : continue" >>> for i in range(5): exec(exp) print i, Traceback (most recent call last): File "<pyshell#17>", line 2, in <module> exec(exp) File "<string>", line 1 SyntaxError: 'continue' not properly in loop (<string>, line 1) On 9/28/07, Kent Johnson <kent37 at tds.net> wrote: > > paulino1 at sapo.pt wrote: > > Hello! > > > > Why doesn't the second code snipet, work like the first? > > > >>>> for i in range(5): > > ... if i == 3 : continue > > ... print i, > > ... > > 0 1 2 4 > > > >>>> exp = "if i == 3 : continue" > >>>> for i in range(5): > > ... exec( exp ) > > ... print i, > > ... > > Traceback (most recent call last): > > File "<input>", line 2, in <module> > > File "<string>", line 1 > > SyntaxError: 'continue' not properly in loop (<string>, line 1) > > I think the code you pass to exec must be syntactically correct on its > own. It is parsed as if it were in a file by itself, then executed in > the local scope. > > 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/20070928/1b177358/attachment.htm From paulino1 at sapo.pt Fri Sep 28 01:14:44 2007 From: paulino1 at sapo.pt (paulino1 at sapo.pt) Date: Fri, 28 Sep 2007 00:14:44 +0100 Subject: [Tutor] exec sintax error or bug? In-Reply-To: <a04dbf4b0709271517s67e16309rb165ac5150839400@mail.gmail.com> References: <20070927174814.ej6t4ub00o44wo88@w6.mail.sapo.pt> <46FBEF92.4050903@tds.net> <a04dbf4b0709271517s67e16309rb165ac5150839400@mail.gmail.com> Message-ID: <20070928001444.cs8pakpysgcogw4o@w7.mail.sapo.pt> Citando Ian Witham <witham.ian at gmail.com>: > What version of Python arre you running Paulino? > > When I run your second snippet on 2.5 I get an error: > > >>> exp = "if i == 3 : continue" > >>> for i in range(5): > exec(exp) > print i, > > Traceback (most recent call last): > File "<pyshell#17>", line 2, in <module> > exec(exp) > File "<string>", line 1 > SyntaxError: 'continue' not properly in loop (<string>, line 1) > > On 9/28/07, KENT JOHNSON <kent37 at tds.net[1]> wrote: paulino1 at sapo.pt[2] wrote: > > Hello! > > > > Why doesn't the second code snipet, work like the first? > > > >>>> for i in range(5): > > ... if i == 3 : continue > > ... print i, > > ... > > 0 1 2 4 > > > >>>> exp = "if i == 3 : continue" > >>>> for i in range(5): > > ... exec( exp ) > > ... print i, > > ... > > Traceback (most recent call last): > > File "<input>", line 2, in <module> > > File "<string>", line 1 > > SyntaxError: 'continue' not properly in loop (<string>, line 1) > > I think the code you pass to exec must be syntactically correct on its > own. It is parsed as if it were in a file by itself, then executed in > the local scope. > > Kent > _______________________________________________ > Tutor maillist - Tutor at python.org[3] > http://mail.python.org/mailman/listinfo/tutor[4] That's my question, the second snippet returns an error... I have 2.5.1 also. Liga????es: --------- [1] mailto:kent37 at tds.net [2] mailto:paulino1 at sapo.pt [3] mailto:Tutor at python.org [4] http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070928/8f55a767/attachment-0001.htm From kent37 at tds.net Fri Sep 28 03:46:49 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 27 Sep 2007 21:46:49 -0400 Subject: [Tutor] How to adjust a text file... In-Reply-To: <39cb7e5d0709271409if7b01edo988af0f35888fcf3@mail.gmail.com> References: <39cb7e5d0709271409if7b01edo988af0f35888fcf3@mail.gmail.com> Message-ID: <46FC5D09.2090405@tds.net> GTXY20 wrote: > Hi, > > I have a CSV file as follows: > > ID Products > 1 a b c d > 1 a e > 2 a b c > 2 a > 3 b c > 3 a > 4 d > 5 a d > > I am trying to write a script that will take the CSV file and output > another text file as follows: > > ID Products > 1 a > 1 b > 1 c > 1 d > 1 a > 1 e > > etc.. for all of the ID's essentially I need to create a single instance > for products for each ID - currently the products are separated by a > space. I am thinking I need a for loop that will search on the space as > a delimiter... I should probably be teaching you to fish but tonight I have extra fish :-) If the products are single words then this is very simple. Something like inp = open('input.txt') out = open('output.txt') # Headers inp.next() out.write('ID\tProducts\n') for line in inp: fields = line.split() prodId = fields[0] products = fields[1:] for product in products: out.write('%s\t%s\n' % (prodId, product)) inp.close() out.close() If the product text is more complex then you might want to use the csv module to help read and write the file. BTW in Python 3 you can write prodId, *products = fields.split() http://www.python.org/dev/peps/pep-3132/ Kent From varsha.purohit at gmail.com Fri Sep 28 04:08:52 2007 From: varsha.purohit at gmail.com (Varsha Purohit) Date: Thu, 27 Sep 2007 19:08:52 -0700 Subject: [Tutor] [tutor]Help needed to read Ascii file in wxPython Message-ID: <c2157c790709271908j198b5a76u6030e3e71f5b5d3c@mail.gmail.com> Hello everyone, I need a basic tutorial which can help me in reading or writing ascii grid file.... thanks in advance, -- Varsha Purohit, Graduate Student, -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070927/21e2ab49/attachment.htm From kent37 at tds.net Fri Sep 28 04:21:21 2007 From: kent37 at tds.net (Kent Johnson) Date: Thu, 27 Sep 2007 22:21:21 -0400 Subject: [Tutor] [tutor]Help needed to read Ascii file in wxPython In-Reply-To: <c2157c790709271908j198b5a76u6030e3e71f5b5d3c@mail.gmail.com> References: <c2157c790709271908j198b5a76u6030e3e71f5b5d3c@mail.gmail.com> Message-ID: <46FC6521.3060902@tds.net> Varsha Purohit wrote: > Hello everyone, > I need a basic tutorial which can help me in reading or writing > ascii grid file.... What is an ascii grid file? Reading and writing text files should be covered in any Python tutorial, find one you like here: http://wiki.python.org/moin/BeginnersGuide/NonProgrammers Kent From varsha.purohit at gmail.com Fri Sep 28 04:36:00 2007 From: varsha.purohit at gmail.com (Varsha Purohit) Date: Thu, 27 Sep 2007 19:36:00 -0700 Subject: [Tutor] [tutor]Help needed to read Ascii file in wxPython In-Reply-To: <46FC6521.3060902@tds.net> References: <c2157c790709271908j198b5a76u6030e3e71f5b5d3c@mail.gmail.com> <46FC6521.3060902@tds.net> Message-ID: <c2157c790709271936n5327bd81u6a25a8569e15578d@mail.gmail.com> Hi Kent, I am writing a program basically in python gui to open a file and display its content. File contains ascii data... here is an example of that. a text file having info like this ncols 4 nrows 4 xllcorner 392800 yllcorner 5376340 cellsize 55 NODATA_value -9999 9 3 7 3 8 3 2 7 3 2 1 3 3 7 3 2 it has predefined rows and colns... i know similar program in simple python but wanna figure out how to do that in wxpython... thanks, Varsha On 9/27/07, Kent Johnson <kent37 at tds.net> wrote: > > Varsha Purohit wrote: > > Hello everyone, > > I need a basic tutorial which can help me in reading or writing > > ascii grid file.... > > What is an ascii grid file? Reading and writing text files should be > covered in any Python tutorial, find one you like here: > http://wiki.python.org/moin/BeginnersGuide/NonProgrammers > > Kent > -- Varsha Purohit, Graduate Student, San Diego State University -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070927/5ca68bf9/attachment.htm From mlangford.cs03 at gtalumni.org Fri Sep 28 05:45:56 2007 From: mlangford.cs03 at gtalumni.org (Michael Langford) Date: Thu, 27 Sep 2007 23:45:56 -0400 Subject: [Tutor] [tutor]Help needed to read Ascii file in wxPython In-Reply-To: <c2157c790709271936n5327bd81u6a25a8569e15578d@mail.gmail.com> References: <c2157c790709271908j198b5a76u6030e3e71f5b5d3c@mail.gmail.com> <46FC6521.3060902@tds.net> <c2157c790709271936n5327bd81u6a25a8569e15578d@mail.gmail.com> Message-ID: <82b4f5810709272045y37f06987j75c6c92c4194b9b4@mail.gmail.com> While I would say wxPython in its fullblown glory is a little much for this mailing list, an easy to use toolkit and associated tutorials for it is not. I would suggest you use pythoncard, which is a toolkit that calls down to wxPython and is much faster to get going with: This will get you up and running in a couple minutes. http://pythoncard.sourceforge.net/walkthrough1.html Run some of the example programs (they're in a subdirectory of your python folder, like the tutorial says). Their source code will lead you to an appropriate sort of file editor. --Michael -- Michael Langford Phone: 404-386-0495 Consulting: http://www.TierOneDesign.com/ Entertaining: http://www.ThisIsYourCruiseDirectorSpeaking.com On 9/27/07, Varsha Purohit <varsha.purohit at gmail.com> wrote: > Hi Kent, > > I am writing a program basically in python gui to open a file and display > its content. File contains ascii data... here is an example of that. > a text file having info like this > > ncols 4 > nrows 4 > xllcorner 392800 > yllcorner 5376340 > cellsize 55 > NODATA_value -9999 > 9 3 7 3 > 8 3 2 7 > 3 2 1 3 > 3 7 3 2 > > it has predefined rows and colns... i know similar program in simple python > but wanna figure out how to do that in wxpython... > > thanks, > Varsha > > > On 9/27/07, Kent Johnson <kent37 at tds.net> wrote: > > Varsha Purohit wrote: > > > Hello everyone, > > > I need a basic tutorial which can help me in reading or writing > > > ascii grid file.... > > > > What is an ascii grid file? Reading and writing text files should be > > covered in any Python tutorial, find one you like here: > > http://wiki.python.org/moin/BeginnersGuide/NonProgrammers > > > > Kent > > > > > > -- > Varsha Purohit, > Graduate Student, > San Diego State University > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From cspears2002 at yahoo.com Fri Sep 28 05:54:26 2007 From: cspears2002 at yahoo.com (Christopher Spears) Date: Thu, 27 Sep 2007 20:54:26 -0700 (PDT) Subject: [Tutor] case insensitivity Message-ID: <207025.62525.qm@web51605.mail.re2.yahoo.com> I wrote a script that checks if two strings match. The script ignores case. #!/usr/bin/env python string_a = raw_input("Enter a string: ") string_b = raw_input("Enter another string: ") if cmp(string_a.lower(), string_b.lower()) == 0: print "The strings match!" else: print "The strings don't match!" Is this the best way to implement case insensitivity? "I'm the last person to pretend that I'm a radio. I'd rather go out and be a color television set." -David Bowie "Who dares wins" -British military motto "I generally know what I'm doing." -Buster Keaton From wesbrooks at gmail.com Fri Sep 28 11:27:58 2007 From: wesbrooks at gmail.com (Wesley Brooks) Date: Fri, 28 Sep 2007 10:27:58 +0100 Subject: [Tutor] Atomic file creation? Message-ID: <eec9f8ee0709280227k2f3b4029j71ca24da263b1c93@mail.gmail.com> Dear Users, I'm looking for an atomic method for creating a file on the hard disk from python. Currently I'm using; def (command): """Creates a file with the name given by command.""" comFile = open(comFileName, 'w') comFile.close() This is not atomic as there are two operations needed to create this file. If the process was disturbed between these two files another process may not be able to read and delete the file (just reading the file name) as the above process may still hold it open. I realise I could do: import os def (command, tempDir='tempFiles', targetDir='commandDirectory'): """Creates a file with the name given by command in a temporary directory then moves it over to a target directory.""" tempName = os.path.join(tempDir,comFileName) finalName = os.path.join(targetDir,comFileName) comFile = open(tempName, 'w') comFile.close() os.rename(tempName, finalName) This is now atomic as far as anything watching targetDir is concerned. In other words as soon as it can be seen in the directory it is safe to be read and destroyed with out having to worry about another process not having closed the file for what ever reason. I do have two problems with this though; 1. This may fail under windows if another file already exists with this file name in the target directory. I always try to get my code working on Linux and windows, this leaves my code more robust and interestingly sometimes the Linux interpreter picks up different errors than the windows interpreter and visa versa. 2. It doesn't look very nice! I'm assuming there must be something in python to create a and release a file on the system in one line of code? Thank in advance of any help. Cheers, Wesley Brooks. From kent37 at tds.net Fri Sep 28 14:07:59 2007 From: kent37 at tds.net (Kent Johnson) Date: Fri, 28 Sep 2007 08:07:59 -0400 Subject: [Tutor] case insensitivity In-Reply-To: <207025.62525.qm@web51605.mail.re2.yahoo.com> References: <207025.62525.qm@web51605.mail.re2.yahoo.com> Message-ID: <46FCEE9F.6060807@tds.net> Christopher Spears wrote: > I wrote a script that checks if two strings match. > The script ignores case. > > #!/usr/bin/env python > > string_a = raw_input("Enter a string: ") > string_b = raw_input("Enter another string: ") > > if cmp(string_a.lower(), string_b.lower()) == 0: if string_a.lower() == string_b.lower(): > Is this the best way to implement case insensitivity? As far as I know. Kent From kent37 at tds.net Fri Sep 28 14:25:04 2007 From: kent37 at tds.net (Kent Johnson) Date: Fri, 28 Sep 2007 08:25:04 -0400 Subject: [Tutor] [tutor]Help needed to read Ascii file in wxPython In-Reply-To: <c2157c790709271936n5327bd81u6a25a8569e15578d@mail.gmail.com> References: <c2157c790709271908j198b5a76u6030e3e71f5b5d3c@mail.gmail.com> <46FC6521.3060902@tds.net> <c2157c790709271936n5327bd81u6a25a8569e15578d@mail.gmail.com> Message-ID: <46FCF2A0.7020606@tds.net> Varsha Purohit wrote: > I am writing a program basically in python gui to open a file and > display its content. i know similar program in simple > python but wanna figure out how to do that in wxpython... See DocViewDemo.py in the wxPythohn demo package /Samples/samples/docview/DocViewDemo.py Kent From thorsten at thorstenkampe.de Fri Sep 28 15:09:24 2007 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Fri, 28 Sep 2007 14:09:24 +0100 Subject: [Tutor] New to Python and Linux References: <4febe39e0709252307j651009e8m51a5667367491f16@mail.gmail.com> Message-ID: <fdiue5$unc$1@sea.gmane.org> * Armand Nell (Wed, 26 Sep 2007 08:07:12 +0200) > I am new to python programming and also the linux enviroment most of my > skills are windows based and programming skills is visual basics. I decided > that it would be a great start and new direction for me to learn python and > at the same time linux. However I have already run into a wall, and any help > would be appreciated even if you can direct me where to find the info or > 'turor'. > [...] > In windows, if i write a program in Python and save it I then can simply > double click the icon and the program will execute in a console window. Now > under Fedoracore I write my program in gedit save it in my > \home\(username)\python directory, when I double click it, it opens up agian > in gedit. Now true it is maybe a simple error from me but mostly it is me > that don't know how to work with python on linux. > > I would like to know how do I test(run) the programs I write under > fedoracore? It's exactly the same as with with Visual Basic ("visual basics? Are you sure you have experience in that language?") and Windows: run it in a command window (like "python myscript.py") or associate the file type (.py) with the program. How you do that depends on your desktop environment (KDE or Gnome probably) but it shouldn't take you more than ten seconds to find out how to do it. Thorsten From jtp at nc.rr.com Fri Sep 28 16:02:46 2007 From: jtp at nc.rr.com (James) Date: Fri, 28 Sep 2007 10:02:46 -0400 Subject: [Tutor] Replacing "source" in Bash Scripting Message-ID: <1787D69C-A97C-41FB-9927-CCF5B28B9560@nc.rr.com> Hi. I'm re-writing a rather complex bash script I've been using for years in Python. The bash script uses a relatively simple configuration file in order to get pertinent information before it runs. The configuration file is relatively simple: about 30 variables are defined in this manner in the config file: VARNAME=value In the bash script I simply "source" this configuration file and the script runs merrily using those variables defined in the configuration file. i.e., "source configFile" I'm trying to implement similar behavior in a Python script, specifically having a configuration file (with a list of variables and their values defined) that my Python program will read once running. I'm not really sure what the best way to implement this is. Ideas? Thanks! .james From mlangford.cs03 at gtalumni.org Fri Sep 28 16:07:38 2007 From: mlangford.cs03 at gtalumni.org (Michael Langford) Date: Fri, 28 Sep 2007 10:07:38 -0400 Subject: [Tutor] Atomic file creation? In-Reply-To: <82b4f5810709280707q70700441o9dda9a0c691c8b5@mail.gmail.com> References: <eec9f8ee0709280227k2f3b4029j71ca24da263b1c93@mail.gmail.com> <82b4f5810709280707q70700441o9dda9a0c691c8b5@mail.gmail.com> Message-ID: <82b4f5810709280707g79fe8223qe97075c7e94b2826@mail.gmail.com> "1. This may fail under windows if another file already exists with this file name in the target directory. I always try to get my code working on Linux and windows, this leaves my code more robust and interestingly sometimes the Linux interpreter picks up different errors than the windows interpreter and visa versa." I'd check to see if the destination file exists before doing all of the above. I think your method is fine. Atomic file creation is not a common worry. I think this is a wholly reasonable quantity of code to pull it off. --Michael On 9/28/07, Wesley Brooks <wesbrooks at gmail.com> wrote: > Dear Users, > > I'm looking for an atomic method for creating a file on the hard disk > from python. > > Currently I'm using; > > def (command): > """Creates a file with the name given by command.""" > comFile = open(comFileName, 'w') > comFile.close() > > This is not atomic as there are two operations needed to create this > file. If the process was disturbed between these two files another > process may not be able to read and delete the file (just reading the > file name) as the above process may still hold it open. > > I realise I could do: > > import os > > def (command, tempDir='tempFiles', targetDir='commandDirectory'): > """Creates a file with the name given by command in a temporary > directory then moves it over to a target directory.""" > tempName = os.path.join(tempDir,comFileName) > finalName = os.path.join(targetDir,comFileName) > comFile = open(tempName, 'w') > comFile.close() > os.rename(tempName, finalName) > > This is now atomic as far as anything watching targetDir is concerned. > In other words as soon as it can be seen in the directory it is safe > to be read and destroyed with out having to worry about another > process not having closed the file for what ever reason. > > I do have two problems with this though; > > 1. This may fail under windows if another file already exists with > this file name in the target directory. I always try to get my code > working on Linux and windows, this leaves my code more robust and > interestingly sometimes the Linux interpreter picks up different > errors than the windows interpreter and visa versa. > > 2. It doesn't look very nice! I'm assuming there must be something in > python to create a and release a file on the system in one line of > code? > > Thank in advance of any help. > > Cheers, > > Wesley Brooks. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Michael Langford Phone: 404-386-0495 Consulting: http://www.TierOneDesign.com/ Entertaining: http://www.ThisIsYourCruiseDirectorSpeaking.com -- Michael Langford Phone: 404-386-0495 Consulting: http://www.TierOneDesign.com/ Entertaining: http://www.ThisIsYourCruiseDirectorSpeaking.com From bgailer at alum.rpi.edu Fri Sep 28 16:13:48 2007 From: bgailer at alum.rpi.edu (bob gailer) Date: Fri, 28 Sep 2007 10:13:48 -0400 Subject: [Tutor] case insensitivity In-Reply-To: <207025.62525.qm@web51605.mail.re2.yahoo.com> References: <207025.62525.qm@web51605.mail.re2.yahoo.com> Message-ID: <46FD0C1C.1080608@alum.rpi.edu> Christopher Spears wrote: > I wrote a script that checks if two strings match. > The script ignores case. > > #!/usr/bin/env python > > string_a = raw_input("Enter a string: ") > string_b = raw_input("Enter another string: ") > > if cmp(string_a.lower(), string_b.lower()) == 0: > Simpler: if string_a.lower() == string_b.lower(): > print "The strings match!" > else: > print "The strings don't match!" > > Is this the best way to implement case insensitivity? Or if you are seeking ultimate terseness: print "The strings " + ("don't", "")[string_a.lower() == string_b.lower()] + " match!" From bgailer at alum.rpi.edu Fri Sep 28 16:19:48 2007 From: bgailer at alum.rpi.edu (bob gailer) Date: Fri, 28 Sep 2007 10:19:48 -0400 Subject: [Tutor] Replacing "source" in Bash Scripting In-Reply-To: <1787D69C-A97C-41FB-9927-CCF5B28B9560@nc.rr.com> References: <1787D69C-A97C-41FB-9927-CCF5B28B9560@nc.rr.com> Message-ID: <46FD0D84.7070208@alum.rpi.edu> James wrote: > Hi. > > I'm re-writing a rather complex bash script I've been using for years > in Python. The bash script uses a relatively simple configuration > file in order to get pertinent information before it runs. The > configuration file is relatively simple: about 30 variables are > defined in this manner in the config file: > > VARNAME=value > > In the bash script I simply "source" this configuration file and the > script runs merrily using those variables defined in the > configuration file. i.e., > > "source configFile" > > I'm trying to implement similar behavior in a Python script, > specifically having a configuration file (with a list of variables > and their values defined) that my Python program will read once > running. I'm not really sure what the best way to implement this is. > > Ideas? > The simplest, IMHO, is: create and import a module (e.g. config.py) with a series of assignments: VARNAME1='value1' VARNAME2='value2' In the script: from config import * There are also a number of modules in the Python library for doing more complex config file manipulation. From kent37 at tds.net Fri Sep 28 16:23:39 2007 From: kent37 at tds.net (Kent Johnson) Date: Fri, 28 Sep 2007 10:23:39 -0400 Subject: [Tutor] Replacing "source" in Bash Scripting In-Reply-To: <1787D69C-A97C-41FB-9927-CCF5B28B9560@nc.rr.com> References: <1787D69C-A97C-41FB-9927-CCF5B28B9560@nc.rr.com> Message-ID: <46FD0E6B.5080303@tds.net> James wrote: > Hi. > > I'm re-writing a rather complex bash script I've been using for years > in Python. The bash script uses a relatively simple configuration > file in order to get pertinent information before it runs. The > configuration file is relatively simple: about 30 variables are > defined in this manner in the config file: > > VARNAME=value > > In the bash script I simply "source" this configuration file and the > script runs merrily using those variables defined in the > configuration file. i.e., > > "source configFile" > > I'm trying to implement similar behavior in a Python script, > specifically having a configuration file (with a list of variables > and their values defined) that my Python program will read once > running. I'm not really sure what the best way to implement this is. Write configFile as a Python source file, then import configFile print configFile.VARNAME or whatever you want to do with VARNAME If configFile.VARNAME is too wordy for you you can import configFile as cf print cf.VARNAME or from configFile import VARNAME print VARNAME or (*not* recommended, it obscures your code and risks importing more than you want) from configFile import * print VARNAME You can also use .ini file format and the ConfigParser module if you prefer. Kent From jtp at nc.rr.com Fri Sep 28 16:29:07 2007 From: jtp at nc.rr.com (James) Date: Fri, 28 Sep 2007 10:29:07 -0400 Subject: [Tutor] for vs while Message-ID: <2AE92A68-8622-46F8-9ACB-08CE28519339@nc.rr.com> All, I have a dumb question...hopefully someone can shed some light on the difference between for and while in the situation below. I'm trying to iterate through a list I've created. The list consists of a command, followed by a 'logging' message (a message printed to a console or log file after the command is run). Here's a small snippet of code: # a list which includes (1) a command, and (2) something to be dumped into a log file after the command runs stuff = [ ["cat /etc/password"] , ["viewed /etc/password"] ] #works i = 0 ; j = 1 while i < len( stuff ): os.system( str( stuff[ i ] ) ) print stuff[ j ] i += 1 ; j += 1 The while loop does precisely what it should do: it runs the first command using os.system(), and then prints out the string in the second position of the list. Then I tried to do the same thing with a for loop that looks logically equivalent. I replaced the while loop with this for loop: # doesn't work for i in len( stuff ): os.system( stuff[ i ] ) j = i + 1 print stuff[ j ] Python doesn't like it, though. It gives me the following error: Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'int' object is not iterable What precisely causes this error? I come from a C background, and while and for loops can be molded to do precisely the same thing; it doesn't seem like this is the case in this scenario. Thoughts/ideas appreciated. :) Thanks! .james From thorsten at thorstenkampe.de Fri Sep 28 16:20:27 2007 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Fri, 28 Sep 2007 15:20:27 +0100 Subject: [Tutor] New to Python and Linux References: <4febe39e0709252307j651009e8m51a5667367491f16@mail.gmail.com> <fdiue5$unc$1@sea.gmane.org> Message-ID: <fdj2je$unc$2@sea.gmane.org> * Thorsten Kampe (Fri, 28 Sep 2007 14:09:24 +0100) > It's exactly the same as with with Visual Basic [...] Guess I mixed that up with VBScript... From bgailer at alum.rpi.edu Fri Sep 28 16:59:40 2007 From: bgailer at alum.rpi.edu (bob gailer) Date: Fri, 28 Sep 2007 10:59:40 -0400 Subject: [Tutor] for vs while In-Reply-To: <2AE92A68-8622-46F8-9ACB-08CE28519339@nc.rr.com> References: <2AE92A68-8622-46F8-9ACB-08CE28519339@nc.rr.com> Message-ID: <46FD16DC.6070500@alum.rpi.edu> James wrote: > All, > > I have a dumb question...hopefully someone can shed some light on the > difference between for and while in the situation below. > > I'm trying to iterate through a list I've created. The list consists > of a command, followed by a 'logging' message (a message printed to a > console or log file after the command is run). > > Here's a small snippet of code: > > # a list which includes (1) a command, and (2) something to be > dumped into a log file after the command runs > stuff = [ ["cat /etc/password"] , ["viewed /etc/password"] ] > > #works > i = 0 ; j = 1 > while i < len( stuff ): > os.system( str( stuff[ i ] ) ) > print stuff[ j ] > i += 1 ; j += 1 > > The while loop does precisely what it should do: it runs the first > command using os.system(), and then prints out the string in the > second position of the list. > > Then I tried to do the same thing with a for loop that looks > logically equivalent. I replaced the while loop with this for loop: > > # doesn't work > for i in len( stuff ): > Try this: > for i in range(len(stuff)): > > > > os.system( stuff[ i ] ) > j = i + 1 > print stuff[ j ] > > Python doesn't like it, though. It gives me the following error: > > Traceback (most recent call last): > File "<stdin>", line 1, in <module> > TypeError: 'int' object is not iterable > > What precisely causes this error? I come from a C background, and > while and for loops can be molded to do precisely the same thing; it > doesn't seem like this is the case in this scenario. > > Thoughts/ideas appreciated. :) > for expects, as the error says, an "iterable". range() provides an iterable. len() just gives an integer. BTW I find it very hard to read code where there are spaces next to () and []. From taserian at gmail.com Fri Sep 28 17:06:12 2007 From: taserian at gmail.com (taserian) Date: Fri, 28 Sep 2007 11:06:12 -0400 Subject: [Tutor] for vs while In-Reply-To: <2AE92A68-8622-46F8-9ACB-08CE28519339@nc.rr.com> References: <2AE92A68-8622-46F8-9ACB-08CE28519339@nc.rr.com> Message-ID: <70dbc4d40709280806t119326c1ma26bc47cc405fd32@mail.gmail.com> On 9/28/07, James <jtp at nc.rr.com> wrote: > > All, > > I have a dumb question...hopefully someone can shed some light on the > difference between for and while in the situation below. > > I'm trying to iterate through a list I've created. The list consists > of a command, followed by a 'logging' message (a message printed to a > console or log file after the command is run). > > Here's a small snippet of code: > > # a list which includes (1) a command, and (2) something to be > dumped into a log file after the command runs > stuff = [ ["cat /etc/password"] , ["viewed /etc/password"] ] > > #works > i = 0 ; j = 1 > while i < len( stuff ): > os.system( str( stuff[ i ] ) ) > print stuff[ j ] > i += 1 ; j += 1 Here you're basing yourself off of the index of the item in the list, so stuff[0], stuff[1], etc. The while loop does precisely what it should do: it runs the first > command using os.system(), and then prints out the string in the > second position of the list. > > Then I tried to do the same thing with a for loop that looks > logically equivalent. I replaced the while loop with this for loop: > > # doesn't work > for i in len( stuff ): > os.system( stuff[ i ] ) > j = i + 1 > print stuff[ j ] Here, you're using *for* in a non-Pythonic way. You mean to use i as an iterator, but len( stuff ) is a simple integer. You could do it this way: for i in range( len(stuff)): os.system( stuff[i] ) j = i + 1 print stuff[ j ] turning the single integer into a range of integers that you can iterate over. Tony R. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070928/0fbdc6c1/attachment.htm From jtp at nc.rr.com Fri Sep 28 17:08:41 2007 From: jtp at nc.rr.com (James) Date: Fri, 28 Sep 2007 11:08:41 -0400 Subject: [Tutor] for vs while In-Reply-To: <46FD16DC.6070500@alum.rpi.edu> References: <2AE92A68-8622-46F8-9ACB-08CE28519339@nc.rr.com> <46FD16DC.6070500@alum.rpi.edu> Message-ID: <1329AA34-C647-4039-A787-E88507A4FB1E@nc.rr.com> On Sep 28, 2007, at 10:59 AM, bob gailer wrote: > James wrote: >> All, >> >> I have a dumb question...hopefully someone can shed some light on >> the difference between for and while in the situation below. >> >> I'm trying to iterate through a list I've created. The list >> consists of a command, followed by a 'logging' message (a message >> printed to a console or log file after the command is run). >> >> Here's a small snippet of code: >> >> # a list which includes (1) a command, and (2) something to be >> dumped into a log file after the command runs >> stuff = [ ["cat /etc/password"] , ["viewed /etc/password"] ] >> >> #works >> i = 0 ; j = 1 >> while i < len( stuff ): >> os.system( str( stuff[ i ] ) ) >> print stuff[ j ] >> i += 1 ; j += 1 >> >> The while loop does precisely what it should do: it runs the >> first command using os.system(), and then prints out the string >> in the second position of the list. >> >> Then I tried to do the same thing with a for loop that looks >> logically equivalent. I replaced the while loop with this for loop: >> >> # doesn't work >> for i in len( stuff ): >> > Try this: >> for i in range(len(stuff)): >> >> >> os.system( stuff[ i ] ) >> j = i + 1 >> print stuff[ j ] >> >> Python doesn't like it, though. It gives me the following error: >> >> Traceback (most recent call last): >> File "<stdin>", line 1, in <module> >> TypeError: 'int' object is not iterable >> >> What precisely causes this error? I come from a C background, >> and while and for loops can be molded to do precisely the same >> thing; it doesn't seem like this is the case in this scenario. >> >> Thoughts/ideas appreciated. :) >> > for expects, as the error says, an "iterable". range() provides an > iterable. len() just gives an integer. Great! I was under the impression that the range was implied, but I guess not. ;) > BTW I find it very hard to read code where there are spaces next to > () and []. I find it difficult to read code where there *aren't* spaces next to the () and [] and there are several parenthesis/brackets next to each other. :) Personal preference. Thanks again. From kent37 at tds.net Fri Sep 28 17:14:48 2007 From: kent37 at tds.net (Kent Johnson) Date: Fri, 28 Sep 2007 11:14:48 -0400 Subject: [Tutor] for vs while In-Reply-To: <2AE92A68-8622-46F8-9ACB-08CE28519339@nc.rr.com> References: <2AE92A68-8622-46F8-9ACB-08CE28519339@nc.rr.com> Message-ID: <46FD1A68.4000503@tds.net> James wrote: > All, > > I have a dumb question...hopefully someone can shed some light on the > difference between for and while in the situation below. > > I'm trying to iterate through a list I've created. The list consists > of a command, followed by a 'logging' message (a message printed to a > console or log file after the command is run). > > Here's a small snippet of code: > > # a list which includes (1) a command, and (2) something to be > dumped into a log file after the command runs > stuff = [ ["cat /etc/password"] , ["viewed /etc/password"] ] > > #works > i = 0 ; j = 1 > while i < len( stuff ): > os.system( str( stuff[ i ] ) ) > print stuff[ j ] > i += 1 ; j += 1 > > The while loop does precisely what it should do: it runs the first > command using os.system(), and then prints out the string in the > second position of the list. Are you sure? When I run this I get sh: line 1: [cat /etc/password]: No such file or directory ['viewed /etc/password'] sh: line 1: [viewed /etc/password]: No such file or directory and then an IndexError. It is calling os.system() on the string representation of a list, and it should increment i and j by 2 each time through the loop. Here is a version that works for me: stuff = [ "cat /etc/password" , "viewed /etc/password" ] #works i = 0 while i < len( stuff ): os.system( str( stuff[ i ] ) ) print stuff[ i+1 ] i += 2 > Then I tried to do the same thing with a for loop that looks > logically equivalent. I replaced the while loop with this for loop: > > # doesn't work > for i in len( stuff ): > os.system( stuff[ i ] ) > j = i + 1 > print stuff[ j ] > > Python doesn't like it, though. It gives me the following error: > > Traceback (most recent call last): > File "<stdin>", line 1, in <module> > TypeError: 'int' object is not iterable > > What precisely causes this error? I come from a C background, and > while and for loops can be molded to do precisely the same thing; it > doesn't seem like this is the case in this scenario. Right. Python for loops are not like anything in C. They iterate over the values of a sequence. The thing after 'in' has to be an instance of a sequence such as a list or tuple, not an integer. (Technically it has to be an instance of an iterable but I don't want to confuse the issue.) The way I would write this program would be to make 'stuff' a list of pairs, where each pair contains a command and the value to print: # Note the parentheses which define a tuple stuff = [ ("cat /etc/password" , "viewed /etc/password") ] # The for statement assigns the elements of each tuple to cmd and echo for cmd, echo in stuff: os.system(cmd) print echo It's worth your time learning about Python data structures and for loops. They are very powerful and useful and unlike anything built-in to C. With a background in C you should find the official tutorial pretty easy to read: http://docs.python.org/tut/tut.html Kent From std3rr at gmail.com Fri Sep 28 17:13:18 2007 From: std3rr at gmail.com (Joshua Simpson) Date: Fri, 28 Sep 2007 08:13:18 -0700 Subject: [Tutor] for vs while In-Reply-To: <2AE92A68-8622-46F8-9ACB-08CE28519339@nc.rr.com> References: <2AE92A68-8622-46F8-9ACB-08CE28519339@nc.rr.com> Message-ID: <3ed9caa10709280813k517da99eqb3d3977077af895e@mail.gmail.com> On 9/28/07, James <jtp at nc.rr.com> wrote: > > > # doesn't work > for i in len( stuff ): > os.system( stuff[ i ] ) > j = i + 1 > print stuff[ j ] > > > Traceback (most recent call last): > File "<stdin>", line 1, in <module> > TypeError: 'int' object is not iterable > > What precisely causes this error? I come from a C background, and > while and for loops can be molded to do precisely the same thing; it > doesn't seem like this is the case in this scenario. You don't want to iterate through the length of the object (stuff), you want to iterate through the object itself. for i, j in stuff: os.system(i) print j and stuff would look like: stuff = [("cat /etc/passwd", "viewed /etc/passwd")] insert the pairs in tuples, rather than a list. cheers Josh -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070928/e249843f/attachment.htm From std3rr at gmail.com Fri Sep 28 17:21:10 2007 From: std3rr at gmail.com (Joshua Simpson) Date: Fri, 28 Sep 2007 08:21:10 -0700 Subject: [Tutor] for vs while In-Reply-To: <46FD1A68.4000503@tds.net> References: <2AE92A68-8622-46F8-9ACB-08CE28519339@nc.rr.com> <46FD1A68.4000503@tds.net> Message-ID: <3ed9caa10709280821q5239d920mee7a8afc6d12c5b@mail.gmail.com> On 9/28/07, Kent Johnson <kent37 at tds.net> wrote: > > > It's worth your time learning about Python data structures and for > loops. They are very powerful and useful and unlike anything built-in to > C. With a background in C you should find the official tutorial pretty > easy to read: > http://docs.python.org/tut/tut.html I found Dive Into Python (http://www.diveintopython.org) helpful as well coming from a primarily C background. cheers Josh -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070928/3d170045/attachment.htm From kent37 at tds.net Fri Sep 28 17:25:31 2007 From: kent37 at tds.net (Kent Johnson) Date: Fri, 28 Sep 2007 11:25:31 -0400 Subject: [Tutor] for vs while In-Reply-To: <1329AA34-C647-4039-A787-E88507A4FB1E@nc.rr.com> References: <2AE92A68-8622-46F8-9ACB-08CE28519339@nc.rr.com> <46FD16DC.6070500@alum.rpi.edu> <1329AA34-C647-4039-A787-E88507A4FB1E@nc.rr.com> Message-ID: <46FD1CEB.6090605@tds.net> James wrote: > Great! I was under the impression that the range was implied, but I > guess not. ;) No. One of the core Python values is "Explicit is better than implicit." If you like implicit behaviour, try Perl ;-) Type 'import this' at the Python prompt for more... Kent From jtp at nc.rr.com Fri Sep 28 17:49:39 2007 From: jtp at nc.rr.com (James) Date: Fri, 28 Sep 2007 11:49:39 -0400 Subject: [Tutor] for vs while In-Reply-To: <46FD1CEB.6090605@tds.net> References: <2AE92A68-8622-46F8-9ACB-08CE28519339@nc.rr.com> <46FD16DC.6070500@alum.rpi.edu> <1329AA34-C647-4039-A787-E88507A4FB1E@nc.rr.com> <46FD1CEB.6090605@tds.net> Message-ID: <4A77D97C-84DD-4CA8-AF49-D696EA932486@nc.rr.com> I shiver at the thought of Perl. ;) Thanks to everyone for your quick and helpful responses! .james On Sep 28, 2007, at 11:25 AM, Kent Johnson wrote: > James wrote: >> Great! I was under the impression that the range was implied, but >> I guess not. ;) > > No. One of the core Python values is "Explicit is better than > implicit." If you like implicit behaviour, try Perl ;-) > > Type 'import this' at the Python prompt for more... > > Kent From andreas at kostyrka.org Fri Sep 28 18:01:09 2007 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Fri, 28 Sep 2007 18:01:09 +0200 Subject: [Tutor] for vs while In-Reply-To: <2AE92A68-8622-46F8-9ACB-08CE28519339@nc.rr.com> References: <2AE92A68-8622-46F8-9ACB-08CE28519339@nc.rr.com> Message-ID: <46FD2545.10904@kostyrka.org> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Try: for item in stuff: os.system(item[0]) print item[1] Alternativly: for cmd, msg in stuff: os.system(cmd) print msg Andreas James wrote: > All, > > I have a dumb question...hopefully someone can shed some light on the > difference between for and while in the situation below. > > I'm trying to iterate through a list I've created. The list consists > of a command, followed by a 'logging' message (a message printed to a > console or log file after the command is run). > > Here's a small snippet of code: > > # a list which includes (1) a command, and (2) something to be > dumped into a log file after the command runs > stuff = [ ["cat /etc/password"] , ["viewed /etc/password"] ] > > #works > i = 0 ; j = 1 > while i < len( stuff ): > os.system( str( stuff[ i ] ) ) > print stuff[ j ] > i += 1 ; j += 1 > > The while loop does precisely what it should do: it runs the first > command using os.system(), and then prints out the string in the > second position of the list. > > Then I tried to do the same thing with a for loop that looks > logically equivalent. I replaced the while loop with this for loop: > > # doesn't work > for i in len( stuff ): > os.system( stuff[ i ] ) > j = i + 1 > print stuff[ j ] > > Python doesn't like it, though. It gives me the following error: > > Traceback (most recent call last): > File "<stdin>", line 1, in <module> > TypeError: 'int' object is not iterable > > What precisely causes this error? I come from a C background, and > while and for loops can be molded to do precisely the same thing; it > doesn't seem like this is the case in this scenario. > > Thoughts/ideas appreciated. :) > > Thanks! > .james > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.2 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFG/SVFHJdudm4KnO0RAhvcAKCKaySj7gnZEJv1Gbhy4ePmynW36wCg6lK5 CTCcgUE8AY83tVmRS+8VDDI= =aPMB -----END PGP SIGNATURE----- From kent37 at tds.net Fri Sep 28 19:26:24 2007 From: kent37 at tds.net (Kent Johnson) Date: Fri, 28 Sep 2007 13:26:24 -0400 Subject: [Tutor] How to adjust a text file... In-Reply-To: <39cb7e5d0709281012w1fc514cft86c8f270e805ce01@mail.gmail.com> References: <39cb7e5d0709271409if7b01edo988af0f35888fcf3@mail.gmail.com> <46FC5D09.2090405@tds.net> <39cb7e5d0709271910g1c1f48c8md1604f9381e8311a@mail.gmail.com> <39cb7e5d0709281012w1fc514cft86c8f270e805ce01@mail.gmail.com> Message-ID: <46FD3940.1070908@tds.net> GTXY20 wrote: > Hi There, > > For some reason I am getting no results and if I alter the code to relect: > > > inp = open('input.txt') > > for line in inp: > fields = line.split(",") > ProdId = fields[0] > products = fields[1:] > for product in products: > print('%s\t%s\n' % (ProdId, Product)) Names are case-sensitive in Python; product and Product are not the same. > > I am left with an error indicating that product is not defined In the future when you get an error, please copy and paste the entire error message, including the traceback, into your email. Also, please use Reply All to reply to the list. Kent From noufal at airtelbroadband.in Fri Sep 28 19:35:52 2007 From: noufal at airtelbroadband.in (Noufal Ibrahim) Date: Fri, 28 Sep 2007 23:05:52 +0530 Subject: [Tutor] how to convert array into tuple In-Reply-To: <ea979d70709271250h13a4e437wf656170d68a2456e@mail.gmail.com> References: <4e7ea3b40709261011u1e0911dax926860a8aeaf446d@mail.gmail.com> <46FBF9F8.1000002@airtelbroadband.in> <46FBFF0E.1060209@tds.net> <ea979d70709271250h13a4e437wf656170d68a2456e@mail.gmail.com> Message-ID: <46FD3B78.4090502@airtelbroadband.in> bhaaluu wrote: > Can you explain how this works? How would this be written in > a "conventional" way? I'm not sure if this is addressed to me but I'll reply anyway. :) >>>> foo = [1,2,3,4,5,6] >>>> [(foo[i],foo[i+1]) for i in range(0,len(foo),2)] range(0,len(foo)) would create a list of consecutive numbers starting from the first argument (0) till (but not including) the last (len(foo)) This will run as range(0,6) and will return [0,1,2,3,4,5] The 2 as the third argument to range specifies the increment (common difference of the arithmetic progression). So if you say range(0,10,2), you'd get [0,2,4,6,8]. If you say range(0,10,3), you'd get [0,3,6,9] etc. Thus the list comprehension is written to iterate over [0,2,4] i is used as the loop variable in the list comprehension and we return tuples consisting of the ith and the i+1th elements of the list. So, it should return [(foo[0],foo[1]), (foo[2],foo[3]), (foo[4],foo[5]) ] Which is the result. Using a for loop, you can write this as res = [] for i in range(0,len(foo),2): res.append( (foo[i],foo[i+1],)) print res I hope I'm clear > Also, what kinds of ways might this be used? I can't off the cuff think of anything. Peace -- ~noufal From jecarnell at saintfrancis.com Fri Sep 28 21:00:20 2007 From: jecarnell at saintfrancis.com (Carnell, James E) Date: Fri, 28 Sep 2007 14:00:20 -0500 Subject: [Tutor] Can a python program access the python interpreter? In-Reply-To: <mailman.2725.1190215715.2656.tutor@python.org> Message-ID: <CEFAE560FE3E3C458A2335A1AA37A82D067639AD@MAIL2W2K3.WarrenNT.SaintFrancis.Loc> Let's say I have a program that is learning how to find patterns in a list etc. list = [1,2,3,5,8,13] So the python program (Kitty.py) opens the python interpreter and copies this list to it. It then can try some pattern finding things it already has stored (PositionN+1 - PositionN etc.) That would be nice. As it stands I have to program all these rules (like Kitty.py typing nonsensical commands, or going outside the array) when the interpreter already has all these rules. I can just insert Kitty.py's "junk" into try exception handling... I don't know how to make this easier. Maybe I just need to get the program out of the computer so that it can use the interpreter. Hey, maybe that portable python... Hmmm.... Any other ideas (I only have Internet at work, and I.T. would hack up a hair ball if I tried to do this here). James Carnell From jecarnell at saintfrancis.com Fri Sep 28 21:13:38 2007 From: jecarnell at saintfrancis.com (Carnell, James E) Date: Fri, 28 Sep 2007 14:13:38 -0500 Subject: [Tutor] VOID Can a python program access the python interpreter? Message-ID: <CEFAE560FE3E3C458A2335A1AA37A82D067639AF@MAIL2W2K3.WarrenNT.SaintFrancis.Loc> Never mind. Sorry, I should have thought about this more before sending this. In a way I already have access to the interpreter. From gtxy20 at gmail.com Fri Sep 28 23:08:02 2007 From: gtxy20 at gmail.com (GTXY20) Date: Fri, 28 Sep 2007 17:08:02 -0400 Subject: [Tutor] How to adjust a text file... In-Reply-To: <46FC5D09.2090405@tds.net> References: <39cb7e5d0709271409if7b01edo988af0f35888fcf3@mail.gmail.com> <46FC5D09.2090405@tds.net> Message-ID: <39cb7e5d0709281408j2e51a12t17fa687090b3629e@mail.gmail.com> Thanks... I was able to use the following to get what i needed done: inp = open('input.txt', 'r') out = open('output.txt', 'w') for line in inp: Fields = line.split(",") ID = Fields[0] ProductMess = Fields[1] Product = ProductMess.split() for item in Funds: out.write ('%s\t%s\n'%(ID, Product)) Now my next challenge is to link a current table to this file and replace values in the Product area based on the value - sort of like a Global replace. Any hints as to where Python might have some sort of lookup table functionality. M. On 9/27/07, Kent Johnson <kent37 at tds.net> wrote: > > GTXY20 wrote: > > Hi, > > > > I have a CSV file as follows: > > > > ID Products > > 1 a b c d > > 1 a e > > 2 a b c > > 2 a > > 3 b c > > 3 a > > 4 d > > 5 a d > > > > I am trying to write a script that will take the CSV file and output > > another text file as follows: > > > > ID Products > > 1 a > > 1 b > > 1 c > > 1 d > > 1 a > > 1 e > > > > etc.. for all of the ID's essentially I need to create a single instance > > for products for each ID - currently the products are separated by a > > space. I am thinking I need a for loop that will search on the space as > > a delimiter... > > I should probably be teaching you to fish but tonight I have extra fish > :-) > > If the products are single words then this is very simple. Something like > > inp = open('input.txt') > out = open('output.txt') > > # Headers > inp.next() > out.write('ID\tProducts\n') > > for line in inp: > fields = line.split() > prodId = fields[0] > products = fields[1:] > for product in products: > out.write('%s\t%s\n' % (prodId, product)) > > inp.close() > out.close() > > > If the product text is more complex then you might want to use the csv > module to help read and write the file. > > BTW in Python 3 you can write > prodId, *products = fields.split() > > http://www.python.org/dev/peps/pep-3132/ > > Kent > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070928/ed3e6a06/attachment.htm From kent37 at tds.net Sat Sep 29 00:13:03 2007 From: kent37 at tds.net (Kent Johnson) Date: Fri, 28 Sep 2007 18:13:03 -0400 Subject: [Tutor] How to adjust a text file... In-Reply-To: <39cb7e5d0709281408j2e51a12t17fa687090b3629e@mail.gmail.com> References: <39cb7e5d0709271409if7b01edo988af0f35888fcf3@mail.gmail.com> <46FC5D09.2090405@tds.net> <39cb7e5d0709281408j2e51a12t17fa687090b3629e@mail.gmail.com> Message-ID: <46FD7C6F.2040709@tds.net> GTXY20 wrote: > Now my next challenge is to link a current table to this file and > replace values in the Product area based on the value - sort of like a > Global replace. Any hints as to where Python might have some sort of > lookup table functionality. A dict is a lookup table (a hash table, specifically). http://docs.python.org/tut/node7.html#SECTION007500000000000000000 http://docs.python.org/lib/typesmapping.html Kent From cspears2002 at yahoo.com Sat Sep 29 01:59:26 2007 From: cspears2002 at yahoo.com (Christopher Spears) Date: Fri, 28 Sep 2007 16:59:26 -0700 (PDT) Subject: [Tutor] detecing palindromic strings Message-ID: <493654.17257.qm@web51601.mail.re2.yahoo.com> I'm trying to write a script that detects if a string is palindromic (same backward as it is forward). This is what I have so far: #!/usr/bin/env python my_str = raw_input("Enter a string: ") string_list = [] for s in my_str: string_list.append(s) string_list_orig = string_list string_list.reverse() print string_list_orig print string_list The problem is that the script gives results like so: io at io-station-1 ./chap6 117> python palindromic.py Enter a string: abc ['c', 'b', 'a'] ['c', 'b', 'a'] Now I understand pointers and Python! :-) Since string_list_orig is pointing to string_list, when I reversed string_list, string_list_orig was reversed as well. How do I get around this? Is there a better way to write this script? I can't figure out how to loop through a string starting from the last character. "I'm the last person to pretend that I'm a radio. I'd rather go out and be a color television set." -David Bowie "Who dares wins" -British military motto "I generally know what I'm doing." -Buster Keaton From brunson at brunson.com Sat Sep 29 02:31:13 2007 From: brunson at brunson.com (Eric Brunson) Date: Fri, 28 Sep 2007 18:31:13 -0600 Subject: [Tutor] detecing palindromic strings In-Reply-To: <493654.17257.qm@web51601.mail.re2.yahoo.com> References: <493654.17257.qm@web51601.mail.re2.yahoo.com> Message-ID: <46FD9CD1.20603@brunson.com> Christopher Spears wrote: > I'm trying to write a script that detects if a string > is palindromic (same backward as it is forward). This > is what I have so far: > > #!/usr/bin/env python > > my_str = raw_input("Enter a string: ") > > string_list = [] > > for s in my_str: > string_list.append(s) > > string_list_orig = string_list > > string_list.reverse() > > print string_list_orig > print string_list > > The problem is that the script gives results like so: > io at io-station-1 ./chap6 117> python palindromic.py > Enter a string: abc > ['c', 'b', 'a'] > Well, since you've converted the string to a list, what you would like to do is: print "".join( string_list_orig ) to connect them back together. However, you can simplify the code greatly: >>> s = "abcd" >>> print s[::-1] dcba >>> if s == s[::-1]: ... print "yay" ... >>> s = "abcdcba" >>> if s == s[::-1]: ... print "yay" ... yay > ['c', 'b', 'a'] > > Now I understand pointers and Python! :-) Since > string_list_orig is pointing to string_list, when I > reversed string_list, string_list_orig was reversed as > well. > > How do I get around this? Is there a better way to > write this script? I can't figure out how to loop > through a string starting from the last character. > > > "I'm the last person to pretend that I'm a radio. I'd rather go out and be a color television set." > -David Bowie > > "Who dares wins" > -British military motto > > "I generally know what I'm doing." > -Buster Keaton > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From carroll at tjc.com Sat Sep 29 02:43:22 2007 From: carroll at tjc.com (Terry Carroll) Date: Fri, 28 Sep 2007 17:43:22 -0700 (PDT) Subject: [Tutor] detecing palindromic strings In-Reply-To: <493654.17257.qm@web51601.mail.re2.yahoo.com> Message-ID: <Pine.LNX.4.44.0709281724500.12322-100000@violet.rahul.net> On Fri, 28 Sep 2007, Christopher Spears wrote: > I'm trying to write a script that detects if a string > is palindromic (same backward as it is forward). This > is what I have so far: > my_str = raw_input("Enter a string: ") > string_list = [] Here you are creating a list and assiging the name string_list to it. > for s in my_str: > string_list.append(s) Now you've manipulated this list > string_list_orig = string_list Here is the problem: you're thinking you're creating another list, named string_list_orig, which is a copy of string_list. you're not. What you're actually doing is assigning another name, string_list_orig, to the existing list that was created above. > string_list.reverse() Now you're reversing that single list. > print string_list_orig > print string_list Now you're printing that list twice, once using each name. > > The problem is that the script gives results like so: > io at io-station-1 ./chap6 117> python palindromic.py > Enter a string: abc > ['c', 'b', 'a'] > ['c', 'b', 'a'] Using your approach, the easiest quick fix is to replace the line: string_list_orig = string_list with: string_list_orig = string_list[:] This creates a new list by slicing from string_list, and assigns it a name string_list_orig. Then you're dealing with two different lists, and reversing one does not affect the other. The notation string_list[:] produces a slice of a list. You usually see it with numbers in there, a la: >>> L = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'] >>> L[2:5] ['C', 'D', 'E'] This slices from position 2 up to (but not including) position 5. ('A' is at position 0). The default for where to start is 0, so L[:5] is the same as L[0:5] : >>> L[:5] ['A', 'B', 'C', 'D', 'E'] The default for where to end is the end of the list, so L[2:] is the same as L starting at 2 and going to the end of the list: >>> L[2:] ['C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'] Putting those two defaults together, leaving both the start and end out means to start at the first element and go all the way to the end: >>> L[:] ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'] So that's what the funky [:] notation gets you. > How do I get around this? Is there a better way to > write this script? I can't figure out how to loop > through a string starting from the last character. You can slice strings the same way you can slice lists. And what's more, you can specify a third parameter on the slice that specifies the stepping of the slicing; the default is 1, but, for example, using 2 will select every other element: >>> S = "ABCDEFGHIJ" >>> S[::2] 'ACEGI' And, here's the thing: if you use a negative number for ttep, it works from the right side of the string, rather than the left. So, if you use a step of -1 you get: >>> S[::-1] 'JIHGFEDCBA' And that's the easiest way to reverse a string, rather than converting it to a list and reversing the list. From bhaaluu at gmail.com Sat Sep 29 02:45:58 2007 From: bhaaluu at gmail.com (bhaaluu) Date: Fri, 28 Sep 2007 20:45:58 -0400 Subject: [Tutor] detecing palindromic strings In-Reply-To: <493654.17257.qm@web51601.mail.re2.yahoo.com> References: <493654.17257.qm@web51601.mail.re2.yahoo.com> Message-ID: <ea979d70709281745x5116dbe0v1e36aae1ebd2b93f@mail.gmail.com> Greetings, Try something with this: >>> string = 'abc' >>> string 'abc' >>> for i in range(len(string)-1,-1,-1): ... print string[i], ... c b a -- b h a a l u u at g m a i l dot c o m http://www.geocities.com/ek.bhaaluu/index.html On 9/28/07, Christopher Spears <cspears2002 at yahoo.com> wrote: > I'm trying to write a script that detects if a string > is palindromic (same backward as it is forward). This > is what I have so far: > > #!/usr/bin/env python > > my_str = raw_input("Enter a string: ") > > string_list = [] > > for s in my_str: > string_list.append(s) > > string_list_orig = string_list > > string_list.reverse() > > print string_list_orig > print string_list > > The problem is that the script gives results like so: > io at io-station-1 ./chap6 117> python palindromic.py > Enter a string: abc > ['c', 'b', 'a'] > ['c', 'b', 'a'] > > Now I understand pointers and Python! :-) Since > string_list_orig is pointing to string_list, when I > reversed string_list, string_list_orig was reversed as > well. > > How do I get around this? Is there a better way to > write this script? I can't figure out how to loop > through a string starting from the last character. > > > "I'm the last person to pretend that I'm a radio. I'd rather go out and be a color television set." > -David Bowie > > "Who dares wins" > -British military motto > > "I generally know what I'm doing." > -Buster Keaton > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From tiagosaboga at terra.com.br Sat Sep 29 02:39:01 2007 From: tiagosaboga at terra.com.br (Tiago Saboga) Date: Fri, 28 Sep 2007 21:39:01 -0300 Subject: [Tutor] detecing palindromic strings In-Reply-To: <493654.17257.qm@web51601.mail.re2.yahoo.com> References: <493654.17257.qm@web51601.mail.re2.yahoo.com> Message-ID: <20070929003901.GB11473@localdomain> On Fri, Sep 28, 2007 at 04:59:26PM -0700, Christopher Spears wrote: > How do I get around this? Is there a better way to > write this script? I can't figure out how to loop > through a string starting from the last character. A string is a sequence of chars, and you can use slices with it [1]. In [23]: a = 'abcdef' In [24]: a[::-1] Out[24]: 'fedcba' Tiago. [1] - http://docs.python.org/lib/typesseq.html From cspears2002 at yahoo.com Sat Sep 29 06:55:44 2007 From: cspears2002 at yahoo.com (Christopher Spears) Date: Fri, 28 Sep 2007 21:55:44 -0700 (PDT) Subject: [Tutor] creating the equivalent of string.strip() Message-ID: <465410.15557.qm@web51609.mail.re2.yahoo.com> I'm working out of chapter 6 of Core Python Programming (2nd Edition). For one problem, I am supposed to write a script that is the equivalent of string.strip(). Obviously, using any version of string.strip() defeats the purpose of the exercise. I'm not sure how to proceed. My biggest stumbling block is how to detect the leading and trailing whitespace. If I wanted to remove all whitespace in a string, I would probably break the string into its individual components, cycle through the string, detect the whitespace, and remove them. Any hints? From alan.gauld at btinternet.com Sat Sep 29 09:53:20 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 29 Sep 2007 08:53:20 +0100 Subject: [Tutor] for vs while References: <2AE92A68-8622-46F8-9ACB-08CE28519339@nc.rr.com> Message-ID: <fdl0af$j9t$1@sea.gmane.org> "James" <jtp at nc.rr.com> wrote > I have a dumb question...hopefully someone can shed some light on > the > difference between for and while in the situation below. You got the basic answer but I'll just add a comment. while is your basic type loop, same as in C and most other languages. for is really a *foreach* loop. It iterates over collections/sequences. It is not an indexing loop and if you find yourself doing for n in range(len(collection)): foo(collection[n]) You should consider whether there is a better way. Normally for item in collection: foo(item) If you really need the index as well as the item then use enumerate(): for n,item in enumerate(collection): print item, 'at index', n > I'm trying to iterate through a list I've created. The list > consists > of a command, followed by a 'logging' message (a message printed to > a > console or log file after the command is run). The easiest way to do this is to put both command and message in a tuple and have a list of tuples: > stuff = [ ["cat /etc/password"] , ["viewed /etc/password"] ] stuff = [ ("cat /etc/password" , "viewed /etc/password") ] for com in stuff: os.system(com[0]) print com[1] Get the data structure right and the code will follow. HTH, Alan G Just back from vacation in Switzerland :-) From alan.gauld at btinternet.com Sat Sep 29 09:58:55 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 29 Sep 2007 08:58:55 +0100 Subject: [Tutor] creating the equivalent of string.strip() References: <465410.15557.qm@web51609.mail.re2.yahoo.com> Message-ID: <fdl0ku$juf$1@sea.gmane.org> "Christopher Spears" <cspears2002 at yahoo.com> wrote > I'm not sure how to proceed. My biggest stumbling > block is how to detect the leading and trailing > whitespace. Use indexing. Recall str[-1] is the last character str[0] is the first... Try using a while loop. Or maybe two? And strings have an isspace method... HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From wolf1boy85 at yahoo.com Sat Sep 29 01:31:40 2007 From: wolf1boy85 at yahoo.com (Robert Jackson) Date: Fri, 28 Sep 2007 18:31:40 -0500 (CDT) Subject: [Tutor] Check if root Message-ID: <105235.6206.qm@web45612.mail.sp1.yahoo.com> I'm trying to write a function that checks to see if the user that is running the python script is 'root' (I'm obviously running this Python program on Linux). Using os.system(), I have done something like this: >>> import os >>> os.system("whoami") robert 0 >>> If I try to assign the output of this snippet of code to a variable, the variable ultimately ends up holding "0" and not the username. I have seen some examples on Google where some individuals have suggested something like this: user=os.system("whoami") if user is not "root": print "You aren't root. Goodbye." sys.exit() But that isn't going to work, for obvious reasons (user holds 0, and not the username). How do I get around this problem? Robert ____________________________________________________________________________________ Moody friends. Drama queens. Your life? Nope! - their life, your story. Play Sims Stories at Yahoo! Games. http://sims.yahoo.com/ From kent37 at tds.net Sat Sep 29 15:28:28 2007 From: kent37 at tds.net (Kent Johnson) Date: Sat, 29 Sep 2007 09:28:28 -0400 Subject: [Tutor] detecing palindromic strings In-Reply-To: <493654.17257.qm@web51601.mail.re2.yahoo.com> References: <493654.17257.qm@web51601.mail.re2.yahoo.com> Message-ID: <46FE52FC.4050908@tds.net> Christopher Spears wrote: > my_str = raw_input("Enter a string: ") > > string_list = [] > > for s in my_str: > string_list.append(s) This can be written: string_list = list(my_str) Kent From kent37 at tds.net Sat Sep 29 15:33:31 2007 From: kent37 at tds.net (Kent Johnson) Date: Sat, 29 Sep 2007 09:33:31 -0400 Subject: [Tutor] Check if root In-Reply-To: <105235.6206.qm@web45612.mail.sp1.yahoo.com> References: <105235.6206.qm@web45612.mail.sp1.yahoo.com> Message-ID: <46FE542B.8090901@tds.net> Robert Jackson wrote: > I'm trying to write a function that checks to see if the user that > is running the python script is 'root' (I'm obviously running this > Python program on Linux). > > > > Using os.system(), I have done something like this: > > >>>> import os > >>>> os.system("whoami") > > robert > > 0 > If I try to assign the output of this snippet of code to a variable, > the variable ultimately ends up holding "0" and not the username. os.system returns the result code from the subprocess, not it's output. Use the subprocess module when you want to capture output: In [6]: from subprocess import Popen, PIPE In [7]: Popen(['whoami'], stdout=PIPE).communicate() Out[7]: ('kent\n', None) In [8]: out, err = Popen(['whoami'], stdout=PIPE).communicate() In [9]: out Out[9]: 'kent\n' Kent From wolf1boy85 at yahoo.com Sat Sep 29 17:36:31 2007 From: wolf1boy85 at yahoo.com (Robert Jackson) Date: Sat, 29 Sep 2007 08:36:31 -0700 (PDT) Subject: [Tutor] strategy in dealing with user input Message-ID: <16815.95335.qm@web45603.mail.sp1.yahoo.com> I have a few lines of code as follows: CONFIGFILE = raw_input("Enter config location: ") while CONFIGFILE == "": CONFIGFILE = raw_input("You must enter configuration file location: ") Let's say the user hits enter past the initial raw_input request. The user will then be in the while loop. Any subsequent "enters" by the user will result in a brand new line that reads: "You must enter configuration file location: ". Is there a way to clear out the CURRENT line while in the *while* loop so that even if the user hits enter a few extra times, it'll stay in the SAME line that reads "You must enter a configuration file location: " (and not fill up the screen with the same text over and over)? ____________________________________________________________________________________ Luggage? GPS? Comic books? Check out fitting gifts for grads at Yahoo! Search http://search.yahoo.com/search?fr=oni_on_mail&p=graduation+gifts&cs=bz From kent37 at tds.net Sat Sep 29 19:06:33 2007 From: kent37 at tds.net (Kent Johnson) Date: Sat, 29 Sep 2007 13:06:33 -0400 Subject: [Tutor] strategy in dealing with user input In-Reply-To: <16815.95335.qm@web45603.mail.sp1.yahoo.com> References: <16815.95335.qm@web45603.mail.sp1.yahoo.com> Message-ID: <46FE8619.3090808@tds.net> Robert Jackson wrote: > I have a few lines of code as follows: > > CONFIGFILE = raw_input("Enter config location: ") > while CONFIGFILE == "": > CONFIGFILE = raw_input("You must enter configuration file location: ") > > Let's say the user hits enter past the initial raw_input request. The user will then be in the while loop. Any subsequent "enters" by the user will result in a brand new line that reads: "You must enter configuration file location: ". > > Is there a way to clear out the CURRENT line while in the *while* loop so that even if the user hits enter a few extra times, it'll stay in the SAME line that reads "You must enter a configuration file location: " (and not fill up the screen with the same text over and over)? CONFIGFILE = raw_input("Enter config location: ") prompt = "You must enter configuration file location: " while CONFIGFILE == "": CONFIGFILE = raw_input(prompt) prompt = "" Kent From std3rr at gmail.com Sat Sep 29 19:13:09 2007 From: std3rr at gmail.com (Joshua Simpson) Date: Sat, 29 Sep 2007 10:13:09 -0700 Subject: [Tutor] Check if root In-Reply-To: <105235.6206.qm@web45612.mail.sp1.yahoo.com> References: <105235.6206.qm@web45612.mail.sp1.yahoo.com> Message-ID: <3ed9caa10709291013v7f596ees3683619edb16b369@mail.gmail.com> On 9/28/07, Robert Jackson <wolf1boy85 at yahoo.com> wrote: > > I'm trying to write a function that checks to see if the user that > is running the python script is 'root' (I'm obviously running this > Python program on Linux). Why not just use os.geteuid() ? import os if os.geteuid() != 0: print "You must be root to run this script." sys.exit(1) -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070929/fff85d1b/attachment.htm From norman at khine.net Sat Sep 29 19:47:09 2007 From: norman at khine.net (Norman Khine) Date: Sat, 29 Sep 2007 19:47:09 +0200 Subject: [Tutor] Check if root In-Reply-To: <105235.6206.qm@web45612.mail.sp1.yahoo.com> References: <105235.6206.qm@web45612.mail.sp1.yahoo.com> Message-ID: <46FE8F9D.1000604@khine.net> Robert Jackson wrote: > I'm trying to write a function that checks to see if the user that > is running the python script is 'root' (I'm obviously running this > Python program on Linux). > > > > Using os.system(), I have done something like this: > > >>>> import os > >>>> os.system("whoami") > > robert > > 0 > > > > > If I try to assign the output of this snippet of code to a variable, > the variable ultimately ends up holding "0" and not the username. > > > > I have seen some examples on Google where some individuals have suggested something like this: > > user=os.system("whoami") > if user is not "root": > print "You aren't root. Goodbye." > sys.exit() > > But that isn't going to work, for obvious reasons (user holds 0, and not the username). How do I get around this problem? > > Robert > > > > > > > ____________________________________________________________________________________ > Moody friends. Drama queens. Your life? Nope! - their life, your story. Play Sims Stories at Yahoo! Games. > http://sims.yahoo.com/ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > maybe this import os, sys # we need to be root if os.getuid(): print "You need to be root, so we now die." sys.exit(0) -- Norman Khine %>>> "".join( [ {'*':'@','^':'.'}.get(c,None) or chr(97+(ord(c)-83)%26) for c in ",adym,*)&uzq^zqf" ] ) From jtp at nc.rr.com Sat Sep 29 19:57:57 2007 From: jtp at nc.rr.com (James) Date: Sat, 29 Sep 2007 13:57:57 -0400 Subject: [Tutor] Check if root In-Reply-To: <105235.6206.qm@web45612.mail.sp1.yahoo.com> References: <105235.6206.qm@web45612.mail.sp1.yahoo.com> Message-ID: <A99AA163-2A76-4F42-8A97-C2FAAD2B152D@nc.rr.com> I've used something like this successfully in the past: import commands if commands.getoutput( "whoami" ) != "root": sys.exit( "Must be root!" ) Hope this helps. .james On Sep 28, 2007, at 7:31 PM, Robert Jackson wrote: > I'm trying to write a function that checks to see if the user that > is running the python script is 'root' (I'm obviously running this > Python program on Linux). > > > > Using os.system(), I have done something like this: > > >>>> import os > >>>> os.system("whoami") > > robert > > 0 > >>>> > > > > If I try to assign the output of this snippet of code to a variable, > the variable ultimately ends up holding "0" and not the username. > > > > I have seen some examples on Google where some individuals have > suggested something like this: > > user=os.system("whoami") > if user is not "root": > print "You aren't root. Goodbye." > sys.exit() > > But that isn't going to work, for obvious reasons (user holds 0, > and not the username). How do I get around this problem? > > Robert > > > > > > > ______________________________________________________________________ > ______________ > Moody friends. Drama queens. Your life? Nope! - their life, your > story. Play Sims Stories at Yahoo! Games. > http://sims.yahoo.com/ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From jtp at nc.rr.com Sat Sep 29 20:23:26 2007 From: jtp at nc.rr.com (James) Date: Sat, 29 Sep 2007 14:23:26 -0400 Subject: [Tutor] Error Using Logging Module Message-ID: <F0A5FC39-E8E0-4C39-B6E3-4213EE53675A@nc.rr.com> All, I'm having some trouble using the Python logging module. Here's the snippet of code that's causing problems: -------- # setting up logging using Python's logging module LOGFILE = "/home/james/log" logging.basicConfig( level=logging.DEBUG, format='%(asctime)s <> %(levelname)s <> %(message)s', datefmt='%a, %d %b %Y %H:%M:%S', filename=LOGFILE, filemode='w') -------- When I run the program, I get this error: -------- Traceback (most recent call last): File "./script.py", line 225, in <module> sys.exit( main() ) File "./script.py", line 119, in main filemode='w') File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/logging/__init__.py", line 1237, in basicConfig hdlr = FileHandler(filename, mode) File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/logging/__init__.py", line 773, in __init__ StreamHandler.__init__(self, stream) File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/logging/__init__.py", line 721, in __init__ Handler.__init__(self) File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/logging/__init__.py", line 582, in __init__ _acquireLock() File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/logging/__init__.py", line 189, in _acquireLock _lock = threading.RLock() AttributeError: 'module' object has no attribute 'RLock' -------- Ideas? Thanks! .james From wolf1boy85 at yahoo.com Sat Sep 29 17:32:37 2007 From: wolf1boy85 at yahoo.com (Robert Jackson) Date: Sat, 29 Sep 2007 08:32:37 -0700 (PDT) Subject: [Tutor] linux terminal coloring in python Message-ID: <309496.28533.qm@web45608.mail.sp1.yahoo.com> I'm trying to get some pretty colored output for a Linux console / terminal window. Google searches only reveal the curses module to colorize output. Is there a simpler way? Curses seems to be FAR too powerful for what it is I want to do (simply to colorize a few 'print' outputs to the console). ____________________________________________________________________________________ Take the Internet to Go: Yahoo!Go puts the Internet in your pocket: mail, news, photos & more. http://mobile.yahoo.com/go?refer=1GNXIC From kent37 at tds.net Sat Sep 29 20:58:14 2007 From: kent37 at tds.net (Kent Johnson) Date: Sat, 29 Sep 2007 14:58:14 -0400 Subject: [Tutor] Error Using Logging Module In-Reply-To: <F0A5FC39-E8E0-4C39-B6E3-4213EE53675A@nc.rr.com> References: <F0A5FC39-E8E0-4C39-B6E3-4213EE53675A@nc.rr.com> Message-ID: <46FEA046.7020900@tds.net> James wrote: > Traceback (most recent call last): > File "./script.py", line 225, in <module> > sys.exit( main() ) > File "./script.py", line 119, in main > filemode='w') > File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ > python2.5/logging/__init__.py", line 1237, in basicConfig > hdlr = FileHandler(filename, mode) > File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ > python2.5/logging/__init__.py", line 773, in __init__ > StreamHandler.__init__(self, stream) > File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ > python2.5/logging/__init__.py", line 721, in __init__ > Handler.__init__(self) > File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ > python2.5/logging/__init__.py", line 582, in __init__ > _acquireLock() > File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ > python2.5/logging/__init__.py", line 189, in _acquireLock > _lock = threading.RLock() > AttributeError: 'module' object has no attribute 'RLock' Do you have a module called threading in your path? Maybe you are hiding the library module. Try this: In [14]: import threading In [15]: threading.__file__ Out[15]: '/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/threading.pyc' to see what threading module you are importing. Kent From jtp at nc.rr.com Sat Sep 29 21:49:11 2007 From: jtp at nc.rr.com (James) Date: Sat, 29 Sep 2007 15:49:11 -0400 Subject: [Tutor] Error Using Logging Module In-Reply-To: <46FEA046.7020900@tds.net> References: <F0A5FC39-E8E0-4C39-B6E3-4213EE53675A@nc.rr.com> <46FEA046.7020900@tds.net> Message-ID: <536C8013-4856-4B7E-81B9-2E444E64F3DF@nc.rr.com> Here's the output of the requested commands: >>> import threading >>> threading.__file__ '/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/ threading.pyc' >>> Looks identical to the output you attached. .james On Sep 29, 2007, at 2:58 PM, Kent Johnson wrote: > James wrote: > >> Traceback (most recent call last): >> File "./script.py", line 225, in <module> >> sys.exit( main() ) >> File "./script.py", line 119, in main >> filemode='w') >> File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ >> python2.5/logging/__init__.py", line 1237, in basicConfig >> hdlr = FileHandler(filename, mode) >> File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ >> python2.5/logging/__init__.py", line 773, in __init__ >> StreamHandler.__init__(self, stream) >> File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ >> python2.5/logging/__init__.py", line 721, in __init__ >> Handler.__init__(self) >> File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ >> python2.5/logging/__init__.py", line 582, in __init__ >> _acquireLock() >> File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ >> python2.5/logging/__init__.py", line 189, in _acquireLock >> _lock = threading.RLock() >> AttributeError: 'module' object has no attribute 'RLock' > > Do you have a module called threading in your path? Maybe you are > hiding the library module. Try this: > > In [14]: import threading > In [15]: threading.__file__ > Out[15]: '/Library/Frameworks/Python.framework/Versions/2.5/lib/ > python2.5/threading.pyc' > > to see what threading module you are importing. > > Kent From fredp101 at mac.com Sat Sep 29 22:13:19 2007 From: fredp101 at mac.com (Fred P) Date: Sat, 29 Sep 2007 13:13:19 -0700 Subject: [Tutor] Learning Python Message-ID: <68FD12A7-5325-4B2A-BFF2-AA542C9FD17D@mac.com> Hey Everyone, I am completely new at python, but not new to programming or scripting. I have a couple of years of LUA scripting experience, about a year of C++ classes, and used to be very efficient at c-shell scripting in unix. My question for you guys: 1) How do I get Started? 2) Recommend any specific Books? 3) Any online tutors/ forums that would benefit a newbie 4) Any online classes that teach python? I have taken online c++ courses, and found them helpful. I was hoping to find something for python. My main objective is to write scripts for the following type of applications File management, file copies/syncs/ compares Text manipulation - like parsing text files to replace or augment specific values Integration into current applications to write redundant routines and maybe some day plugins I am not even sure what else, but I do know that every time i think of something that we need at work, other people say, "That would be a good task for a python script" and I would eventually like to be able to do something about that. Thanks Fred From mlangford.cs03 at gtalumni.org Sat Sep 29 22:23:18 2007 From: mlangford.cs03 at gtalumni.org (Michael Langford) Date: Sat, 29 Sep 2007 16:23:18 -0400 Subject: [Tutor] Learning Python In-Reply-To: <68FD12A7-5325-4B2A-BFF2-AA542C9FD17D@mac.com> References: <68FD12A7-5325-4B2A-BFF2-AA542C9FD17D@mac.com> Message-ID: <82b4f5810709291323l6da24d4anc18da9da97eec665@mail.gmail.com> http://www.diveintopython.com is a *Great* start for experienced software developers. Within a weekend with that book I'd written an entire parser/decompiler when I'd never used python before that. --michael On 9/29/07, Fred P <fredp101 at mac.com> wrote: > Hey Everyone, > > I am completely new at python, but not new to programming or > scripting. I have a couple of years of LUA scripting experience, > about a year of C++ classes, and used to be very efficient at c-shell > scripting in unix. > > My question for you guys: > > 1) How do I get Started? > > 2) Recommend any specific Books? > > 3) Any online tutors/ forums that would benefit a newbie > > 4) Any online classes that teach python? I have taken online c++ > courses, and found them helpful. I was hoping to find something for > python. > > My main objective is to write scripts for the following type of > applications > File management, file copies/syncs/ compares > Text manipulation - like parsing text files to replace or augment > specific values > Integration into current applications to write redundant routines and > maybe some day plugins > > I am not even sure what else, but I do know that every time i think > of something that we need at work, other people say, "That would be a > good task for a python script" and I would eventually like to be > able to do something about that. > > Thanks > Fred > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Michael Langford Phone: 404-386-0495 Consulting: http://www.TierOneDesign.com/ Entertaining: http://www.ThisIsYourCruiseDirectorSpeaking.com From mlangford.cs03 at gtalumni.org Sat Sep 29 22:24:13 2007 From: mlangford.cs03 at gtalumni.org (Michael Langford) Date: Sat, 29 Sep 2007 16:24:13 -0400 Subject: [Tutor] Learning Python In-Reply-To: <82b4f5810709291323l6da24d4anc18da9da97eec665@mail.gmail.com> References: <68FD12A7-5325-4B2A-BFF2-AA542C9FD17D@mac.com> <82b4f5810709291323l6da24d4anc18da9da97eec665@mail.gmail.com> Message-ID: <82b4f5810709291324x27bc7c8fq9d3a4b217104d9@mail.gmail.com> err....http://www.diveintopython.org is the actual url =Michael On 9/29/07, Michael Langford <mlangford.cs03 at gtalumni.org> wrote: > http://www.diveintopython.com is a *Great* start for experienced > software developers. Within a weekend with that book I'd written an > entire parser/decompiler when I'd never used python before that. > > --michael > > On 9/29/07, Fred P <fredp101 at mac.com> wrote: > > Hey Everyone, > > > > I am completely new at python, but not new to programming or > > scripting. I have a couple of years of LUA scripting experience, > > about a year of C++ classes, and used to be very efficient at c-shell > > scripting in unix. > > > > My question for you guys: > > > > 1) How do I get Started? > > > > 2) Recommend any specific Books? > > > > 3) Any online tutors/ forums that would benefit a newbie > > > > 4) Any online classes that teach python? I have taken online c++ > > courses, and found them helpful. I was hoping to find something for > > python. > > > > My main objective is to write scripts for the following type of > > applications > > File management, file copies/syncs/ compares > > Text manipulation - like parsing text files to replace or augment > > specific values > > Integration into current applications to write redundant routines and > > maybe some day plugins > > > > I am not even sure what else, but I do know that every time i think > > of something that we need at work, other people say, "That would be a > > good task for a python script" and I would eventually like to be > > able to do something about that. > > > > Thanks > > Fred > > > > > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > -- > Michael Langford > Phone: 404-386-0495 > Consulting: http://www.TierOneDesign.com/ > Entertaining: http://www.ThisIsYourCruiseDirectorSpeaking.com > -- Michael Langford Phone: 404-386-0495 Consulting: http://www.TierOneDesign.com/ Entertaining: http://www.ThisIsYourCruiseDirectorSpeaking.com From kent37 at tds.net Sat Sep 29 23:50:22 2007 From: kent37 at tds.net (Kent Johnson) Date: Sat, 29 Sep 2007 17:50:22 -0400 Subject: [Tutor] Learning Python In-Reply-To: <68FD12A7-5325-4B2A-BFF2-AA542C9FD17D@mac.com> References: <68FD12A7-5325-4B2A-BFF2-AA542C9FD17D@mac.com> Message-ID: <46FEC89E.8080504@tds.net> Fred P wrote: > 1) How do I get Started? The official tutorial is quite accessible if you have some programming experience. More tutorials are listed here: http://wiki.python.org/moin/BeginnersGuide/Programmers > 2) Recommend any specific Books? I like Learning Python (O'Reilly) Python in a Nutshell is good if you want a compressed but readable introduction. > 3) Any online tutors/ forums that would benefit a newbie You found that already; stick around! Kent From kent37 at tds.net Sat Sep 29 23:53:32 2007 From: kent37 at tds.net (Kent Johnson) Date: Sat, 29 Sep 2007 17:53:32 -0400 Subject: [Tutor] Error Using Logging Module In-Reply-To: <536C8013-4856-4B7E-81B9-2E444E64F3DF@nc.rr.com> References: <F0A5FC39-E8E0-4C39-B6E3-4213EE53675A@nc.rr.com> <46FEA046.7020900@tds.net> <536C8013-4856-4B7E-81B9-2E444E64F3DF@nc.rr.com> Message-ID: <46FEC95C.9090909@tds.net> James wrote: > Here's the output of the requested commands: > > >>> import threading > >>> threading.__file__ > '/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/threading.pyc' > > >>> > > Looks identical to the output you attached. Strange. How about >>> import threading >>> threading.RLock <function RLock at 0x10e6870> ? Kent > > .james > > > On Sep 29, 2007, at 2:58 PM, Kent Johnson wrote: > >> James wrote: >> >>> Traceback (most recent call last): >>> File "./script.py", line 225, in <module> >>> sys.exit( main() ) >>> File "./script.py", line 119, in main >>> filemode='w') >>> File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ >>> python2.5/logging/__init__.py", line 1237, in basicConfig >>> hdlr = FileHandler(filename, mode) >>> File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ >>> python2.5/logging/__init__.py", line 773, in __init__ >>> StreamHandler.__init__(self, stream) >>> File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ >>> python2.5/logging/__init__.py", line 721, in __init__ >>> Handler.__init__(self) >>> File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ >>> python2.5/logging/__init__.py", line 582, in __init__ >>> _acquireLock() >>> File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ >>> python2.5/logging/__init__.py", line 189, in _acquireLock >>> _lock = threading.RLock() >>> AttributeError: 'module' object has no attribute 'RLock' >> >> Do you have a module called threading in your path? Maybe you are >> hiding the library module. Try this: >> >> In [14]: import threading >> In [15]: threading.__file__ >> Out[15]: >> '/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/threading.pyc' >> >> >> to see what threading module you are importing. >> >> Kent > > From tiagosaboga at terra.com.br Sun Sep 30 00:11:35 2007 From: tiagosaboga at terra.com.br (Tiago Saboga) Date: Sat, 29 Sep 2007 19:11:35 -0300 Subject: [Tutor] linux terminal coloring in python In-Reply-To: <309496.28533.qm@web45608.mail.sp1.yahoo.com> References: <309496.28533.qm@web45608.mail.sp1.yahoo.com> Message-ID: <20070929221135.GF11473@localdomain> On Sat, Sep 29, 2007 at 08:32:37AM -0700, Robert Jackson wrote: > I'm trying to get some pretty colored output for a Linux console / terminal window. Google searches only reveal the curses module to colorize output. > Is there a simpler way? Curses seems to be FAR too powerful for what it is I want to do (simply to colorize a few 'print' outputs to the console). I have looked for that last week and the best I could find was ColorANSI module, distributed with ipython (in a debian system, it's /usr/share/python-support/ipython/IPython/ColorANSI.py). I just bookmarked it, and don't know how to make it work. But it seems quite simple. Tiago. From alan.gauld at btinternet.com Sun Sep 30 00:42:25 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 29 Sep 2007 23:42:25 +0100 Subject: [Tutor] linux terminal coloring in python References: <309496.28533.qm@web45608.mail.sp1.yahoo.com> Message-ID: <fdmkdg$1hq$1@sea.gmane.org> "Robert Jackson" <wolf1boy85 at yahoo.com> wrote > I'm trying to get some pretty colored output for a Linux console > / terminal window. Google searches only reveal the curses module > to colorize output. curses means it will work for any console supporting color and curses. > Is there a simpler way? Curses seems to be FAR too powerful If you know for sure what terminal you are using then you can send control codes to the screen directly. But since color terninals are far from standard you will need to find out what kind of terminal you are using (eg Dec VT340 supports color as do various Tectronics and Wyse terminals). On Linux you are probably using a terminal emulator running in an xterm or some other window interface. Xterm uses the terminal settings you tell it to use in the X resources. But some more modern consoles have their own codes so you need to look them up. In short if you know the control codes used to change color then it's easy to print them out. Something like: # These codes are just made up, you need the real ones! YELLOW = 0x23 BLUE = 0x4A RED = 0xB2 print YELLOW, 'This is yellow', RED, 'and this is red' But that will produce something completely different in another console type. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From jtp at nc.rr.com Sun Sep 30 00:52:22 2007 From: jtp at nc.rr.com (James) Date: Sat, 29 Sep 2007 18:52:22 -0400 Subject: [Tutor] Error Using Logging Module In-Reply-To: <46FEC95C.9090909@tds.net> References: <F0A5FC39-E8E0-4C39-B6E3-4213EE53675A@nc.rr.com> <46FEA046.7020900@tds.net> <536C8013-4856-4B7E-81B9-2E444E64F3DF@nc.rr.com> <46FEC95C.9090909@tds.net> Message-ID: <3AF958FB-CC05-4954-A939-A30A4F372670@nc.rr.com> Wow this has gotten awfully strange. I'm running Python on OS X. Here's a quick rundown of what I just found: (a) If I open a terminal and then run my python script (./script.py), it fails giving me the RLock error I attached in my original e-mail. (b) If I open a FRESH terminal, run the interpreter (python), import threading & logging and then run the same exact code snipped in question (logging.basicConfig( ... )), it works fine (no errors). Further, running "threading.RLock" will generate the expected output. (specifically: <function RLock at 0x10e6870>). However... (c) Let's say I open a terminal and then run my script. It fails with, citing the RLock error. Then, in the *same* terminal window, I open the python interpreter, import logging and threading, and then run the same exact code snippet (logging.basicConfig( ... )). Despite the fact that I have imported all the required modules, I will get the same RLock error I received before. If I attempt to run the command "threading.RLock" in the interpreter, I receive the following error message: >>> threading.RLock Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'module' object has no attribute 'RLock' ? ...now I'm even more confused. ;) Thoughts? .james On Sep 29, 2007, at 5:53 PM, Kent Johnson wrote: > James wrote: >> Here's the output of the requested commands: >> >>> import threading >> >>> threading.__file__ >> '/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/ >> threading.pyc' >>> >> Looks identical to the output you attached. > > Strange. How about > >>> import threading > >>> threading.RLock > <function RLock at 0x10e6870> > > ? > > Kent > >> .james >> On Sep 29, 2007, at 2:58 PM, Kent Johnson wrote: >>> James wrote: >>> >>>> Traceback (most recent call last): >>>> File "./script.py", line 225, in <module> >>>> sys.exit( main() ) >>>> File "./script.py", line 119, in main >>>> filemode='w') >>>> File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ >>>> python2.5/logging/__init__.py", line 1237, in basicConfig >>>> hdlr = FileHandler(filename, mode) >>>> File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ >>>> python2.5/logging/__init__.py", line 773, in __init__ >>>> StreamHandler.__init__(self, stream) >>>> File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ >>>> python2.5/logging/__init__.py", line 721, in __init__ >>>> Handler.__init__(self) >>>> File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ >>>> python2.5/logging/__init__.py", line 582, in __init__ >>>> _acquireLock() >>>> File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ >>>> python2.5/logging/__init__.py", line 189, in _acquireLock >>>> _lock = threading.RLock() >>>> AttributeError: 'module' object has no attribute 'RLock' >>> >>> Do you have a module called threading in your path? Maybe you are >>> hiding the library module. Try this: >>> >>> In [14]: import threading >>> In [15]: threading.__file__ >>> Out[15]: '/Library/Frameworks/Python.framework/Versions/2.5/lib/ >>> python2.5/threading.pyc' >>> >>> to see what threading module you are importing. >>> >>> Kent From alan.gauld at btinternet.com Sun Sep 30 00:52:13 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 29 Sep 2007 23:52:13 +0100 Subject: [Tutor] strategy in dealing with user input References: <16815.95335.qm@web45603.mail.sp1.yahoo.com> Message-ID: <fdmkvt$30k$1@sea.gmane.org> "Robert Jackson" <wolf1boy85 at yahoo.com> wrote >I have a few lines of code as follows: > > CONFIGFILE = raw_input("Enter config location: ") > while CONFIGFILE == "": > CONFIGFILE = raw_input("You must enter configuration file > location: ") All uppercasse is usually used to indicate a constant value. Also the second line indent is wrong, so it should look like: CONFIGFILE = raw_input("Enter config location: ") while CONFIGFILE == "": CONFIGFILE = raw_input("You must enter configuration file location: ") > Is there a way to clear out the CURRENT line while in the *while* > loop > so that even if the user hits enter a few extra times, it'll stay in > the SAME line There are various ways to do that, the best solution is to use curses, but thats a steep lrearning curve. An easier way is just not to print the line inside the loop, like this: CONFIGFILE = raw_input("Enter config location: ") if not ConfigFile: print "You must enter configuration file location: " while CONFIGFILE == "": CONFIGFILE = raw_input() However that will still scroll the line up the screen, not so pretty. The next simplest solution is to use sys.stdout/sys.stdin to access the input/output buffers directly. This will allow you to read the input directly including the newline character and to write control codes to stdout to erase p[revious characters etc. But this gets messy quickly. Which takes us back to curses (assuming you are on Linux!) or the msvcrt module if you are on Windows. Both of these have a getch function to read characters one by one and allows you to process them. No easy solutions, but several ways to do it depending on your needs and enthusiasm levels. -- 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 Sep 30 00:56:24 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 29 Sep 2007 23:56:24 +0100 Subject: [Tutor] Learning Python References: <68FD12A7-5325-4B2A-BFF2-AA542C9FD17D@mac.com> Message-ID: <fdml7o$3gf$1@sea.gmane.org> "Fred P" <fredp101 at mac.com> wrote > I am completely new at python, but not new to programming or > scripting. I have a couple of years of LUA scripting experience, > about a year of C++ classes, and used to be very efficient at > c-shell > scripting in unix. > > My question for you guys: > > 1) How do I get Started? Download/install python > 2) Recommend any specific Books? > 3) Any online tutors/ forums that would benefit a newbie There are a bunch of them in the beginners section of the python web site. The best starting point is the official tutor which can be skipped through in a half day and will give you all the basics (and quite a lot of the non basics too) > 4) Any online classes that teach python? I have taken online c++ > courses, and found them helpful. I was hoping to find something for > python. You might like the ShowMeDo videos. > My main objective is to write scripts for the following type of > applications > File management, file copies/syncs/ compares > Text manipulation - like parsing text files to replace or augment > specific values > Integration into current applications to write redundant routines > and > maybe some day plugins You might even find my tutorial useful since it targets those kinds of tasks. It is aimed at absolute beginners however so may well be too basic for 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 Sun Sep 30 01:03:22 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 30 Sep 2007 00:03:22 +0100 Subject: [Tutor] Error Using Logging Module References: <F0A5FC39-E8E0-4C39-B6E3-4213EE53675A@nc.rr.com> Message-ID: <fdmlkq$4f7$1@sea.gmane.org> "James" <jtp at nc.rr.com> wrote > I'm having some trouble using the Python logging module. Here's the > snippet of code that's causing problems: > > -------- > > # setting up logging using Python's logging module > LOGFILE = "/home/james/log" > logging.basicConfig( level=logging.DEBUG, > format='%(asctime)s <> %(levelname)s <> %(message)s', > datefmt='%a, %d %b %Y %H:%M:%S', > filename=LOGFILE, > filemode='w') > > -------- > > When I run the program, I get this error: > > -------- > > > Traceback (most recent call last): > File "./script.py", line 225, in <module> > sys.exit( main() ) I don't see how it would cause your problems but it's the only strange thing I can see in the traceback, so, in the interests of minimising the variables, can you change the code to call main() outside of sys.exit? Does that change anything? -- 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 Sep 30 01:09:30 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 30 Sep 2007 00:09:30 +0100 Subject: [Tutor] Error Using Logging Module References: <F0A5FC39-E8E0-4C39-B6E3-4213EE53675A@nc.rr.com><46FEA046.7020900@tds.net><536C8013-4856-4B7E-81B9-2E444E64F3DF@nc.rr.com><46FEC95C.9090909@tds.net> <3AF958FB-CC05-4954-A939-A30A4F372670@nc.rr.com> Message-ID: <fdmm0a$5ah$1@sea.gmane.org> "James" <jtp at nc.rr.com> wrote > (a) If I open a terminal and then run my python script > (./script.py), > it fails giving me the RLock error I attached in my original e-mail. > (b) If I open a FRESH terminal, run the interpreter (python), import > threading & logging and then run the same exact code snipped in > question (logging.basicConfig( ... )), it works fine (no errors). So the error seems to be in the script Do you modify sys.path in your code anywhere? > (c) Let's say I open a terminal and then run my script. It fails > with, citing the RLock error. Then, in the *same* terminal window, > I > open the python interpreter, import logging and threading, and then > run the same exact code snippet (logging.basicConfig( ... )). > Despite the fact that I have imported all the required modules, I > will get the same RLock error I received before. If I attempt to > run > the command "threading.RLock" in the interpreter, I receive the > following error message: Do you have a PYTHONPATH setting in your shell config stuff(.profile etc?) It looks like the vanilla Python session is picking up the libs but your script is getting something different. Can you try Kent's debugging statements inside your script, rather than from the >>> prompt? -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From trey at opmstech.org Sun Sep 30 01:08:23 2007 From: trey at opmstech.org (Trey Keown) Date: Sat, 29 Sep 2007 18:08:23 -0500 (CDT) Subject: [Tutor] Disable keyboard/mouse input on windows? Message-ID: <61872.68.191.136.241.1191107303.squirrel@webmail.opmstech.org> Hey everybody, I was wondering, how could I disable all keyboard/mouse input for the whole windows system while I have a video playing? So the user can't press, for example, the super key [one with windows logo on it], and have the windows menu pop up? Could this be accomplished somehow through system hooks? Thanks From wormwood_3 at yahoo.com Sun Sep 30 01:33:28 2007 From: wormwood_3 at yahoo.com (wormwood_3) Date: Sat, 29 Sep 2007 16:33:28 -0700 (PDT) Subject: [Tutor] linux terminal coloring in python Message-ID: <247976.6714.qm@web32412.mail.mud.yahoo.com> Hello, I actually wanted/looked for colored output in the CLI for quite a while myself, and finally found the solution! The magic?: "echo -e". The syntax is a little odd to use it, and I don't think I can explain it very succinctly. It may be best to see an example of it in action. I wrote a bash script to summarize files, and I used the "echo -e" syntax to color the output. Actual code: http://launchpod.homelinux.com:81/trac/code/browser/userextensions/summarizer.sh Details here, with screenshots: http://assistedsilicon.blogspot.com/2007/04/summary-execution.html Good luck! -Sam _____________________________________ ----- Original Message ---- From: Tiago Saboga <tiagosaboga at terra.com.br> To: tutor at python.org Sent: Saturday, September 29, 2007 6:11:35 PM Subject: Re: [Tutor] linux terminal coloring in python On Sat, Sep 29, 2007 at 08:32:37AM -0700, Robert Jackson wrote: > I'm trying to get some pretty colored output for a Linux console / terminal window. Google searches only reveal the curses module to colorize output. > Is there a simpler way? Curses seems to be FAR too powerful for what it is I want to do (simply to colorize a few 'print' outputs to the console). I have looked for that last week and the best I could find was ColorANSI module, distributed with ipython (in a debian system, it's /usr/share/python-support/ipython/IPython/ColorANSI.py). I just bookmarked it, and don't know how to make it work. But it seems quite simple. Tiago. _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From ghashsnaga at gmail.com Sun Sep 30 06:14:29 2007 From: ghashsnaga at gmail.com (Ara Kooser) Date: Sat, 29 Sep 2007 22:14:29 -0600 Subject: [Tutor] Learning Python (Ara Kooser) Message-ID: <2107481c0709292114m37cef57akf7afd68f08678de3@mail.gmail.com> Fred, I've been learning python off and on for a couple years now. I recommend: Alan Gauld's Learning to Program http://www.freenetpages.co.uk/hp/alan.gauld/ and How to Think Like a Computer Scientist http://www.ibiblio.org/obp/thinkCSpy/ Also find a project you are passionate about and try to program it in Python. I like Traveller (an old rpg) and text adventure games. So I used Python to create some utilities and then a game. Hope this helps. Ara -- Quis hic locus, quae regio, quae mundi plaga. Ubi sum. Sub ortu solis an sub cardine glacialis ursae. From wormwood_3 at yahoo.com Sun Sep 30 07:30:18 2007 From: wormwood_3 at yahoo.com (wormwood_3) Date: Sat, 29 Sep 2007 22:30:18 -0700 (PDT) Subject: [Tutor] CGI File Woes Message-ID: <190562.64178.qm@web32403.mail.mud.yahoo.com> Hello all, I am working on a very simple CGI script. The site I want to use it on is a shared linux host, but I confirmed that .py files in the right dir with the right permissions and shebang execute just fine, Hello World sort of tests were successful. So now something a little more involved: #!/usr/bin/python2.4 import cgitb; cgitb.enable() thefile = open("template.html", "r") templatestuff = thefile.read() thefile.close() print "Content-Type: text/html" if templatestuff: print "Found it" title1 = "I am a title!" body1 = "I am some hot content" print templatestuff % (title1, body1) "template.html" is in the same dir, and is simply: http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <html> <head> <title> %s </title> </head> <body> %s </body> </html> If I run this script without the 3 lines after the import line, it works fine (namely I get an error that templatestuff is not defined, as would be expected). With those lines however, I am getting a 500 Internal Server Error. Since I am not shown an error page with cgitb, this would likely mean a syntax error. However, if I run the script locally, it works just fine, printing out the HTML with variables filled in. Now for the odd part: If I change that open line to "thefile = open("asdas", "r")", I get "IOError: [Errno 2] No such file or directory: 'asdas' ". So it seems the script is finding the template file when I have it as above, but is throwing something when it tries to open it. I have confirmed the file has the right permissions, I have even tried it with all permissions set on that file. I am just totally baffled why I cannot open any files from the script. Any ideas? -Sam From sli1que at yahoo.com Sun Sep 30 08:38:18 2007 From: sli1que at yahoo.com (Eric Walker) Date: Sat, 29 Sep 2007 23:38:18 -0700 (PDT) Subject: [Tutor] CGI File Woes In-Reply-To: <190562.64178.qm@web32403.mail.mud.yahoo.com> Message-ID: <807312.61673.qm@web60117.mail.yahoo.com> The best way to debug cgi is to tail the server log when you don't get commandline output. This will give you a clue to what is happening.. shoulld be something like /var/log/apache or something like that... Eric.... wormwood_3 <wormwood_3 at yahoo.com> wrote: Hello all, I am working on a very simple CGI script. The site I want to use it on is a shared linux host, but I confirmed that .py files in the right dir with the right permissions and shebang execute just fine, Hello World sort of tests were successful. So now something a little more involved: #!/usr/bin/python2.4 import cgitb; cgitb.enable() thefile = open("template.html", "r") templatestuff = thefile.read() thefile.close() print "Content-Type: text/html" if templatestuff: print "Found it" title1 = "I am a title!" body1 = "I am some hot content" print templatestuff % (title1, body1) "template.html" is in the same dir, and is simply: http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> %s %s If I run this script without the 3 lines after the import line, it works fine (namely I get an error that templatestuff is not defined, as would be expected). With those lines however, I am getting a 500 Internal Server Error. Since I am not shown an error page with cgitb, this would likely mean a syntax error. However, if I run the script locally, it works just fine, printing out the HTML with variables filled in. Now for the odd part: If I change that open line to "thefile = open("asdas", "r")", I get "IOError: [Errno 2] No such file or directory: 'asdas' ". So it seems the script is finding the template file when I have it as above, but is throwing something when it tries to open it. I have confirmed the file has the right permissions, I have even tried it with all permissions set on that file. I am just totally baffled why I cannot open any files from the script. Any ideas? -Sam _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor --------------------------------- Catch up on fall's hot new shows on Yahoo! TV. Watch previews, get listings, and more! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20070929/8833bdc7/attachment.htm From wescpy at gmail.com Sun Sep 30 09:51:36 2007 From: wescpy at gmail.com (wesley chun) Date: Sun, 30 Sep 2007 00:51:36 -0700 Subject: [Tutor] detecing palindromic strings In-Reply-To: <493654.17257.qm@web51601.mail.re2.yahoo.com> References: <493654.17257.qm@web51601.mail.re2.yahoo.com> Message-ID: <78b3a9580709300051w279a259kfc6d1127be2c0dde@mail.gmail.com> greetings, and welcome to Python! there were some good solutions using the extended slice operator ([::-1]), but that may be an obscure notation to many newbies to Python, as powerful as it can be. i'm going to pick up terry's response and further clarify here (i hope!): > string_list_orig = string_list this is a critical assignment. and yes, you already figured out that you are just "copying pointers" here. in Python, we say that you are creating an alias or another reference to the same object. you are not creating a new one which is a copy. there are a couple of ways to do the copy. 1. terry already mentioned string_list[:] takes an improper (or complete) slice of the existing string 2. kent also chimed in with list(string_list), which will do exactly the same 3. more off the beaten path, you can also using copy.copy(): import copy string_list_orig = copy.copy(string_list) all 3 do exactly the same thing: create a new list but copy the *references* to the internal objects. these are known as "shallow copies." they don't *copy* the contained objects themselves. this is another place that newbies go HUH?!? the bottom line is that if the contained objects are mutable (meaning their values can be altered), changing them from one reference will affect the outcome via an alias. in order to copy the container as well as its contents, you need to use copy.deepcopy(). see the man page there for more details. there's also a section in the book on this. > string_list.reverse() because both variable names reference the same object, doing this [or string_list_orig.reverse()] will have the same effect. > print string_list_orig > print string_list both "point" to the exact same object, hence the duplicate output. 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 Sun Sep 30 10:02:05 2007 From: wescpy at gmail.com (wesley chun) Date: Sun, 30 Sep 2007 01:02:05 -0700 Subject: [Tutor] creating the equivalent of string.strip() In-Reply-To: <fdl0ku$juf$1@sea.gmane.org> References: <465410.15557.qm@web51609.mail.re2.yahoo.com> <fdl0ku$juf$1@sea.gmane.org> Message-ID: <78b3a9580709300102x12cbe392uebb988ed965c7202@mail.gmail.com> > > I'm not sure how to proceed. My biggest stumbling > > block is how to detect the leading and trailing > > whitespace. > > Use indexing. > Try using a while loop. > Or maybe two? > > And strings have an isspace method... unfortunately, the isspace() string method only returns True if all chars in the string are whitespace chars and False otherwise, so that's a bummer. on the other hand, the string module also has an attribute called string.whitespace that contains all (valid/recognized) whitespace characters with which you can compare individual characters of your string with. an alternative (yet possibly more complex) solution can use regular expressions. you can also "cheat" and read the source code for the *strip() methods and just duplicate them in Python. ;-) regardless of what method you use, you should recognize that strings cannot be modified (immutable), meaning that you will have to create a new string (with all the whitespace removed). good luck! -- 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 Sun Sep 30 10:02:48 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 30 Sep 2007 09:02:48 +0100 Subject: [Tutor] CGI File Woes References: <190562.64178.qm@web32403.mail.mud.yahoo.com> Message-ID: <fdnl88$12i$1@sea.gmane.org> "wormwood_3" <wormwood_3 at yahoo.com> wrote > #!/usr/bin/python2.4 > > import cgitb; cgitb.enable() > > thefile = open("template.html", "r") > templatestuff = thefile.read() > thefile.close() > print "Content-Type: text/html" > if templatestuff: > print "Found it" > title1 = "I am a title!" > body1 = "I am some hot content" > print templatestuff % (title1, body1) > > "template.html" is in the same dir, and is simply: > > http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> > <html> > <html> Did you mean for there to be two <html> tags or is it a typo? > <head> > <title> %s </title> > </head> > <body> > %s > </body> > </html> > > If I run this script without the 3 lines after the import line, > it works fine (namely I get an error that templatestuff is not > defined, > I am getting a 500 Internal Server Error. > Since I am not shown an error page with cgitb, this would likely > mean a syntax error. I've never used gcitb (and until now didn't know it existed!) so can't comment. But I usually see this when the web user doesn't have permission to open the html file. But... > .... I have confirmed the file has the right permissions, > I have even tried it with all permissions set on that file. For all users? Remember that the web server runs as a separate user and that's the user than needs to open the file. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From noufal at airtelbroadband.in Sun Sep 30 11:31:02 2007 From: noufal at airtelbroadband.in (Noufal Ibrahim) Date: Sun, 30 Sep 2007 15:01:02 +0530 Subject: [Tutor] linux terminal coloring in python In-Reply-To: <309496.28533.qm@web45608.mail.sp1.yahoo.com> References: <309496.28533.qm@web45608.mail.sp1.yahoo.com> Message-ID: <46FF6CD6.7000907@airtelbroadband.in> Robert Jackson wrote: > I'm trying to get some pretty colored output for a Linux console / terminal window. Google searches only reveal the curses module to colorize output. > > Is there a simpler way? Curses seems to be FAR too powerful for what it is I want to do (simply to colorize a few 'print' outputs to the console). > I stumbled across a recipe for a portable terminal colouring scheme here http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/475116 You need to use the curses module but don't need to put the terminal into raw mode etc. Maybe it will suit your needs. Peace -- ~noufal From noufal at airtelbroadband.in Sun Sep 30 11:37:59 2007 From: noufal at airtelbroadband.in (Noufal Ibrahim) Date: Sun, 30 Sep 2007 15:07:59 +0530 Subject: [Tutor] questions about tuples In-Reply-To: <4e7ea3b40709261007g15fe6e3al5ad3ab48c09e181b@mail.gmail.com> References: <4e7ea3b40709261007g15fe6e3al5ad3ab48c09e181b@mail.gmail.com> Message-ID: <46FF6E77.7040802@airtelbroadband.in> Fangwen Lu wrote: > Dear all- > > I want to do some loops. Each loop will generate a tuple. Eventually I > want to put tuples together in a higher level of tuple. Do you know how > to do this? > > Say a=(1,2,3), b=(4,3,2),c=(9,5,6). I want to get a tuple as ((1,2,3), > (4,3,2),(9,5,6)). > > If there are just 2 tuples, I can write x=a and then x=(x,b). But for 3 > tuples or more, I will get something like (((1,2,3), (4,3,2)),(9,5,6)). > Are you sure you need tuples? Wouldn't lists be better, you can append generated elements to the list and finally (if you want) convert it into a tuple. -- ~noufal From mlangford.cs03 at gtalumni.org Sun Sep 30 16:15:27 2007 From: mlangford.cs03 at gtalumni.org (Michael Langford) Date: Sun, 30 Sep 2007 10:15:27 -0400 Subject: [Tutor] CGI File Woes In-Reply-To: <190562.64178.qm@web32403.mail.mud.yahoo.com> References: <190562.64178.qm@web32403.mail.mud.yahoo.com> Message-ID: <82b4f5810709300715g25889ddn29536e6feef48763@mail.gmail.com> Remember, you can always add more logging that goes to your own log file. Have it open a file in /tmp and write out a log of what's happening. Wrap your main code block in an exception handler, etc. Have it print out the exception to the log file. This will allow you to look and see what the error is rather than speculating about it. --Michael On 9/30/07, wormwood_3 <wormwood_3 at yahoo.com> wrote: > Hello all, > > I am working on a very simple CGI script. The site I want to use it on is a shared linux host, but I confirmed that .py files in the right dir with the right permissions and shebang execute just fine, Hello World sort of tests were successful. > > So now something a little more involved: > > > #!/usr/bin/python2.4 > > import cgitb; cgitb.enable() > > thefile = open("template.html", "r") > templatestuff = thefile.read() > thefile.close() > print "Content-Type: text/html" > if templatestuff: > print "Found it" > title1 = "I am a title!" > body1 = "I am some hot content" > print templatestuff % (title1, body1) > > "template.html" is in the same dir, and is simply: > > http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> > <html> > <html> > <head> > <title> %s </title> > </head> > <body> > %s > </body> > </html> > > If I run this script without the 3 lines after the import line, it works fine (namely I get an error that templatestuff is not defined, as would be expected). With those lines however, I am getting a 500 Internal Server Error. Since I am not shown an error page with cgitb, this would likely mean a syntax error. However, if I run the script locally, it works just fine, printing out the HTML with variables filled in. Now for the odd part: If I change that open line to "thefile = open("asdas", "r")", I get "IOError: [Errno 2] No such file or directory: 'asdas' > ". So it seems the script is finding the template file when I have it as above, but is throwing something when it tries to open it. I have confirmed the file has the right permissions, I have even tried it with all permissions set on that file. > > I am just totally baffled why I cannot open any files from the script. > > Any ideas? > -Sam > > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Michael Langford Phone: 404-386-0495 Consulting: http://www.TierOneDesign.com/ Entertaining: http://www.ThisIsYourCruiseDirectorSpeaking.com From alan.gauld at btinternet.com Sun Sep 30 17:00:51 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 30 Sep 2007 16:00:51 +0100 Subject: [Tutor] questions about tuples References: <4e7ea3b40709261007g15fe6e3al5ad3ab48c09e181b@mail.gmail.com> Message-ID: <fdodo3$1db$1@sea.gmane.org> "Fangwen Lu" <lufangwen at gmail.com> wrote > I want to do some loops. Each loop will generate a tuple. Eventually > I want > to put tuples together in a higher level of tuple. Do you know how > to do > this? Inaddition to other replies, you might be able to use a generator expression to do it in one line: >>> tuple( ( (x,x+1) for x in range(3) ) ) ((0, 1), (1, 2), (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 Sun Sep 30 17:02:34 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 30 Sep 2007 16:02:34 +0100 Subject: [Tutor] creating the equivalent of string.strip() References: <465410.15557.qm@web51609.mail.re2.yahoo.com><fdl0ku$juf$1@sea.gmane.org> <78b3a9580709300102x12cbe392uebb988ed965c7202@mail.gmail.com> Message-ID: <fdodra$1lu$1@sea.gmane.org> "wesley chun" <wescpy at gmail.com> wrote in message news:78b3a9580709300102x12cbe392uebb988ed965c7202 at mail.gmail.com... >> > I'm not sure how to proceed. My biggest stumbling >> > block is how to detect the leading and trailing >> > whitespace. >> >> Use indexing. >> Try using a while loop. >> Or maybe two? >> >> And strings have an isspace method... > > unfortunately, the isspace() string method only returns True if all > chars in the string are whitespace chars and False otherwise, so > that's a bummer. But the string can be one character long: s = 'fred\n' print s[-1].isspace() # --> True :-) Alan G From wormwood_3 at yahoo.com Sun Sep 30 17:38:45 2007 From: wormwood_3 at yahoo.com (wormwood_3) Date: Sun, 30 Sep 2007 08:38:45 -0700 (PDT) Subject: [Tutor] CGI File Woes Message-ID: <853537.54170.qm@web32405.mail.mud.yahoo.com> >>Did you mean for there to be two <html> tags or is it a typo? Just a typo. Should not have a big effect, but it has been fixed. >>I've never used cgitb (and until now didn't know it existed!) >>so can't comment. I had not heard of it until this week when I started working on CGI stuff, but I have found it super handy! All you have to do it "import cgitb; cgitb.enable()" and all tracebacks will get printed to nicely formatted HTML output on the page you were trying to load. >>But I usually see this when the web user doesn't have >>permission to open the html file. But... This definitely would make the most sense in that the error is not a Python error, at least I am assuming so from the lack of traceback. However, the odd thing is that if I hit template.html directly, the page renders just fine. This would mean the web user can access it, right? And I was assuming the Python script was being run by the web user as well, but perhaps it is not. >>For all users? >>Remember that the web server runs as a separate user >>and that's the user than needs to open the file. Sorry, I stated that poorly. What I meant was that in the process of troubleshooting, I ended up enabling ALL permissions, so user, group, and others could read, write, and execute. So since this is now the case, and the script runs fine locally, and I can hit template.html on its own on the web server... I am still quite baffled! -Sam From alan.gauld at btinternet.com Sun Sep 30 18:26:17 2007 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 30 Sep 2007 17:26:17 +0100 Subject: [Tutor] CGI File Woes References: <853537.54170.qm@web32405.mail.mud.yahoo.com> Message-ID: <fdoio9$fak$1@sea.gmane.org> "wormwood_3" <wormwood_3 at yahoo.com> wrote > I had not heard of it until this week when I started working on > CGI stuff, but I have found it super handy! All you have to do > it "import cgitb; cgitb.enable()" and all tracebacks will get > printed to nicely formatted HTML output on the page you > were trying to load. Ok, Heres a thought. try forcing an error after opening the file. See what the traceback says. You can add a message string to an exception so that it will print... class LogError(Exception): pass raise LogError, "Any old text here" So you force the cgitb to kick in and print the mesage you specify, use it like a print statement to debug whats happening... Its a bit laborious but better than nothing! See if that helps Alan G From noufal at airtelbroadband.in Sun Sep 30 19:58:22 2007 From: noufal at airtelbroadband.in (Noufal Ibrahim) Date: Sun, 30 Sep 2007 23:28:22 +0530 Subject: [Tutor] CGI File Woes In-Reply-To: <190562.64178.qm@web32403.mail.mud.yahoo.com> References: <190562.64178.qm@web32403.mail.mud.yahoo.com> Message-ID: <46FFE3BE.30108@airtelbroadband.in> wormwood_3 wrote: > Hello all, > I am working on a very simple CGI script. The site I want to use it > on is a shared linux host, but I confirmed that .py files in the > right dir with the right permissions and shebang execute just fine, > Hello World sort of tests were successful. Those are the first things I'd try too. > So now something a little more involved: > > > #!/usr/bin/python2.4 > > import cgitb; cgitb.enable() > > thefile = open("template.html", "r") > templatestuff = thefile.read() > thefile.close() > print "Content-Type: text/html" > if templatestuff: > print "Found it" > title1 = "I am a title!" > body1 = "I am some hot content" > print templatestuff % (title1, body1) > > "template.html" is in the same dir, and is simply: > > http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> > <html> > <html> > <head> > <title> %s </title> > </head> > <body> > %s > </body> > </html> [..] > Any ideas? Here are a few ideas plus some suggestions. I've been dabbling with python/cgi myself and so there might be something you can take from these comments. - If your webserver and the machine where you executed this from are different (home directories are NFS mounts etc.), then the permissions and directory visibilities might affect things. - It looks fairly obvious that the problem is in those three lines. Your content-type header is printed only after those lines are executed so if there is an error there, you'll get an error 500. Try putting your content-type line right after your import cgitb. - Wrap the 3 suspicious lines in a try block and print out the execption which you catch. - Tail the server logs to see what happened. Good luck. -- ~noufal From mwalsh at groktech.org Sun Sep 30 19:07:02 2007 From: mwalsh at groktech.org (Martin Walsh) Date: Sun, 30 Sep 2007 12:07:02 -0500 Subject: [Tutor] CGI File Woes In-Reply-To: <853537.54170.qm@web32405.mail.mud.yahoo.com> References: <853537.54170.qm@web32405.mail.mud.yahoo.com> Message-ID: <46FFD7B6.7020103@groktech.org> wormwood_3 wrote: >>> I've never used cgitb (and until now didn't know it existed!) >>> so can't comment. > > I had not heard of it until this week when I started working on CGI stuff, but I have found it super handy! All you have to do it "import cgitb; cgitb.enable()" and all tracebacks will get printed to nicely formatted HTML output on the page you were trying to load. > No doubt cgitb is a great tool for debugging cgi, but IIUC there are at least two instances when you will not get the pretty printed tracebacks in the browser when using cgitb. One is after, what I would call, a 'compile time' exception such as SyntaxError, in your python code. The other is when the python code runs without exception, but you have not separated the header and the document content with a newline. At least, I have found these to be true when using apache-cgi. Consider the following examples: #!/usr/bin/env python # raises a SyntaxError import cgi import cgitb; cgitb.enable() print "Content-type: text/html\n\n" # NOTE: purposeful misspelling of the print statement prin "<html><body><p>Hello, world!</p></body></html>" # the code above will produce a server 500, with apache # complaining about "premature end of script headers" ... #!/usr/bin/env python # good python, bad data import cgi import cgitb; cgitb.enable() print "Content-type: text/html" print "<html><body><p>Hello, world!</p></body></html>" # this is syntactically correct python, and will # run from the command line, but the html header # and html content have no separation, so apache # will consider all of it to be header info, resulting # in another server 500, "malformed header" As others have advised, under these circumstances you can review the apache error log (if your webhost allows it). Or roll-your-own logging equivalent, and run your cgi from a terminal to catch SyntaxErrors and the like. HTH, Marty From wormwood_3 at yahoo.com Sun Sep 30 22:26:59 2007 From: wormwood_3 at yahoo.com (wormwood_3) Date: Sun, 30 Sep 2007 13:26:59 -0700 (PDT) Subject: [Tutor] CGI File Woes Message-ID: <939808.45127.qm@web32411.mail.mud.yahoo.com> Those examples were a lot of help Martin. Turned out the only issue was that I did not have this line right: print "Content-type: text/html\n\n" With that form, it loaded just fine. It had been running fine from the terminal, but without this line being right, Apache did not know what to do with it. I had spoken with my web-hosting provider, but since I had a shared account I was unable to view the server logs. And the person helping me knew nothing about Python (he kept slipping and calling it PHP actually, to my dismay and chagrin:-) ). Thanks for all the help, Alan and Martin. -Sam _________________ ----- Original Message ---- From: Martin Walsh <mwalsh at groktech.org> To: tutor at python.org Sent: Sunday, September 30, 2007 1:07:02 PM Subject: Re: [Tutor] CGI File Woes No doubt cgitb is a great tool for debugging cgi, but IIUC there are at least two instances when you will not get the pretty printed tracebacks in the browser when using cgitb. One is after, what I would call, a 'compile time' exception such as SyntaxError, in your python code. The other is when the python code runs without exception, but you have not separated the header and the document content with a newline. At least, I have found these to be true when using apache-cgi. Consider the following examples: #!/usr/bin/env python # raises a SyntaxError import cgi import cgitb; cgitb.enable() print "Content-type: text/html\n\n" # NOTE: purposeful misspelling of the print statement prin "<html><body><p>Hello, world!</p></body></html>" # the code above will produce a server 500, with apache # complaining about "premature end of script headers" ... #!/usr/bin/env python # good python, bad data import cgi import cgitb; cgitb.enable() print "Content-type: text/html" print "<html><body><p>Hello, world!</p></body></html>" # this is syntactically correct python, and will # run from the command line, but the html header # and html content have no separation, so apache # will consider all of it to be header info, resulting # in another server 500, "malformed header" As others have advised, under these circumstances you can review the apache error log (if your webhost allows it). Or roll-your-own logging equivalent, and run your cgi from a terminal to catch SyntaxErrors and the like. HTH, Marty _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor