From scot@possum.in-berlin.de Sat Feb 1 00:21:02 2003 From: scot@possum.in-berlin.de (Scot Stevenson) Date: Sat Feb 1 00:21:02 2003 Subject: [Tutor] Getting mail out of the box and into the email module Message-ID: <200301312212.34659.scot@possum.in-berlin.de> Hi there, Progress strikes again: I'm rewriting an older program of mine that takes mail out of my mailbox, plays around with it and then saves it. Up until now, I've done it with the UnixMailbox part of the "mailbox" module, which you can hit with a "next()" method to get the individual mails as a rfc822.Message object. That was fun and worked, but it was one of my first larger efforts and the program, uh, sucks. Hence the rewrite. Now, Python 2.2 has a new module called "email" which seems to be a lot easier to use and also seems set to superseed the rfc822 module. There is one small problem, though: I can't get the mailbox module to hand me an email.Message object. In theory, you can pass the mailbox object a "factory", but that only seems to work with rfc822: Python 2.2.1 (#1, Sep 10 2002, 17:49:17) [GCC 3.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import mailbox >>> import email >>> thebox = file("test.mbox", "r") >>> rawbox = mailbox.UnixMailbox(thebox, email.Message) >>> rawbox.next() Traceback (most recent call last): File "", line 1, in ? File "/usr/lib/python2.2/mailbox.py", line 34, in next return self.factory(_Subfile(self.fp, start, stop)) TypeError: 'module' object is not callable The difference seems to be that the email.Message constructor doesn't take arguments, in constrast to rfc822.Message, which takes anything that has a readline() method. Bummer. Of course, what I could do is take the rfc822.Message object, save it as a file (or rather a file-like object in memory), and reload it with some of the tricks of the email module -- but then I could just as well use the rfc822 module directly. Now, am I missing something here, or has the mailbox module failed to go with the times? And just how do you get a message out of a Unix mailbox and into a email.Message object? Thanks, Y, Scot -- Scot W. Stevenson -- scot@possum.in-berlin.de -- Zepernick, Germany From pversteegen@gcnetmail.net Sat Feb 1 09:37:01 2003 From: pversteegen@gcnetmail.net (Pete Versteegen) Date: Sat Feb 1 09:37:01 2003 Subject: [Tutor] Global scope Message-ID: Listers, I am confused about global variables. I have a C/C++ program with a large number of functions, and a block of global variables (I know its best to pass references to functions, but the pass-through list would often be long, and its hence much easier to keep track of the definitions in a single block) that I'm converting to python. I am translating the functions into corresponding modules. Functions call functions, which in turn call othr functions, etc. How do I declare some variables, including lists and dictionaries, that are used in these lower functions to be globals, accessible by all functions? I used a statement such as: global case_number in a function, and declare it case_number = 0 in the main module, but I get: NameError: global name 'case_number' is not defined BTW, I asked some time ago about formatting a la Fortran. At the link below is a module that does all of that. http://starship.python.net/crew/hinsen/part2.html Thanks! Pete Versteegen pversteegen@gcnetmail.net __________________________ From francois.granger@free.fr Sat Feb 1 10:06:02 2003 From: francois.granger@free.fr (Francois Granger) Date: Sat Feb 1 10:06:02 2003 Subject: [Tutor] Global scope In-Reply-To: References: Message-ID: At 09:36 -0500 01/02/2003, in message [Tutor] Global scope, Pete Versteegen wrote: > >I used a statement such as: global case_number in a function, and declare >it case_number = 0 in the main module, but I get: > >NameError: global name 'case_number' is not defined #! python global case_number, other case_number = 0 def myFunc(): global case_number case_number += 1 Untested. But if you have a lot of them, you will have a better time creating a separate module for all these and import it or have a dict holding all of them. #! python myvars = {'case_number': 0, 'other': 1 } def myFunc(vars): vars['case_number'] += 1 result = myFunc(myvars) -- Recently using MacOSX....... From milosc@poczta.fm Sat Feb 1 10:32:02 2003 From: milosc@poczta.fm (zywy) Date: Sat Feb 1 10:32:02 2003 Subject: [Tutor] Exponentially distributed random number generation Message-ID: <001201bbf789$35df7dc0$ade871d9@zh648jn04g8z0l> This is a multi-part message in MIME format. ------=_NextPart_000_000F_01BBF791.96C96440 Content-Type: text/plain; charset="iso-8859-2" Content-Transfer-Encoding: quoted-printable Does anyone know whether there is a python function to generate = exponentially distributed random numbers? Or do I have to use simple = random generator to write my own generator(i.e. exponentially = distributed random generator)? ------=_NextPart_000_000F_01BBF791.96C96440 Content-Type: text/html; charset="iso-8859-2" Content-Transfer-Encoding: quoted-printable
Does anyone know whether there is = a python=20 function to generate exponentially distributed random numbers? Or do I = have to=20 use simple random generator to write my own generator(i.e.=20 exponentially distributed random generator)?
----------------------------------------------------------------------
W Internecie kupuj i plac BEZPIECZNIE >>> http://link.interia.pl/f16c5
------=_NextPart_000_000F_01BBF791.96C96440-- From pversteegen@gcnetmail.net Sat Feb 1 13:43:02 2003 From: pversteegen@gcnetmail.net (Pete Versteegen) Date: Sat Feb 1 13:43:02 2003 Subject: [Tutor] Global scope In-Reply-To: Message-ID: It's not working.... Here is what I'm doing: The following code is saved in a file named main.py #!/usr/bin/python from myFunc1 import myFunc1 global case_number case_number = 0 last_case = myFunc1() print case_number The following code is saved in a file named myFunc1.py def myFunc1(): global case_number case_number += 1 When I execute main: ./main.py, I get: Traceback (most recent call last): File "./main.py", line 8, in ? last_case = myFunc1() File "./myFunc1.py", line 3, in myFunc1 case_number += 1 NameError: global name 'case_number' is not defined Pete Versteegen pversteegen@gcnetmail.net __________________________ From dyoo@hkn.eecs.berkeley.edu Sat Feb 1 13:52:08 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat Feb 1 13:52:08 2003 Subject: [Tutor] Exponentially distributed random number generation In-Reply-To: <001201bbf789$35df7dc0$ade871d9@zh648jn04g8z0l> Message-ID: On Wed, 1 Jan 1997, zywy wrote: > Does anyone know whether there is a python function to generate > exponentially distributed random numbers? Hi Zywy, Yup: you'll probably want to use the 'random' module's "expovariate()" function: here's a link to its documentation: http://www.python.org/doc/lib/module-random.html If you have more questions, please feel free to ask. Good luck! From Janssen@rz.uni-frankfurt.de Sat Feb 1 14:59:01 2003 From: Janssen@rz.uni-frankfurt.de (Michael Janssen) Date: Sat Feb 1 14:59:01 2003 Subject: [Tutor] Getting mail out of the box and into the email module In-Reply-To: <200301312212.34659.scot@possum.in-berlin.de> Message-ID: Hello Scot, hey "email" must be great! Thanks for pointing me to this. You must import email.Message to get email.Message.Message() email.Message.Message provides the object-model; email.Parser.Parser reads Strings into email.Message.Message instances. When you take a look at mailbox.UnixMailbox, you will see, that the "factory" takes a _subfile which UnixMailbox produce from the original file-object. The parser method from email.Parser.Parser is what you want as factory. Or with a shortcut: email.message_from_file() I currently make experiences with: mb = mailbox.UniMailbox(fp, email.message_from_file) I have adapted msg.unixfrom to get_unixfrom() and those getsomething stuff to get_something. Now my mailbox-reading script is functional but doesn't do what it was expected to do (kill attachments and uneccessary headers)... let's see. Michael On Fri, 31 Jan 2003, Scot Stevenson wrote: > Hi there, > > Progress strikes again: > > I'm rewriting an older program of mine that takes mail out of my mailbox, > plays around with it and then saves it. Up until now, I've done it with the > UnixMailbox part of the "mailbox" module, which you can hit with a "next()" > method to get the individual mails as a rfc822.Message object. That was fun > and worked, but it was one of my first larger efforts and the program, uh, > sucks. Hence the rewrite. > > Now, Python 2.2 has a new module called "email" which seems to be a lot easier > to use and also seems set to superseed the rfc822 module. There is one small > problem, though: I can't get the mailbox module to hand me an email.Message > object. In theory, you can pass the mailbox object a "factory", but that only > seems to work with rfc822: > > Python 2.2.1 (#1, Sep 10 2002, 17:49:17) > [GCC 3.2] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> import mailbox > >>> import email > >>> thebox = file("test.mbox", "r") > >>> rawbox = mailbox.UnixMailbox(thebox, email.Message) > >>> rawbox.next() > Traceback (most recent call last): > File "", line 1, in ? > File "/usr/lib/python2.2/mailbox.py", line 34, in next > return self.factory(_Subfile(self.fp, start, stop)) > TypeError: 'module' object is not callable > > The difference seems to be that the email.Message constructor doesn't take > arguments, in constrast to rfc822.Message, which takes anything that has a > readline() method. Bummer. > > Of course, what I could do is take the rfc822.Message object, save it as a > file (or rather a file-like object in memory), and reload it with some of the > tricks of the email module -- but then I could just as well use the rfc822 > module directly. > > Now, am I missing something here, or has the mailbox module failed to go with > the times? And just how do you get a message out of a Unix mailbox and into a > email.Message object? > > Thanks, > Y, Scot > > -- > Scot W. Stevenson -- scot@possum.in-berlin.de -- Zepernick, Germany > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From ramrom@earthling.net Sat Feb 1 16:34:01 2003 From: ramrom@earthling.net (Bob Gailer) Date: Sat Feb 1 16:34:01 2003 Subject: [Tutor] Global scope In-Reply-To: References: Message-ID: <5.2.0.9.0.20030201142050.02f28bd8@66.28.54.253> --=======44DA7583======= Content-Type: text/plain; x-avg-checked=avg-ok-72668EC; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit The scope of globals is the containing module. Thus "global case_number" wants case_number to be in module myFunc1. It will NOT look anywhere else. Importing is hierarchical; main can import other modules, and can reference objects therein; the imported modules can't see objects in the main module. Please tell us a bit more about what you want to accomplish, then we can suggest alternatives. At 01:42 PM 2/1/2003 -0500, Pete Versteegen wrote: >It's not working.... Here is what I'm doing: > >The following code is saved in a file named main.py > >#!/usr/bin/python > >from myFunc1 import myFunc1 > >global case_number >case_number = 0 > >last_case = myFunc1() > >print case_number > > > >The following code is saved in a file named myFunc1.py > >def myFunc1(): > global case_number > case_number += 1 > > >When I execute main: ./main.py, I get: > >Traceback (most recent call last): > File "./main.py", line 8, in ? > last_case = myFunc1() > File "./myFunc1.py", line 3, in myFunc1 > case_number += 1 >NameError: global name 'case_number' is not defined > > > > >Pete Versteegen >pversteegen@gcnetmail.net >__________________________ > > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > >--- >Incoming mail is certified Virus Free. >Checked by AVG anti-virus system (http://www.grisoft.com). >Version: 6.0.445 / Virus Database: 250 - Release Date: 1/21/2003 Bob Gailer mailto:ramrom@earthling.net 303 442 2625 --=======44DA7583======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-72668EC Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.445 / Virus Database: 250 - Release Date: 1/21/2003 --=======44DA7583=======-- From ramrom@earthling.net Sat Feb 1 16:50:02 2003 From: ramrom@earthling.net (Bob Gailer) Date: Sat Feb 1 16:50:02 2003 Subject: [Tutor] Global scope In-Reply-To: References: Message-ID: <5.2.0.9.0.20030201144434.02f2d438@66.28.54.253> --=======7D624F9E======= Content-Type: text/plain; x-avg-checked=avg-ok-72668EC; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit This is probably NOT the best solution, but here's how you can "peek" at the main module. In myFunc1 put: import sys main = sys.modules['__main__'] print main.a You can do anything you want with main.a (as long as its legal in Python). This technique also lets you reference anything in any imported module. At 01:42 PM 2/1/2003 -0500, Pete Versteegen wrote: >It's not working.... Here is what I'm doing: > >The following code is saved in a file named main.py > >#!/usr/bin/python > >from myFunc1 import myFunc1 > >global case_number >case_number = 0 > >last_case = myFunc1() > >print case_number > > > >The following code is saved in a file named myFunc1.py > >def myFunc1(): > global case_number > case_number += 1 > > >When I execute main: ./main.py, I get: > >Traceback (most recent call last): > File "./main.py", line 8, in ? > last_case = myFunc1() > File "./myFunc1.py", line 3, in myFunc1 > case_number += 1 >NameError: global name 'case_number' is not defined > > > > >Pete Versteegen >pversteegen@gcnetmail.net >__________________________ > > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > >--- >Incoming mail is certified Virus Free. >Checked by AVG anti-virus system (http://www.grisoft.com). >Version: 6.0.445 / Virus Database: 250 - Release Date: 1/21/2003 Bob Gailer mailto:ramrom@earthling.net 303 442 2625 --=======7D624F9E======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-72668EC Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.445 / Virus Database: 250 - Release Date: 1/21/2003 --=======7D624F9E=======-- From antoneheyward@hotmail.com Sat Feb 1 17:12:01 2003 From: antoneheyward@hotmail.com (antone heyward) Date: Sat Feb 1 17:12:01 2003 Subject: [Tutor] drive size Message-ID: is there an easy way to get a systems local drives along with its totalspace, freespace, and usedspace. _________________________________________________________________ MSN 8 with e-mail virus protection service: 2 months FREE* http://join.msn.com/?page=features/virus From tbrauch@mindless.com Sat Feb 1 17:14:03 2003 From: tbrauch@mindless.com (Timothy M. Brauch) Date: Sat Feb 1 17:14:03 2003 Subject: [Tutor] ftplib Message-ID: <000c01c2ca3f$1dc69860$6600a8c0@tbrauch> I am trying to write a small python program that will login to an ftp server and put a file there. I am using ftplib, and I have figured out how to log in (that was easy). However, I cannot seem to figure out how to put a file. - Tim From Janssen@rz.uni-frankfurt.de Sat Feb 1 17:32:02 2003 From: Janssen@rz.uni-frankfurt.de (Michael Janssen) Date: Sat Feb 1 17:32:02 2003 Subject: [Tutor] drive size In-Reply-To: Message-ID: On Sat, 1 Feb 2003, antone heyward wrote: > is there an easy way to get a systems local drives along with its > totalspace, freespace, and usedspace. on unix: statvfs() (in module os) ---> os-file-dir.html#l2h-1195 > > > > > > _________________________________________________________________ > MSN 8 with e-mail virus protection service: 2 months FREE* > http://join.msn.com/?page=features/virus > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From ramrom@earthling.net Sat Feb 1 17:42:04 2003 From: ramrom@earthling.net (Bob Gailer) Date: Sat Feb 1 17:42:04 2003 Subject: [Tutor] ftplib In-Reply-To: <000c01c2ca3f$1dc69860$6600a8c0@tbrauch> Message-ID: <5.2.0.9.0.20030201153926.02f41d00@66.28.54.253> --=======69DD463F======= Content-Type: multipart/alternative; x-avg-checked=avg-ok-72668EC; boundary="=====================_14786622==.ALT" --=====================_14786622==.ALT Content-Type: text/plain; x-avg-checked=avg-ok-72668EC; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit At 05:13 PM 2/1/2003 -0500, Timothy M. Brauch wrote: >I am trying to write a small python program that will login to an ftp server >and put a file there. I am using ftplib, and I have figured out how to log >in (that was easy). However, I cannot seem to figure out how to put a file. Did you study the ftplib documentation in the Python Library reference? It offers:storbinary(command, file[, blocksize]) Store a file in binary transfer mode. command should be an appropriate "STOR" command: "STOR filename". file is an open file object which is read until EOF using its read() method in blocks of size blocksize to provide the data to be stored. The blocksize argument defaults to 8192. Changed in version 2.1: default for blocksize added. storlines(command, file) Store a file in ASCII transfer mode. command should be an appropriate "STOR" command (see storbinary()). Lines are read until EOF from the open file object file using its readline() method to provide the data to be stored. Bob Gailer mailto:ramrom@earthling.net 303 442 2625 --=====================_14786622==.ALT Content-Type: text/html; x-avg-checked=avg-ok-72668EC; charset=us-ascii Content-Transfer-Encoding: 8bit At 05:13 PM 2/1/2003 -0500, Timothy M. Brauch wrote:

I am trying to write a small python program that will login to an ftp server
and put a file there.  I am using ftplib, and I have figured out how to log
in (that was easy).  However, I cannot seem to figure out how to put a file.

Did you study the ftplib documentation in the Python Library reference? It offers:storbinary(command, file[, blocksize])
Store a file in binary transfer mode. command should be an appropriate "STOR" command: "STOR filename". file is an open file object which is read until EOF using its read() method in blocks of size blocksize to provide the data to be stored. The blocksize argument defaults to 8192. Changed in version 2.1: default for blocksize added.

storlines(command, file)
Store a file in ASCII transfer mode. command should be an appropriate "STOR" command (see storbinary()). Lines are read until EOF from the open file object file using its readline() method to provide the data to be stored.

Bob Gailer
mailto:ramrom@earthling.net
303 442 2625
--=====================_14786622==.ALT-- --=======69DD463F======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-72668EC Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.445 / Virus Database: 250 - Release Date: 1/21/2003 --=======69DD463F=======-- From R. Alan Monroe" References: Message-ID: <155121659487.20030201174814@columbus.rr.com> > is there an easy way to get a systems local drives along with its > totalspace, freespace, and usedspace. While we're on the subject, is there any handy way of getting a tree containing the filesize of all files on the hard drive? Something like: folder games 300000 bytes folder pacman 100000 bytes file game 10000 bytes file gfx 20000 bytes file sound 70000 bytes folder galaxian 150000 bytes ...etc. I found os.path.walk, but I assume I have to roll my own data structure to store this. That's the part I wasn't too sure about. Especially since the traditional way is to use pointers. I don't know the pythonic way of doing trees. Alan From tbrauch@mindless.com Sat Feb 1 17:48:00 2003 From: tbrauch@mindless.com (Timothy M. Brauch) Date: Sat Feb 1 17:48:00 2003 Subject: [Tutor] ftplib References: <5.2.0.9.0.20030201153926.02f41d00@66.28.54.253> Message-ID: <003f01c2ca43$e7224e80$6600a8c0@tbrauch> Yes, I finally figured it out. I was trying to store file.read(), instead of just file. - Tim =================== From: Bob Gailer Did you study the ftplib documentation in the Python Library reference? It offers:storbinary(command, file[, blocksize]) Store a file in binary transfer mode. command should be an appropriate "STOR" command: "STOR filename". file is an open file object which is read until EOF using its read() method in blocks of size blocksize to provide the data to be stored. The blocksize argument defaults to 8192. Changed in version 2.1: default for blocksize added. storlines(command, file) Store a file in ASCII transfer mode. command should be an appropriate "STOR" command (see storbinary()). Lines are read until EOF from the open file object file using its readline() method to provide the data to be stored. Bob Gailer From pversteegen@gcnetmail.net Sat Feb 1 19:10:02 2003 From: pversteegen@gcnetmail.net (Pete Versteegen) Date: Sat Feb 1 19:10:02 2003 Subject: [Tutor] Global scope In-Reply-To: <5.2.0.9.0.20030201142050.02f28bd8@66.28.54.253> Message-ID: Thanks for the explanation. What I basically would like to do is to define a block of variables and lists which I can access by any module. I have a C/C++ program that I want to convert to python and that's made up of 83 separate files, most of which contain one function or procedure an a header file with declarations of zillions of external variables/arrays. To pass the needed variables/lists to each function gets often messy, and is not easy to maintain. If I define a module with all of the variables/lists and import it in each function that requires a variable/list from that module, would that work? Thanks! Pete Versteegen pversteegen@gcnetmail.net __________________________ On 2/1/03 4:31 PM, "Bob Gailer" wrote: > The scope of globals is the containing module. Thus "global case_number" > wants case_number to be in module myFunc1. It will NOT look anywhere else. > > Importing is hierarchical; main can import other modules, and can reference > objects therein; the imported modules can't see objects in the main module. > > Please tell us a bit more about what you want to accomplish, then we can > suggest alternatives. > > At 01:42 PM 2/1/2003 -0500, Pete Versteegen wrote: > >> It's not working.... Here is what I'm doing: >> >> The following code is saved in a file named main.py >> >> #!/usr/bin/python >> >> from myFunc1 import myFunc1 >> >> global case_number >> case_number = 0 >> >> last_case = myFunc1() >> >> print case_number >> >> >> >> The following code is saved in a file named myFunc1.py >> >> def myFunc1(): >> global case_number >> case_number += 1 >> >> >> When I execute main: ./main.py, I get: >> >> Traceback (most recent call last): >> File "./main.py", line 8, in ? >> last_case = myFunc1() >> File "./myFunc1.py", line 3, in myFunc1 >> case_number += 1 >> NameError: global name 'case_number' is not defined >> >> >> >> >> Pete Versteegen >> pversteegen@gcnetmail.net >> __________________________ >> >> >> >> _______________________________________________ >> Tutor maillist - Tutor@python.org >> http://mail.python.org/mailman/listinfo/tutor >> >> >> --- >> Incoming mail is certified Virus Free. >> Checked by AVG anti-virus system (http://www.grisoft.com). >> Version: 6.0.445 / Virus Database: 250 - Release Date: 1/21/2003 > > Bob Gailer > mailto:ramrom@earthling.net > 303 442 2625 > > > --- > Outgoing mail is certified Virus Free. > Checked by AVG anti-virus system (http://www.grisoft.com). > Version: 6.0.445 / Virus Database: 250 - Release Date: 1/21/2003 > From magnus@thinkware.se Sat Feb 1 19:43:01 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Sat Feb 1 19:43:01 2003 Subject: [Tutor] Getting mail out of the box and into the email module In-Reply-To: <200301312212.34659.scot@possum.in-berlin.de> Message-ID: <5.1.0.14.0.20030202013901.02a62ce0@www.thinkware.se> At 22:12 2003-01-31 +0100, Scot Stevenson wrote: > >>> import mailbox > >>> import email > >>> thebox = file("test.mbox", "r") > >>> rawbox = mailbox.UnixMailbox(thebox, email.Message) > >>> rawbox.next() >Traceback (most recent call last): > File "", line 1, in ? > File "/usr/lib/python2.2/mailbox.py", line 34, in next > return self.factory(_Subfile(self.fp, start, stop)) >TypeError: 'module' object is not callable Read the traceback carefully! Look at the last line here! And then check your modules... >>> import email.Message >>> type(email.Message) >>> email.Message.Message Maybe it works if you just hand over the *class* email.Message.Message instead of the *module* email.Message! -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From pversteegen@gcnetmail.net Sat Feb 1 19:44:03 2003 From: pversteegen@gcnetmail.net (Pete Versteegen) Date: Sat Feb 1 19:44:03 2003 Subject: [Tutor] Global scope In-Reply-To: <5.2.0.9.0.20030201142050.02f28bd8@66.28.54.253> Message-ID: Hi, I suppose one solution is to write a program that combines all of the individual modules into a single module so that it can access the global variable/list space. Pete Versteegen pversteegen@gcnetmail.net __________________________ On 2/1/03 4:31 PM, "Bob Gailer" wrote: > The scope of globals is the containing module. Thus "global case_number" > wants case_number to be in module myFunc1. It will NOT look anywhere else. > > Importing is hierarchical; main can import other modules, and can reference > objects therein; the imported modules can't see objects in the main module. > > Please tell us a bit more about what you want to accomplish, then we can > suggest alternatives. > > At 01:42 PM 2/1/2003 -0500, Pete Versteegen wrote: > >> It's not working.... Here is what I'm doing: >> >> The following code is saved in a file named main.py >> >> #!/usr/bin/python >> >> from myFunc1 import myFunc1 >> >> global case_number >> case_number = 0 >> >> last_case = myFunc1() >> >> print case_number >> >> >> >> The following code is saved in a file named myFunc1.py >> >> def myFunc1(): >> global case_number >> case_number += 1 >> >> >> When I execute main: ./main.py, I get: >> >> Traceback (most recent call last): >> File "./main.py", line 8, in ? >> last_case = myFunc1() >> File "./myFunc1.py", line 3, in myFunc1 >> case_number += 1 >> NameError: global name 'case_number' is not defined >> >> >> >> >> Pete Versteegen >> pversteegen@gcnetmail.net >> __________________________ >> >> >> >> _______________________________________________ >> Tutor maillist - Tutor@python.org >> http://mail.python.org/mailman/listinfo/tutor >> >> >> --- >> Incoming mail is certified Virus Free. >> Checked by AVG anti-virus system (http://www.grisoft.com). >> Version: 6.0.445 / Virus Database: 250 - Release Date: 1/21/2003 > > Bob Gailer > mailto:ramrom@earthling.net > 303 442 2625 > > > --- > Outgoing mail is certified Virus Free. > Checked by AVG anti-virus system (http://www.grisoft.com). > Version: 6.0.445 / Virus Database: 250 - Release Date: 1/21/2003 > From magnus@thinkware.se Sat Feb 1 19:51:01 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Sat Feb 1 19:51:01 2003 Subject: [Tutor] Global scope In-Reply-To: References: Message-ID: <5.1.0.14.0.20030202014413.02b42978@www.thinkware.se> At 13:42 2003-02-01 -0500, Pete Versteegen wrote: >It's not working.... Here is what I'm doing: As Bob wrote, globals are still restricted to a module. I would really suggest that you rewrite this properly, passing variables, or using classes to contain data as attributes. But if you want something like C++ global variables, why don't you just have a module for that. Let's call it data.py. I guess it can be empty. I don't know, maybe it must at least contain a 'pass' statement? # a.py import data data.x = 5 # b.py import data print data.x ... You get the idea? -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From dman@dman.ddts.net Sat Feb 1 23:38:01 2003 From: dman@dman.ddts.net (Derrick 'dman' Hudson) Date: Sat Feb 1 23:38:01 2003 Subject: [Tutor] Re: Checking a file size before moving it In-Reply-To: <7497DCA1C240C042B28F6657ADFD8E0974DAA9@i2km11-ukbr.domain1.systemhost.net> References: <7497DCA1C240C042B28F6657ADFD8E0974DAA9@i2km11-ukbr.domain1.systemhost.net> Message-ID: <20030202043711.GA11672@dman.ddts.net> --k+w/mQv8wyuph6w0 Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Fri, Jan 31, 2003 at 01:55:46PM -0000, alan.gauld@bt.com wrote: | > I assume that there is no simple way to tell if a file is=20 | > being accessed. |=20 | OK, I'm at work now with access to my Unix books... |=20 | The fcntl function allows you to get a lock. If the file is already=20 | locked you get that lock back. Within the lock structure you can=20 | read the user and process IDs. If they aint your own then the file=20 | is already locked by another user 0- and you know which one! First of all, fcntl won't tell you if a file is being accessed if it isn't locked. I'm also not sure how the fcntl() interface interacts with the flock() interface on any system (but I know that different Unices do it differently). In any case the locking is merely advisory and any program is free to disregard it. On windows you can ascertain whether or not a file is being accessed by trying to remove it (an error will occur if the file is "in use"). Unix doesn't have that problem (or feature, as you may perceive it right now). I can't think of any reliable way to determine whether or not a file is currently open. The only things I can think of involve assuming a maximum time for the transfer operation -- for example you could look at the create (or access) time for the file and only move it if that time is more than X seconds in the past. =20 What method do people use to put the files in the directory? If you can control that, then perhaps you can build a better solution. For example, if you can specify that a certain command (instead of 'cp') is to be used, that command can run the python script or set some flags. If you can require that the file copy is performed through a web server or some such you can have the server-side handler do whatever is necessary (run the script, set flags, etc.). HTH, -D --=20 "GUIs normally make it simple to accomplish simple actions and impossible to accomplish complex actions." --Doug Gwyn (22/Jun/91 in comp.unix.wizards) =20 http://dman.ddts.net/~dman/ --k+w/mQv8wyuph6w0 Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iEYEARECAAYFAj48oHcACgkQO8l8XBKTpRQ4oQCgnHHR233P7oy4tu2jATp3EhRG hP0AoIcg2CTZvARpBaLRyLgJmns98X0G =cLAM -----END PGP SIGNATURE----- --k+w/mQv8wyuph6w0-- From Janssen@rz.uni-frankfurt.de Sat Feb 1 23:59:01 2003 From: Janssen@rz.uni-frankfurt.de (Michael Janssen) Date: Sat Feb 1 23:59:01 2003 Subject: [Tutor] Re: Checking a file size before moving it In-Reply-To: <20030202043711.GA11672@dman.ddts.net> Message-ID: On Fri, Jan 31, 2003 at 01:55:46PM -0000, alan.gauld@bt.com wrote: | > I assume that there is no simple way to tell if a file is | > being accessed. I havn't followed the thread, but this might be of interest: lsof shows you (on linux and others) the complete and very long LiSt of Open Files. Just grep for it. The manpage of lsof is very long and every time I read it I come to believe it will explain how lsof works, but that's hard to tell (for me). Michael From antoneheyward@hotmail.com Sun Feb 2 08:22:01 2003 From: antoneheyward@hotmail.com (antone heyward) Date: Sun Feb 2 08:22:01 2003 Subject: [Tutor] drive size Message-ID: how about for windows? >From: Michael Janssen >To: antone heyward >CC: >Subject: Re: [Tutor] drive size >Date: Sat, 1 Feb 2003 23:30:55 +0100 (CET) > >On Sat, 1 Feb 2003, antone heyward wrote: > > > is there an easy way to get a systems local drives along with its > > totalspace, freespace, and usedspace. > >on unix: >statvfs() (in module os) ---> os-file-dir.html#l2h-1195 > > > > > > > > > > > > > _________________________________________________________________ > > MSN 8 with e-mail virus protection service: 2 months FREE* > > http://join.msn.com/?page=features/virus > > > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor _________________________________________________________________ Protect your PC - get McAfee.com VirusScan Online http://clinic.mcafee.com/clinic/ibuy/campaign.asp?cid=3963 From blackmariah@shmups.com Sun Feb 2 08:30:01 2003 From: blackmariah@shmups.com (Michael Miller) Date: Sun Feb 2 08:30:01 2003 Subject: [Tutor] ASCII art generator In-Reply-To: <5.1.0.14.0.20030131140049.02d593a8@www.thinkware.se> References: <5.1.0.14.0.20030131132854.02c79d78@www.thinkware.se> <5.1.0.14.0.20030131140049.02d593a8@www.thinkware.se> Message-ID: <200302020726.18366.blackmariah@shmups.com> --Boundary_(ID_ejBwXmFt1jhqmvdvQn3FVQ) Content-type: text/plain; charset=iso-8859-1 Content-transfer-encoding: 7BIT I got this thing working in about 4 hours time the other night (an amazing feat for me) and have been messing with it sense. It's a very simple script that takes the value of a pixel, changes it to the hex value, then formats in in HTML and writes the info to a file. I'm happy with the way it works like it is, but I'd like for it to be usable for other people too. I plan to add a gui to it sometime soo, but need to learn to make a gui first (Walking? Forget that, I'm all about running. Usually into trees). The two more pressing issues are making sure that the user is using an image file as the input and not, for instance, their grocery list (I haven't checked to see what happens if they do). Second, I need a status indicator. Right now all it does is sit until it's done and as slow as this thing is, that's a problem. I was thinking of a percentage indicator based on the total amount of pixels in the image, but I have no clue how to implement that right now (I'll give it a shot later). I realise that this is a rather brute force method of doing this, but I just don't have the skill to make anything more elegant. Any idea on how to do so, or any help with the problems I mentioned above would be most appreciated. Also, sorry that I had to attach the file. My crappy free webhost (my good free webhost is down ATM) won't allow Python files. Thanks for any help. Michael Miller --Boundary_(ID_ejBwXmFt1jhqmvdvQn3FVQ) Content-type: text/x-python; charset=iso-8859-1; name=asciigui.py Content-transfer-encoding: 7BIT Content-disposition: attachment; filename=asciigui.py ############################## # ASCII art generation script WITH GUI!x # # Written by Michael Miller # blackmariah@techie.com # # Thanks to Magnus Lycka from the # Python tutor mailing list for helping # with the decimal/hex conversion. ############################## ##################### #--- Let's import some stuff. from dialog import * import Image import string import random #################### #--- Functions ---# def makerand(): #-- Choose a random character to print. mylet = list(string.printable) foo = random.randrange(0, 93) #-- We use this range because after this is weird characters and whitespace. return mylet[foo] def ascgen(): #--- The fun stuff. x = 0 y = 0 im = Image.open(file_name) im.load() sz = im.size szlist = list(sz) width = sz[0] height = sz[1] total = width*height while x < width: value = im.getpixel([x, y]) #--- Get the RGB value of the pixel at [x, y] vallist = list(value) #--- Turn the tuple returned by im.getpixel() into a list r = vallist[0] g = vallist[1] b = vallist[2] #--- Convert the numbers in vallist into their hex equivalents. out = '',makerand(),'' myfile.writelines(out) #--- Write the above line to file. x = x+1 if x == width: #--- Checks to see if we've hit the end of a line or end of file myfile.write("
") #print y y = y+1 x = 0 if y == height: return def main(): #-- The main loop. Duh. Prints the HTML portions of the file. myfile.write("") myfile.write('') myfile.write('') ascgen() myfile.write("") myfile.write("") myfile.write("") return #--- The main stuff. print "ASCII art generator" print "Make pretty pictures from other pictures." print "ALMOST entirely, but not quite pointless.\n" print "First, we need an input file." print "Be sure to use the full path. Example: /home/foo/bar.jpg" file_name = raw_input(">>>") print "Now we need an output file name." print "Remember to type the extension too: FOO.HTML" output_file = raw_input(">>>") myfile = open(output_file, 'a') main() print file_name print "Done." --Boundary_(ID_ejBwXmFt1jhqmvdvQn3FVQ)-- From Janssen@rz.uni-frankfurt.de Sun Feb 2 11:31:06 2003 From: Janssen@rz.uni-frankfurt.de (Michael Janssen) Date: Sun Feb 2 11:31:06 2003 Subject: [Tutor] ASCII art generator In-Reply-To: <200302020726.18366.blackmariah@shmups.com> Message-ID: Hello Michael, okey, i've commented out the dialog import as you advised me personnally and import Image as PIL.Image. You better should have told me, that an 7MB file with 250000 font-tags is not that nice in a browser ;-) Now I'm working with a downscaled image of 50x60 Pixel. That's fine. Before spend it a GUI, why not gather the color-info from a couple of pixel in case width and or height is about 50! A simple version of a "status-bar" can be added like this: def ascgen(): ..... print width * height while x < width: if nn % 1000 == 0: print nn,"iterations" nn += 1 ...... This fills up the console, but the script doesn't sits any longer there silently. To enhance these messages: sys.stdout.write("%6s iterations\n\033[A" % nn) \033[A is the ansi-code to scrollback one line, i.e. to the start of the last written status (and overwrite it). From here it's not hard to compute procents. minor hints: your main function needn't a return statement. Leave it away (ascgen need it - not to actually return something but to jump out of the while loop; on the other hand: a simple "break" would be enough) "out" should be a string not a tuple. The html-file becomes cleaner. I assume the file-handling is meant for expert use only and leave this point for further versions ;-) Michael On Sun, 2 Feb 2003, Michael Miller wrote: > I got this thing working in about 4 hours time the other night (an amazing > feat for me) and have been messing with it sense. It's a very simple script > that takes the value of a pixel, changes it to the hex value, then formats in > in HTML and writes the info to a file. I'm happy with the way it works like > it is, but I'd like for it to be usable for other people too. I plan to add a > gui to it sometime soo, but need to learn to make a gui first (Walking? > Forget that, I'm all about running. Usually into trees). > > The two more pressing issues are making sure that the user is using an image > file as the input and not, for instance, their grocery list (I haven't > checked to see what happens if they do). Second, I need a status indicator. > Right now all it does is sit until it's done and as slow as this thing is, > that's a problem. I was thinking of a percentage indicator based on the total > amount of pixels in the image, but I have no clue how to implement that right > now (I'll give it a shot later). > > I realise that this is a rather brute force method of doing this, but I just > don't have the skill to make anything more elegant. Any idea on how to do so, > or any help with the problems I mentioned above would be most appreciated. > Also, sorry that I had to attach the file. My crappy free webhost (my good > free webhost is down ATM) won't allow Python files. Thanks for any help. > > Michael Miller > From blackmariah@shmups.com Sun Feb 2 12:15:04 2003 From: blackmariah@shmups.com (Michael Miller) Date: Sun Feb 2 12:15:04 2003 Subject: [Tutor] ASCII art generator In-Reply-To: References: Message-ID: <200302021111.25382.blackmariah@shmups.com> > You better should have told me, that an 7MB file with 250000 font-tags is > not that nice in a browser ;-) > Now I'm working with a downscaled image of 50x60 Pixel. That's fine. > Before spend it a GUI, why not gather the color-info from a couple of > pixel in case width and or height is about 50! > Eep. Yeah, I should have. Really, I should have. Having to sit through a few hundred thousand pixels being converted to ascii isn't fun. Even a 50x50 image can be tough on a browser. ;) I was thinking of ways to optimize this thing, and the only ways I could come up with are way beyond my abilities at this time (I'm working on it though. :). > \033[A is the ansi-code to scrollback one line, i.e. to the start of the > last written status (and overwrite it). From here it's not hard to compute > procents. > Muahahahaha! I was just going to ask about that... ;) I'll try out your ideas real quick and see what sticks. > your main function needn't a return statement. Leave it away > (ascgen need it - not to actually return something but to jump out of the > while loop; on the other hand: a simple "break" would be enough) Hrm... A bit of an oops there. I'm still damaged from my QBASIC days of 10 years past, apparently. In that, return is used to break out of a loop and break is used to end a program. It's amazing how the more I learn the more I understand why it's said that BASIC causes brain damage. A rerereread of the control flow section in the manual is in order for me now. > "out" should be a string not a tuple. The html-file becomes cleaner. You lost me there. The HTML ends up as #, which is just fine as far as HTML goes. To show my stupidity a bit more, I thought it already was a string... > I assume the file-handling is meant for expert use only and leave this > point for further versions ;-) Ehh... pretty much. ;) It will be ironed out. Everything is still in "Just make it work" mode. Thanks for all the help. I'll try out your idea on the counter and read up on break/return stuff (I feel really mega stupid for getting that wrong. DOH). Michael From Janssen@rz.uni-frankfurt.de Sun Feb 2 12:53:02 2003 From: Janssen@rz.uni-frankfurt.de (Michael Janssen) Date: Sun Feb 2 12:53:02 2003 Subject: [Tutor] ASCII art generator - tuple and writelines In-Reply-To: <200302021111.25382.blackmariah@shmups.com> Message-ID: On Sun, 2 Feb 2003, Michael Miller wrote: > > "out" should be a string not a tuple. The html-file becomes cleaner. > > You lost me there. The HTML ends up as #, which > is just fine as far as HTML goes. To show my stupidity a bit more, I thought > it already was a string... you're right, I was wrong. I've always thought writelines adds newlines in case they arn't allready there. But it doesn't. Therefore out as tuple is written to one line. To make it a string change: out = ''+makerand(),'\n' to: out = ''+makerand()+'\n' and myfile.writelines(out) to myfile.write(out). Michael 2 From blackmariah@shmups.com Sun Feb 2 13:37:01 2003 From: blackmariah@shmups.com (Michael Miller) Date: Sun Feb 2 13:37:01 2003 Subject: [Tutor] ASCII art generator - tuple and writelines In-Reply-To: References: Message-ID: <200302021233.22078.blackmariah@shmups.com> > To make it a string change: > out = ''+makerand(),'\n' > to: > out = ''+makerand()+'\n' > > and myfile.writelines(out) to myfile.write(out). I tried that before, and it wouldn't work for some reason. I can't remember the exact error I had, but it wouldn't write it that way. > Michael 2 LOL Nah, I think you're Michael 1. I'm new here. ;) Michael From Janssen@rz.uni-frankfurt.de Sun Feb 2 14:11:02 2003 From: Janssen@rz.uni-frankfurt.de (Michael Janssen) Date: Sun Feb 2 14:11:02 2003 Subject: [Tutor] ASCII art generator In-Reply-To: <200302020726.18366.blackmariah@shmups.com> Message-ID: On Sun, 2 Feb 2003, Michael Miller wrote: > I realise that this is a rather brute force method of doing this, but I just > don't have the skill to make anything more elegant. Any idea on how to do so, Sometimes I narrow my eyes and look crossover the code, it helps me to visually detect inelegant (and possibly unpythonic - huhu ;-) parts. The core function ascgen is pretty long and looks desintegrated. To make it shorter you can take out the logic for transforming the im.getpixel([x, y]) return value into a string suiteable for a html-color (this is especially a good idea, because you might change this part in the future; perhaps you want to test if css-style colors are faster than font-tags.). Alos you can correct more easily possibly mistakes and at last: you can provide a docstring for this part. And now the very last advantages: you can reuse this common function. The while loop doesn't even look desintegrated. You provide (x < width) as the condition, but this is never false, because you catch it with the if-clause condition (x == width). You can change the while condition to 1, but the whole while-if-if construct lacks a bit readability. Let's see.. What you want to do is to iterate trough every line. This means: line-by-line and inside one line "pixel"-by-"pixel". This means you need two for loops: The first iterates over the lines of the picture (I call this the outer iteration) and the second iterates over any pixel of any line: for y in range(height): outer: line-by-line for x in range(width): inner each line since this mailing list is called "tutor", I leave you with this hints. It's fun to work it out yourself (ehhm in python it is fun :-). A little note on lists and tuples: value = im.getpixel([x, y]) vallist = list(value) # you just needn't this step: tuple can be # indexed in the same way as lists. r = vallist[0] g = vallist[1] b = vallist[2] out = ''\ +makerand(),'\n' You can even write (because for string-formatting you need tuples...): out = ''+makerand(),'\n' That's good, isn't it? Michael From dyoo@hkn.eecs.berkeley.edu Sun Feb 2 14:16:01 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun Feb 2 14:16:01 2003 Subject: [Tutor] ftplib In-Reply-To: <000c01c2ca3f$1dc69860$6600a8c0@tbrauch> Message-ID: On Sat, 1 Feb 2003, Timothy M. Brauch wrote: > I am trying to write a small python program that will login to an ftp > server and put a file there. I am using ftplib, and I have figured out > how to log in (that was easy). However, I cannot seem to figure out how > to put a file. Hi Tim, Try the storbinary() or storlines() methods in the ftp object; I think those functions should do the trick for you. For example, here's a mythical example: ### >>> ftp = ftplib.FTP("hades.net") >>> ftp.login('dante', 'virgiliscool') >>> ftp.storlines('STOR virtue.txt', open('virtue.txt')) ### Good luck! From magnus@thinkware.se Mon Feb 3 03:42:02 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Mon Feb 3 03:42:02 2003 Subject: [Tutor] Re: you may regret that comment Magnus!! In-Reply-To: <20030203033116.91068.qmail@web13408.mail.yahoo.com> References: <5.1.0.14.0.20030131111035.02c78fd0@www.thinkware.se> Message-ID: <5.1.0.14.0.20030203090952.02b39690@www.thinkware.se> At 19:31 2003-02-02 -0800, Mic Forster wrote: >the output is printed as a list in a single line. I'm reverting this back to the list--tell me if you want a paid private consultation instead... ;) To get two lists printed in a column each, you can do: >>> for a_b_pair in zip(a,b): ... print "%s\t%s" % a_b_pair ... 1 a 2 b 3 c 4 d 5 e >Ideally >I would like to copy and paste the expected results >into Excel as a column rather than a row. You can let Python do that! (Assumes the win32all package. (It's included by default in ActivePython, or can be installed separately.) >>> import win32com.client >>> xl = win32com.client.Dispatch("Excel.Application") >>> xl.visible = 1 >>> xl.Workbooks.Add() >>> row = 1 >>> col = 1 >>> for value in a: ... xl.Cells(row, col).Value = value ... row += 1 ... >>> row = 1 >>> col = 2 >>> for value in b: ... xl.Cells(row, col).Value = value ... row += 1 Unfortunately, these things are not so easy to find in the docs. The win32all docs give generic information, but you have to go to Excel to find Visual Basic functions, objects, methods etc,and then translate how to translate that to Python. Another option is to simply put your data in the clipboard, and just go to excel and paste where you like. >>> data = "\n".join(["%s\t%s" % x for x in zip(a,b)]) >>> print data 1 a 2 b 3 c 4 d 5 e >>> # Looks ok. >>> import win32clipboard >>> win32clipboard.OpenClipboard() >>> win32clipboard.EmptyClipboard() >>> win32clipboard.SetClipboardText(data) 8782532 >>> win32clipboard.CloseClipboard() Now, just mark a cell in Excel and do Ctrl-V. -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From micforster@yahoo.com Mon Feb 3 05:07:02 2003 From: micforster@yahoo.com (Mic Forster) Date: Mon Feb 3 05:07:02 2003 Subject: [Tutor] Re: you may regret that comment Magnus!! In-Reply-To: <5.1.0.14.0.20030203090952.02b39690@www.thinkware.se> Message-ID: <20030203100624.48760.qmail@web13405.mail.yahoo.com> --- Magnus Lycka wrote: > At 19:31 2003-02-02 -0800, Mic Forster wrote: > >the output is printed as a list in a single line. > > I'm reverting this back to the list--tell me if you > want a paid private consultation instead... ;) > Thanks once again, Magnus. My problem is I keep hitting the reply button instead of reply all. I am on about 6 other tutor/chat/discussion groups and this is the only one you have to do that...... __________________________________________________ Do you Yahoo!? Yahoo! Mail Plus - Powerful. Affordable. Sign up now. http://mailplus.yahoo.com From magnus@thinkware.se Mon Feb 3 05:14:02 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Mon Feb 3 05:14:02 2003 Subject: Reply to list... Re: [Tutor] Re: you may regret that comment Magnus!! In-Reply-To: <20030203100624.48760.qmail@web13405.mail.yahoo.com> References: <5.1.0.14.0.20030203090952.02b39690@www.thinkware.se> Message-ID: <5.1.0.14.0.20030203110918.02b2cb60@www.thinkware.se> At 02:06 2003-02-03 -0800, Mic Forster wrote: >Thanks once again, Magnus. My problem is I keep >hitting the reply button instead of reply all. I am on >about 6 other tutor/chat/discussion groups and this is >the only one you have to do that...... On the other hand, with just "reply", most mailers will give you a quote with a heading like: At 02:06 2003-02-03 -0800, you wrote: instead of At 02:06 2003-02-03 -0800, Mic Forster wrote: But perhaps it would still be better with reply-to set to the mailing list. I guess this is configurable. Danny? -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From janos.juhasz@VELUX.com Mon Feb 3 06:18:01 2003 From: janos.juhasz@VELUX.com (janos.juhasz@VELUX.com) Date: Mon Feb 3 06:18:01 2003 Subject: [Tutor] date of 1900.01.01 in sql table Message-ID: Dear gurus, a found that: ******* import odbc import dbi odbc.odbc('an mssql system dsn') cr =3D db.cursor() cr.execute('select * from anytable') data =3D cr.fetchall() ******* gives me a kind of wrong result when fetch a date, that can be seen as 1900.01.01 in the sqlquery. I have got PythonWin 2.2.1 (#34, Apr 15 2002, 09:51:39) [MSC 32 bit (Intel)] on wi= n32. Portions Copyright 1994-2001 Mark Hammond (mhammond@skippinet.com.au) -= see 'Help/About PythonWin' for further copyright information. on my MS W2K. It is a problem with ADO too ***************** >>> int(rs.fields[8].value) Traceback (most recent call last): File "", line 1, in ? ValueError: illegal time value ***************** So I can't covert it into int, so I can't convert it into date. Where can I start to solve it? May I use try statement to convert it and give back 1900.01.01 at exception? Best regards, ----------------------- Juh=E1sz J=E1nos IT department = From kalle@lysator.liu.se Mon Feb 3 08:11:02 2003 From: kalle@lysator.liu.se (Kalle Svensson) Date: Mon Feb 3 08:11:02 2003 Subject: Reply to list... Re: [Tutor] Re: you may regret that comment Magnus!! In-Reply-To: <5.1.0.14.0.20030203110918.02b2cb60@www.thinkware.se> References: <5.1.0.14.0.20030203090952.02b39690@www.thinkware.se> <5.1.0.14.0.20030203110918.02b2cb60@www.thinkware.se> Message-ID: <20030203131049.GP1289@i92.ryd.student.liu.se> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 [Magnus Lycka] > But perhaps it would still be better with reply-to set to > the mailing list. I guess this is configurable. Danny? No, it isn't (better). Please read '"Reply-To" Munging Considered Harmful' (http://www.unicom.com/pw/reply-to-harmful.html). Peace, Kalle - -- Kalle Svensson, http://www.juckapan.org/~kalle/ Student, root and saint in the Church of Emacs. -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.7 (GNU/Linux) Comment: Processed by Mailcrypt 3.5.6 iD8DBQE+PmpOdNeA1787sd0RArkPAJ0cNe8qYXKxyq9c6Jovc14IsYWJSACfUyN6 hUKRJl4tc5bodBn9wgmnir4= =1Cvq -----END PGP SIGNATURE----- From janos.juhasz@VELUX.com Mon Feb 3 10:54:01 2003 From: janos.juhasz@VELUX.com (janos.juhasz@VELUX.com) Date: Mon Feb 3 10:54:01 2003 Subject: [Tutor] test Message-ID: Dear All, how can I test if an object is or not ? Best regards, ----------------------- Juh=E1sz J=E1nos = From bwinton@latte.ca Mon Feb 3 10:55:06 2003 From: bwinton@latte.ca (Blake Winton) Date: Mon Feb 3 10:55:06 2003 Subject: Reply to list... Re: [Tutor] Re: you may regret that comment Magnus!! In-Reply-To: <20030203131049.GP1289@i92.ryd.student.liu.se> References: <5.1.0.14.0.20030203090952.02b39690@www.thinkware.se> <5.1.0.14.0.20030203110918.02b2cb60@www.thinkware.se> <20030203131049.GP1289@i92.ryd.student.liu.se> Message-ID: <20030203165358.GA2024@latte.ca> * Kalle Svensson [030203 10:11]: > > But perhaps it would still be better with reply-to set to > > the mailing list. I guess this is configurable. Danny? > No, it isn't (better). Please read '"Reply-To" Munging Considered > Harmful' (http://www.unicom.com/pw/reply-to-harmful.html). And while you're there, read '"Reply-To" Munging Considered Useful' (http://www.metasystema.org/essays/reply-to-useful.mhtml) I would tend to side with the "Don't Munge" crowd, but it is still an open question. (Actually, now I'm starting to like the third option: http://www.mindspring.com/~pwiseman/reply-to.html which is set it, unless the user has already set it.) Later, Blake. -- 11:51am up 2:20, 1 user, load average: 0.00, 0.00, 0.00 From Deirdre Hackett" Message-ID: <004301c2cba1$983b6e00$0400a8c0@egbert> I want to take information into my program continuously at 20 samples per second, The command to send to the device is *99c\r. What do i need to change in regard to just polling the device? Know this isn't very clear, but not sure myself. Deirdre From dman@dman.ddts.net Mon Feb 3 11:44:02 2003 From: dman@dman.ddts.net (Derrick 'dman' Hudson) Date: Mon Feb 3 11:44:02 2003 Subject: [Tutor] Re: test In-Reply-To: References: Message-ID: <20030203164326.GA26296@dman.ddts.net> --0OAP2g/MAC+5xKAE Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Mon, Feb 03, 2003 at 04:53:09PM +0100, janos.juhasz@VELUX.com wrote: | Dear All, |=20 | how can I test if an object is or not ? if isinstance( obj , DbiDate ) : print "It is a DbiDate" else: print "It is not a DbiDate, it is %s" % str(obj.__class__) It isn't quite as straight forward (but it might be) in python < 2.2. Let us know if you are using an old python. -D --=20 Consider what God has done: Who can straighten what He has made crooked? Ecclesiastes 7:13 =20 http://dman.ddts.net/~dman/ --0OAP2g/MAC+5xKAE Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iEYEARECAAYFAj4+nC4ACgkQO8l8XBKTpRR0VgCeKWIp+cAVtx4VVP4QtK3K1eof Xy0AoLMV5XVEeEB0Mo+UEalteVXgNYl5 =8m6c -----END PGP SIGNATURE----- --0OAP2g/MAC+5xKAE-- From dman@dman.ddts.net Mon Feb 3 11:51:01 2003 From: dman@dman.ddts.net (Derrick 'dman' Hudson) Date: Mon Feb 3 11:51:01 2003 Subject: [Tutor] Re: Reply to list... Re: Re: you may regret that comment Magnus!! In-Reply-To: <20030203165358.GA2024@latte.ca> References: <5.1.0.14.0.20030203090952.02b39690@www.thinkware.se> <5.1.0.14.0.20030203110918.02b2cb60@www.thinkware.se> <20030203131049.GP1289@i92.ryd.student.liu.se> <20030203165358.GA2024@latte.ca> Message-ID: <20030203165011.GB26296@dman.ddts.net> --JP+T4n/bALQSJXh8 Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Mon, Feb 03, 2003 at 11:53:58AM -0500, Blake Winton wrote: | * Kalle Svensson [030203 10:11]: | > > But perhaps it would still be better with reply-to set to | > > the mailing list. I guess this is configurable. Danny? | > No, it isn't (better). Please read '"Reply-To" Munging Considered | > Harmful' (http://www.unicom.com/pw/reply-to-harmful.html). I totally agree. With a good mail program you can hit "List Reply" (instead of "Reply" or "Reply to all") and send the reply to the list only. It is really very convenient. [snip some think it is useful] | (Actually, now I'm starting to like the third option: | http://www.mindspring.com/~pwiseman/reply-to.html | which is set it, unless the user has already set it.) For users who have a problem with not munging, this sounds even worse. It would mean that for _some_ messages "reply" is sufficient, but for others "reply all" is necessary. Since my mailer has a "ignore_list_reply_to" option it wouldn't hurt me at all, but I'm not the one who's mailer lacks good list support :-). -D --=20 If Microsoft would build a car... =2E.. Occasionally your car would die on the freeway for no reason. You would have to pull over to the side of the road, close all of the car windows, shut it off, restart it, and reopen the windows before you could continue. For some reason you would simply accept this. =20 http://dman.ddts.net/~dman/ --JP+T4n/bALQSJXh8 Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iEYEARECAAYFAj4+ncMACgkQO8l8XBKTpRQDwgCgvyE+6tWAqqDRQNcV2PTUcPR3 ZZoAoMhDESwTJppjHpKTh6qXwi51roIr =AR55 -----END PGP SIGNATURE----- --JP+T4n/bALQSJXh8-- From borelan@wanadoo.fr Mon Feb 3 12:10:09 2003 From: borelan@wanadoo.fr (D2) Date: Mon Feb 3 12:10:09 2003 Subject: [Tutor] Python notations Message-ID: <3E3E943A.30905@wanadoo.fr> Hello, New to python, i'm trying to understand Python's notations. Is there some place to find a tutorial on Python various notations ? I looled in Python's manual but it's not very clear. I'd like to find an exhaustive list of the different notations and how they are used (maybe too ambitious ?) TIA -- Andre From =?Windows-1251?B?YW50b25tdWhpbiDt4CByYW1ibGVyLnJ1?= Mon Feb 3 12:20:03 2003 From: =?Windows-1251?B?YW50b25tdWhpbiDt4CByYW1ibGVyLnJ1?= (=?Windows-1251?B?YW50b25tdWhpbiDt4CByYW1ibGVyLnJ1?=) Date: Mon Feb 3 12:20:03 2003 Subject: [Tutor] Re: you may regret that comment Magnus!! Message-ID: <8629547927.20030203201937@rambler.ru> Hello Magnus, Monday, February 3, 2003, 11:40:53 AM, you wrote: >>Ideally >>I would like to copy and paste the expected results >>into Excel as a column rather than a row. ML> You can let Python do that! (Assumes the win32all package. ML> (It's included by default in ActivePython, or can be ML> installed separately.) [snipped] BTW, Excel 2002 supports XML as its native format (no information loss). It's relatively simple---I managed to create simple Excel sheets with EmPy in couple of hours. And really quick. I hope, it might help you. -- Best regards, anton mailto:antonmuhin@rambler.ru From alan.gauld@bt.com Mon Feb 3 12:20:10 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon Feb 3 12:20:10 2003 Subject: [Tutor] Global scope Message-ID: <7497DCA1C240C042B28F6657ADFD8E097023B4@i2km11-ukbr.domain1.systemhost.net> > I am confused about global variables. I have a C/C++ program > with a large number of functions, and a block of global variables > ...that I'm converting to python. I am translating the > functions into corresponding modules. If you don't store them in separate files in C++ why do so in Python (or maybe that should be the other way around?!) > functions, etc. How do I declare some variables, including lists and > dictionaries, that are used in these lower functions to be globals, > accessible by all functions? Put the variables in a module and import that module into the other modules that need access to them. Much better to reduce the globals thgough either by passing them as parameters to the functions or, better still, bundling them up as a class and making your functions methods of the class. If these functions are all related to the same set of global data theres a good chance they are functionally related too. If so they would be a good class candidate. > I used a statement such as: global case_number in a > function, and declare it case_number = 0 in the main > module, but I get: global in python means the variable is in the same file but not in the same function. You need to import your main module then referebce the globals there: import main def myfunc(): main.foo = 42 return 5 * main.x etc... Alan g. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld/ From alan.gauld@bt.com Mon Feb 3 12:26:12 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon Feb 3 12:26:12 2003 Subject: [Tutor] drive size Message-ID: <7497DCA1C240C042B28F6657ADFD8E097023B5@i2km11-ukbr.domain1.systemhost.net> > is there an easy way to get a systems local drives along with its > totalspace, freespace, and usedspace. Like so many things it depends on the OS. If its windows there are Win32 API functions that can tell you this. Probably they are exposed in Mark Hammonds Winall package. If its Unix/Mac OS then there are other ways. But my guess is you are on Windows since those are the only folks who normally are interested in low level details like drives. Alan g. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld/ From alan.gauld@bt.com Mon Feb 3 12:30:01 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon Feb 3 12:30:01 2003 Subject: [Tutor] drive size Message-ID: <7497DCA1C240C042B28F6657ADFD8E097023B6@i2km11-ukbr.domain1.systemhost.net> > Especially since the traditional way is to use pointers. I don't know > the pythonic way of doing trees. Python variables are referemces so think of them as pointers without the dereferencing mess. class TreeNode: def __init__(self, data, left, right): self.data = data self.left = left self.right = right base1 = TreeNode(1,None,None) base2 = TreeNode(2,None,None) node = TreeNode(3,base1,base2) print node.data print node.left.data print node.right.data I leave the rest as an excercise for the reader! :-) Alan g. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld/ From alan.gauld@bt.com Mon Feb 3 12:35:13 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon Feb 3 12:35:13 2003 Subject: [Tutor] Re: Checking a file size before moving it Message-ID: <7497DCA1C240C042B28F6657ADFD8E097023B7@i2km11-ukbr.domain1.systemhost.net> > > The fcntl function allows you to get a lock. If the file is already > > First of all, fcntl won't tell you if a file is being accessed if it > isn't locked. That's true. I was assuming (always dangerous! :) that only locked files would cause a problem. I also assume (but haven't checked!) that Unix will lock a file that's being written to? That's all the sleep solution protects against too... Alan g From dyoo@hkn.eecs.berkeley.edu Mon Feb 3 12:39:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Feb 3 12:39:02 2003 Subject: [Tutor] Re: Reply to list... [think of the digested users] In-Reply-To: <20030203131049.GP1289@i92.ryd.student.liu.se> Message-ID: On Mon, 3 Feb 2003, Kalle Svensson wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > [Magnus Lycka] > > > But perhaps it would still be better with reply-to set to the mailing > > list. I guess this is configurable. Danny? > > No, it isn't (better). But it is configurable. *grin* Here's another reason for keeping the status quo: if the replier properly uses their emailer "reply-to-all", then the receiver directly receives replies. I guess I'm stating the obvious. *grin* But this feature is very important for people who are running in "digest mode". Digested users who don't follow every single message on Tutor still can ask and receive direct answers. I did a quick check on the number of subscribers; about half are digested users, so we'd better not ignore them. *grin* So that's another good reasons to not force replies to go only to the list. Talk to you later! From alan.gauld@bt.com Mon Feb 3 12:50:02 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon Feb 3 12:50:02 2003 Subject: [Tutor] Continuous input at sample rate Message-ID: <7497DCA1C240C042B28F6657ADFD8E097023B8@i2km11-ukbr.domain1.systemhost.net> > I want to take information into my program continuously at 20 > samples per second, > I didn't understand the rest but to loop 20 times a second - provided your machine is fast enough! - do this: while 1: sleep(0.05) # 1/20s delay # do something here if someCondition: break > The command to send to the device is *99c\r. > What do i need to change in regard to just polling the device? Are you sending or polling(reading)? Or both? Do you send to get a result back? I don't understand sorry. Alan g From carroll@tjc.com Mon Feb 3 13:36:12 2003 From: carroll@tjc.com (Terry Carroll) Date: Mon Feb 3 13:36:12 2003 Subject: [Tutor] Exponentially distributed random number generation In-Reply-To: <001201bbf789$35df7dc0$ade871d9@zh648jn04g8z0l> Message-ID: On Wed, 1 Jan 1997, zywy wrote: > Does anyone know whether there is a python function to generate > exponentially distributed random numbers? I'm not sure, but given the timestamp on this message, I wouldn't use your system's clock as a seed value! -- Terry Carroll | "To have this rare opportunity Santa Clara, CA | is a rare opportunity." carroll@tjc.com | - Houston Rockets' Yao Ming, on being named Modell delendus est | starting center for the 2003 NBA All-Star Game From Janssen@rz.uni-frankfurt.de Mon Feb 3 14:29:02 2003 From: Janssen@rz.uni-frankfurt.de (Michael Janssen) Date: Mon Feb 3 14:29:02 2003 Subject: [Tutor] Re: Reply to list... Re: Re: you may regret that comment Magnus!! In-Reply-To: <20030203165011.GB26296@dman.ddts.net> Message-ID: On Mon, 3 Feb 2003, Derrick 'dman' Hudson wrote: > On Mon, Feb 03, 2003 at 11:53:58AM -0500, Blake Winton wrote: > | > Harmful' (http://www.unicom.com/pw/reply-to-harmful.html). > > For users who have a problem with not munging, this sounds even worse. > It would mean that for _some_ messages "reply" is sufficient, but for > others "reply all" is necessary. Since my mailer has a > "ignore_list_reply_to" option it wouldn't hurt me at all, but I'm not > the one who's mailer lacks good list support :-). Is the world that worse outside? Pine simply ask you wether it should use Reply-To and it's your simple task to decide. Do other MUA make the decision for you and carry you directly to the reply-to address when givven? That's bad. Perhaps GUI MUAs want to avoid the click box with the question. Michael > > -D > > -- > If Microsoft would build a car... > ... Occasionally your car would die on the freeway for no reason. You > would have to pull over to the side of the road, close all of the car > windows, shut it off, restart it, and reopen the windows before you > could continue. For some reason you would simply accept this. > > http://dman.ddts.net/~dman/ > From ahimsa@onetel.net.uk Mon Feb 3 15:21:30 2003 From: ahimsa@onetel.net.uk (ahimsa) Date: Mon Feb 3 15:21:30 2003 Subject: [Tutor] Python notations In-Reply-To: <3E3E943A.30905@wanadoo.fr> References: <3E3E943A.30905@wanadoo.fr> Message-ID: <1044303596.1713.200.camel@localhost.localdomain> On Mon, 2003-02-03 at 16:09, D2 wrote: > New to python, i'm trying to understand Python's notations. > Is there some place to find a tutorial on Python various notations ? > I looled in Python's manual but it's not very clear. I'd like to find an > exhaustive list of the different notations and how they are used (maybe > too ambitious ?) The Python Reference Manual on the python.org site is pretty useful for that kind of thing, if I understand what you are meaning by 'notations'. HTH -- ahimsa From magnus@thinkware.se Mon Feb 3 15:54:14 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Mon Feb 3 15:54:14 2003 Subject: [Tutor] test In-Reply-To: Message-ID: <5.1.0.14.0.20030203215008.02ba1008@www.thinkware.se> At 16:53 2003-02-03 +0100, janos.juhasz@VELUX.com wrote: >how can I test if an object is or not ? Instanciate another DbiDate and compare their types. import dbi if type(object) == type(dbi.DbiDate(0)): print "It's a dbi.DbiDate" Works with all versions of Python I think... -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From magnus@thinkware.se Mon Feb 3 15:55:04 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Mon Feb 3 15:55:04 2003 Subject: [Tutor] Python notations In-Reply-To: <3E3E943A.30905@wanadoo.fr> Message-ID: <5.1.0.14.0.20030203215342.02ab99a0@www.thinkware.se> At 12:09 2003-02-03 -0400, D2 wrote: >New to python, i'm trying to understand Python's notations. What do you mean by notations? Can you give an example? -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From killemilystump@yahoo.com Mon Feb 3 16:10:02 2003 From: killemilystump@yahoo.com (Bryan Tanenholz) Date: Mon Feb 3 16:10:02 2003 Subject: [Tutor] unsubscribe me Message-ID: <20030203210938.38617.qmail@web13101.mail.yahoo.com> --0-1649950076-1044306578=:37947 Content-Type: text/plain; charset=us-ascii please unsubscribe me thanks you killemilystump@yahoo.com --------------------------------- Do you Yahoo!? Yahoo! Mail Plus - Powerful. Affordable. Sign up now --0-1649950076-1044306578=:37947 Content-Type: text/html; charset=us-ascii

please unsubscribe me thanks you

 

                       killemilystump@yahoo.com



Do you Yahoo!?
Yahoo! Mail Plus - Powerful. Affordable. Sign up now --0-1649950076-1044306578=:37947-- From magnus@thinkware.se Mon Feb 3 17:13:02 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Mon Feb 3 17:13:02 2003 Subject: [Tutor] Re: Reply to list... Re: Re: you may regret that comment Magnus!! In-Reply-To: References: <20030203165011.GB26296@dman.ddts.net> Message-ID: <5.1.0.14.0.20030203220250.02abc8b0@www.thinkware.se> At 20:27 2003-02-03 +0100, Michael Janssen wrote: >Is the world that worse outside? Pine simply ask you wether it should use >Reply-To and it's your simple task to decide. Do other MUA make the >decision for you and carry you directly to the reply-to address when >given? That's bad. Perhaps GUI MUAs want to avoid the click box with the >question. If Reply-To is set, it really means that replies should go to that address, and not to the From address. That's the only point of that header. It's not really intended as an option. To assume that the responder should regularly make an optimal choice on when to ignore the Reply-To header is probably not a good idea. I'd say that this is a fix in pine because it's more slow and error prone to edit addresses there than it is in let's say Eudora. For instance in Eudora 5.2, it's enough for me to press M in the Cc: field, and your email address pops up. I also get a drop down box with all mail addresses that begin with M (or m) that have occured recently. If I press Reply (or Ctrl-R) instead of Reply-To-All, I'll just have to do Shift-Tab, Shift-Tab, T, and tutor@python.org will appear in Cc:. If I have a more current address starting with t, I'll have to press down-arrow once or twice followed by enter. It's not a big effort compared to typing letters... Copy - paste is fast as well. I like pine, not least because it was the best mailer to use when I checked mail from my old Nokia Communicator. It's the mailer I'll use with a ssh/telnet/text console session on a unix machine. (Telnet was the only really good program in that phone...) I much prefer a GUI mailer today if I can use one though. Switching folders, browsing and copying text from different sources etc is much faster here, despite many years of pine use. Anyway, regardless of what tool we use, we just have to remember one simple rule. Read through the mail thoroughly before sending it. This applies to To:, Cc: and Subject: fields as well as to the mail body. To do that is a way to show that we care for, and appreciate, the other people on the list. If we don't feel like that, I don't think we should be here. I think all people on the list *do* feel like that, but it's easy to forget ones behaviour sometimes, particularly when we are in a hurry. Doing these things are much less work than the efforts we put into describing problems and thinking out answers, so it's certainly a reasonable thing to ask from the people on the list. No one is perfect, and we all make mistakes now and then. That's ok, but I think we should all *try* to remember to hold back when we are about to send an email by reflex. Then it's time that we ask ourselves a few questions: Am I really done? No typos or other mistakes? Have I read through the whole mail properly? Is it understandable from the perspective of the reader? Not above or below her? Am I overly wordy? (Yes usually, but I try...) Are the To/Cc headers correctly set? Does the Subject header describe the essence of my question? (If it's not a reply.) If it _is_ a reply: Is my quoting reasonable, enough to read my response without having the original mail on screen, but without redundant quotations? Etc... Perhaps the [Send] button should have a "Are you sure" dialog with [No] as default choice? ;) I wonder how many people lost jobs or friends because they mailed something that they soon after realized they shouldn't have sent... Here is one point to pine, and zero points to the GUI mailers. Pine asks "Send message?", even if default is wrong ;). I think all GUI mailers send at once as you let go of the mouse button on the [Send] button. Actually, you can press the button, and then think a bit before you let go... If you change your mind you just more the mouse away from the button before you release the button. Whatever ritual fits you best... -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From ahimsa@onetel.net.uk Mon Feb 3 17:40:09 2003 From: ahimsa@onetel.net.uk (ahimsa) Date: Mon Feb 3 17:40:09 2003 Subject: [Tutor] rock, paper, scissors (ro sham bo) part deux Message-ID: <1044311824.1640.212.camel@localhost.localdomain> --=-1dowTb3laGaVs1+b9qz5 Content-Type: text/plain Content-Transfer-Encoding: 7bit Sean, Magnus, Alan, Bob and Gregor At the risk of belabouring this thread, I wanted to update you with developments on my earlier requests for input and since you all so graciously contributed something to helping me, I wanted to share where it is at (to date). I utilised Magnus's idea regarding turning the rock, paper, scissors combination into a dictionary, and calling the key/value pair to ascertain which wins. I also wanted to allow the user to keep the game going rather than just play once and have to press F5 again to start it off, which is why I created the game as a module itself that can just be called. Finally, I wanted to provide a little more feedback to the user - hence all the stuff about the round summary. I was hoping that I might be able to carry a round winner's total over from one game to the next to give a series summary upon quitting, but haven't figured out how to do that yet. Anyway, have attached the code, and would naturally welcome comments. It is probably too many lines for what the program actually does, so if you have any ideas how parsimony can be achieved, please share them with me, but I'd also appreciate it if you could explain what it is that you are actually doing too - that would aid my learning. Thanks folks. Kind regards Andrew -- ahimsa --=-1dowTb3laGaVs1+b9qz5 Content-Disposition: attachment; filename=rock2.py Content-Type: text/x-python; name=rock2.py; charset=UTF-8 Content-Transfer-Encoding: 7bit # Rock Game v.2 print print "Rock & Paper & Scissors, v.2" print "----------------------------" print # Initialisation: import random def item( a ): # Convert int to string if a == 1: return "Rock" elif a == 2: return "Paper" elif a == 3: return "Scissors" def whoWins( b, c ): # Dictionary calling module if options[ b ] == c: print c, "beats", b, "- You lost!" elif options[ c ] == b: print b, "beats", c, "- You win!!" else: print "A tie - play again" def playGame( ): # The game module itself counter = 0 compWin = 0 playWin = 0 totComp = 0 totPlay = 0 while counter < 3: # 3 turns only x = random.randrange( 1, 4 ) print print "Rock (1), Paper (2), Scissors (3)" print y = int( raw_input( "Make a selection: " ) ) whoWins( item( y ), item( x )) counter += 1 # counter controlled loop if options[ item( y ) ] == item( x ): # keep score compWin += 1 elif options[ item( x ) ] == item( y ): playWin += 1 print print "You won", playWin # output results print "The Computer won", compWin if playWin > compWin: print "You won that round" elif compWin > playWin: print "The Computer won that round" else: print "That round was a tie" print print "--------%%%%%%------------" print "Do you want to play again?" doPlay = int( raw_input( "Enter 1 for 'YES' or 0 for 'NO': " )) # keep the game rolling if doPlay == 1: # sentinel value control playGame() else: doPlay != 1 print "Hit ENTER to return to the prompt" # graceful exit print # Processing Phase options = { "Rock" : "Paper", "Scissors" : "Rock", "Paper" : "Scissors" } # Dict template print "Do you want to play?" doPlay = int( raw_input( "Enter 1 for 'YES' or 0 for 'NO': " )) # User gets a choice if doPlay == 1: playGame() # Play ball!!!! else: print "Hit ENTER to return to the prompt" --=-1dowTb3laGaVs1+b9qz5-- From Sean Abrahams Mon Feb 3 18:18:01 2003 From: Sean Abrahams (Sean Abrahams) Date: Mon Feb 3 18:18:01 2003 Subject: [Tutor] rock, paper, scissors (ro sham bo) part deux In-Reply-To: <1044311824.1640.212.camel@localhost.localdomain> References: <1044311824.1640.212.camel@localhost.localdomain> Message-ID: <194521318000.20030203152035@sfsu.edu> I'm not an expert programmer, but I noticed right away that instead of making 'item' a function, you could simply make it a list (or tuple, since the selections are finite; you can only select rock, paper, or scissors) So: >def item( a ): # Convert int to string > if a == 1: > return "Rock" > elif a == 2: > return "Paper" > elif a == 3: > return "Scissors" becomes: item = ('Rock','Paper','Scissors') However, this presents a problem. Since tuples/lists start counting from 0, your selections won't match up. Meaning, in your example item function, Rock == 1, but in my item tuple example Rock == 0. So, here's a good question for the more experienced programmers out there. Is it better to still use a list/tuple and just put an empty value for item[0] (Assuming we want to keep the UI the same, 1) for the user to pick Rock, 2) for Paper, etc.) Or, would it be better to use a dictionary like so? item = {1 : 'Rock', 2 : 'Paper', 3 : 'Scissors'} Then reference the values using item[n]? --Sean Abrahams (Not 'Shaleh' Perry) Monday, February 3, 2003, 2:41:07 PM, you wrote: a> Sean, Magnus, Alan, Bob and Gregor a> At the risk of belabouring this thread, I wanted to update you with a> developments on my earlier requests for input and since you all so a> graciously contributed something to helping me, I wanted to share where a> it is at (to date). a> I utilised Magnus's idea regarding turning the rock, paper, scissors a> combination into a dictionary, and calling the key/value pair to a> ascertain which wins. a> I also wanted to allow the user to keep the game going rather than just a> play once and have to press F5 again to start it off, which is why I a> created the game as a module itself that can just be called. a> Finally, I wanted to provide a little more feedback to the user - hence a> all the stuff about the round summary. a> I was hoping that I might be able to carry a round winner's total over a> from one game to the next to give a series summary upon quitting, but a> haven't figured out how to do that yet. a> Anyway, have attached the code, and would naturally welcome comments. a> It is probably too many lines for what the program actually does, so if a> you have any ideas how parsimony can be achieved, please share them with a> me, but I'd also appreciate it if you could explain what it is that you a> are actually doing too - that would aid my learning. a> Thanks folks. a> Kind regards a> Andrew From magnus@thinkware.se Mon Feb 3 18:42:01 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Mon Feb 3 18:42:01 2003 Subject: [Tutor] rock, paper, scissors (ro sham bo) part deux In-Reply-To: <1044311824.1640.212.camel@localhost.localdomain> Message-ID: <5.1.0.14.0.20030204002102.02b3bc58@www.thinkware.se> At 22:41 2003-02-03 +0000, ahimsa wrote: >Sean, Magnus, Alan, Bob and Gregor > >At the risk of belabouring this thread, I wanted to update you with >developments on my earlier requests for input and since you all so >graciously contributed something to helping me, I wanted to share where >it is at (to date). Nice! Keep on going! I'll just like to show how a few lines of code code could look even better. Don't forget to use descriptive variable names, and for style issues, have a look at the style guide: http://www.python.org/peps/pep-0008.html # "Value" wins over "Key" winner = { "Rock" : "Paper", "Scissors" : "Rock", "Paper" : "Scissors" } I think winner is a more descriptive name than options. I also think it's clearer with one entry per line. I also think the changed comment helps to understanf the purpose of the dict better. menu = ["Rock", "Paper", "Scissors"] def item( choice ): 'Translate menu choice 1,2,3 to descriptive string' return menu[choice - 1] For me, this is also clearer than the if-statement. It's certainly shorter. You can also use the menu list when you create the menu that you present to the user. That way you can change order between the items in just one place if you would suddenly want scissors first etc. def whoWins( player1, player2 ): 'Value in winner dictionary wins over its key' if winner[player1] == player2: print player2, "beats", player1, "- You lost!" return player2 elif winner[player2] == player1: print player1, "beats", player2, "- You win!!" return player1 else: print "A tie - play again" ... winnerThisTurn = whoWins(player, computer) # keep score if computer == winnerThisTurn : compWin += 1 elif player == winnerThisTurn : playWin += 1 Don't determine who won twice, and don't forget to use descriptive names. You will get used to typing fast in due time... >I was hoping that I might be able to carry a round winner's total over >from one game to the next to give a series summary upon quitting, but >haven't figured out how to do that yet. You need another (outer) loop. numberOfTurns = 3 # Total score totComp = totPlayer = 0 while True: # Score this round compWin = playWin = 0 for i in range(numberOfTurns): ... if playWin > compWin: print "You won that round" totPlay += 1 elif compWin > playWin: print "The Computer won that round" totComp += 1 else: print "That round was a tie" ... if not wantToPlayMore(): break >Anyway, have attached the code, and would naturally welcome comments. >It is probably too many lines for what the program actually does, so if >you have any ideas how parsimony can be achieved, please share them with >me, but I'd also appreciate it if you could explain what it is that you >are actually doing too - that would aid my learning. There are a few places where you repeat code, and that's better broken out to separate functions or centralized to one place in the code. For instance you calculate who wins twice. Once for the message, and once for the score keeping. This is error prone, you might change it in one place because you came up with some improvement and forget the other place, and end up with the score and the messages being out of sync. See above. -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From Sean Abrahams Mon Feb 3 19:13:02 2003 From: Sean Abrahams (Sean Abrahams) Date: Mon Feb 3 19:13:02 2003 Subject: Re[2]: [Tutor] rock, paper, scissors (ro sham bo) part deux In-Reply-To: <194521318000.20030203152035@sfsu.edu> References: <1044311824.1640.212.camel@localhost.localdomain> <194521318000.20030203152035@sfsu.edu> Message-ID: <182524589781.20030203161507@sfsu.edu> Solution to my own question. SA> item = ('Rock','Paper','Scissors') SA> However, this presents a problem. Since tuples/lists start counting SA> from 0, your selections won't match up. Meaning, in your example item SA> function, Rock == 1, but in my item tuple example Rock == 0. You can reference it as item[n-1]. --Sean Monday, February 3, 2003, 3:20:35 PM, you wrote: SA> I'm not an expert programmer, but I noticed right away that instead of SA> making 'item' a function, you could simply make it a list (or tuple, SA> since the selections are finite; you can only select rock, paper, or SA> scissors) SA> So: >>def item( a ): # Convert int to string >> if a == 1: >> return "Rock" >> elif a == 2: >> return "Paper" >> elif a == 3: >> return "Scissors" SA> becomes: SA> item = ('Rock','Paper','Scissors') SA> However, this presents a problem. Since tuples/lists start counting SA> from 0, your selections won't match up. Meaning, in your example item SA> function, Rock == 1, but in my item tuple example Rock == 0. SA> So, here's a good question for the more experienced programmers out SA> there. Is it better to still use a list/tuple and just put an empty SA> value for item[0] (Assuming we want to keep the UI the same, 1) for SA> the user to pick Rock, 2) for Paper, etc.) Or, would it be better to SA> use a dictionary like so? SA> item = {1 : 'Rock', 2 : 'Paper', 3 : 'Scissors'} SA> Then reference the values using item[n]? SA> --Sean Abrahams SA> (Not 'Shaleh' Perry) SA> Monday, February 3, 2003, 2:41:07 PM, you wrote: a>> Sean, Magnus, Alan, Bob and Gregor a>> At the risk of belabouring this thread, I wanted to update you with a>> developments on my earlier requests for input and since you all so a>> graciously contributed something to helping me, I wanted to share where a>> it is at (to date). a>> I utilised Magnus's idea regarding turning the rock, paper, scissors a>> combination into a dictionary, and calling the key/value pair to a>> ascertain which wins. a>> I also wanted to allow the user to keep the game going rather than just a>> play once and have to press F5 again to start it off, which is why I a>> created the game as a module itself that can just be called. a>> Finally, I wanted to provide a little more feedback to the user - hence a>> all the stuff about the round summary. a>> I was hoping that I might be able to carry a round winner's total over a>> from one game to the next to give a series summary upon quitting, but a>> haven't figured out how to do that yet. a>> Anyway, have attached the code, and would naturally welcome comments. a>> It is probably too many lines for what the program actually does, so if a>> you have any ideas how parsimony can be achieved, please share them with a>> me, but I'd also appreciate it if you could explain what it is that you a>> are actually doing too - that would aid my learning. a>> Thanks folks. a>> Kind regards a>> Andrew SA> _______________________________________________ SA> Tutor maillist - Tutor@python.org SA> http://mail.python.org/mailman/listinfo/tutor From jeff@ccvcorp.com Mon Feb 3 19:27:01 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Mon Feb 3 19:27:01 2003 Subject: [Tutor] Global scope References: Message-ID: <3E3F063F.7020200@ccvcorp.com> Pete Versteegen wrote: >If I define a module with all of the variables/lists and import it in each >function that requires a variable/list from that module, would that work? > > Yes, but it's likely to lead to a rather ugly solution. You probably are much better off if you invest the time and effort to convert the global variables and the functions that operate on them into a set of classes. You'll end up with something that's *much* easier to understand (and thus easier to extend, maintain, and use). Jeff Shannon Technician/Programmer Credit International From mongo57a@comcast.net Mon Feb 3 19:31:01 2003 From: mongo57a@comcast.net (andy surany) Date: Mon Feb 3 19:31:01 2003 Subject: [Tutor] The concept of string arrays Message-ID: <00cf01c2cbe4$ae5233c0$2502a8c0@emily.ewndsr01.nj.comcast.net> Hello Members! I'm reading an Excel file into memory. The values are all strings. My no frills approach to doing this was to simply set up a list, read the values from a file, and append the list. Each element is then referenced via position. For example, First_Name Last_Name Address Date_of_Birth would be input as follows: client.append(First_Name) client.append(Last_Name) client.append(Address) client.append(Fate_of_Birth) now if I want to reference the 45th row in the cell, I would start at position 45*4. This works - but I know that there have to be more elegant solutions. I tried creating a 4 dim array - but found that string types were not allowed. Is it possible to create a multi dimensional list or tuple? or???? TIA. Andy From erikprice@mac.com Mon Feb 3 20:16:04 2003 From: erikprice@mac.com (Erik Price) Date: Mon Feb 3 20:16:04 2003 Subject: [Tutor] The concept of string arrays In-Reply-To: <00cf01c2cbe4$ae5233c0$2502a8c0@emily.ewndsr01.nj.comcast.net> Message-ID: <29A882D3-37E0-11D7-9A02-00039351FE6A@mac.com> On Monday, February 3, 2003, at 07:30 PM, andy surany wrote: > I'm reading an Excel file into memory. The values are all strings. My > no > frills approach to doing this was to simply set up a list, read the > values from a file, and append the list. Each element is then > referenced > via position. For example, > > First_Name Last_Name Address Date_of_Birth > > would be input as follows: > > client.append(First_Name) > client.append(Last_Name) > client.append(Address) > client.append(Fate_of_Birth) > > now if I want to reference the 45th row in the cell, I would start at > position 45*4. > > This works - but I know that there have to be more elegant solutions. I > tried creating a 4 dim array - but found that string types were not > allowed. Is it possible to create a multi dimensional list or tuple? > or???? Elegance is probably in the eye of the beholder, but I personally hate multi-dimensional arrays. Maybe they're helpful if you're programming in C, or if you're concerned with performance, I have no idea. Why not just create a couple of objects to represent the data you're working with? My own approach would be to create a Record or Row class that represents a row of the spreadsheet. It would have four fields, each named after one of the columns. You could write another object called SpreadSheet which could serve as a handy wrapper object around a list (or perhaps a tuple if you're doing read-only work), with some convenience methods. The Record object is probably self-explanatory, but the SpreadSheet class might look something like: class SpreadSheet: def __init__(): this.recordlist = [] def get_records: return this.recordlist def get_record(index): return this.recordlist[index] def append_record(record): this.recordlist.append(record) def read_record(): ...etc... Then, when you want to use your classes, you can do something to the effect of: f = open("spreadsheet.xls") ss = new SpreadSheet() for i in f.readlines(): r = new Record(i) ss.append(r) or something like that. (I haven't written Python in a long time so my syntax may be incorrect, but it's to give you the gist of what one person considers elegant.) As I said before, it's a matter of taste, but I find that designs which make use of objects help clarify what is going on in the program and make for a more elegant design. Erik -- Erik Price email: erikprice@mac.com jabber: erikprice@jabber.org From Don Arnold" Message-ID: <0d5d01c2cbf3$fdd177d0$7912ba3f@defaultcomp> ----- Original Message ----- From: "andy surany" To: Sent: Monday, February 03, 2003 6:30 PM Subject: [Tutor] The concept of string arrays > Hello Members! > > I'm reading an Excel file into memory. The values are all strings. My no > frills approach to doing this was to simply set up a list, read the > values from a file, and append the list. Each element is then referenced > via position. For example, > > First_Name Last_Name Address Date_of_Birth > > would be input as follows: > > client.append(First_Name) > client.append(Last_Name) > client.append(Address) > client.append(Fate_of_Birth) > > now if I want to reference the 45th row in the cell, I would start at > position 45*4. > > This works - but I know that there have to be more elegant solutions. I > tried creating a 4 dim array - but found that string types were not > allowed. Is it possible to create a multi dimensional list or tuple? > or???? > > TIA. > > Andy > I'm not sure this is what you're shooting for, but it might be a step in the right direction: class Holder: def __init__(self,headers,data): for key, value in zip(headers,data): self.__dict__[key] = value def __getitem__(self,key): return self.__dict__[key] ## assumes you've already read in the first line (which contains the column ## names) and converted it via one of the CSV modules into a list of strings headerValues = ['First_Name','Last_Name','Address','Date_of_Birth'] ## same thing with current spreadsheet row dataLine = ['Don','Arnold','12345 Main St','1967-02-21'] client = Holder(headerValues, dataLine) for key, value in client.__dict__.items(): print "client['%s'] = %s" % (key, client[key]) ---- begin script output ---- client['First_Name'] = Don client['Last_Name'] = Arnold client['Date_of_Birth'] = 1967-02-21 client['Address'] = 12345 Main St ---- end script output ---- As you can see, you are now able to access a specific field in the row by column name, instead of column position. This is especially useful if columns get swapped around: you don't care where the column for the first name is, as long as it's called First_Name. You can build a list of these Holder instances as you would any other list, and still access each ones fields as before: clientList = [] fileLines = [ ['John','Smith','1 Grand Ave','1930-01-01'], ['Bob','Jones','5 Willow Pk','1925-03-17'], ['Susan','Smith','4 Milky Way','1980-07-04'] ] for dataLine in fileLines: clientList.append(Holder(headerValues,dataLine)) print clientList[0]['First_Name'] print clientList[1]['Last_Name'] print clientList[2]['Address'] ---- begin script output ---- John Jones 4 Milky Way ---- end script output ---- HTH, Don From shalehperry@attbi.com Mon Feb 3 23:47:07 2003 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Mon Feb 3 23:47:07 2003 Subject: [Tutor] rock, paper, scissors (ro sham bo) part deux In-Reply-To: <1044311824.1640.212.camel@localhost.localdomain> References: <1044311824.1640.212.camel@localhost.localdomain> Message-ID: <200302032046.16772.shalehperry@attbi.com> --------------Boundary-00=_49PRW8AZUA06T1D25V41 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable On Monday 03 February 2003 14:41, ahimsa wrote: > Sean, Magnus, Alan, Bob and Gregor > > At the risk of belabouring this thread, I wanted to update you with > developments on my earlier requests for input and since you all so > graciously contributed something to helping me, I wanted to share where > it is at (to date). nah, this is good for the list. One thing to remember is there are two "customers" of python tutor: a) the people asking questions today b) the people looking for answers tomorrow by reading the archives. Since you asked for "how would you do it?", enclosed is a simple version = that=20 points you there. Feel free to ask on the list about anything you do not= =20 understand. You also asked about storing scores between games. Look into "pickle" an= d=20 pickling. --------------Boundary-00=_49PRW8AZUA06T1D25V41 Content-Type: text/x-python; charset="iso-8859-1"; name="roshambo.py" Content-Transfer-Encoding: 7bit Content-Disposition: attachment; filename="roshambo.py" #!/usr/bin/python ## # # written by Sean 'Shaleh' Perry 2003 # # permission is given to use, modify, redistribute this code without limitation # this code is without warranty # ## import random outcomes = { "rock": "scissors", "paper": "rock", "scissors": "paper" } def decide_outcome(player1, player2): if outcomes[player1] == player2: return 1 elif outcomes[player2] == player1: return 2 else: return 0 def random_player_input(): return random.choice(outcomes.keys()) if __name__ == '__main__': score = [0, 0, 0] get_player1_choice = random_player_input get_player2_choice = random_player_input rounds = 3 counter = 0 while counter < rounds: player1 = get_player1_choice() player2 = get_player2_choice() winner = decide_outcome(player1, player2) score[winner] += 1 counter += 1 print score --------------Boundary-00=_49PRW8AZUA06T1D25V41-- From johnca@ourpla.net Tue Feb 4 01:41:14 2003 From: johnca@ourpla.net (John Abbe) Date: Tue Feb 4 01:41:14 2003 Subject: [Tutor] Objectifying code In-Reply-To: <5.1.0.14.0.20030124181208.02cffed8@www.thinkware.se> References: <5.1.0.14.0.20030124181208.02cffed8@www.thinkware.se> Message-ID: At 7:42 PM +0100 2003-01-24, Magnus Lycka wrote: >To be honest, I didn't bother reading through the code well enough >to understand what it did. This is partly because I'm in a hurry, >and partly because it's written in a way that is difficult to read. > >I would suggest that you use the normal convention of python code, >instead of writing something looking like an overgrown bat-file. ;) >In other words, use the standard idiom of > >if __name__ == '__main__': > main() > >in the end, make a main() function that captures the main >abstractions of the program, so that people can read that function >(which is hopefully note more than a screenful) and understand >what it's all about. You don't need classes for this, you can use >well named functions. This seems less readable to me, but i can see how it might make modularization more obvious (eg two functions doing almost identical things). Will do. >I would also suggest that you remove all the big strings from the >main body of the code. They completely mess up the readability that >python normally provides. Let's have a look at a piece of code: [...code with lots of long in-line strings...] >I can't make myself try to follow this without giving >it an overhaul. ... >recordEditForm = """ >

Editing %(firstname)s %)(lastname)s's record

>
[...edited for brevity...] >
""" > >The only thing left in the part of the program where I cut out >this section would be: > > elif 'edit' in Args: > # Edit a record > for entry in lankaDB: > if entry['firstname'] + entry['lastname'] == Args['edit']: > print recordEditForm % (entry + {'cgiaddr': cgiaddr}) Hm, my Python says "TypeError: unsupported operand types for +: 'dict' and 'dict'" So, i replaced that last line with: entry.update({'cgiaddr': cgiaddr}) print recordEditForm % entry (This only works because i don't mind altering the "entry" dict here. Is there a function that returns the merging of two dictionaries?) >This is easier to read, isn't it? We don't have to worry about HTML >form layout and program flow at the same time. The indentation is >helpful in suggesting a structure, and the use of string % dict instead >of string % tuple both cleans up the print statement and makes it >much easier to modify and review the HTML forms. B-b-b-b-b! Cool, i didn't know about the % dict trick with %(key)s. I guess that's why i'm on the python-newbies list :) I'm re-working the code now and may re-submit it later for objectifying help... Life, John -- All you /\/\ John Abbe "If you don't like the news, need \ / CatHerder go out and make some of your own." is... \/ http://ourpla.net/john/ --Wes Nisker From magnus@thinkware.se Tue Feb 4 02:16:01 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Tue Feb 4 02:16:01 2003 Subject: [Tutor] Objectifying code In-Reply-To: References: <5.1.0.14.0.20030124181208.02cffed8@www.thinkware.se> <5.1.0.14.0.20030124181208.02cffed8@www.thinkware.se> Message-ID: <5.1.0.14.0.20030204080115.02b85220@www.thinkware.se> At 10:47 2003-02-04 +0630, John Abbe wrote: >Hm, my Python says "TypeError: unsupported operand types for +: 'dict' and >'dict'" Mine too. How silly of me! "When in doubt, refuse the temptation to guess." I should have known that Python would refuse to do something unclearly defined like that. The problem is what to do when you run into the same key in both dicts. Of course your approach works. I guess I should have done: import copy stringFields = copy.copy(entry) stringFields['cgiaddr'] = cgiaddr print x % stringFields Or, for a more generic (simply overwriting) merge >>> def dictMerge(*dicts): ... all = {} ... for dict in dicts: ... for key, value in dict.items(): ... all[key] = value ... return all ... >>> print dictMerge({1:2,2:3},{2:4,3:4},{'a':'b'}) {'a': 'b', 1: 2, 2: 4, 3: 4} print x % dictMerge(entry, {'cgiaddr': cgiaddr}) -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From charlie@begeistert.org Tue Feb 4 06:26:03 2003 From: charlie@begeistert.org (Charlie Clark) Date: Tue Feb 4 06:26:03 2003 Subject: [Tutor] Finding out what causes the crash Message-ID: <20030204122547.1214.4@.1044349930.fake> Dear list, I've got a script which causes the Python binary to crash. Initial observations tell me it has something to do with a particular database insert but it is not always the same one and it does not always appear to be the same string. I get the same problem using Python 2.1.1 on windows and Python 2.1.3 What is the best way to find out more about what's happening? By the way please reply to me directly as I'm one of those digest readers :o) thanx as always for the help From Adam Vardy Tue Feb 4 08:04:04 2003 From: Adam Vardy (Adam Vardy) Date: Tue Feb 4 08:04:04 2003 Subject: [Tutor] Out of range Message-ID: <143384318000.20030204092734@roadrunner.nf.net> Someone have any suggestions on this index error? IndexError: string index out of range SyntaxError: invalid syntax >>> >>> print index Traceback (most recent call last): File "", line 1, in ? print index NameError: name 'index' is not defined >>> -- Adam Vardy From magnus@thinkware.se Tue Feb 4 08:06:50 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Tue Feb 4 08:06:50 2003 Subject: [Tutor] Objectifying code In-Reply-To: <200302040256.10651.stephan.richter@tufts.edu> References: <5.1.0.14.0.20030204080115.02b85220@www.thinkware.se> <5.1.0.14.0.20030124181208.02cffed8@www.thinkware.se> <5.1.0.14.0.20030204080115.02b85220@www.thinkware.se> Message-ID: <5.1.0.14.0.20030204135805.02b9f4f8@www.thinkware.se> At 02:56 2003-02-04 -0500, Stephan Richter wrote: >Shrug, what about dict1.update(dict2)? This function is fast, since it is >written in C. Right, a dict merge that doesn't modify any of the original dicts should be faster as d={};d.update(dict1);d.update(dict2) than with my loops. So, written as a function it would be def dictMerge(*dicts): all = {} for dict in dicts: all.update(dict) return all Thanks Stephan. I should also reread Chapter 2 of library reference more often. I forgot about update... -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From francois.granger@free.fr Tue Feb 4 08:13:01 2003 From: francois.granger@free.fr (Fran=?ISO-8859-1?B?5w==?=ois Granger) Date: Tue Feb 4 08:13:01 2003 Subject: [Tutor] Finding out what causes the crash In-Reply-To: <20030204122547.1214.4@.1044349930.fake> Message-ID: on 4/02/03 12:25, Charlie Clark at charlie@begeistert.org wrote: > I've got a script which causes the Python binary to crash. Initial > observations tell me it has something to do with a particular database > insert but it is not always the same one and it does not always appear to > be the same string. > > I get the same problem using Python 2.1.1 on windows and Python 2.1.3 > > What is the best way to find out more about what's happening? Keep a log with a simple log utils. Just before the faulty code, log the parameters. class logthis: def __init__(self, logfile): import time self.t = time.ctime self.logfile = logfile try: fp = file(self.logfile) except: fp = file(self.logfile, 'w') # will creat the file if not avail fp.close() def __call__(self, *args): t = self.t() l = [] for item in args: l.append(str(item)) file(self.logfile, 'a').write(t + '\t' + '\t'.join(l) + '\n') At biggining of program: L = logthis('toto.txt') Then: Params = list(things) L(Params) -- Le courrier est un moyen de communication. Les gens devraient se poser des questions sur les implications politiques des choix (ou non choix) de leurs outils et technologies. Pour des courriers propres : -- From borelan@wanadoo.fr Tue Feb 4 08:30:02 2003 From: borelan@wanadoo.fr (D2) Date: Tue Feb 4 08:30:02 2003 Subject: [Tutor] Python notations References: <5.1.0.14.0.20030203215342.02ab99a0@www.thinkware.se> Message-ID: <3E3FBF66.8010106@wanadoo.fr> for example, when do i use object.method or method(parameters), or object.method() or something.method().other_method().something (pan) I didn't find something explicit to help me understand the way that works= =2E Maybe it's so clear that i can't see it ??? :) Thanks for your help Magnus Lycka a =E9crit: > At 12:09 2003-02-03 -0400, D2 wrote: > >> New to python, i'm trying to understand Python's notations. > > > What do you mean by notations? Can you give an example? > > --=20 Andre From magnus@thinkware.se Tue Feb 4 08:33:02 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Tue Feb 4 08:33:02 2003 Subject: [Tutor] Finding out what causes the crash In-Reply-To: <20030204122547.1214.4@.1044349930.fake> Message-ID: <5.1.0.14.0.20030204140541.00be7710@www.thinkware.se> At 12:25 2003-02-04 +0100, Charlie Clark wrote: >What is the best way to find out more about what's happening? A start is to either run in a debugger or insert print statements in strategic places to find out where it happens. -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From glingl@aon.at Tue Feb 4 08:38:02 2003 From: glingl@aon.at (Gregor Lingl) Date: Tue Feb 4 08:38:02 2003 Subject: [Tutor] Out of range References: <143384318000.20030204092734@roadrunner.nf.net> Message-ID: <3E3FC22E.1000806@aon.at> Adam Vardy schrieb: >Someone have any suggestions on this index error? > >IndexError: string index out of range >SyntaxError: invalid syntax > > >>>>print index >>>> >>>> >Traceback (most recent call last): > File "", line 1, in ? > print index >NameError: name 'index' is not defined > > > > > You report us three Errors. The last one is clear (for me), as there is no name index in Python (unless you define it). In Python index is a method either of string or of list objects: >>> "abcde".index("c") 2 >>> [1,2,3,4,5].index(4) 3 What are the situations, where the other two occur? The first on is easy to imagine: >>> a = "hey!" >>> a[4] Traceback (most recent call last): File "", line 1, in ? a[4] IndexError: string index out of range This occurs because ... >>> for c in a: c, a.index(c) ('h', 0) ('e', 1) ('y', 2) ('!', 3) >>> There is no character with index 4 in "hey!" Only from knowing that a SyntaxError occured, it's impossible to imagine what it possibly caused ... Regards, Gregor From Deirdre Hackett" Message-ID: <004301c2cc58$3c108860$0400a8c0@egbert> This is a multi-part message in MIME format. ------=_NextPart_000_0040_01C2CC58.39698440 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable > I want to take information into my program continuously at 20=20 > samples per second, >=20 I didn't understand the rest but to loop 20 times a second - provided your machine is fast enough! - do this: while 1: sleep(0.05) # 1/20s delay # do something here if someCondition: break > The command to send to the device is *99c\r=20 > What do i need to change in regard to just polling the device? Are you sending or polling(reading)? Or both? Do you send to get a result back?=20 I don't understand sorry.=20 Alan g Normally I would just poll the sensor i am using by sending *99p\r to = the sensor.=20 ser.write("*99c\r") In response to this command the sensor would output a single sample.=20 996 - 3,898 - 7,541 These are the x, y and z components of the strength and direction of a = magnetic field. I would like to take in continuous readings at the sample rate which is = 20sps. To do this, send *99c\r to the serial port.=20 The output should send continuous readings to the computer through the = serial port.=20 Not sure that this clears things up but it is a start Thanks, Deirdre=20 ------=_NextPart_000_0040_01C2CC58.39698440 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable =FF=FE<=00!=00D=00O=00C=00T=00Y=00P=00E=00 =00H=00T=00M=00L=00 = =00P=00U=00B=00L=00I=00C=00 = =00"=00-=00/=00/=00W=003=00C=00/=00/=00D=00T=00D=00 =00H=00T=00M=00L=00 = =004=00.=000=00 = =00T=00r=00a=00n=00s=00i=00t=00i=00o=00n=00a=00l=00/=00/=00E=00N=00"=00>=00= =0D=00=0A= =00<=00H=00T=00M=00L=00>=00<=00H=00E=00A=00D=00>=00=0D=00=0A= =00<=00M=00E=00T=00A=00 = =00c=00o=00n=00t=00e=00n=00t=00=3D=00"=00t=00e=00x=00t=00/=00h=00t=00m=00= l=00;=00 = =00c=00h=00a=00r=00s=00e=00t=00=3D=00u=00n=00i=00c=00o=00d=00e=00"=00 = =00h=00t=00t=00p=00-=00e=00q=00u=00i=00v=00=3D=00C=00o=00n=00t=00e=00n=00= t=00-=00T=00y=00p=00e=00>=00=0D=00=0A= =00<=00M=00E=00T=00A=00 = =00c=00o=00n=00t=00e=00n=00t=00=3D=00"=00M=00S=00H=00T=00M=00L=00 = =005=00.=000=000=00.=002=006=001=004=00.=003=005=000=000=00"=00 = =00n=00a=00m=00e=00=3D=00G=00E=00N=00E=00R=00A=00T=00O=00R=00>=00=0D=00=0A= =00<=00S=00T=00Y=00L=00E=00>=00<=00/=00S=00T=00Y=00L=00E=00>=00=0D=00=0A= =00<=00/=00H=00E=00A=00D=00>=00=0D=00=0A= =00<=00B=00O=00D=00Y=00>=00=0D=00=0A= =00<=00D=00I=00V=00>=00<=00F=00O=00N=00T=00 = =00f=00a=00c=00e=00=3D=00A=00r=00i=00a=00l=00 = =00s=00i=00z=00e=00=3D=002=00>=00&=00g=00t=00;=00 =00I=00 = =00w=00a=00n=00t=00 =00t=00o=00 =00t=00a=00k=00e=00 = =00i=00n=00f=00o=00r=00m=00a=00t=00i=00o=00n=00 =00i=00n=00t=00o=00 = =00m=00y=00 =00p=00r=00o=00g=00r=00a=00m=00 =00=0D=00=0A= =00c=00o=00n=00t=00i=00n=00u=00o=00u=00s=00l=00y=00 =00a=00t=00 = =002=000=00 =00<=00B=00R=00>=00&=00g=00t=00;=00 = =00s=00a=00m=00p=00l=00e=00s=00 =00p=00e=00r=00 = =00s=00e=00c=00o=00n=00d=00,=00<=00B=00R=00>=00&=00g=00t=00;=00 = =00<=00/=00F=00O=00N=00T=00>=00<=00/=00D=00I=00V=00>=00=0D=00=0A= =00<=00D=00I=00V=00>=00&=00n=00b=00s=00p=00;=00<=00/=00D=00I=00V=00>=00=0D= =00=0A= =00<=00D=00I=00V=00>=00<=00F=00O=00N=00T=00 = =00f=00a=00c=00e=00=3D=00A=00r=00i=00a=00l=00 = =00s=00i=00z=00e=00=3D=002=00>=00I=00 =00d=00i=00d=00n=00'=00t=00 = =00u=00n=00d=00e=00r=00s=00t=00a=00n=00d=00 =00t=00h=00e=00 = =00r=00e=00s=00t=00 =00b=00u=00t=00 =00t=00o=00 =00l=00o=00o=00p=00 = =002=000=00 =00t=00i=00m=00e=00s=00 =00a=00 =00=0D=00=0A= =00s=00e=00c=00o=00n=00d=00<=00B=00R=00>=00&=00n=00b=00s=00p=00;=00-=00 = =00p=00r=00o=00v=00i=00d=00e=00d=00 =00y=00o=00u=00r=00 = =00m=00a=00c=00h=00i=00n=00e=00 =00i=00s=00 =00f=00a=00s=00t=00 = =00e=00n=00o=00u=00g=00h=00!=00 =00-=00 =00d=00o=00 = =00t=00h=00i=00s=00:=00<=00/=00F=00O=00N=00T=00>=00<=00/=00D=00I=00V=00>=00= =0D=00=0A= =00<=00D=00I=00V=00>=00&=00n=00b=00s=00p=00;=00<=00/=00D=00I=00V=00>=00=0D= =00=0A= =00<=00D=00I=00V=00>=00<=00F=00O=00N=00T=00 = =00f=00a=00c=00e=00=3D=00A=00r=00i=00a=00l=00 = =00s=00i=00z=00e=00=3D=002=00>=00w=00h=00i=00l=00e=00 = =001=00:=00<=00B=00R=00>=00&=00n=00b=00s=00p=00;=00&=00n=00b=00s=00p=00;=00= =00s=00l=00e=00e=00p=00(=000=00.=000=005=00)=00&=00n=00b=00s=00p=00;=00 = =00#=00 =001=00/=002=000=00s=00 =00=0D=00=0A= =00d=00e=00l=00a=00y=00<=00B=00R=00>=00&=00n=00b=00s=00p=00;=00&=00n=00b=00= s=00p=00;=00 =00#=00 =00d=00o=00 =00s=00o=00m=00e=00t=00h=00i=00n=00g=00 = =00h=00e=00r=00e=00<=00B=00R=00>=00&=00n=00b=00s=00p=00;=00&=00n=00b=00s=00= p=00;=00 =00i=00f=00 = =00s=00o=00m=00e=00C=00o=00n=00d=00i=00t=00i=00o=00n=00:=00 =00=0D=00=0A= =00b=00r=00e=00a=00k=00<=00/=00F=00O=00N=00T=00>=00<=00/=00D=00I=00V=00>=00= =0D=00=0A= =00<=00D=00I=00V=00>=00&=00n=00b=00s=00p=00;=00<=00/=00D=00I=00V=00>=00=0D= =00=0A= =00<=00D=00I=00V=00>=00<=00B=00R=00>=00<=00F=00O=00N=00T=00 = =00f=00a=00c=00e=00=3D=00A=00r=00i=00a=00l=00 = =00s=00i=00z=00e=00=3D=002=00>=00&=00g=00t=00;=00 =00T=00h=00e=00 = =00c=00o=00m=00m=00a=00n=00d=00 =00t=00o=00 =00s=00e=00n=00d=00 = =00t=00o=00 =00t=00h=00e=00 =00d=00e=00v=00i=00c=00e=00 =00i=00s=00 = =00=0D=00=0A= =00*=009=009=00c=00\=00r=00 =00<=00B=00R=00>=00&=00g=00t=00;=00 = =00W=00h=00a=00t=00 =00d=00o=00 =00i=00 =00n=00e=00e=00d=00 =00t=00o=00 = =00c=00h=00a=00n=00g=00e=00 =00i=00n=00 =00r=00e=00g=00a=00r=00d=00 = =00t=00o=00 =00j=00u=00s=00t=00 =00p=00o=00l=00l=00i=00n=00g=00 = =00t=00h=00e=00 =00=0D=00=0A= =00d=00e=00v=00i=00c=00e=00?=00<=00/=00F=00O=00N=00T=00>=00<=00/=00D=00I=00= V=00>=00=0D=00=0A= =00<=00D=00I=00V=00>=00&=00n=00b=00s=00p=00;=00<=00/=00D=00I=00V=00>=00=0D= =00=0A= =00<=00D=00I=00V=00>=00<=00F=00O=00N=00T=00 = =00f=00a=00c=00e=00=3D=00A=00r=00i=00a=00l=00 = =00s=00i=00z=00e=00=3D=002=00>=00A=00r=00e=00 =00y=00o=00u=00 = =00s=00e=00n=00d=00i=00n=00g=00 =00o=00r=00 = =00p=00o=00l=00l=00i=00n=00g=00(=00r=00e=00a=00d=00i=00n=00g=00)=00?=00<=00= B=00R=00>=00O=00r=00 =00b=00o=00t=00h=00?=00 =00D=00o=00 =00=0D=00=0A= =00y=00o=00u=00 =00s=00e=00n=00d=00 =00t=00o=00 =00g=00e=00t=00 =00a=00 = =00r=00e=00s=00u=00l=00t=00 =00b=00a=00c=00k=00?=00 = =00<=00/=00F=00O=00N=00T=00>=00<=00/=00D=00I=00V=00>=00=0D=00=0A= =00<=00D=00I=00V=00>=00&=00n=00b=00s=00p=00;=00<=00/=00D=00I=00V=00>=00=0D= =00=0A= =00<=00D=00I=00V=00>=00<=00F=00O=00N=00T=00 = =00f=00a=00c=00e=00=3D=00A=00r=00i=00a=00l=00 = =00s=00i=00z=00e=00=3D=002=00>=00I=00 =00d=00o=00n=00'=00t=00 = =00u=00n=00d=00e=00r=00s=00t=00a=00n=00d=00 =00s=00o=00r=00r=00y=00.=00 = =00<=00/=00F=00O=00N=00T=00>=00<=00/=00D=00I=00V=00>=00=0D=00=0A= =00<=00D=00I=00V=00>=00&=00n=00b=00s=00p=00;=00<=00/=00D=00I=00V=00>=00=0D= =00=0A= =00<=00D=00I=00V=00>=00<=00F=00O=00N=00T=00 = =00f=00a=00c=00e=00=3D=00A=00r=00i=00a=00l=00 = =00s=00i=00z=00e=00=3D=002=00>=00A=00l=00a=00n=00 = =00g=00<=00/=00F=00O=00N=00T=00>=00<=00/=00D=00I=00V=00>=00=0D=00=0A= =00<=00D=00I=00V=00>=00&=00n=00b=00s=00p=00;=00<=00/=00D=00I=00V=00>=00=0D= =00=0A= =00<=00D=00I=00V=00>=00<=00F=00O=00N=00T=00 = =00f=00a=00c=00e=00=3D=00A=00r=00i=00a=00l=00 = =00s=00i=00z=00e=00=3D=002=00>=00N=00o=00r=00m=00a=00l=00l=00y=00 = =00I=00 =00w=00o=00u=00l=00d=00 =00j=00u=00s=00t=00 =00p=00o=00l=00l=00 = =00t=00h=00e=00 =00s=00e=00n=00s=00o=00r=00 =00i=00 =00a=00m=00 = =00u=00s=00i=00n=00g=00 =00b=00y=00 =00=0D=00=0A= =00s=00e=00n=00d=00i=00n=00g=00 =00*=009=009=00p=00\=00r=00 =00t=00o=00 = =00t=00h=00e=00 =00s=00e=00n=00s=00o=00r=00.=00 = =00<=00/=00F=00O=00N=00T=00>=00<=00/=00D=00I=00V=00>=00=0D=00=0A= =00<=00D=00I=00V=00>=00<=00F=00O=00N=00T=00 = =00f=00a=00c=00e=00=3D=00A=00r=00i=00a=00l=00 = =00s=00i=00z=00e=00=3D=002=00>=00=0D=00=0A= =00<=00D=00I=00V=00>=00<=00F=00O=00N=00T=00 = =00f=00a=00c=00e=00=3D=00A=00r=00i=00a=00l=00 = =00s=00i=00z=00e=00=3D=002=00>=00&=00n=00b=00s=00p=00;=00&=00n=00b=00s=00= p=00;=00&=00n=00b=00s=00p=00;=00&=00n=00b=00s=00p=00;=00 = =00&=00n=00b=00s=00p=00;=00&=00n=00b=00s=00p=00;=00&=00n=00b=00s=00p=00;=00= =00<=00F=00O=00N=00T=00 =00=0D=00=0A= =00c=00o=00l=00o=00r=00=3D=00#=000=000=000=000=00f=00f=00>=00s=00e=00r=00= .=00w=00r=00i=00t=00e=00(=00"=00*=009=009=00c=00\=00r=00"=00)=00<=00/=00F= =00O=00N=00T=00>=00<=00/=00F=00O=00N=00T=00>=00<=00/=00D=00I=00V=00>=00<=00= /=00F=00O=00N=00T=00>=00<=00/=00D=00I=00V=00>=00=0D=00=0A= =00<=00D=00I=00V=00>=00<=00F=00O=00N=00T=00 = =00f=00a=00c=00e=00=3D=00A=00r=00i=00a=00l=00 = =00s=00i=00z=00e=00=3D=002=00>=00I=00n=00 = =00r=00e=00s=00p=00o=00n=00s=00e=00 =00t=00o=00 =00t=00h=00i=00s=00 = =00c=00o=00m=00m=00a=00n=00d=00 =00t=00h=00e=00 = =00s=00e=00n=00s=00o=00r=00 =00w=00o=00u=00l=00d=00 = =00o=00u=00t=00p=00u=00t=00 =00=0D=00=0A= =00a=00 =00s=00i=00n=00g=00l=00e=00 =00s=00a=00m=00p=00l=00e=00.=00 = =00<=00/=00F=00O=00N=00T=00>=00<=00/=00D=00I=00V=00>=00=0D=00=0A= =00<=00D=00I=00V=00>=00<=00F=00O=00N=00T=00 = =00f=00a=00c=00e=00=3D=00A=00r=00i=00a=00l=00 = =00s=00i=00z=00e=00=3D=002=00>=00=0D=00=0A= =00<=00D=00I=00V=00>=00<=00F=00O=00N=00T=00 = =00f=00a=00c=00e=00=3D=00A=00r=00i=00a=00l=00 = =00s=00i=00z=00e=00=3D=002=00>=00&=00n=00b=00s=00p=00;=00&=00n=00b=00s=00= p=00;=00&=00n=00b=00s=00p=00;=00 = =009=009=006=00&=00n=00b=00s=00p=00;=00&=00n=00b=00s=00p=00;=00 =00-=00 = =00=0D=00=0A= =003=00,=008=009=008=00&=00n=00b=00s=00p=00;=00&=00n=00b=00s=00p=00;=00 = =00-=00 = =007=00,=005=004=001=00<=00/=00F=00O=00N=00T=00>=00<=00/=00D=00I=00V=00>=00= <=00/=00F=00O=00N=00T=00>=00<=00/=00D=00I=00V=00>=00=0D=00=0A= =00<=00D=00I=00V=00>=00<=00F=00O=00N=00T=00 = =00f=00a=00c=00e=00=3D=00A=00r=00i=00a=00l=00 = =00s=00i=00z=00e=00=3D=002=00>=00<=00F=00O=00N=00T=00 = =00f=00a=00c=00e=00=3D=00A=00r=00i=00a=00l=00 = =00s=00i=00z=00e=00=3D=002=00>=00T=00h=00e=00s=00e=00 =00a=00r=00e=00 = =00t=00h=00e=00 =00x=00,=00 =00y=00 =00a=00n=00d=00 =00=0D=00=0A= =00z=00&=00n=00b=00s=00p=00;=00c=00o=00m=00p=00o=00n=00e=00n=00t=00s=00 = =00o=00f=00 =00t=00h=00e=00 =00s=00t=00r=00e=00n=00g=00t=00h=00 = =00a=00n=00d=00 =00d=00i=00r=00e=00c=00t=00i=00o=00n=00 =00o=00f=00 = =00a=00 =00m=00a=00g=00n=00e=00t=00i=00c=00 =00=0D=00=0A= =00f=00i=00e=00l=00d=00.=00<=00/=00F=00O=00N=00T=00>=00<=00/=00F=00O=00N=00= T=00>=00<=00/=00D=00I=00V=00>=00=0D=00=0A= =00<=00D=00I=00V=00>=00<=00F=00O=00N=00T=00 = =00f=00a=00c=00e=00=3D=00A=00r=00i=00a=00l=00 = =00s=00i=00z=00e=00=3D=002=00>=00I=00 =00w=00o=00u=00l=00d=00 = =00l=00i=00k=00e=00 =00t=00o=00 =00t=00a=00k=00e=00 =00i=00n=00 = =00c=00o=00n=00t=00i=00n=00u=00o=00u=00s=00 = =00r=00e=00a=00d=00i=00n=00g=00s=00 =00a=00t=00 =00t=00h=00e=00 =00=0D=00=0A= =00s=00a=00m=00p=00l=00e=00 =00r=00a=00t=00e=00 =00w=00h=00i=00c=00h=00 = =00i=00s=00 = =002=000=00s=00p=00s=00.=00<=00/=00F=00O=00N=00T=00>=00<=00/=00D=00I=00V=00= >=00=0D=00=0A= =00<=00D=00I=00V=00>=00<=00F=00O=00N=00T=00 = =00f=00a=00c=00e=00=3D=00A=00r=00i=00a=00l=00 = =00s=00i=00z=00e=00=3D=002=00>=00T=00o=00 =00d=00o=00 = =00t=00h=00i=00s=00,=00 =00s=00e=00n=00d=00 =00*=009=009=00c=00\=00r=00 = =00t=00o=00 =00t=00h=00e=00 =00s=00e=00r=00i=00a=00l=00 = =00p=00o=00r=00t=00.=00 =00=0D=00=0A= =00<=00/=00F=00O=00N=00T=00>=00<=00/=00D=00I=00V=00>=00=0D=00=0A= =00<=00D=00I=00V=00>=00<=00F=00O=00N=00T=00 = =00f=00a=00c=00e=00=3D=00A=00r=00i=00a=00l=00 = =00s=00i=00z=00e=00=3D=002=00>=00T=00h=00e=00 = =00o=00u=00t=00p=00u=00t=00 =00s=00h=00o=00u=00l=00d=00 = =00s=00e=00n=00d=00 =00c=00o=00n=00t=00i=00n=00u=00o=00u=00s=00 = =00r=00e=00a=00d=00i=00n=00g=00s=00 =00t=00o=00 =00t=00h=00e=00 =00=0D=00=0A= =00c=00o=00m=00p=00u=00t=00e=00r=00 =00t=00h=00r=00o=00u=00g=00h=00 = =00t=00h=00e=00 =00s=00e=00r=00i=00a=00l=00 =00p=00o=00r=00t=00.=00 = =00<=00/=00F=00O=00N=00T=00>=00<=00/=00D=00I=00V=00>=00=0D=00=0A= =00<=00D=00I=00V=00>=00&=00n=00b=00s=00p=00;=00<=00/=00D=00I=00V=00>=00=0D= =00=0A= =00<=00D=00I=00V=00>=00<=00F=00O=00N=00T=00 = =00f=00a=00c=00e=00=3D=00A=00r=00i=00a=00l=00 = =00s=00i=00z=00e=00=3D=002=00>=00N=00o=00t=00 =00s=00u=00r=00e=00 = =00t=00h=00a=00t=00 =00t=00h=00i=00s=00 =00c=00l=00e=00a=00r=00s=00 = =00t=00h=00i=00n=00g=00s=00 =00u=00p=00 =00b=00u=00t=00 =00i=00t=00 = =00i=00s=00 =00a=00 =00=0D=00=0A= =00s=00t=00a=00r=00t=00<=00/=00F=00O=00N=00T=00>=00<=00/=00D=00I=00V=00>=00= =0D=00=0A= =00<=00D=00I=00V=00>=00<=00F=00O=00N=00T=00 = =00f=00a=00c=00e=00=3D=00A=00r=00i=00a=00l=00 = =00s=00i=00z=00e=00=3D=002=00>=00T=00h=00a=00n=00k=00s=00,=00<=00/=00F=00= O=00N=00T=00>=00<=00/=00D=00I=00V=00>=00=0D=00=0A= =00<=00D=00I=00V=00>=00<=00F=00O=00N=00T=00 = =00f=00a=00c=00e=00=3D=00A=00r=00i=00a=00l=00 = =00s=00i=00z=00e=00=3D=002=00>=00D=00e=00i=00r=00d=00r=00e=00 = =00<=00/=00F=00O=00N=00T=00>=00<=00/=00D=00I=00V=00>=00=0D=00=0A= =00<=00D=00I=00V=00>=00&=00n=00b=00s=00p=00;=00<=00/=00D=00I=00V=00>=00=0D= =00=0A= =00<=00D=00I=00V=00>=00<=00B=00R=00>=00&=00n=00b=00s=00p=00;=00<=00/=00D=00= I=00V=00>=00<=00/=00B=00O=00D=00Y=00>=00<=00/=00H=00T=00M=00L=00>=00=0D=00=0A= =00 ------=_NextPart_000_0040_01C2CC58.39698440-- From Deirdre Hackett" This is a multi-part message in MIME format. ------=_NextPart_000_00C3_01C2CC59.C6C12EA0 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable ----- Original Message -----=20 From: Deirdre Hackett=20 To: alan.gauld@bt.com ; tutor@python.org=20 Sent: Tuesday, February 04, 2003 2:18 PM Subject: Re: [Tutor] Continuous input at sample rate > I want to take information into my program continuously at 20=20 > samples per second, >=20 I didn't understand the rest but to loop 20 times a second - provided your machine is fast enough! - do this: while 1: sleep(0.05) # 1/20s delay # do something here if someCondition: break > The command to send to the device is *99c\r=20 > What do i need to change in regard to just polling the device? Are you sending or polling(reading)? Or both? Do you send to get a result back?=20 I don't understand sorry.=20 Alan g Normally I would just poll the sensor i am using by sending *99p\r to = the sensor.=20 ser.write("*99c\r") In response to this command the sensor would output a single sample.=20 996 - 3,898 - 7,541 These are the x, y and z components of the strength and direction of a = magnetic field. I would like to take in continuous readings at the sample rate which is = 20sps. To do this, send *99c\r to the serial port.=20 The output should send continuous readings to the computer through the = serial port.=20 Not sure that this clears things up, but it is a start Thanks, Deirdre=20 =20 ------=_NextPart_000_00C3_01C2CC59.C6C12EA0 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable =FF=FE<=00!=00D=00O=00C=00T=00Y=00P=00E=00 =00H=00T=00M=00L=00 = =00P=00U=00B=00L=00I=00C=00 = =00"=00-=00/=00/=00W=003=00C=00/=00/=00D=00T=00D=00 =00H=00T=00M=00L=00 = =004=00.=000=00 = =00T=00r=00a=00n=00s=00i=00t=00i=00o=00n=00a=00l=00/=00/=00E=00N=00"=00>=00= =0D=00=0A= =00<=00H=00T=00M=00L=00>=00<=00H=00E=00A=00D=00>=00=0D=00=0A= =00<=00M=00E=00T=00A=00 = =00c=00o=00n=00t=00e=00n=00t=00=3D=00"=00t=00e=00x=00t=00/=00h=00t=00m=00= l=00;=00 = =00c=00h=00a=00r=00s=00e=00t=00=3D=00u=00n=00i=00c=00o=00d=00e=00"=00 = =00h=00t=00t=00p=00-=00e=00q=00u=00i=00v=00=3D=00C=00o=00n=00t=00e=00n=00= t=00-=00T=00y=00p=00e=00>=00=0D=00=0A= =00<=00M=00E=00T=00A=00 = =00c=00o=00n=00t=00e=00n=00t=00=3D=00"=00M=00S=00H=00T=00M=00L=00 = =005=00.=000=000=00.=002=006=001=004=00.=003=005=000=000=00"=00 = =00n=00a=00m=00e=00=3D=00G=00E=00N=00E=00R=00A=00T=00O=00R=00>=00=0D=00=0A= =00<=00S=00T=00Y=00L=00E=00>=00<=00/=00S=00T=00Y=00L=00E=00>=00=0D=00=0A= =00<=00/=00H=00E=00A=00D=00>=00=0D=00=0A= =00<=00B=00O=00D=00Y=00 = =00b=00g=00C=00o=00l=00o=00r=00=3D=00#=00f=00f=00f=00f=00f=00f=00>=00=0D=00=0A= =00<=00D=00I=00V=00>=00&=00n=00b=00s=00p=00;=00<=00/=00D=00I=00V=00>=00=0D= =00=0A= =00<=00D=00I=00V=00 = =00s=00t=00y=00l=00e=00=3D=00"=00F=00O=00N=00T=00:=00 = =001=000=00p=00t=00 =00a=00r=00i=00a=00l=00"=00>=00-=00-=00-=00-=00-=00 = =00O=00r=00i=00g=00i=00n=00a=00l=00 =00M=00e=00s=00s=00a=00g=00e=00 = =00-=00-=00-=00-=00-=00 =00=0D=00=0A= =00<=00D=00I=00V=00 = =00s=00t=00y=00l=00e=00=3D=00"=00B=00A=00C=00K=00G=00R=00O=00U=00N=00D=00= :=00 =00#=00e=004=00e=004=00e=004=00;=00 = =00f=00o=00n=00t=00-=00c=00o=00l=00o=00r=00:=00 = =00b=00l=00a=00c=00k=00"=00>=00<=00B=00>=00F=00r=00o=00m=00:=00<=00/=00B=00= >=00 =00<=00A=00 =00=0D=00=0A= =00h=00r=00e=00f=00=3D=00"=00m=00a=00i=00l=00t=00o=00:=00d=00e=00i=00r=00= d=00r=00e=00h=00a=00c=00@=00l=00y=00c=00o=00s=00.=00c=00o=00.=00u=00k=00"= =00 = =00t=00i=00t=00l=00e=00=3D=00d=00e=00i=00r=00d=00r=00e=00h=00a=00c=00@=00= l=00y=00c=00o=00s=00.=00c=00o=00.=00u=00k=00>=00D=00e=00i=00r=00d=00r=00e= =00 =00=0D=00=0A= =00H=00a=00c=00k=00e=00t=00t=00<=00/=00A=00>=00 = =00<=00/=00D=00I=00V=00>=00=0D=00=0A= =00<=00D=00I=00V=00>=00<=00B=00>=00T=00o=00:=00<=00/=00B=00>=00 = =00<=00A=00 = =00h=00r=00e=00f=00=3D=00"=00m=00a=00i=00l=00t=00o=00:=00a=00l=00a=00n=00= .=00g=00a=00u=00l=00d=00@=00b=00t=00.=00c=00o=00m=00"=00 =00=0D=00=0A= =00t=00i=00t=00l=00e=00=3D=00a=00l=00a=00n=00.=00g=00a=00u=00l=00d=00@=00= b=00t=00.=00c=00o=00m=00>=00a=00l=00a=00n=00.=00g=00a=00u=00l=00d=00@=00b= =00t=00.=00c=00o=00m=00<=00/=00A=00>=00 =00;=00 =00<=00A=00 =00=0D=00=0A= =00h=00r=00e=00f=00=3D=00"=00m=00a=00i=00l=00t=00o=00:=00t=00u=00t=00o=00= r=00@=00p=00y=00t=00h=00o=00n=00.=00o=00r=00g=00"=00 = =00t=00i=00t=00l=00e=00=3D=00t=00u=00t=00o=00r=00@=00p=00y=00t=00h=00o=00= n=00.=00o=00r=00g=00>=00t=00u=00t=00o=00r=00@=00p=00y=00t=00h=00o=00n=00.= =00o=00r=00g=00<=00/=00A=00>=00 =00=0D=00=0A= =00<=00/=00D=00I=00V=00>=00=0D=00=0A= =00<=00D=00I=00V=00>=00<=00B=00>=00S=00e=00n=00t=00:=00<=00/=00B=00>=00 = =00T=00u=00e=00s=00d=00a=00y=00,=00 =00F=00e=00b=00r=00u=00a=00r=00y=00 = =000=004=00,=00 =002=000=000=003=00 =002=00:=001=008=00 = =00P=00M=00<=00/=00D=00I=00V=00>=00=0D=00=0A= =00<=00D=00I=00V=00>=00<=00B=00>=00S=00u=00b=00j=00e=00c=00t=00:=00<=00/=00= B=00>=00 =00R=00e=00:=00 =00[=00T=00u=00t=00o=00r=00]=00 = =00C=00o=00n=00t=00i=00n=00u=00o=00u=00s=00 =00i=00n=00p=00u=00t=00 = =00a=00t=00 =00s=00a=00m=00p=00l=00e=00 = =00r=00a=00t=00e=00<=00/=00D=00I=00V=00>=00<=00/=00D=00I=00V=00>=00=0D=00=0A= =00<=00D=00I=00V=00>=00<=00B=00R=00>=00<=00/=00D=00I=00V=00>=00=0D=00=0A= =00<=00D=00I=00V=00>=00<=00F=00O=00N=00T=00 = =00f=00a=00c=00e=00=3D=00A=00r=00i=00a=00l=00 = =00s=00i=00z=00e=00=3D=002=00>=00&=00g=00t=00;=00 =00I=00 = =00w=00a=00n=00t=00 =00t=00o=00 =00t=00a=00k=00e=00 = =00i=00n=00f=00o=00r=00m=00a=00t=00i=00o=00n=00 =00i=00n=00t=00o=00 = =00m=00y=00 =00p=00r=00o=00g=00r=00a=00m=00 =00=0D=00=0A= =00c=00o=00n=00t=00i=00n=00u=00o=00u=00s=00l=00y=00 =00a=00t=00 = =002=000=00 =00<=00B=00R=00>=00&=00g=00t=00;=00 = =00s=00a=00m=00p=00l=00e=00s=00 =00p=00e=00r=00 = =00s=00e=00c=00o=00n=00d=00,=00<=00B=00R=00>=00&=00g=00t=00;=00 = =00<=00/=00F=00O=00N=00T=00>=00<=00/=00D=00I=00V=00>=00=0D=00=0A= =00<=00D=00I=00V=00>=00&=00n=00b=00s=00p=00;=00<=00/=00D=00I=00V=00>=00=0D= =00=0A= =00<=00D=00I=00V=00>=00<=00F=00O=00N=00T=00 = =00f=00a=00c=00e=00=3D=00A=00r=00i=00a=00l=00 = =00s=00i=00z=00e=00=3D=002=00>=00I=00 =00d=00i=00d=00n=00'=00t=00 = =00u=00n=00d=00e=00r=00s=00t=00a=00n=00d=00 =00t=00h=00e=00 = =00r=00e=00s=00t=00 =00b=00u=00t=00 =00t=00o=00 =00l=00o=00o=00p=00 = =002=000=00 =00t=00i=00m=00e=00s=00 =00a=00 =00=0D=00=0A= =00s=00e=00c=00o=00n=00d=00<=00B=00R=00>=00&=00n=00b=00s=00p=00;=00-=00 = =00p=00r=00o=00v=00i=00d=00e=00d=00 =00y=00o=00u=00r=00 = =00m=00a=00c=00h=00i=00n=00e=00 =00i=00s=00 =00f=00a=00s=00t=00 = =00e=00n=00o=00u=00g=00h=00!=00 =00-=00 =00d=00o=00 = =00t=00h=00i=00s=00:=00<=00/=00F=00O=00N=00T=00>=00<=00/=00D=00I=00V=00>=00= =0D=00=0A= =00<=00D=00I=00V=00>=00&=00n=00b=00s=00p=00;=00<=00/=00D=00I=00V=00>=00=0D= =00=0A= =00<=00D=00I=00V=00>=00<=00F=00O=00N=00T=00 = =00f=00a=00c=00e=00=3D=00A=00r=00i=00a=00l=00 = =00s=00i=00z=00e=00=3D=002=00>=00w=00h=00i=00l=00e=00 = =001=00:=00<=00B=00R=00>=00&=00n=00b=00s=00p=00;=00&=00n=00b=00s=00p=00;=00= =00s=00l=00e=00e=00p=00(=000=00.=000=005=00)=00&=00n=00b=00s=00p=00;=00 = =00#=00 =001=00/=002=000=00s=00 =00=0D=00=0A= =00d=00e=00l=00a=00y=00<=00B=00R=00>=00&=00n=00b=00s=00p=00;=00&=00n=00b=00= s=00p=00;=00 =00#=00 =00d=00o=00 =00s=00o=00m=00e=00t=00h=00i=00n=00g=00 = =00h=00e=00r=00e=00<=00B=00R=00>=00&=00n=00b=00s=00p=00;=00&=00n=00b=00s=00= p=00;=00 =00i=00f=00 = =00s=00o=00m=00e=00C=00o=00n=00d=00i=00t=00i=00o=00n=00:=00 =00=0D=00=0A= =00b=00r=00e=00a=00k=00<=00/=00F=00O=00N=00T=00>=00<=00/=00D=00I=00V=00>=00= =0D=00=0A= =00<=00D=00I=00V=00>=00&=00n=00b=00s=00p=00;=00<=00/=00D=00I=00V=00>=00=0D= =00=0A= =00<=00D=00I=00V=00>=00<=00B=00R=00>=00<=00F=00O=00N=00T=00 = =00f=00a=00c=00e=00=3D=00A=00r=00i=00a=00l=00 = =00s=00i=00z=00e=00=3D=002=00>=00&=00g=00t=00;=00 =00T=00h=00e=00 = =00c=00o=00m=00m=00a=00n=00d=00 =00t=00o=00 =00s=00e=00n=00d=00 = =00t=00o=00 =00t=00h=00e=00 =00d=00e=00v=00i=00c=00e=00 =00i=00s=00 = =00=0D=00=0A= =00*=009=009=00c=00\=00r=00 =00<=00B=00R=00>=00&=00g=00t=00;=00 = =00W=00h=00a=00t=00 =00d=00o=00 =00i=00 =00n=00e=00e=00d=00 =00t=00o=00 = =00c=00h=00a=00n=00g=00e=00 =00i=00n=00 =00r=00e=00g=00a=00r=00d=00 = =00t=00o=00 =00j=00u=00s=00t=00 =00p=00o=00l=00l=00i=00n=00g=00 = =00t=00h=00e=00 =00=0D=00=0A= =00d=00e=00v=00i=00c=00e=00?=00<=00/=00F=00O=00N=00T=00>=00<=00/=00D=00I=00= V=00>=00=0D=00=0A= =00<=00D=00I=00V=00>=00&=00n=00b=00s=00p=00;=00<=00/=00D=00I=00V=00>=00=0D= =00=0A= =00<=00D=00I=00V=00>=00<=00F=00O=00N=00T=00 = =00f=00a=00c=00e=00=3D=00A=00r=00i=00a=00l=00 = =00s=00i=00z=00e=00=3D=002=00>=00A=00r=00e=00 =00y=00o=00u=00 = =00s=00e=00n=00d=00i=00n=00g=00 =00o=00r=00 = =00p=00o=00l=00l=00i=00n=00g=00(=00r=00e=00a=00d=00i=00n=00g=00)=00?=00<=00= B=00R=00>=00O=00r=00 =00b=00o=00t=00h=00?=00 =00D=00o=00 =00=0D=00=0A= =00y=00o=00u=00 =00s=00e=00n=00d=00 =00t=00o=00 =00g=00e=00t=00 =00a=00 = =00r=00e=00s=00u=00l=00t=00 =00b=00a=00c=00k=00?=00 = =00<=00/=00F=00O=00N=00T=00>=00<=00/=00D=00I=00V=00>=00=0D=00=0A= =00<=00D=00I=00V=00>=00&=00n=00b=00s=00p=00;=00<=00/=00D=00I=00V=00>=00=0D= =00=0A= =00<=00D=00I=00V=00>=00<=00F=00O=00N=00T=00 = =00f=00a=00c=00e=00=3D=00A=00r=00i=00a=00l=00 = =00s=00i=00z=00e=00=3D=002=00>=00I=00 =00d=00o=00n=00'=00t=00 = =00u=00n=00d=00e=00r=00s=00t=00a=00n=00d=00 =00s=00o=00r=00r=00y=00.=00 = =00<=00/=00F=00O=00N=00T=00>=00<=00/=00D=00I=00V=00>=00=0D=00=0A= =00<=00D=00I=00V=00>=00&=00n=00b=00s=00p=00;=00<=00/=00D=00I=00V=00>=00=0D= =00=0A= =00<=00D=00I=00V=00>=00<=00F=00O=00N=00T=00 = =00f=00a=00c=00e=00=3D=00A=00r=00i=00a=00l=00 = =00s=00i=00z=00e=00=3D=002=00>=00A=00l=00a=00n=00 = =00g=00<=00/=00F=00O=00N=00T=00>=00<=00/=00D=00I=00V=00>=00=0D=00=0A= =00<=00D=00I=00V=00>=00&=00n=00b=00s=00p=00;=00<=00/=00D=00I=00V=00>=00=0D= =00=0A= =00<=00D=00I=00V=00>=00<=00F=00O=00N=00T=00 = =00f=00a=00c=00e=00=3D=00A=00r=00i=00a=00l=00 = =00s=00i=00z=00e=00=3D=002=00>=00N=00o=00r=00m=00a=00l=00l=00y=00 = =00I=00 =00w=00o=00u=00l=00d=00 =00j=00u=00s=00t=00 =00p=00o=00l=00l=00 = =00t=00h=00e=00 =00s=00e=00n=00s=00o=00r=00 =00i=00 =00a=00m=00 = =00u=00s=00i=00n=00g=00 =00b=00y=00 =00=0D=00=0A= =00s=00e=00n=00d=00i=00n=00g=00 =00*=009=009=00p=00\=00r=00 =00t=00o=00 = =00t=00h=00e=00 =00s=00e=00n=00s=00o=00r=00.=00 = =00<=00/=00F=00O=00N=00T=00>=00<=00/=00D=00I=00V=00>=00=0D=00=0A= =00<=00D=00I=00V=00>=00<=00F=00O=00N=00T=00 = =00f=00a=00c=00e=00=3D=00A=00r=00i=00a=00l=00 = =00s=00i=00z=00e=00=3D=002=00>=00=0D=00=0A= =00<=00D=00I=00V=00>=00<=00F=00O=00N=00T=00 = =00f=00a=00c=00e=00=3D=00A=00r=00i=00a=00l=00 = =00s=00i=00z=00e=00=3D=002=00>=00&=00n=00b=00s=00p=00;=00&=00n=00b=00s=00= p=00;=00&=00n=00b=00s=00p=00;=00&=00n=00b=00s=00p=00;=00 = =00&=00n=00b=00s=00p=00;=00&=00n=00b=00s=00p=00;=00&=00n=00b=00s=00p=00;=00= =00=0D=00=0A= =00s=00e=00r=00.=00w=00r=00i=00t=00e=00(=00"=00*=009=009=00c=00\=00r=00"=00= )=00<=00/=00F=00O=00N=00T=00>=00<=00/=00D=00I=00V=00>=00<=00/=00F=00O=00N= =00T=00>=00<=00/=00D=00I=00V=00>=00=0D=00=0A= =00<=00D=00I=00V=00>=00<=00F=00O=00N=00T=00 = =00f=00a=00c=00e=00=3D=00A=00r=00i=00a=00l=00 = =00s=00i=00z=00e=00=3D=002=00>=00I=00n=00 = =00r=00e=00s=00p=00o=00n=00s=00e=00 =00t=00o=00 =00t=00h=00i=00s=00 = =00c=00o=00m=00m=00a=00n=00d=00 =00t=00h=00e=00 = =00s=00e=00n=00s=00o=00r=00 =00w=00o=00u=00l=00d=00 = =00o=00u=00t=00p=00u=00t=00 =00=0D=00=0A= =00a=00 =00s=00i=00n=00g=00l=00e=00 =00s=00a=00m=00p=00l=00e=00.=00 = =00<=00/=00F=00O=00N=00T=00>=00<=00/=00D=00I=00V=00>=00=0D=00=0A= =00<=00D=00I=00V=00>=00<=00F=00O=00N=00T=00 = =00f=00a=00c=00e=00=3D=00A=00r=00i=00a=00l=00 = =00s=00i=00z=00e=00=3D=002=00>=00=0D=00=0A= =00<=00D=00I=00V=00>=00<=00F=00O=00N=00T=00 = =00f=00a=00c=00e=00=3D=00A=00r=00i=00a=00l=00 = =00s=00i=00z=00e=00=3D=002=00>=00&=00n=00b=00s=00p=00;=00&=00n=00b=00s=00= p=00;=00&=00n=00b=00s=00p=00;=00 = =009=009=006=00&=00n=00b=00s=00p=00;=00&=00n=00b=00s=00p=00;=00 =00-=00 = =00=0D=00=0A= =003=00,=008=009=008=00&=00n=00b=00s=00p=00;=00&=00n=00b=00s=00p=00;=00 = =00-=00 = =007=00,=005=004=001=00<=00/=00F=00O=00N=00T=00>=00<=00/=00D=00I=00V=00>=00= <=00/=00F=00O=00N=00T=00>=00<=00/=00D=00I=00V=00>=00=0D=00=0A= =00<=00D=00I=00V=00>=00<=00F=00O=00N=00T=00 = =00f=00a=00c=00e=00=3D=00A=00r=00i=00a=00l=00 = =00s=00i=00z=00e=00=3D=002=00>=00<=00F=00O=00N=00T=00 = =00f=00a=00c=00e=00=3D=00A=00r=00i=00a=00l=00 = =00s=00i=00z=00e=00=3D=002=00>=00T=00h=00e=00s=00e=00 =00a=00r=00e=00 = =00t=00h=00e=00 =00x=00,=00 =00y=00 =00a=00n=00d=00 =00=0D=00=0A= =00z=00&=00n=00b=00s=00p=00;=00c=00o=00m=00p=00o=00n=00e=00n=00t=00s=00 = =00o=00f=00 =00t=00h=00e=00 =00s=00t=00r=00e=00n=00g=00t=00h=00 = =00a=00n=00d=00 =00d=00i=00r=00e=00c=00t=00i=00o=00n=00 =00o=00f=00 = =00a=00 =00m=00a=00g=00n=00e=00t=00i=00c=00 =00=0D=00=0A= =00f=00i=00e=00l=00d=00.=00<=00/=00F=00O=00N=00T=00>=00<=00/=00F=00O=00N=00= T=00>=00<=00/=00D=00I=00V=00>=00=0D=00=0A= =00<=00D=00I=00V=00>=00<=00F=00O=00N=00T=00 = =00f=00a=00c=00e=00=3D=00A=00r=00i=00a=00l=00 = =00s=00i=00z=00e=00=3D=002=00>=00I=00 =00w=00o=00u=00l=00d=00 = =00l=00i=00k=00e=00 =00t=00o=00 =00t=00a=00k=00e=00 =00i=00n=00 = =00c=00o=00n=00t=00i=00n=00u=00o=00u=00s=00 = =00r=00e=00a=00d=00i=00n=00g=00s=00 =00a=00t=00 =00t=00h=00e=00 =00=0D=00=0A= =00s=00a=00m=00p=00l=00e=00 =00r=00a=00t=00e=00 =00w=00h=00i=00c=00h=00 = =00i=00s=00 = =002=000=00s=00p=00s=00.=00<=00/=00F=00O=00N=00T=00>=00<=00/=00D=00I=00V=00= >=00=0D=00=0A= =00<=00D=00I=00V=00>=00<=00F=00O=00N=00T=00 = =00f=00a=00c=00e=00=3D=00A=00r=00i=00a=00l=00 = =00s=00i=00z=00e=00=3D=002=00>=00T=00o=00 =00d=00o=00 = =00t=00h=00i=00s=00,=00 =00s=00e=00n=00d=00 =00*=009=009=00c=00\=00r=00 = =00t=00o=00 =00t=00h=00e=00 =00s=00e=00r=00i=00a=00l=00 = =00p=00o=00r=00t=00.=00 =00=0D=00=0A= =00<=00/=00F=00O=00N=00T=00>=00<=00/=00D=00I=00V=00>=00=0D=00=0A= =00<=00D=00I=00V=00>=00<=00F=00O=00N=00T=00 = =00f=00a=00c=00e=00=3D=00A=00r=00i=00a=00l=00 = =00s=00i=00z=00e=00=3D=002=00>=00T=00h=00e=00 = =00o=00u=00t=00p=00u=00t=00 =00s=00h=00o=00u=00l=00d=00 = =00s=00e=00n=00d=00 =00c=00o=00n=00t=00i=00n=00u=00o=00u=00s=00 = =00r=00e=00a=00d=00i=00n=00g=00s=00 =00t=00o=00 =00t=00h=00e=00 =00=0D=00=0A= =00c=00o=00m=00p=00u=00t=00e=00r=00 =00t=00h=00r=00o=00u=00g=00h=00 = =00t=00h=00e=00 =00s=00e=00r=00i=00a=00l=00 =00p=00o=00r=00t=00.=00 = =00<=00/=00F=00O=00N=00T=00>=00<=00/=00D=00I=00V=00>=00=0D=00=0A= =00<=00D=00I=00V=00>=00&=00n=00b=00s=00p=00;=00<=00/=00D=00I=00V=00>=00=0D= =00=0A= =00<=00D=00I=00V=00>=00<=00F=00O=00N=00T=00 = =00f=00a=00c=00e=00=3D=00A=00r=00i=00a=00l=00 = =00s=00i=00z=00e=00=3D=002=00>=00N=00o=00t=00 =00s=00u=00r=00e=00 = =00t=00h=00a=00t=00 =00t=00h=00i=00s=00 =00c=00l=00e=00a=00r=00s=00 = =00t=00h=00i=00n=00g=00s=00 =00u=00p=00,=00 =00b=00u=00t=00 =00i=00t=00 = =00i=00s=00 =00a=00 =00=0D=00=0A= =00s=00t=00a=00r=00t=00<=00/=00F=00O=00N=00T=00>=00<=00/=00D=00I=00V=00>=00= =0D=00=0A= =00<=00D=00I=00V=00>=00<=00F=00O=00N=00T=00 = =00f=00a=00c=00e=00=3D=00A=00r=00i=00a=00l=00 = =00s=00i=00z=00e=00=3D=002=00>=00T=00h=00a=00n=00k=00s=00,=00<=00/=00F=00= O=00N=00T=00>=00<=00/=00D=00I=00V=00>=00=0D=00=0A= =00<=00D=00I=00V=00>=00<=00F=00O=00N=00T=00 = =00f=00a=00c=00e=00=3D=00A=00r=00i=00a=00l=00 = =00s=00i=00z=00e=00=3D=002=00>=00D=00e=00i=00r=00d=00r=00e=00 = =00<=00/=00F=00O=00N=00T=00>=00<=00/=00D=00I=00V=00>=00=0D=00=0A= =00<=00D=00I=00V=00>=00&=00n=00b=00s=00p=00;=00<=00/=00D=00I=00V=00>=00=0D= =00=0A= =00<=00D=00I=00V=00>=00<=00B=00R=00>=00&=00n=00b=00s=00p=00;=00<=00/=00D=00= I=00V=00>=00<=00/=00B=00O=00D=00Y=00>=00<=00/=00H=00T=00M=00L=00>=00=0D=00=0A= =00 ------=_NextPart_000_00C3_01C2CC59.C6C12EA0-- From Deirdre Hackett" ----- Original Message ----- From: Deirdre Hackett To: tutor@python.org Sent: Tuesday, February 04, 2003 2:29 PM Subject: Fw: [Tutor] Continuous input at sample rate ----- Original Message ----- From: Deirdre Hackett To: alan.gauld@bt.com ; tutor@python.org Sent: Tuesday, February 04, 2003 2:18 PM Subject: Re: [Tutor] Continuous input at sample rate > I want to take information into my program continuously at 20 > samples per second, > I didn't understand the rest but to loop 20 times a second - provided your machine is fast enough! - do this: while 1: sleep(0.05) # 1/20s delay # do something here if someCondition: break > The command to send to the device is *99c\r > What do i need to change in regard to just polling the device? Are you sending or polling(reading)? Or both? Do you send to get a result back? I don't understand sorry. Alan g Normally I would just poll the sensor i am using by sending *99p\r to the sensor. ser.write("*99c\r") In response to this command the sensor would output a single sample. 996 - 3,898 - 7,541 These are the x, y and z components of the strength and direction of a magnetic field. I would like to take in continuous readings at the sample rate which is 20sps. To do this, send *99c\r to the serial port. The output should send continuous readings to the computer through the serial port. Not sure that this clears things up, but it is a start Thanks, Deirdre From charlie@begeistert.org Tue Feb 4 10:33:02 2003 From: charlie@begeistert.org (Charlie Clark) Date: Tue Feb 4 10:33:02 2003 Subject: [Tutor] Finding out what causes the crash In-Reply-To: <5.1.0.14.0.20030204140541.00be7710@www.thinkware.se> References: <5.1.0.14.0.20030204140541.00be7710@www.thinkware.se> Message-ID: <20030204163248.2191.2@.1044371027.fake> On 2003-02-04 at 14:06:38 [+0100], Magnus Lycka wrote: > At 12:25 2003-02-04 +0100, Charlie Clark wrote: > >What is the best way to find out more about what's happening? > > A start is to either run in a debugger or insert print statements in > strategic places to find out where it happens. I've managed to locate the statement which causes the problems. I broke the insert into chunks of 100 and ran this using the debugger in IDLE and couldn't see anything suspicious. However, because the debugger stopped execution every 100 inserts I was able to go through more loops than just letting the program run through all of them. I'll try building in a few seconds pause and see how that works. Here is the offending code: print count,"Arztkammer %s, PT-Kammer %s, KV %s, KV-Nr %s, PT-Nr %s" %(id_arztkammer, id_pt_kammer, id_kv, kv_nr, pt_nr) mycursor.execute('INSERT into therapist (id_person, id_arztkammer, id_pt_kammer, id_kv, pt_nr, kv_nr)\ VALUES (%s, %s, %s, %s, %s, %s)', \ (id_person, id_arztkammer, id_pt_kammer, id_kv, pt_nr, kv_nr) ) I'm not the world's best DB-programmer but this looks okay to me and it doesn't cause syntax errors in Python or PostgreSQL. One of the offending lines is: Arztkammer None, PT-Kammer None, KV 20, KV-Nr 6121101, PT-Nr None which looks perfectly harmless to me. When running the script in a DOS window Abnormal Program Termination seems to be routine independent of the amount actually processed. The program has lots of inserts but this is the only that causes problems; if I comment it out I don't get any errors. I'm running psycopg 1.0.12 on windows and trying to get a more up to date binary. I'm also in contact with Federico di Georgio about psycopg anyway. From magnus@thinkware.se Tue Feb 4 10:37:03 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Tue Feb 4 10:37:03 2003 Subject: [Tutor] Python notations In-Reply-To: <3E3FBF66.8010106@wanadoo.fr> References: <5.1.0.14.0.20030203215342.02ab99a0@www.thinkware.se> Message-ID: <5.1.0.14.0.20030204155252.02ce1078@www.thinkware.se> At 09:25 2003-02-04 -0400, D2 wrote: >for example, when do i use object.method or method(parameters), or >object.method() or something.method().other_method().something (pan) >I didn't find something explicit to help me understand the way that works. All calls require (). If you access a method/function without (), you just get a reference to it back, you don't call it. The dot-notation a.b is used to get access to an object b which is part of an object a. The word object is used in a fairly wide meaning in Python, far beyond an instance of a class. Like this: >>> class C: ... def m(self): ... return "I'm a method in the class of %s" % self ... >>> o = C() >>> print o.m > >>> print o.m() I'm a method in the class of <__main__.C instance at 0x06E7E810> All object references can be assigned to variables. >>> ref_to_method_m_of_instance_o = o.m >>> print ref_to_method_m_of_instance_o > >>> print ref_to_method_m_of_instance_o() I'm a method in the class of <__main__.C instance at 0x06E7E810> Or: >>> import math >>> sinus = math.sin >>> angle = math.pi/4 >>> sinus(angle) 0.70710678118654746 >>> math.sin >>> math.sin(angle) 0.70710678118654746 math.sin returns a reference to the sin-function, which can be assigned to another variable, like sinus. math.sin(x) is a function call with the parameter x. Sometimes, a function call will return an object that can be called. (The example below is meaningless, but there are certainly useful applications for this...) >>> def returnsFunction(): ... def x(a, b): ... return a + b ... return x ... >>> x = returnsFunction() >>> print x(2,3) 5 Instead of using a reference to the returned function, and call it through that reference (x above), we can call it at once. >>> returnsFunction()(6,7) 13 If you see "x.y().z()" it means that you have an object x which contains an object y that can be called. If x is a module, y is a function or a class, and if x is an instance of a class, y is a method of its class. The call to x.y() will return an object z that can be called, for instance a function, a class or an instance with a __call__ method. E.g. if you have a module... # x.py - a module class y: def z(self): print "Hello" ..... And then you use it: >>> import x >>> x.y().z() Hello -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From Deirdre Hackett" Hi, Does anyone know where i can download a version of NumTut for windows. I have a pdf version of An Open Source project - Numerical Python. It says "mumtut is distributed along with the numeric source distribution in the demo subdirectory". What does this mean? I can only find it with a *.tgz file extension and don't have a clue what to do with that? Thanks, Deirdre. From magnus@thinkware.se Tue Feb 4 11:50:03 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Tue Feb 4 11:50:03 2003 Subject: [Tutor] NumTut for windows In-Reply-To: <011c01c2cc69$a3553d20$0400a8c0@egbert> Message-ID: <5.1.0.14.0.20030204174400.02b9bce0@www.thinkware.se> At 16:22 2003-02-04 +0000, Deirdre Hackett wrote: >I can only find it with a *.tgz file extension and don't have a clue what to >do with that? That might well be the file you are after. .tgz is short for .tar.gz, or in other words, a Gnu-Zipped Tape ARchive file. It's similar to a .zip archive, and very common in Unix. In Windows, most uncompress utilities like WinZip etc can open it. If you open it with directory structure preserved, or view it in the GUI of WinZip etc, you might be able to locate the file in the suggested location... -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From Adam Vardy Tue Feb 4 11:57:19 2003 From: Adam Vardy (Adam Vardy) Date: Tue Feb 4 11:57:19 2003 Subject: [Tutor] Out of range In-Reply-To: <3E3FC22E.1000806@aon.at> References: <143384318000.20030204092734@roadrunner.nf.net> <3E3FC22E.1000806@aon.at> Message-ID: <160398563834.20030204132500@roadrunner.nf.net> Tuesday, February 4, 2003, 10:07:50 AM, you wrote: >> >> >> You report us three Errors. The last one is clear (for me), >> as there is no name index in Python (unless you define it). There is actually. In a little loop in a function, it counts up. Trying to read a file. And it worked fine with a previous file. No errors. But there's some problem now. The bother is that, as shown, it wouldn't let me print the index. Nor any other variable used. Without a way for feedback, it's stopping me from making sense of how it can fail. -- Adam Vardy From magnus@thinkware.se Tue Feb 4 12:04:02 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Tue Feb 4 12:04:02 2003 Subject: [Tutor] Finding out what causes the crash In-Reply-To: <20030204163248.2191.2@.1044371027.fake> References: <5.1.0.14.0.20030204140541.00be7710@www.thinkware.se> <5.1.0.14.0.20030204140541.00be7710@www.thinkware.se> Message-ID: <5.1.0.14.0.20030204175129.02b93e38@www.thinkware.se> At 16:32 2003-02-04 +0100, Charlie Clark wrote: >print count,"Arztkammer %s, PT-Kammer %s, KV %s, KV-Nr %s, PT-Nr %s" >%(id_arztkammer, id_pt_kammer, id_kv, kv_nr, pt_nr) >mycursor.execute('INSERT into therapist (id_person, id_arztkammer, >id_pt_kammer, id_kv, pt_nr, kv_nr)\ > VALUES (%s, %s, %s, %s, %s, %s)', \ > (id_person, id_arztkammer, id_pt_kammer, id_kv, >pt_nr, kv_nr) ) > >I'm not the world's best DB-programmer but this looks okay to me and it >doesn't cause syntax errors in Python or PostgreSQL. Well, there are other errors besides Syntax Errors... Does this line get executed successfully with other data, or do they all fail? >One of the offending lines is: >Arztkammer None, PT-Kammer None, KV 20, KV-Nr 6121101, PT-Nr None Are types correct for all values? is there a problem with None/NULL? In what way are the bad different from the lines you managed to insert? Do I understand correctly that this just causes a windows applcation crash? No Python traceback etc? This suggests that the crash happens in code written in C or C++, in your database module. Maybe you should ask on a mailing list for your database driver, or on the db-sig mailing list? -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From magnus@thinkware.se Tue Feb 4 12:26:01 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Tue Feb 4 12:26:01 2003 Subject: [Tutor] Out of range In-Reply-To: <160398563834.20030204132500@roadrunner.nf.net> References: <3E3FC22E.1000806@aon.at> <143384318000.20030204092734@roadrunner.nf.net> <3E3FC22E.1000806@aon.at> Message-ID: <5.1.0.14.0.20030204182411.02b93f80@www.thinkware.se> At 13:25 2003-02-04 -03-30, Adam Vardy wrote: > >> You report us three Errors. The last one is clear (for me), > >> as there is no name index in Python (unless you define it). > >There is actually. In a little loop in a function, it counts up. >Trying to read a file. And it worked fine with a previous file. No >errors. But there's some problem now. Show your code. There is no way we can help you unless we can see what you are really doing. -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From charlie@begeistert.org Tue Feb 4 12:26:11 2003 From: charlie@begeistert.org (Charlie Clark) Date: Tue Feb 4 12:26:11 2003 Subject: [Tutor] Finding out what causes the crash In-Reply-To: <5.1.0.14.0.20030204175129.02b93e38@www.thinkware.se> References: <5.1.0.14.0.20030204140541.00be7710@www.thinkware.se> <5.1.0.14.0.20030204140541.00be7710@www.thinkware.se> <5.1.0.14.0.20030204175129.02b93e38@www.thinkware.se> Message-ID: <20030204182531.3643.2@.1044378361.fake> On 2003-02-04 at 18:00:00 [+0100], Magnus Lycka wrote: > Well, there are other errors besides Syntax Errors... > > Does this line get executed successfully with other data, or do they all > fail? It works inconsistently with the same data 8-( Problems are occur after about every 150 INSERTs Other parts of the script have been fine with up to 5000 INSERTs at once. > >One of the offending lines is: > >Arztkammer None, PT-Kammer None, KV 20, KV-Nr 6121101, PT-Nr None > > Are types correct for all values? is there a problem with None/NULL? In > what way are the bad different from the lines you managed to insert? Not at all really. I'll try and pass some empty strings in to see what difference that makes. > Do I understand correctly that this just causes a windows applcation > crash? No Python traceback etc? This suggests that the crash happens in > code written in C or C++, in your database module. It causes python.exe or pythonw.exe depending which is running. I do not get a traceback so I don't know if running python -d makes much difference. I do suspect the driver (psycopg) and am in touch with the author Ferderico di Gregorgio about it. > Maybe you should ask on a mailing list for your database driver, or on > the db-sig mailing list? will do, thanx Charlie From Adam Vardy Tue Feb 4 12:50:07 2003 From: Adam Vardy (Adam Vardy) Date: Tue Feb 4 12:50:07 2003 Subject: [Tutor] Sorting numbers Message-ID: <34401853264.20030204141949@roadrunner.nf.net> If I'd like to sort a simple kinda list like: 45K 100K 3.4Meg 17K 300K 9.3Meg How do you suppose I can approach it? -- Adam Vardy From borelan@wanadoo.fr Tue Feb 4 13:26:32 2003 From: borelan@wanadoo.fr (D2) Date: Tue Feb 4 13:26:32 2003 Subject: [Tutor] Python notations References: <5.1.0.14.0.20030203215342.02ab99a0@www.thinkware.se> <5.1.0.14.0.20030204155252.02ce1078@www.thinkware.se> Message-ID: <3E400483.6070301@wanadoo.fr> Many thanks, Magnus, That's a thorough explanation. It will be easier to read Zope's code. Andre Magnus Lycka a =E9crit: > At 09:25 2003-02-04 -0400, D2 wrote: >=20 >> for example, when do i use object.method or method(parameters), or >> object.method() or something.method().other_method().something (pan) >> I didn't find something explicit to help me understand the way that=20 >> works. >=20 >=20 > All calls require (). If you access a method/function without (), > you just get a reference to it back, you don't call it. >=20 > The dot-notation a.b is used to get access to an object b which > is part of an object a. The word object is used in a fairly > wide meaning in Python, far beyond an instance of a class. >=20 > Like this: >=20 > >>> class C: > ... def m(self): > ... return "I'm a method in the class of %s" % self > ... > >>> o =3D C() > >>> print o.m > > > >>> print o.m() > I'm a method in the class of <__main__.C instance at 0x06E7E810> >=20 > All object references can be assigned to variables. >=20 > >>> ref_to_method_m_of_instance_o =3D o.m > >>> print ref_to_method_m_of_instance_o > > > >>> print ref_to_method_m_of_instance_o() > I'm a method in the class of <__main__.C instance at 0x06E7E810> >=20 > Or: >=20 > >>> import math > >>> sinus =3D math.sin > >>> angle =3D math.pi/4 > >>> sinus(angle) > 0.70710678118654746 > >>> math.sin > > >>> math.sin(angle) > 0.70710678118654746 >=20 > math.sin returns a reference to the sin-function, which can > be assigned to another variable, like sinus. math.sin(x) is > a function call with the parameter x. >=20 > Sometimes, a function call will return an object that can be > called. (The example below is meaningless, but there are > certainly useful applications for this...) >=20 > >>> def returnsFunction(): > ... def x(a, b): > ... return a + b > ... return x > ... > >>> x =3D returnsFunction() > >>> print x(2,3) > 5 >=20 > Instead of using a reference to the returned function, and > call it through that reference (x above), we can call it > at once. >=20 > >>> returnsFunction()(6,7) > 13 >=20 > If you see "x.y().z()" it means that you have an object x > which contains an object y that can be called. If x is a > module, y is a function or a class, and if x is an instance of > a class, y is a method of its class. The call to x.y() will > return an object z that can be called, for instance a function, > a class or an instance with a __call__ method. >=20 > E.g. if you have a module... >=20 > # x.py - a module >=20 > class y: > def z(self): > print "Hello" >=20 > ..... >=20 > And then you use it: >=20 > >>> import x > >>> x.y().z() > Hello >=20 >=20 --=20 Andre From Adam Vardy Tue Feb 4 13:30:11 2003 From: Adam Vardy (Adam Vardy) Date: Tue Feb 4 13:30:11 2003 Subject: [Tutor] NumTut for windows In-Reply-To: <011c01c2cc69$a3553d20$0400a8c0@egbert> References: <011c01c2cc69$a3553d20$0400a8c0@egbert> Message-ID: <81404199868.20030204145856@roadrunner.nf.net> Tuesday, February 4, 2003, 12:52:04 PM, you wrote: >> Hi, >> Does anyone know where i can download a version of NumTut for windows. I >> have a pdf version of An Open Source project - Numerical Python. >> It says "mumtut is distributed along with the numeric source distribution in >> the demo subdirectory". What does this mean? >> I can only find it with a *.tgz file extension and don't have a clue what to >> do with that? I searched out Numeric Python. I could find it. And actually there were no .tgz files there. These SourceForge pages all seem to come with a specific pattern. Like near the top they say perhaps "Summary, Admin ... CVS, Files". Now in a lot of these cases, I would look at the page, and never see sign of where the downloads are for the project. I think though, you need to click on Files. Most sites have a Downloads link, probably on the left frame. My eyes easily miss a Files link. And I mean, if I even thought it was right, it would say to myself "Files to what? Example files to show you what it looks like? Just a few misc. files to illustrate what our project does? Files needed from third parties before you should download the actual project?" Doesn't seem like a sensible arrangement to make it easy for people to identify the aims, and how to try out a project, just IMO. Some of those projects have a very narrow audience I think. While others have a very broad audience. In my opinion, it is not very efficiently distinguished to your average webpage browser which is the case, the way they typically lay out their links. If you click on *Summary*, all you get is: --- Numerical Python adds a fast array facility to the Python language. --- Rather unimpressive way to get a serious appreciation for a project. I think a .tgz file is basically a warning: don't download me on your windows computer. You won't know which file to run; it will probably crash your computer; and there's probably no documentation. So it's more than likely a waste of CPU cycles to download. -- Adam Vardy From alan.gauld@bt.com Tue Feb 4 13:43:01 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Tue Feb 4 13:43:01 2003 Subject: [Tutor] Re: Reply to list... [think of the digested users] Message-ID: <7497DCA1C240C042B28F6657ADFD8E097023C0@i2km11-ukbr.domain1.systemhost.net> > replies. I guess I'm stating the obvious. *grin* But this feature is > very important for people who are running in "digest mode". Digested > users who don't follow every single message on Tutor still can ask and > receive direct answers. I agree, this is useful for me. I can chase a live thread for which I've replied(or even raised!) without waiting for the ( ~twice daily) digest. Alan G From alan.gauld@bt.com Tue Feb 4 13:57:01 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Tue Feb 4 13:57:01 2003 Subject: [Tutor] Python notations Message-ID: <7497DCA1C240C042B28F6657ADFD8E097023C1@i2km11-ukbr.domain1.systemhost.net> > for example, when do i use object.method or method(parameters), or > object.method() or something.method().other_method().something (pan) > I didn't find something explicit to help me understand the > way that works. I don't remember if you said you could program in other langages but from the above I suspect not. In that case visit the Newbies page on the www.python.org website for a list of more suitable tutors. Or just visit mine below.... Work through it systematically and raise specific questions here if you find things you don't understand. (If you use mine you can send mail direct to me too, but there are many more helpers on this list!) Alan g. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld/ From Adam Vardy Tue Feb 4 14:42:02 2003 From: Adam Vardy (Adam Vardy) Date: Tue Feb 4 14:42:02 2003 Subject: [Tutor] Out of range In-Reply-To: <7497DCA1C240C042B28F6657ADFD8E097023C2@i2km11-ukbr.domain1.systemhost.net> References: <7497DCA1C240C042B28F6657ADFD8E097023C2@i2km11-ukbr.domain1.systemhost.net> Message-ID: <56408570823.20030204161147@roadrunner.nf.net> Tuesday, February 4, 2003, 3:30:31 PM, you wrote: >> If its defined in a function then you can't see it outside of >> that function. You need to use a debugger to stop execution inside >> the function and print it in the debugger(IDLE's debugger or >> pdb will both do that happily) Is there a command I can add in my program that will do this? I presume that hoping a debugger to stop in the right place by chance is not quite effective. Oh and, what happens if the function runs a second time? Are the variables like they were before? From jeff@ccvcorp.com Tue Feb 4 14:58:02 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Tue Feb 4 14:58:02 2003 Subject: [Tutor] Sorting numbers References: <34401853264.20030204141949@roadrunner.nf.net> Message-ID: <3E401B0D.6010606@ccvcorp.com> Adam Vardy wrote: >If I'd like to sort a simple kinda list like: > >45K >100K >3.4Meg >17K >300K >9.3Meg > >How do you suppose I can approach it? > Are your suffixes (K, Meg, etc) standardized? If so, you can use that to separate your list into sublists, sort each sublist, and then present the sublists in appropriate order. When sorting sublists, you'll have to be careful, though -- you're dealing with strings, and you want them sorted in numeric order instead of alphabetical order. (In alphabetical order, '35' comes after '300'.) I'd split each string into a numeric part and a suffix. Use the suffix as a dictionary key, and add the numeric part to a list pointed to by that key. Then, when you sort each list, convert each numeric string to a float for sorting comparisons -- but *only* use the float for sorting, and then display the original string value. Let's start by writing a function that'll split the suffix from the numeric part: >>> def splitsuffix(item): ... for suffix in ['K', 'Meg', 'Gig']: ... if item.endswith(suffix): ... trim = -( len(suffix) ) ... numpart = item[:trim] ... return (numpart, suffix) ... # If no suffix matches, we have a plain number ... return (item, '') ... >>> Now, we'll take our raw data, and process that into a dictionary using our splitsuffix() function: >>> rawdata ['45K', '100K', '3.4Meg', '17K', '300K', '9.3Meg', '512', '23Meg'] >>> srt = {} >>> for item in rawdata: ... num, suffix = splitsuffix(item) ... value = srt.get(suffix, []) ... value.append(num) ... srt[suffix] = value ... >>> srt {'': ['512'], 'K': ['45', '100', '17', '300'], 'Meg': ['3.4', '9.3', '23']} >>> Now, we're going to need to sort our strings by numeric order, so let's define a quick sortfunction that'll do that: >>> def sortfunc(a, b): ... return cmp( float(a), float(b) ) ... >>> Now we're set to grab each sublist, sort it, and then display it. >>> for key in ['', 'K', 'Meg', 'Gig']: ... values = srt.get(key, []) ... values.sort(sortfunc) ... for item in values: ... print '%5s%s' % (item, key) ... 512 17K 45K 100K 300K 3.4Meg 9.3Meg 23Meg >>> That looks like the order we want! An alternative approach would be to write a function that converts, say, '17K' to the integer value 17000, and '3.4Meg' to 3,400,000. Then you could sort your raw data based on the results of that function. A good way to convert these values would be to make a dictionary that links a given suffix to a multiplier. Then you can separate the numeric part from the suffix (we already know how to do that), use the suffix to get the multiplier, do the math and return the result. And once we have a function to expand these numbers, we can simply write a comparison function that uses the expanded numbers for sorting. >>> rawdata ['45K', '100K', '3.4Meg', '17K', '300K', '9.3Meg', '512', '23Meg'] >>> suff = { '':1, 'K':1000, 'Meg':1000000, 'Gig':1000000000 } >>> def expand(item, suffixes = suff): ... numpart, suffixpart = splitsuffix(item) ... multiplier = suffixes[suffixpart] ... return float(numpart) * multiplier ... >>> def sortfunc(a, b): ... return cmp(expand(a), expand(b)) ... >>> rawdata.sort(sortfunc) >>> rawdata ['512', '17K', '45K', '100K', '300K', '3.4Meg', '9.3Meg', '23Meg'] >>> Here I've sorted the data in-place. If you need to leave the original data alone for whatever reason, you can simply make a copy of the list ( sortedlist = rawdata[:] ) and then sort the new list. Jeff Shannon Technician/Programmer Credit International From alan.gauld@bt.com Tue Feb 4 15:19:22 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Tue Feb 4 15:19:22 2003 Subject: [Tutor] Out of range Message-ID: <7497DCA1C240C042B28F6657ADFD8E097023C2@i2km11-ukbr.domain1.systemhost.net> > >> as there is no name index in Python (unless you define it). > > There is actually. In a little loop in a function, .... > > The bother is that, as shown, it wouldn't let me print the index. If its defined in a function then you can't see it outside of that function. You need to use a debugger to stop execution inside the function and print it in the debugger(IDLE's debugger or pdb will both do that happily) Alternatively just put a temporary print statement in. If its a long loop then maybe only print occasionally: if not index % 5: print index # print every 5th time Alan G. From hall@ouhep5.nhn.ou.edu Tue Feb 4 15:21:17 2003 From: hall@ouhep5.nhn.ou.edu (Isaac Hall) Date: Tue Feb 4 15:21:17 2003 Subject: [Tutor] Sorting numbers In-Reply-To: <3E401B0D.6010606@ccvcorp.com> Message-ID: On Tue, 4 Feb 2003, Jeff Shannon wrote: > > Adam Vardy wrote: > > >If I'd like to sort a simple kinda list like: > > > >45K > >100K > >3.4Meg > >17K > >300K > >9.3Meg > > > >How do you suppose I can approach it? > > > > Are your suffixes (K, Meg, etc) standardized? If so, you can use that > to separate your list into sublists, sort each sublist, and then present > the sublists in appropriate order. When sorting sublists, you'll have > to be careful, though -- you're dealing with strings, and you want them > sorted in numeric order instead of alphabetical order. (In alphabetical > order, '35' comes after '300'.) > > I'd split each string into a numeric part and a suffix. Use the suffix > as a dictionary key, and add the numeric part to a list pointed to by > that key. Then, when you sort each list, convert each numeric string to > a float for sorting comparisons -- but *only* use the float for sorting, > and then display the original string value. > This is a good method, however this would fail if we want to place a numbers like [2000K, 1.5Meg]. Since in reality, 2000K=2Meg (or if we are talking computer speak, 2048K=2Meg), but anyway, this method would place 2000K before 1.5Meg, which we know is false. > An alternative approach would be to write a function that converts, say, > '17K' to the integer value 17000, and '3.4Meg' to 3,400,000. Then you > could sort your raw data based on the results of that function. > > A good way to convert these values would be to make a dictionary that > links a given suffix to a multiplier. Then you can separate the numeric > part from the suffix (we already know how to do that), use the suffix to > get the multiplier, do the math and return the result. And once we have > a function to expand these numbers, we can simply write a comparison > function that uses the expanded numbers for sorting. > > >>> rawdata > ['45K', '100K', '3.4Meg', '17K', '300K', '9.3Meg', '512', '23Meg'] > >>> suff = { '':1, 'K':1000, 'Meg':1000000, 'Gig':1000000000 } > >>> def expand(item, suffixes = suff): > ... numpart, suffixpart = splitsuffix(item) > ... multiplier = suffixes[suffixpart] > ... return float(numpart) * multiplier > ... > >>> def sortfunc(a, b): > ... return cmp(expand(a), expand(b)) > ... > >>> rawdata.sort(sortfunc) > >>> rawdata > ['512', '17K', '45K', '100K', '300K', '3.4Meg', '9.3Meg', '23Meg'] > >>> > I like this method much better. We avoid stepping into pitfalls if we get wierd numbers to sort (like say 2000K or 0.5 Meg) or things like that...) and if you are using computerspeak, then we just assign a value of 1024 for each subsequent suffix (ie. 1.2Meg = 1.2*1024*1024) Ike > Here I've sorted the data in-place. If you need to leave the original > data alone for whatever reason, you can simply make a copy of the list ( > sortedlist = rawdata[:] ) and then sort the new list. > > Jeff Shannon > Technician/Programmer > Credit International > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- From magnus@thinkware.se Tue Feb 4 15:55:04 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Tue Feb 4 15:55:04 2003 Subject: [Tutor] Out of range In-Reply-To: <56408570823.20030204161147@roadrunner.nf.net> References: <7497DCA1C240C042B28F6657ADFD8E097023C2@i2km11-ukbr.domain1.systemhost.net> <7497DCA1C240C042B28F6657ADFD8E097023C2@i2km11-ukbr.domain1.systemhost.net> Message-ID: <5.1.0.14.0.20030204214750.02cc1c40@www.thinkware.se> At 16:11 2003-02-04 -03-30, Adam Vardy wrote: > >> If its defined in a function then you can't see it outside of > >> that function. You need to use a debugger to stop execution inside > >> the function and print it in the debugger(IDLE's debugger or > >> pdb will both do that happily) > >Is there a command I can add in my program that will do this? I >presume that hoping a debugger to stop in the right place by chance is >not quite effective. No, you would set a breakpoint explicitly to the line where you want it to stop. >Oh and, what happens if the function runs a second time? Are the >variables like they were before? What once was will be sadly forgotten, and it's all for the best. This is the way we expect local variables in functions to behave. If you want the values to persist, you either use global variables, as in: x = 0 def increase_x(i): global x x = x + i or, we use a class, and store our value as an attribute, but that's a little more advanced. -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From Adam Vardy Tue Feb 4 16:26:40 2003 From: Adam Vardy (Adam Vardy) Date: Tue Feb 4 16:26:40 2003 Subject: [Tutor] Out of range In-Reply-To: <5.1.0.14.0.20030204182411.02b93f80@www.thinkware.se> References: <3E3FC22E.1000806@aon.at> <143384318000.20030204092734@roadrunner.nf.net> <3E3FC22E.1000806@aon.at> <5.1.0.14.0.20030204182411.02b93f80@www.thinkware.se> Message-ID: <139414804377.20030204175540@roadrunner.nf.net> Tuesday, February 4, 2003, 1:54:46 PM, you wrote: >> >>There is actually. In a little loop in a function, it counts up. >>Trying to read a file. And it worked fine with a previous file. No >>errors. But there's some problem now. >> Show your code. There is no way we can help you unless >> we can see what you are really doing. Here is the described function. The 1st IF statement was added to try to repair things after the last message. I had to add a variable, index, because my FOR statement does not keep track of the numeric ordinal index of the FOR loop. If it counted 7 times, then it would be counting 1,2,3,4,5,6,7. Which I think it must do internally anyway, so realistically, we shouldn't be having to add an extra variable. And make the function longer, and something to complain about. This function tries to adapt the prefix somewhere so the whole thing will sort properly. --------------------------------------------- def fixit(text): index=0 if text[0].isdigit()==0: return text for i in text: if i.isalpha()==1: break index=index+1 out=text[index] num=text[:index] rest=text[index:] ## print"out:"+out ## print"num:"+num ## print"rest:"+rest ## return out+num+rest ----------------------------------------------- And the error I get at the moment, after adding the first IF statement. Happens right away: if text[0].isdigit()==0: IndexError: string index out of range -- Adam Vardy From magnus@thinkware.se Tue Feb 4 16:39:03 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Tue Feb 4 16:39:03 2003 Subject: [Tutor] Out of range In-Reply-To: <139414804377.20030204175540@roadrunner.nf.net> References: <5.1.0.14.0.20030204182411.02b93f80@www.thinkware.se> <3E3FC22E.1000806@aon.at> <143384318000.20030204092734@roadrunner.nf.net> <3E3FC22E.1000806@aon.at> <5.1.0.14.0.20030204182411.02b93f80@www.thinkware.se> Message-ID: <5.1.0.14.0.20030204223116.02bc0958@www.thinkware.se> At 17:55 2003-02-04 -03-30, Adam Vardy wrote: >And the error I get at the moment, after adding the first IF >statement. Happens right away: > > if text[0].isdigit()==0: >IndexError: string index out of range You are trying to access a part of the string that doesn't exist. In this case the first character. It will work if you don't call it with an empty string. If you are certain that your function is always called with a string, you can do this: if (not text) or (not text[0].isdigit()): #handle empty string or non-numeric return text ... -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From Adam Vardy Tue Feb 4 17:10:02 2003 From: Adam Vardy (Adam Vardy) Date: Tue Feb 4 17:10:02 2003 Subject: [Tutor] Out of range In-Reply-To: <5.1.0.14.0.20030204223116.02bc0958@www.thinkware.se> References: <5.1.0.14.0.20030204182411.02b93f80@www.thinkware.se> <3E3FC22E.1000806@aon.at> <143384318000.20030204092734@roadrunner.nf.net> <3E3FC22E.1000806@aon.at> <5.1.0.14.0.20030204182411.02b93f80@www.thinkware.se> <5.1.0.14.0.20030204223116.02bc0958@www.thinkware.se> Message-ID: <130417417754.20030204183914@roadrunner.nf.net> Sorting is now going like this. We have for instance, 1Meg, 1.2Meg etc., and 10 Meg, 11 Meg, and then 2Meg, 3Meg ... -- Adam Vardy From jeff@ccvcorp.com Tue Feb 4 17:51:34 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Tue Feb 4 17:51:34 2003 Subject: [Tutor] Out of range References: <3E3FC22E.1000806@aon.at> <143384318000.20030204092734@roadrunner.nf.net> <3E3FC22E.1000806@aon.at> <5.1.0.14.0.20030204182411.02b93f80@www.thinkware.se> <139414804377.20030204175540@roadrunner.nf.net> Message-ID: <3E4043AB.5040000@ccvcorp.com> Adam Vardy wrote: >This function tries to adapt the prefix somewhere so the whole thing >will sort properly. > > As Magnus already pointed out, the only way to get an IndexError here is if you pass in an empty string. I'd also guess, though, that the results of this function are not quite what you're expecting. (By the way, it's not necessary to comapre your isdigit() and isalpha() results explicitly with 1 and 0, nor is it considered good style...) >>> def fixit(text): ... index = 0 ... if not text[0].isdigit(): ... return text ... for i in text: ... if i.isalpha(): ... break ... index = index + 1 ... out = text[index] ... num = text[:index] ... rest = text[index:] ... return out + num + rest ... >>> fixit('testing') 'testing' >>> fixit('1-2-testing') 't1-2-testing' >>> fixit('1234abcd') 'a1234abcd' >>> Note that 'text[index]' will be the first non-digit character, 'text[:index]' will be the initial run of digits, and 'text[index:]' will be everything after the initial run of digits. Adding these together gives you your initial string, prepended by the first non-digit character. If we don't add them together, and instead return a tuple: >>> def fixit(text): ... index = 0 ... if text[0].isdigit() == 0: ... return text ... for i in text: ... if i.isalpha() == 1: ... break ... index = index + 1 ... out = text[index] ... num = text[:index] ... rest = text[index:] ... return out, num, rest ... >>> Note that the only line I've changed is the return statement. Our results are much different now: >>> fixit('1234abcd') ('a', '1234', 'abcd') >>> fixit('1.5Meg') ('M', '1.5', 'Meg') >>> fixit('1-2-testing') ('t', '1-2-', 'testing') >>> fixit('123abc456') ('a', '123', 'abc456') >>> So the part we're returning as 'num' is now the initial numeric part, and 'rest' is indeed the rest of it. Since I presume you're wanting to use this to sort items in numeric order, you then need to convert the string of digits into an actual number, so that they're compared in numeric order instead of lexicographic order. For ideas on what to do with 'num' and 'rest' now that you've got them separated, see my previous reply on 'Sorting Numbers'. Jeff Shannon Technician/Programmer Credit International From magnus@thinkware.se Tue Feb 4 18:06:32 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Tue Feb 4 18:06:32 2003 Subject: [Tutor] Out of range In-Reply-To: <130417417754.20030204183914@roadrunner.nf.net> References: <5.1.0.14.0.20030204223116.02bc0958@www.thinkware.se> <5.1.0.14.0.20030204182411.02b93f80@www.thinkware.se> <3E3FC22E.1000806@aon.at> <143384318000.20030204092734@roadrunner.nf.net> <3E3FC22E.1000806@aon.at> <5.1.0.14.0.20030204182411.02b93f80@www.thinkware.se> <5.1.0.14.0.20030204223116.02bc0958@www.thinkware.se> Message-ID: <5.1.0.14.0.20030205000323.02ccba38@www.thinkware.se> At 18:39 2003-02-04 -03-30, Adam Vardy wrote: >Sorting is now going like this. We have for instance, 1Meg, 1.2Meg >etc., and 10 Meg, 11 Meg, and then 2Meg, 3Meg ... You are sorting strings, i.e. text. For numerical sorting you must sort values of a numeric type. Se my conversion functions posted previously. '5' is more than '10', but 10 is more than 5. Right? -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From churmtom@hotmail.com Wed Feb 5 04:59:02 2003 From: churmtom@hotmail.com (Tom Churm) Date: Wed Feb 5 04:59:02 2003 Subject: [Tutor] FTP: Binary vs. Text Mode Message-ID: i'm writing an ftp upload app in python but am ignorant of the consequences of uploading all files in binary mode. what's the worst that can happen when a text file is uploaded in binary mode? thanks, tom _________________________________________________________________ Add photos to your messages with MSN 8. Get 2 months FREE*. http://join.msn.com/?page=features/featuredemail From magnus@thinkware.se Wed Feb 5 05:14:02 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Wed Feb 5 05:14:02 2003 Subject: [Tutor] FTP: Binary vs. Text Mode In-Reply-To: Message-ID: <5.1.0.14.0.20030205110707.02b5cf50@www.thinkware.se> At 10:58 2003-02-05 +0100, Tom Churm wrote: >what's the worst that can happen when a text file is uploaded in binary mode? This has nothing to do with Python really, but the issue is that different operating systems have different standards for line endings. DOS and derivates use a carriage return (ASCII value 13) followed by a line feed (ASCII value 10). Unix uses only line feed, and Mac uses only carriage return. Text mode FTP transfer translates this. Binary mode don't. So, the consequences depend on what combinations of operating systems you use on servers and clients. If you consistently use binary mode for both download and upload, and only use one OS family on the clients, you won't notice a thing. -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From charlie@begeistert.org Wed Feb 5 05:30:03 2003 From: charlie@begeistert.org (Charlie Clark) Date: Wed Feb 5 05:30:03 2003 Subject: [Tutor] Re: What's causing the crash In-Reply-To: <20030204205504.6787.27641.Mailman@mail.python.org> References: <20030204205504.6787.27641.Mailman@mail.python.org> Message-ID: <20030205112948.710.5@.1044439675.fake> On 2003-02-04 at 21:55:04 [+0100], tutor-request@python.org wrote: > > > Do I understand correctly that this just causes a windows applcation > > crash? No Python traceback etc? This suggests that the crash happens in > > code written in C or C++, in your database module. So after more testing I found a workaround: it did have something to do with the number None's being inserted. This was confirmed by the driver's writer: "ah-ah! that is. you it a memory leak that was solved in 1.0.14.2, the None object was DECREFfed too many times, resulting in segfault soon or later. this only happens when a None e object is traslated into NULL using a %s, that's why your fix solved the problem." My next problem is being restricted to windows for development on this and not having MSVC to do the compile. oh well, lucky it was only for test data. Thanx again Magnus Charlie From Adam Vardy Wed Feb 5 06:37:01 2003 From: Adam Vardy (Adam Vardy) Date: Wed Feb 5 06:37:01 2003 Subject: [Tutor] Sorting numbers In-Reply-To: <3E401B0D.6010606@ccvcorp.com> References: <34401853264.20030204141949@roadrunner.nf.net> <3E401B0D.6010606@ccvcorp.com> Message-ID: <189465828375.20030205080604@roadrunner.nf.net> Tuesday, February 4, 2003, 4:27:01 PM, you wrote: >> Now, we'll take our raw data, and process that into a dictionary using >> our splitsuffix() function: >> >>> rawdata >> ['45K', '100K', '3.4Meg', '17K', '300K', '9.3Meg', '512', '23Meg'] >> >>> srt = {} >> >>> for item in rawdata: >> ... num, suffix = splitsuffix(item) >> ... value = srt.get(suffix, []) >> ... value.append(num) >> ... srt[suffix] = value Can you explain the last three lines here? -- Adam Vardy From Adam Vardy Wed Feb 5 06:39:11 2003 From: Adam Vardy (Adam Vardy) Date: Wed Feb 5 06:39:11 2003 Subject: [Tutor] NumTut for windows In-Reply-To: <81404199868.20030204145856@roadrunner.nf.net> References: <011c01c2cc69$a3553d20$0400a8c0@egbert> <81404199868.20030204145856@roadrunner.nf.net> Message-ID: <153465993573.20030205080849@roadrunner.nf.net> Tuesday, February 4, 2003, 2:58:56 PM, you wrote: >> click on Files. Most sites have a Downloads link, probably on the left >> frame. My eyes easily miss a Files link. And I mean, if I even thought >> it was right, it would say to myself 'I would say'. ^^ Typo. excuse me. -- Adam Vardy From Adam Vardy Wed Feb 5 08:20:04 2003 From: Adam Vardy (Adam Vardy) Date: Wed Feb 5 08:20:04 2003 Subject: [Tutor] Out of range In-Reply-To: <5.1.0.14.0.20030205000323.02ccba38@www.thinkware.se> References: <5.1.0.14.0.20030204223116.02bc0958@www.thinkware.se> <5.1.0.14.0.20030204182411.02b93f80@www.thinkware.se> <3E3FC22E.1000806@aon.at> <143384318000.20030204092734@roadrunner.nf.net> <3E3FC22E.1000806@aon.at> <5.1.0.14.0.20030204182411.02b93f80@www.thinkware.se> <5.1.0.14.0.20030204223116.02bc0958@www.thinkware.se> <5.1.0.14.0.20030205000323.02ccba38@www.thinkware.se> Message-ID: <102469935.20030205094953@roadrunner.nf.net> Tuesday, February 4, 2003, 7:35:03 PM, you wrote: >> At 18:39 2003-02-04 -03-30, Adam Vardy wrote: >>Sorting is now going like this. We have for instance, 1Meg, 1.2Meg >>etc., and 10 Meg, 11 Meg, and then 2Meg, 3Meg ... >> You are sorting strings, i.e. text. For numerical sorting >> you must sort values of a numeric type. Se my conversion >> functions posted previously. Which conversions were they? If I sort just some plain numbers, I am still left with some unsorted lines of text. -- Adam Vardy From magnus@thinkware.se Wed Feb 5 09:10:02 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Wed Feb 5 09:10:02 2003 Subject: [Tutor] Out of range In-Reply-To: <102469935.20030205094953@roadrunner.nf.net> References: <5.1.0.14.0.20030205000323.02ccba38@www.thinkware.se> <5.1.0.14.0.20030204223116.02bc0958@www.thinkware.se> <5.1.0.14.0.20030204182411.02b93f80@www.thinkware.se> <3E3FC22E.1000806@aon.at> <143384318000.20030204092734@roadrunner.nf.net> <3E3FC22E.1000806@aon.at> <5.1.0.14.0.20030204182411.02b93f80@www.thinkware.se> <5.1.0.14.0.20030204223116.02bc0958@www.thinkware.se> <5.1.0.14.0.20030205000323.02ccba38@www.thinkware.se> Message-ID: <5.1.0.14.0.20030205145223.029b9880@www.thinkware.se> At 09:49 2003-02-05 -03-30, Adam Vardy wrote: >Which conversions were they? Two functions called sci2float and float2sci. >If I sort just some plain numbers, I am >still left with some unsorted lines of text. >>> i = 5 >>> type(i) >>> s = '5' >>> type(s) Just because a string only contains digits doesn't mean that it becomes a number in Python. Some languages behave in that way, and it can cause a lot of problems. In python you must explicitly tell the computer to extract a number from a string if you want that. >>> s = '5' >>> i = int(s) >>> print i, type(i) 5 >>> f = float(s) >>> print f, type(f) 5.0 In a few selected cases, Python will actually perform an implicit type conversion. For instance, you don't have to do a = 5 b = 6.3 print float(a) + b Python will automatically coerce a float and an integer on addition, so you can just type a = 5 b = 6.3 print a + b and get the float 11.3 as result, but you can never do print 5 + '6.3' Python will refuse to convert strings to numbers implicitly. In some languages, OCaml for instance, you must explicitly convert an integer to a float if you want to add it to another float. This is partly a tradeoff between convenience and performance. It's also an issue of avoiding bugs. I think Python strikes the right balance. -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From lbrannma@cablespeed.com Wed Feb 5 10:17:07 2003 From: lbrannma@cablespeed.com (Lance) Date: Wed Feb 5 10:17:07 2003 Subject: [Tutor] list concatenation Message-ID: <000f01c2cd2c$79fd1740$f228eb42@MYNEWBOX> Hi All, What's the fastest way to concatenate the same string to all elements of a list? I have a list of filenames and want to concatentate the path, a common path, to each of them. Thanks, Lance From jrbeckstrom@sbcglobal.net Wed Feb 5 11:03:03 2003 From: jrbeckstrom@sbcglobal.net (Jim Beckstrom) Date: Wed Feb 5 11:03:03 2003 Subject: [Tutor] Apply() Message-ID: <3E4135BD.2020209@sbcglobal.net> An explanation of the use of apply(), please. Thanks, Jim From Deirdre Hackett" This is a multi-part message in MIME format. ------=_NextPart_000_0060_01C2CD37.8AE42CA0 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable ----- Original Message -----=20 From: Deirdre Hackett=20 To: tutor@python.org=20 Sent: Wednesday, February 05, 2003 4:49 PM Subject: indexing of arrays in numeric=20 I downloaded numeric to help me with my array problems.... =20 I either have the data in this format, data =3D ([2345,4567,-6754]) or =20 xin =3D 2345 yin =3D 4567 zin =3D -6754 =20 I created an array of 10 rows and 3 columns, datab =3D zeros((10,3)) =20 I want the 3 values to be along each row but I am having trouble = figuring out how to index the array specifically. =20 for x, in arange(28): put(datab, [x], xin) put(datab, [x+1], yin) put(datab, [x+2], zin) =20 This obviously does not work but I hope it will give you an idea of what = I mean. Not sure how the sequence works. I know that you can say, a =3D arrayrange(9) a.shape =3D (3,3) print a[0,0] #will give you first row, first column,ie first element print a[0] #get first row =20 I want to be able to do this except the opposite way around. Thanks=20 Deirdre ------=_NextPart_000_0060_01C2CD37.8AE42CA0 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
 
----- Original Message -----=20
From: Deirdre=20 Hackett
Sent: Wednesday, February 05, 2003 4:49 PM
Subject: indexing of arrays in numeric

I downloaded numeric to help me with my = array=20 problems....
 
I either have the data in this = format,
    data =3D = ([2345,4567,-6754])
or=20    
    xin =3D = 2345
    yin =3D = 4567
    zin =3D = -6754
 
I created an array of 10 rows and 3=20 columns,
   datab =3D zeros((10,3))
 
I want the 3 values to be along each = row but I am=20 having trouble figuring out how to index the array = specifically.
 
for x, in = arange(28):
   =20 put(datab, [x], xin)
    put(datab, [x+1],=20 yin)
    put(datab, [x+2], zin)
 
This obviously does not work but I hope = it will=20 give you an idea of what I mean.
Not sure how the sequence works. I know = that you=20 can say,
a =3D arrayrange(9)
a.shape =3D (3,3)
print a[0,0] #will give you first row, = first=20 column,ie first element
print a[0]    #get first = row
 
I want to be able to do this except the opposite way around.
Thanks
Deirdre
------=_NextPart_000_0060_01C2CD37.8AE42CA0-- From jeff@ccvcorp.com Wed Feb 5 12:37:01 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Wed Feb 5 12:37:01 2003 Subject: [Tutor] Sorting numbers References: <34401853264.20030204141949@roadrunner.nf.net> <3E401B0D.6010606@ccvcorp.com> <189465828375.20030205080604@roadrunner.nf.net> Message-ID: <3E414B8E.5050001@ccvcorp.com> Adam Vardy wrote: >Tuesday, February 4, 2003, 4:27:01 PM, you wrote: > >>> >>> rawdata >>>['45K', '100K', '3.4Meg', '17K', '300K', '9.3Meg', '512', '23Meg'] >>> >>> srt = {} >>> >>> for item in rawdata: >>>... num, suffix = splitsuffix(item) >>>... value = srt.get(suffix, []) >>>... value.append(num) >>>... srt[suffix] = value >>> >>> > >Can you explain the last three lines here? > > Sure. First let's look at the line 'value = srt.get(suffix, [])'. We have a dictionary called srt, and we want to see if it has anything in the key that's held in suffix. I could've said 'value = srt[suffix]', and then value would contain whatever had previously been stored in the dictionary with that key, but what happens if nothing had been previously stored? >>> srt = {} >>> value = srt['Meg'] Traceback (most recent call last): File "", line 1, in ? KeyError: Meg >>> We get an exception. Now, since I'm starting with an empty dictionary, I know that I'm going to try looking up nonexistent keys at least a few times. I *could* use a try/except block, and respond to the exception, but there's an easier way. Dictionaries have a convenient get() method, which will look up a key like normal, but if that key is not found then it will return a default value. >>> value = srt.get('Meg', []) >>> value [] >>> value = srt.get('Meg', []) >>> value ['2.4', '9.6'] >>> This basically asks the dictionary, "Give me whatever you've got for 'Meg', but if you don't have anything, then give me an empty list instead." Now 'value' is a list containing whatever had been previously been stored in the dictionary with that suffix -- or an empty list if nothing had been stored previously. The next line, 'value.append(num)', tacks the current numeric value onto the end of that list. Finally, the last line 'srt[suffix] = value' takes the modified list and stores that list back in the dictionary, under the same key as before. The overall effect of these three lines, then, is that the list that the dictionary has stored under a given suffix has the current value of num tacked on the end, with new lists being created as necessary when new suffixes are found. As the original list of raw data is iterated through, it's sorted into a series of lists depending on what the non-numeric suffix on the string is. Eventually, all of the items that had ended in 'Meg' are stored in srt['Meg'], all of the numbers that had ended in 'K' are stored in srt['K'], and so on. Hope that helps. If there's anything else you're not clear on, feel free to ask. Jeff Shannon Technician/Programmer Credit International From jeff@ccvcorp.com Wed Feb 5 12:45:01 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Wed Feb 5 12:45:01 2003 Subject: [Tutor] list concatenation References: <000f01c2cd2c$79fd1740$f228eb42@MYNEWBOX> Message-ID: <3E414D60.3020300@ccvcorp.com> Lance wrote: >Hi All, > >What's the fastest way to concatenate the same string to all elements of a >list? I have a list of filenames and want to concatentate the path, a common >path, to each of them. > > Since you're working with filenames, you'll want to use the os.path module. To perform the same procedure on every element of a list, you're probably best off using a list comprehension. Presuming that you have your common initial path in 'commonpath' and your list of files is called 'filenames': import os fullfilenames = [os.path.join(commonpath, name) for name in filenames] Jeff Shannon Technician/Programmer Credit International From ramrom@earthling.net Wed Feb 5 13:39:02 2003 From: ramrom@earthling.net (Bob Gailer) Date: Wed Feb 5 13:39:02 2003 Subject: [Tutor] list concatenation In-Reply-To: <000f01c2cd2c$79fd1740$f228eb42@MYNEWBOX> Message-ID: <5.2.0.9.0.20030205113414.01a57948@66.28.54.253> --=======DFB19B1======= Content-Type: text/plain; x-avg-checked=avg-ok-66062ABC; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit At 07:37 AM 2/5/2003 -0800, Lance wrote: >What's the fastest way to concatenate the same string to all elements of a >list? List comprehension provides the least code way to do this: list = ['name1', 'name2', 'name3'] path = 'c:\\folder\\' full_list = [path + fn for fn in list] Bob Gailer mailto:ramrom@earthling.net 303 442 2625 --=======DFB19B1======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-66062ABC Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.445 / Virus Database: 250 - Release Date: 1/21/2003 --=======DFB19B1=======-- From mike@daboyz.org Wed Feb 5 13:50:02 2003 From: mike@daboyz.org (Michael Barrett) Date: Wed Feb 5 13:50:02 2003 Subject: [Tutor] Compiling Python w/o SSL Message-ID: <20030205180633.GA395@daboyz.org> I'm not certain if this is the place to post this, but I'm having issues with compiling python on solaris 2.6 without ssl. The SSL library is installed, but I want to compile python without it since the SSL installation is broken. Is there anyway to specify this in the ./configure or in the Makefile? Thanks for any help you can give. -- ________________________________________________________________________ Mike Barrett | "I used to read, now I go to raves." mike@daboyz.org | -- Random MUNI Rider, speaking www.daboyz.org | to my friend Allison. ------------------------+----------------------------------------------- From ramrom@earthling.net Wed Feb 5 13:50:12 2003 From: ramrom@earthling.net (Bob Gailer) Date: Wed Feb 5 13:50:12 2003 Subject: [Tutor] Apply() In-Reply-To: <3E4135BD.2020209@sbcglobal.net> Message-ID: <5.2.0.9.0.20030205113841.02e74700@66.28.54.253> --=======1ABB75D6======= Content-Type: text/plain; x-avg-checked=avg-ok-66062ABC; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit At 11:03 AM 2/5/2003 -0500, Jim Beckstrom wrote: >An explanation of the use of apply(), please. Mechanics: apply(function, sequence-of-positional-parameters, mapping-of-named-parameters) This lets you write code that calls an arbitrary function with arbitrary parameters. Say you create a set of functions; they all expect the same parameters; they do different things. It is only at execution time that the program chooses one of these based on some conditions. Instead of a series of if ... elif statements you use apply to "apply" the chosen function to the arguments. # define functions def a1(b,c):blah blah def a2(b,c):blah blah ... # associate functions with some key dict = (1:a1, 2:a2, ...} # determine which function to use func_key = result of some calculation or user input # apply that function apply(dict[func_key], (values for b and c)) #is equivalent to: if func_key == 1:a1(values for b and c) elif func_key == 2:a2(values for b and c) Bob Gailer mailto:ramrom@earthling.net 303 442 2625 --=======1ABB75D6======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-66062ABC Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.445 / Virus Database: 250 - Release Date: 1/21/2003 --=======1ABB75D6=======-- From op73418@mail.telepac.pt Wed Feb 5 16:26:02 2003 From: op73418@mail.telepac.pt (=?iso-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Wed Feb 5 16:26:02 2003 Subject: [Tutor] list concatenation References: <000f01c2cd2c$79fd1740$f228eb42@MYNEWBOX> Message-ID: <001101c2cd5e$161acbf0$68100dd5@violante> ----- Original Message ----- From: "Lance" To: "Tutor" Sent: Wednesday, February 05, 2003 3:37 PM Subject: [Tutor] list concatenation > Hi All, > > What's the fastest way to concatenate the same string to all elements of a > list? I have a list of filenames and want to concatentate the path, a common > path, to each of them. > There aren't many choices really. Supposing lst is your list and pathname is the path to concatenate, use the os.path module as in: import os #Avoid recurrent name resolution. joinpath = os.path.join #Change list in place => avoid allocation of new list. for i in range(len(lst)): lst[i] = joinpath(lst[i], pathname) If you need to keep the old list lst a list comprehension will do, as in: newlist = [joinpath(path, pathname) for path in lst] > Thanks, > Lance > Hope it helps, G. Rodrigues From eprice@ptc.com Wed Feb 5 18:02:07 2003 From: eprice@ptc.com (Erik Price) Date: Wed Feb 5 18:02:07 2003 Subject: [Tutor] capitalize() but only first letter Message-ID: <3E419751.6000405@ptc.com> I'm writing a Python script that generates a JavaBean getter method and setter method based on command line parameters (type and property name). It works beautiful, except for one thing. I'm using the capitalize() method of the Python String type, and although this does capitalize the first letter of the word, it lowercases all the rest of the letters. I need to capitalize just the first letter and leave all the other letters in the word alone. (1) Where can I read the source of the String type? I'm using Python 2.2.2 on Cygwin. (2) What would be the best way to extract the first character from a string variable? Thanks, Erik From eprice@ptc.com Wed Feb 5 18:12:22 2003 From: eprice@ptc.com (Erik Price) Date: Wed Feb 5 18:12:22 2003 Subject: [Tutor] capitalize() but only first letter In-Reply-To: <3E419751.6000405@ptc.com> References: <3E419751.6000405@ptc.com> Message-ID: <3E4198B5.5@ptc.com> Erik Price wrote: > I'm writing a Python script that generates a JavaBean getter method and > setter method based on command line parameters (type and property name). > It works beautiful, except for one thing. I'm using the capitalize() > method of the Python String type, and although this does capitalize the > first letter of the word, it lowercases all the rest of the letters. I > need to capitalize just the first letter and leave all the other letters > in the word alone. > > (1) Where can I read the source of the String type? I'm using Python > 2.2.2 on Cygwin. > > (2) What would be the best way to extract the first character from a > string variable? Actually, I posted too soon -- I figured it out. Strings are lists of characters, apparently. But what is the elegant way of declaring a slice of s[n] to the end of s, so I can capitalize the first character and prepend it to the rest? s = "string" s = s[0].capitalize() + s[1] (and all the rest of the chars too) Erik From fredm@smartypantsco.com Wed Feb 5 18:33:01 2003 From: fredm@smartypantsco.com (Alfred Milgrom) Date: Wed Feb 5 18:33:01 2003 Subject: [Tutor] capitalize() but only first letter In-Reply-To: <3E4198B5.5@ptc.com> References: <3E419751.6000405@ptc.com> <3E419751.6000405@ptc.com> Message-ID: <5.1.0.14.0.20030206102236.02465be0@192.168.1.1> The simple way to slice a string is to use the string[start:end] construct. The start and end parameters are optional (but remember we start at 0), so you can have: s = 'everything But The kitchen siNk' s[3:7] means slice from 4th to 8th letter (inclusive) 'ryth' s[:-1] means everything from the beginning except the last letter 'everything But The kitchen siN' s[1:] means everything except the first letter 'verything But The kitchen siNk' HTH Fred Milgrom At 06:05 PM 5/02/03 -0500, Erik Price wrote: >Erik Price wrote: >>I'm writing a Python script that generates a JavaBean getter method and >>setter method based on command line parameters (type and property >>name). It works beautiful, except for one thing. I'm using the >>capitalize() method of the Python String type, and although this does >>capitalize the first letter of the word, it lowercases all the rest of >>the letters. I need to capitalize just the first letter and leave all >>the other letters in the word alone. >>(1) Where can I read the source of the String type? I'm using Python >>2.2.2 on Cygwin. >>(2) What would be the best way to extract the first character from a >>string variable? > >Actually, I posted too soon -- I figured it out. Strings are lists of >characters, apparently. But what is the elegant way of declaring a slice >of s[n] to the end of s, so I can capitalize the first character and >prepend it to the rest? > >s = "string" >s = s[0].capitalize() + s[1] (and all the rest of the chars too) > > >Erik > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From eprice@ptc.com Wed Feb 5 18:56:20 2003 From: eprice@ptc.com (Erik Price) Date: Wed Feb 5 18:56:20 2003 Subject: [Tutor] capitalize() but only first letter In-Reply-To: <5.1.0.14.0.20030206102236.02465be0@192.168.1.1> References: <3E419751.6000405@ptc.com> <3E419751.6000405@ptc.com> <5.1.0.14.0.20030206102236.02465be0@192.168.1.1> Message-ID: <3E41A370.7050002@ptc.com> Alfred Milgrom wrote: > The simple way to slice a string is to use the string[start:end] construct. > The start and end parameters are optional (but remember we start at 0), > so you can have: > > s = 'everything But The kitchen siNk' > > s[3:7] means slice from 4th to 8th letter (inclusive) > 'ryth' > s[:-1] means everything from the beginning except the last letter > 'everything But The kitchen siN' > s[1:] means everything except the first letter > 'verything But The kitchen siNk' > > HTH > Fred Milgrom Yes, thanks Fred. That is exactly what I was looking for. I had tried s[1-] and s[1...] but I had forgotten that it was the colon. Here is the script I ended up with... I'd like to make some additions to it, so that if I specify an overloaded setter method it calls the "true" setter method (the one that actually modifies the property), but it's been a long day and I'm going to go home now. Erik #!/usr/bin/python # gettersetter.py # creates getters and setters for a JavaBean # from property type and name arguments # Usage: gettersetter.py -b|-s|-g type propertyName # Example: gettersetter.py -b String userId def usage(): """ returns the usage for gettersetter.py """ usage = "Usage: gettersetter.py -b|-s|-g type propertyName" + "\n" \ + "Example: gettersetter.py -b String userId\n" return usage def cap_camelcase(target): """ capitalizes only first character of a string """ return target[0].capitalize() + target[1:] def make_getter(propertytype, propertyname): """ returns a getter method definition with javadoc comment """ pn = cap_camelcase(propertyname) methodname = "get" + pn comment = "/**\n * returns the " + propertyname \ + " property\n */\n" getter = "public " + propertytype + " " + methodname + "() {\n" \ + " return this." + propertyname + ";\n" \ + "}\n" return comment + getter def make_setter(propertytype, propertyname): """ returns a setter method definition with javadoc comment """ pn = cap_camelcase(propertyname) methodname = "set" + pn comment = "/**\n * sets the " + propertyname \ + " property\n */\n" setter = "public void " + methodname + "(" \ + propertytype + " " + propertyname + ") {\n" \ + " this." + propertyname + " = " + propertyname \ + ";\n" + "}\n" return comment + setter if __name__ == "__main__": import sys if len(sys.argv) < 4: # 3, includes script name itself print usage() sys.exit(1) opt = sys.argv[1] propertytype = sys.argv[2] propertyname = sys.argv[3] if opt == "-s": print make_setter(propertytype, propertyname) elif opt == "-g": print make_getter(propertytype, propertyname) elif opt == "-b": print make_getter(propertytype, propertyname) print make_setter(propertytype, propertyname) else: print usage() sys.exit(1) From shalehperry@attbi.com Wed Feb 5 20:27:06 2003 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Wed Feb 5 20:27:06 2003 Subject: [Tutor] capitalize() but only first letter In-Reply-To: <3E41A370.7050002@ptc.com> References: <3E419751.6000405@ptc.com> <5.1.0.14.0.20030206102236.02465be0@192.168.1.1> <3E41A370.7050002@ptc.com> Message-ID: <200302051725.45942.shalehperry@attbi.com> On Wednesday 05 February 2003 15:51, Erik Price wrote: > > Here is the script I ended up with... I'd like to make some additions t= o > it, so that if I specify an overloaded setter method it calls the "true= " > setter method (the one that actually modifies the property), but it's > been a long day and I'm going to go home now. > it is generally more efficient to do: l =3D [] l.append('hello') l.append(' ') l.append('world') import string output =3D string.join('', l) # use an empty string as glue than it is to use 'hello' + ' ' + 'world', especially when the number of=20 pieces glued together is larger than a handful. From erikprice@mac.com Wed Feb 5 21:51:04 2003 From: erikprice@mac.com (Erik Price) Date: Wed Feb 5 21:51:04 2003 Subject: [Tutor] capitalize() but only first letter In-Reply-To: <200302051725.45942.shalehperry@attbi.com> Message-ID: On Wednesday, February 5, 2003, at 08:25 PM, Sean 'Shaleh' Perry wrote: > it is generally more efficient to do: > > l = [] > l.append('hello') > l.append(' ') > l.append('world') > import string > output = string.join('', l) # use an empty string as glue > > than it is to use 'hello' + ' ' + 'world', especially when the number > of > pieces glued together is larger than a handful. Is that because concatenating separate strings instantiates separate objects, whereas appending to a list does not? (There is a similar though not identical condition in Java with string concatenation vs StringBuffer, but the rules may be different in Python.) If my guess is wrong, what is the reason for the better efficiency in appending to a list? Finally, how does this compare: print("%s %s") % ('hello', 'world') TIA, Erik -- Erik Price email: erikprice@mac.com jabber: erikprice@jabber.org From erikprice@mac.com Wed Feb 5 22:19:02 2003 From: erikprice@mac.com (Erik Price) Date: Wed Feb 5 22:19:02 2003 Subject: [Tutor] Apply() In-Reply-To: <5.2.0.9.0.20030205113841.02e74700@66.28.54.253> Message-ID: On Wednesday, February 5, 2003, at 01:49 PM, Bob Gailer wrote: > Mechanics: apply(function, sequence-of-positional-parameters, > mapping-of-named-parameters) > > This lets you write code that calls an arbitrary function with > arbitrary parameters. Say you create a set of functions; they all > expect the same parameters; they do different things. It is only at > execution time that the program chooses one of these based on some > conditions. Instead of a series of if ... elif statements you use > apply to "apply" the chosen function to the arguments. That's nifty ... thanks for explaining. But I don't see it in the index of the Python docs on the web site. Is that something that isn't in Python yet, or... ? Erik -- Erik Price email: erikprice@mac.com jabber: erikprice@jabber.org From jeff@ccvcorp.com Wed Feb 5 22:32:02 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Wed Feb 5 22:32:02 2003 Subject: [Tutor] capitalize() but only first letter References: Message-ID: <3E41D6F6.7050700@ccvcorp.com> Erik Price wrote: > On Wednesday, February 5, 2003, at 08:25 PM, Sean 'Shaleh' Perry wrote: > >> it is generally more efficient to do: >> >> l = [] >> l.append('hello') >> l.append(' ') >> l.append('world') >> import string >> output = string.join('', l) # use an empty string as glue >> >> than it is to use 'hello' + ' ' + 'world', especially when the number of >> pieces glued together is larger than a handful. > > > Is that because concatenating separate strings instantiates separate > objects, whereas appending to a list does not? (There is a similar > though not identical condition in Java with string concatenation vs > StringBuffer, but the rules may be different in Python.) Yes, this is indeed the reason. Each addition creates a new string object, of which all but one are almost immediately thrown away. Appending to a list and then using join() creates a single string object (and may require creating a new list object) regardless of how many pieces you're concatenating. By the way, instead of adding spaces to the list and joining with an empty string, I'd simply join on a space. I also prefer using join() as a string method, instead of importing the string module. l.append('hello') l.append('world') ' '.join(l) I suspect that Sean finds the string method syntax of join() to be awkward (there was quite a bit of discussion when this was added to Python, and many people still disagree with Guido's decision), but I find it less awkward than needlessly importing the string module. ;) > Finally, how does this compare: > > print("%s %s") % ('hello', 'world') This is much preferable, at least to my tastes. It still avoids the creating of multiple intermediate strings, and also avoids the multiple function calls used by the append()/join() method, and is clearer in its intent. There are only three situations where I find the append()/join() method preferable to this -- 1) The strings are already in a list, so it's really just a single join() 2) There's an extremely large number of strings, so that typing a sequence of %s's becomes cumbersome 3) There's a variable number of strings, so that you don't know at compile-time just how many %s's to use Jeff Shannon Technician/Programmer Credit International From erikprice@mac.com Wed Feb 5 22:41:01 2003 From: erikprice@mac.com (Erik Price) Date: Wed Feb 5 22:41:01 2003 Subject: [Tutor] capitalize() but only first letter In-Reply-To: <3E41D6F6.7050700@ccvcorp.com> Message-ID: On Wednesday, February 5, 2003, at 10:31 PM, Jeff Shannon wrote: > I suspect that Sean finds the string method syntax of join() to be > awkward (there was quite a bit of discussion when this was added to > Python, and many people still disagree with Guido's decision), but I > find it less awkward than needlessly importing the string module. ;) I also prefer to use methods of objects rather than pass objects to functions, but it seems like six on one side, half a dozen on the other. I find methods a little simpler. (This actually raises another question that I wanted to ask, but it's so unrelated to this thread that I'll spawn a new one.) >> Finally, how does this compare: >> >> print("%s %s") % ('hello', 'world') > > > This is much preferable, at least to my tastes. It still avoids the > creating of multiple intermediate strings Let me just play devil's advocate here then, because I'm a little confused -- if it avoids creating multiple intermediate strings, then what would those elements of the tuple be? They are not references to string objects? (I sound obstinate here but I'm trying to be curious.) > There are only three situations where I find the append()/join() > method preferable to this All very good points, thank you. Erik -- Erik Price email: erikprice@mac.com jabber: erikprice@jabber.org From erikprice@mac.com Wed Feb 5 22:46:24 2003 From: erikprice@mac.com (Erik Price) Date: Wed Feb 5 22:46:24 2003 Subject: [Tutor] adding methods to native types Message-ID: <5FA30625-3987-11D7-AB64-00039351FE6A@mac.com> Pardon me for asking such a strange question (perhaps), but is there any way to add methods to the native types in Python? I wrote my first Python script in a long time today and I pined for the length() method of Java's List type -- it took me a while to figure out that there's no way to determine the length of a list using a list method, you have to use the len() function. It led me to wonder if it's possible to subclass the native types in Python and add additional features. If not, there's nothing to stop one from composing the list within another class and adding the additional features, which actually relieves me of the burden of ensuring that the subclass is completely compatible with the internal/external implementation of the base class, but I'm curious if you can do it. Essentially, I prefer "string".split("") to split("", string) and wanted to do list.len() instead of len(list) Thanks, Erik -- Erik Price email: erikprice@mac.com jabber: erikprice@jabber.org From Don Arnold" Message-ID: <00e101c2cd95$4b217420$b1d1b241@defaultcomp> ----- Original Message ----- From: "Erik Price" To: Sent: Wednesday, February 05, 2003 9:59 PM Subject: [Tutor] adding methods to native types > Pardon me for asking such a strange question (perhaps), but is there > any way to add methods to the native types in Python? I wrote my first > Python script in a long time today and I pined for the length() method > of Java's List type -- it took me a while to figure out that there's no > way to determine the length of a list using a list method, you have to > use the len() function. > > It led me to wonder if it's possible to subclass the native types in > Python and add additional features. If not, there's nothing to stop > one from composing the list within another class and adding the > additional features, which actually relieves me of the burden of > ensuring that the subclass is completely compatible with the > internal/external implementation of the base class, but I'm curious if > you can do it. > > Essentially, I prefer > > "string".split("") > > to > > split("", string) > > and wanted to do > > list.len() > > instead of > > len(list) > Lists already have a builtin magical method for this (which is what the len function calls to get its value): Python 2.2.1 (#34, Apr 9 2002, 19:34:33) [MSC 32 bit (Intel)] on win32 Type "copyright", "credits" or "license" for more information. IDLE 0.8 -- press F1 for help >>> a = [1,2,3,4,5] >>> a.__len__() 5 >>> > Thanks, > > Erik > > -- > Erik Price > > email: erikprice@mac.com > jabber: erikprice@jabber.org HTH, Don From shalehperry@attbi.com Wed Feb 5 23:22:15 2003 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Wed Feb 5 23:22:15 2003 Subject: [Tutor] adding methods to native types In-Reply-To: <00e101c2cd95$4b217420$b1d1b241@defaultcomp> References: <5FA30625-3987-11D7-AB64-00039351FE6A@mac.com> <00e101c2cd95$4b217420$b1d1b241@defaultcomp> Message-ID: <200302052019.47958.shalehperry@attbi.com> On Wednesday 05 February 2003 20:07, Don Arnold wrote: > > Lists already have a builtin magical method for this (which is what the= len > function calls to get its value): > > Python 2.2.1 (#34, Apr 9 2002, 19:34:33) [MSC 32 bit (Intel)] on win32 > Type "copyright", "credits" or "license" for more information. > IDLE 0.8 -- press F1 for help > > >>> a =3D [1,2,3,4,5] > >>> a.__len__() > > 5 > true. However "magic" methods are just that and should not be used in ca= sual=20 code. From shalehperry@attbi.com Wed Feb 5 23:26:03 2003 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Wed Feb 5 23:26:03 2003 Subject: [Tutor] adding methods to native types In-Reply-To: <5FA30625-3987-11D7-AB64-00039351FE6A@mac.com> References: <5FA30625-3987-11D7-AB64-00039351FE6A@mac.com> Message-ID: <200302052024.30512.shalehperry@attbi.com> On Wednesday 05 February 2003 19:59, Erik Price wrote: > Pardon me for asking such a strange question (perhaps), but is there > any way to add methods to the native types in Python? I wrote my first > Python script in a long time today and I pined for the length() method > of Java's List type -- it took me a while to figure out that there's no > way to determine the length of a list using a list method, you have to > use the len() function. > > It led me to wonder if it's possible to subclass the native types in > Python and add additional features. If not, there's nothing to stop > one from composing the list within another class and adding the > additional features, which actually relieves me of the burden of > ensuring that the subclass is completely compatible with the > internal/external implementation of the base class, but I'm curious if > you can do it. > As of the latest python releases you can subclass list, dict, etc. >>> class MyList(list): =2E.. def len(self): =2E.. return self.__len__() =2E..=20 >>> a =3D MyList() >>> a.append(1) >>> a.append(2) >>> a.append(3) >>> a.len() 3 However it is quite Pythonic to mix functional and OO styles. Forcing a = pure=20 OO style will move you away from common idioms and make your code feel=20 slightly less natural to the common Python coder. Rather than fight it, you should learn to enjoy the functional choices=20 available to you. Many of us find the mix fun and less effortless. From erikprice@mac.com Wed Feb 5 23:39:01 2003 From: erikprice@mac.com (Erik Price) Date: Wed Feb 5 23:39:01 2003 Subject: [Tutor] adding methods to native types In-Reply-To: <200302052024.30512.shalehperry@attbi.com> Message-ID: On Wednesday, February 5, 2003, at 11:24 PM, Sean 'Shaleh' Perry wrote: > Rather than fight it, you should learn to enjoy the functional choices > available to you. Many of us find the mix fun and less effortless. Fun is definitely cool, but what I was looking for choosing Python over Java for that quick script would be that it is *more* effortless... ! :) Erik -- Erik Price email: erikprice@mac.com jabber: erikprice@jabber.org From shalehperry@attbi.com Wed Feb 5 23:45:01 2003 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Wed Feb 5 23:45:01 2003 Subject: [Tutor] adding methods to native types In-Reply-To: References: Message-ID: <200302052043.44645.shalehperry@attbi.com> On Wednesday 05 February 2003 20:52, Erik Price wrote: > On Wednesday, February 5, 2003, at 11:24 PM, Sean 'Shaleh' Perry wrote= : > > Rather than fight it, you should learn to enjoy the functional choice= s > > available to you. Many of us find the mix fun and less effortless. > > Fun is definitely cool, but what I was looking for choosing Python over > Java for that quick script would be that it is *more* effortless... ! > > :) > > Erik I find len(foo) less of a pain than object.len() -- if nothing else I sav= e one=20 character (no dot (-:) But that is just me. The nice thing about functions is you can pass any object to them. len() = works=20 on any object that supports __len__(). From shalehperry@attbi.com Wed Feb 5 23:46:02 2003 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Wed Feb 5 23:46:02 2003 Subject: [Tutor] capitalize() but only first letter In-Reply-To: References: Message-ID: <200302051949.07464.shalehperry@attbi.com> On Wednesday 05 February 2003 19:54, Erik Price wrote: > On Wednesday, February 5, 2003, at 10:31 PM, Jeff Shannon wrote: > > I suspect that Sean finds the string method syntax of join() to be > > awkward (there was quite a bit of discussion when this was added to > > Python, and many people still disagree with Guido's decision), but I > > find it less awkward than needlessly importing the string module. ;) > > I also prefer to use methods of objects rather than pass objects to > functions, but it seems like six on one side, half a dozen on the > other. I find methods a little simpler. (This actually raises another > question that I wanted to ask, but it's so unrelated to this thread > that I'll spawn a new one.) > I personally find ''.join() awkward to read. Is that "join with an empty= =20 string" or "join with a space"? Very rarely do we see other=20 "string".method() style invocations. If I had to (and I almost did in my= =20 first email) I would do: space =3D ' ' output =3D space.join(list) > >> Finally, how does this compare: > >> > >> print("%s %s") % ('hello', 'world') > > > > This is much preferable, at least to my tastes. It still avoids the > > creating of multiple intermediate strings > > Let me just play devil's advocate here then, because I'm a little > confused -- if it avoids creating multiple intermediate strings, then > what would those elements of the tuple be? They are not references to > string objects? (I sound obstinate here but I'm trying to be curious.) > yes it generates a throw away tuple. Not quite as bad as a list, but it = does=20 create that object. From erikprice@mac.com Thu Feb 6 00:03:07 2003 From: erikprice@mac.com (Erik Price) Date: Thu Feb 6 00:03:07 2003 Subject: [Tutor] adding methods to native types In-Reply-To: <200302052043.44645.shalehperry@attbi.com> Message-ID: <30E30987-3992-11D7-AB64-00039351FE6A@mac.com> On Wednesday, February 5, 2003, at 11:43 PM, Sean 'Shaleh' Perry wrote: > The nice thing about functions is you can pass any object to them. > len() works > on any object that supports __len__(). Strangely, it is more reassuring knowing that len() is just calling __len__(). I suppose because at least then the element-counting functionality *is* encapsulated within the class, which is where [I think] it should be. So does that mean that if I define a class and add a __len__() method, then it will work with the len() function? Let me try: >>> class TestLen: ... def __len__(self): ... return 8080 ... >>> t = TestLen() >>> len(t) 8080 Guess so! But if the len() function simply calls the __len__() method, why make that method "magic" at all? Why not just offer it as a regular method? [To me] there's nothing magic about using a method to get some data about an object. Erik -- Erik Price email: erikprice@mac.com jabber: erikprice@jabber.org From shalehperry@attbi.com Thu Feb 6 00:21:01 2003 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Thu Feb 6 00:21:01 2003 Subject: [Tutor] adding methods to native types In-Reply-To: <30E30987-3992-11D7-AB64-00039351FE6A@mac.com> References: <30E30987-3992-11D7-AB64-00039351FE6A@mac.com> Message-ID: <200302052120.19904.shalehperry@attbi.com> On Wednesday 05 February 2003 21:16, Erik Price wrote: > On Wednesday, February 5, 2003, at 11:43 PM, Sean 'Shaleh' Perry wrote= : > > The nice thing about functions is you can pass any object to them. > > len() works > > on any object that supports __len__(). > > Strangely, it is more reassuring knowing that len() is just calling > __len__(). I suppose because at least then the element-counting > functionality *is* encapsulated within the class, which is where [I > think] it should be. > true enough. > > Guess so! But if the len() function simply calls the __len__() method, > why make that method "magic" at all? Why not just offer it as a > regular method? [To me] there's nothing magic about using a method to > get some data about an object. > easy answer: it has been that way since Python began. much of python lets you interact with objects without actually using meth= ods. =20 I think len() is one of those vestiges. I wonder if it had something to do with trying to ease people into OO (Py= thon=20 was meant to help those learning programming). From johnca@ourpla.net Thu Feb 6 02:06:22 2003 From: johnca@ourpla.net (John Abbe) Date: Thu Feb 6 02:06:22 2003 Subject: [Tutor] Sometimes unreferenced!? Message-ID: Okay, as suggested, i'm trying to modularize my code, and now Python is complaining about a variable being referenced before assignment, *but* only with some ways i reference it. To give a much-simplified but real example -- the code: ================================= #!/usr/local/bin/python groupData = [1, 2, 3] def e(): groupData.reverse() def f(): records = [4, 5] groupData += records def main(): print "Before e: %s\n\n" % groupData e() print "After e, Before f: %s\n\n" % groupData f() print "After f: %s\n" % groupData if __name__ == '__main__': main() ================================= [Unix prompt]> problem.py [problem.py is the name of the above file] Before e: [1, 2, 3] After e, Before f: [3, 2, 1] Traceback (most recent call last): File "./problem.py", line 20, in ? main() File "./problem.py", line 16, in main f() File "./problem.py", line 10, in f groupData += records UnboundLocalError: local variable 'groupData' referenced before assignment ================================= Help? Life, John -- ------===>> AbbeNormal <<===------ | ..:::.. A wiki-weblog, somewhere under the | .:::::::*:::. multi-dimensional normal curve | ..:::::::::::::::.. http://ourpla.net/cgi/pikie |....::::::::::*:::::::::::*.... From dyoo@hkn.eecs.berkeley.edu Thu Feb 6 02:46:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Feb 6 02:46:02 2003 Subject: [Tutor] Apply() In-Reply-To: Message-ID: On Wed, 5 Feb 2003, Erik Price wrote: > > Instead of a series of if ... elif statements you use apply to "apply" > > the chosen function to the arguments. > > That's nifty ... thanks for explaining. But I don't see it in the index > of the Python docs on the web site. Is that something that isn't in > Python yet, or... ? Hi Eric, Ok, found it! Here you go: http://www.python.org/doc/lib/built-in-funcs.html#l2h-4 apply() is one of those functions that you might see in a lot of functional programming, but it's not as common in Python because there's an alternative syntax for it. Rather than explain it, here's an example that shows it. *grin* ### >>> def add(*args): ... sum = 0 ... for num in args: ... sum = sum + num ... return sum ... >>> def neg(x): ... return -x ... >>> import sys >>> cmds = { 'add' : add, ... 'neg' : neg, ... 'quit' : sys.exit } >>> def loop(): ... while 1: ... statement = raw_input("> ") ... (c, rest) = (statement.split()[0], ... map(float, statement.split()[1:])) ... print cmds[c](*rest) ... >>> loop() > add 3 4 5 6 7 8 9 10 52.0 > neg 42 -42.0 > quit 0 0.0 ### The part that would normally involve 'apply()' is the line: print cmds[c](*rest) With apply(), that might look like: print apply(cmds[c], rest) Hope this helps! From janos.juhasz@VELUX.com Thu Feb 6 03:54:01 2003 From: janos.juhasz@VELUX.com (janos.juhasz@VELUX.com) Date: Thu Feb 6 03:54:01 2003 Subject: [Tutor] Sorting numbers Message-ID: What is your opinion about this kind of solution ***************** import re class info: """ to handle kilobytes and megabyte, or even terras """ def __init__(self, val): val =3D "%s" % val ## convert val to string, if it isn't that num =3D re.sub('[\s]', '', "%s" % val) ## remove the non numeri= c chars num =3D float(num) ## get back the numeric content suffix =3D re.sub('[\d.]', '', val) ## remove the numeric chars= suffix =3D suffix.upper() ## standardize the suffix if re.match('KB', val): num =3D num * 1024 if re.match('MB', val): num =3D num * 1024**2 if re.match('GB', val): num =3D num * 1024**3 if re.match('TB', val): num =3D num * 1024**4 self.val =3D num ## self.val is a number now def __str__(self): if self.val >=3D 1024**4: return "%.3f TB" % (self.val/1024**4) if self.val >=3D 1024**3: return "%.3f GB" % (self.val/1024**3) if self.val >=3D 1024**2: return "%.3f MB" % (self.val/1024**2) if self.val >=3D 1024: return "%.3f KB" % (self.val/1024) else: return "%.3f B" % self.val def __cmp__(self, other): self.val.__cmp__(other.val) ***************** I have no got enough skill to make it work, but it close to working :( Can someone shape it? Best regards, ----------------------- Juh=E1sz J=E1nos IT department = =20 "Jeff Shannon" To: tutor@python.= org =20 =20 m> bcc: = =20 Subject: Re: [Tut= or] Sorting numbers =20 Sent by: = =20 tutor-admin@pyth = =20 on.org = =20 = =20 = =20 02/05/2003 18:36 = =20 = =20 = =20 Adam Vardy wrote: >Tuesday, February 4, 2003, 4:27:01 PM, you wrote: > >>> >>> rawdata >>>['45K', '100K', '3.4Meg', '17K', '300K', '9.3Meg', '512', '23Meg'] >>> >>> srt =3D {} >>> >>> for item in rawdata: >>>... num, suffix =3D splitsuffix(item) >>>... value =3D srt.get(suffix, []) >>>... value.append(num) >>>... srt[suffix] =3D value >>> >>> > >Can you explain the last three lines here? > > Sure. First let's look at the line 'value =3D srt.get(suffix, [])'. W= e have a dictionary called srt, and we want to see if it has anything in the key that's held in suffix. I could've said 'value =3D srt[suffix]'= , and then value would contain whatever had previously been stored in the= dictionary with that key, but what happens if nothing had been previously stored? >>> srt =3D {} >>> value =3D srt['Meg'] Traceback (most recent call last): File "", line 1, in ? KeyError: Meg >>> We get an exception. Now, since I'm starting with an empty dictionary,= I know that I'm going to try looking up nonexistent keys at least a few= times. I *could* use a try/except block, and respond to the exception,= but there's an easier way. Dictionaries have a convenient get() method= , which will look up a key like normal, but if that key is not found then= it will return a default value. >>> value =3D srt.get('Meg', []) >>> value [] >>> value =3D srt.get('Meg', []) >>> value ['2.4', '9.6'] >>> This basically asks the dictionary, "Give me whatever you've got for 'Meg', but if you don't have anything, then give me an empty list inste= ad." Now 'value' is a list containing whatever had been previously been stored in the dictionary with that suffix -- or an empty list if nothin= g had been stored previously. The next line, 'value.append(num)', tacks the current numeric value onto the end of that list. Finally, the last= line 'srt[suffix] =3D value' takes the modified list and stores that li= st back in the dictionary, under the same key as before. The overall effect of these three lines, then, is that the list that th= e dictionary has stored under a given suffix has the current value of num= tacked on the end, with new lists being created as necessary when new suffixes are found. As the original list of raw data is iterated through, it's sorted into a series of lists depending on what the non-numeric suffix on the string is. Eventually, all of the items that= had ended in 'Meg' are stored in srt['Meg'], all of the numbers that ha= d ended in 'K' are stored in srt['K'], and so on. Hope that helps. If there's anything else you're not clear on, feel free to ask. Jeff Shannon Technician/Programmer Credit International _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor = From erikprice@mac.com Thu Feb 6 08:02:35 2003 From: erikprice@mac.com (Erik Price) Date: Thu Feb 6 08:02:35 2003 Subject: [Tutor] Apply() In-Reply-To: Message-ID: <1E0F17B4-39D5-11D7-AB64-00039351FE6A@mac.com> On Thursday, February 6, 2003, at 02:45 AM, Danny Yoo wrote: > The part that would normally involve 'apply()' is the line: > > print cmds[c](*rest) > > > With apply(), that might look like: > > print apply(cmds[c], rest) > > > > Hope this helps! Yes, I think I understand ... you can just add parens to the end of any name and, if a function has been defined with that name, it will be called? Thanks! Erik -- Erik Price email: erikprice@mac.com jabber: erikprice@jabber.org From erikprice@mac.com Thu Feb 6 08:07:01 2003 From: erikprice@mac.com (Erik Price) Date: Thu Feb 6 08:07:01 2003 Subject: [Tutor] capitalize() but only first letter In-Reply-To: <200302051949.07464.shalehperry@attbi.com> Message-ID: On Wednesday, February 5, 2003, at 10:49 PM, Sean 'Shaleh' Perry wrote: >> Let me just play devil's advocate here then, because I'm a little >> confused -- if it avoids creating multiple intermediate strings, then >> what would those elements of the tuple be? They are not references to >> string objects? (I sound obstinate here but I'm trying to be >> curious.) >> > > yes it generates a throw away tuple. Not quite as bad as a list, but > it does > create that object. A tuple with string-based elements, right? So what I'm confused about is how the strings in the tuple are more memory-efficient than just using strings with the concat operator. Unless it is because every time a concatenation is performed, then a *new* string is created, so you end up with (x + (x - 1)x) strings (because as the parser moves to the next string, it creates a new string to represent the strings concatted thus far, then again with the *next* string, etc). Whereas with the tuple or list, you just have a set of x strings and they are all merged in one fell swoop at the same time, with no "intermediate" strings. I think I understand it now. Thanks! Erik -- Erik Price email: erikprice@mac.com jabber: erikprice@jabber.org From erikprice@mac.com Thu Feb 6 08:10:01 2003 From: erikprice@mac.com (Erik Price) Date: Thu Feb 6 08:10:01 2003 Subject: [Tutor] adding methods to native types In-Reply-To: <200302052120.19904.shalehperry@attbi.com> Message-ID: <2C5D363E-39D6-11D7-AB64-00039351FE6A@mac.com> On Thursday, February 6, 2003, at 12:20 AM, Sean 'Shaleh' Perry wrote: > easy answer: it has been that way since Python began. > > much of python lets you interact with objects without actually using > methods. > I think len() is one of those vestiges. > > I wonder if it had something to do with trying to ease people into OO > (Python > was meant to help those learning programming). Okay. So there's nothing wrong with doing: class MyList(): def __init__(self): self._mylist = [] def len(self): return len(self) ? It feels "dirty" to use the __init__ method since it has those magic underscores (I feel the same way about using if __name__ == "__main__"). But there is no other name for the constructor, right? Erik -- Erik Price email: erikprice@mac.com jabber: erikprice@jabber.org From Deirdre Hackett" This is a multi-part message in MIME format. ------=_NextPart_000_009B_01C2CDF7.6B776C40 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: 7bit This is a profram to read in a string from the serial port. I want to take in the information and store if (for the moment ) in an array of some type. I am getting bogged down and can't move forward. I would appreciate any advice on where i am going wrong. The data comes in as ' - 2345 4565 - 5678 ' Thanks Deirdre ------=_NextPart_000_009B_01C2CDF7.6B776C40 Content-Type: text/plain; name="tkinter4.txt" Content-Transfer-Encoding: 7bit Content-Disposition: attachment; filename="tkinter4.txt" from Tkinter import * from threading import * import timer import time import array from Numeric import * import serial root = Tk() ser = serial.Serial(0, timeout=1) data = [] def send(): ser.write("*99p\r") def take_in_data(): xinput = "" yinput = "" zinput = "" input = ser.readline() xinput = input[:9] yinput = input[9:18] zinput = input[18:27] xsplit = xinput.split() ysplit = yinput.split() zsplit = zinput.split() x2string = "" for n in range(len(xsplit)): x2string += xsplit[n] y2string = "" for n in range(len(ysplit)): y2string += ysplit[n] z2string = "" for n in range(len(zsplit)): z2string += zsplit[n] if x2string > 3: xcommasplit = x2string.split(',') if y2string > 3: ycommasplit = y2string.split(',') if z2string > 3: zcommasplit = z2string.split(',') x3string = "" for n in range(len(xcommasplit)): x3string += xcommasplit[n] y3string = "" for n in range(len(ycommasplit)): y3string += ycommasplit[n] z2string = "" for n in range(len(zcommasplit)): z3string += zcommasplit[n] data.append(int(x2string)) data.append(int(y2string)) data.append(int(z2string)) #data.append(input) for n in range(10): t = Timer(0.05, send) t.start() #print n a = Timer(0.05, take_in_data) a.start() #print input #for b in range(10): #print data[b] ser.close() root.mainloop() ------=_NextPart_000_009B_01C2CDF7.6B776C40-- From gerrit@nl.linux.org Thu Feb 6 11:51:24 2003 From: gerrit@nl.linux.org (Gerrit Holl) Date: Thu Feb 6 11:51:24 2003 Subject: [Tutor] Apply() In-Reply-To: <1E0F17B4-39D5-11D7-AB64-00039351FE6A@mac.com> References: <1E0F17B4-39D5-11D7-AB64-00039351FE6A@mac.com> Message-ID: <20030206165143.GA3632@nl.linux.org> Erik Price schreef op donderdag 6 februari om 14:03:12 +0000: > Yes, I think I understand ... you can just add parens to the end of any > name and, if a function has been defined with that name, it will be > called? python -c 'print str(__import__("operator").truth(len(locals()))) + "!"' yours, Gerrit. -- Asperger Syndroom - een persoonlijke benadering: http://people.nl.linux.org/~gerrit/ Het zijn tijden om je zelf met politiek te bemoeien: http://www.sp.nl/ From jeff@ccvcorp.com Thu Feb 6 12:09:01 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Thu Feb 6 12:09:01 2003 Subject: [Tutor] capitalize() but only first letter References: Message-ID: <3E429698.4030305@ccvcorp.com> Erik Price wrote: > Unless it is because every time a concatenation is performed, then a > *new* string is created, so you end up with (x + (x - 1)x) strings > (because as the parser moves to the next string, it creates a new > string to represent the strings concatted thus far, then again with > the *next* string, etc). This is exactly the case. When you execute a line of code like, say, greeting = "Hello" + " " + "world" + "!" You end up building and then throwing away several strings. First the parser will see "Hello + " " and perform that addition, creating a new string "Hello ". Next it adds *that* string to "world", creating the string "Hello world", and throwing away the just-created string "Hello ". Then it adds "!", creating the complete string "Hello world!", and throwing away the previous "Hello world". Each addition beyond the first results in a "wasted" string. By contrast, look at the following almost-equivalent bits of code: words = ["Hello", " ", "world", "!"] greeting = ''.join(words) greeting = '%s%s%s%s' % ("Hello", " ", "world", "!") Both of these snippets start with the same source strings as the addition version. Each of them creates one other object (a list in the first case, a tuple in the second), but no matter how many more words are added, there are no other "wasted" objects getting thrown away. Adding 12 words together results in 10 throwaway strings, but joining or %-formatting 12 words still results in a single throwaway sequence object. As a minor additional (pun not intended) point, I have a personal preference to avoid using + with strings because eventually, that's going to lead to code that reads something like "1" + "2", which may lead to expecting either a result of "12" or "3". (Obviously, the real result is "12", but if I scanned over that in the middle of a page of unfamiliar code, I might not see the obvious... especially since, as I understand it, that same code in Perl *would* yield 3!) Jeff Shannon Technician/Programmer Credit International From jeff@ccvcorp.com Thu Feb 6 12:24:08 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Thu Feb 6 12:24:08 2003 Subject: [Tutor] Sometimes unreferenced!? References: Message-ID: <3E429A16.5000501@ccvcorp.com> John Abbe wrote: > def f(): > records = [4, 5] > groupData += records > UnboundLocalError: local variable 'groupData' referenced before > assignment This is one of the standard local/global scope traps -- everyone trips over it at some point. The trick is that the parser examines every variable in a function as it's reading in the def, and decides at that time whether a variable is local or global. Local variables get special treatment (resulting in much faster lookup times, etc), and the key to deciding whether a variable is local or global is whether the name is bound (or re-bound) within the function. (Anything that creates a new object for the name to point to is re-binding.) In your first function e(), you modify the object that groupData points to, by calling its reverse() method. But it's still the same list object, so there's no re-binding, so groupData is considered a global name. This means that Python looks it up properly at runtime. In your f() function, though, you use += to create a *new* list (which is the union of groupData and records), and then re-bind groupData to point to that new list. Here's where things get tricky -- Python sees the re-binding before running the code, so it presumes that groupData is a local variable here. So a new, local name is created that shadows the global groupData. Now, 'groupData += records' is (loosely) equivalent to 'groupData = groupData + records', so Python tries to look up the contents of the (local) groupData variable to add them to the contents of the 'records' variable -- but at this point, the local version of groupData doesn't point to anything yet. There's a couple of ways to fix this problem. The first is to simply avoid using global variables. ;) There's actually quite a few reasons to avoid them, as they tend to make confusing code easier to write. If you re-write your functions so that groupData is passed in as a parameter and then returned as a result, it doesn't matter whether it shadows a global variable or not -- you'll always get the expected results because you're always dealing with local variables. The second way is to simply inform the interpreter that the re-binding in f() is *not* intended to create a local variable. This is done with the 'global' keyword -- you're letting Python know that, in this function, the given variable should be considered global and no shadowing local variable should be created. def f(): global groupData records = [4, 5] groupData += records Hope this clarifies a few things. Feel free to ask more questions if there's anything unclear, though. Jeff Shannon Technician/Programmer Credit International From eprice@ptc.com Thu Feb 6 12:41:16 2003 From: eprice@ptc.com (Erik Price) Date: Thu Feb 6 12:41:16 2003 Subject: [Tutor] capitalize() but only first letter In-Reply-To: <3E429698.4030305@ccvcorp.com> References: <3E429698.4030305@ccvcorp.com> Message-ID: <3E429DB3.5030007@ptc.com> Jeff Shannon wrote: [...] Thanks for the clarification, Jeff. > As a minor additional (pun not intended) point, I have a personal > preference to avoid using + with strings because eventually, that's > going to lead to code that reads something like "1" + "2", which may > lead to expecting either a result of "12" or "3". I changed my script to use the sprintf-style method, since it just "felt" more appropriate than using list.append().join(). It looks a lot beter now. I'm still somewhat confused since I would think that the following tuple uses four throwaway objects (three strings and the tuple itself), but I can see that you don't add an "additional" intermediate string between each string element of the tuple when you use join(). t = ("first", "second", "third") > (Obviously, the real > result is "12", but if I scanned over that in the middle of a page of > unfamiliar code, I might not see the obvious... especially since, as I > understand it, that same code in Perl *would* yield 3!) You're right, though it's because Perl doesn't use + for concat (it uses a dot, which is kind of a pain since most OO langs use that for dot notation of object and method calls, so Perl had to use an arrow (->), which is even uglier than normal Perl code). Erik From dyoo@hkn.eecs.berkeley.edu Thu Feb 6 14:41:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Feb 6 14:41:02 2003 Subject: [Tutor] Apply() [function calling depends on end parentheses] In-Reply-To: <1E0F17B4-39D5-11D7-AB64-00039351FE6A@mac.com> Message-ID: On Thu, 6 Feb 2003, Erik Price wrote: > > On Thursday, February 6, 2003, at 02:45 AM, Danny Yoo wrote: > > > The part that would normally involve 'apply()' is the line: > > > > print cmds[c](*rest) > > > > > > With apply(), that might look like: > > > > print apply(cmds[c], rest) > > > > > > > > Hope this helps! > > Yes, I think I understand ... you can just add parens to the end of any > name and, if a function has been defined with that name, it will be > called? Hi Erik, Yes, very much so. The big concept here is that functions are values, just like numbers and strings: ### >>> def sayHello(): ... print "hello" ... >>> sayHello() hello >>> def doItTwice(some_function): ... some_function() ... some_function() ... >>> doItTwice(sayHello) hello hello ### We're passing a function value, ### >>> sayHello ### off to our doItTwice() function, as if it were a regular value. And they are! Function values can be stuffed into dictionaries, boxed off into lists, or even passed off as arguments to other functions. The thing that makes functions unique from values, like strings and numbers, is that they can be "called" by using those parentheses at the end. In technical terms, functions can be "applied" or "called". In some programming languages, the term "apply" is prevalent, but in Python, it looks like "call" is the term that is most frequently used. (Perhaps the 'apply()' builtin should have been renamed as 'call()'... but I'm just digressing. *grin*) That's what makes something like: ### >>> f = sayHello >>> f() hello ### possible: 'f' is a name that's directed to the same function value. The first statement doesn't do an application: it merely does a variable name assignment, just like any other assignment we've seen. We can still get 'f' to fire off by doing the parentheses "application". This is also one reason why, if we forget the parentheses, that "nothing" happens: ### >>> sayHello >>> f ### Nothing fires off, but that's because we haven't told Python to call. So the parentheses are the things that triggers functions to "apply" in Python. But what happens if we try adding ending parentheses on something that isn't a function? ### >>> s = "foobar" >>> s() Traceback (most recent call last): File "", line 1, in ? TypeError: 'str' object is not callable ### Please feel free to ask more questions about this. I hope this helps! From jeff@ccvcorp.com Thu Feb 6 14:42:02 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Thu Feb 6 14:42:02 2003 Subject: [Tutor] capitalize() but only first letter References: <3E429698.4030305@ccvcorp.com> <3E429DB3.5030007@ptc.com> Message-ID: <3E42BA26.5070802@ccvcorp.com> Erik Price wrote: > I'm still somewhat confused since I would think that the following > tuple uses four throwaway objects (three strings and the tuple > itself), but I can see that you don't add an "additional" intermediate > string between each string element of the tuple when you use join(). > > t = ("first", "second", "third") But those three strings are your source strings, and are necessarily present in *any* concatenation. t = "first" + "second" + "third" has those same three strings, plus it generates the string "firstsecond" which is thrown away, before creating the complete string which is bound to t. (Yes, this does seem to imply that only when there are more than two string additions would the sprintf-style formatting be likely to yield notable performance benefits, but I would still argue that it's preferable for appearance and consistency.) Jeff Shannon Technician/Programmer Credit International From eprice@ptc.com Thu Feb 6 15:20:02 2003 From: eprice@ptc.com (Erik Price) Date: Thu Feb 6 15:20:02 2003 Subject: [Tutor] Apply() [function calling depends on end parentheses] In-Reply-To: References: Message-ID: <3E42C321.4040201@ptc.com> Danny Yoo wrote: [...] > The thing that makes functions unique from values, like strings and > numbers, is that they can be "called" by using those parentheses at the > end. In technical terms, functions can be "applied" or "called". In some > programming languages, the term "apply" is prevalent, but in Python, it > looks like "call" is the term that is most frequently used. (Perhaps the > 'apply()' builtin should have been renamed as 'call()'... but I'm just > digressing. *grin*) After reading the link you sent earlier in this thread, I noticed that the term "callable" is found all over the Python docs. So Python is a lot different from Java, since I don't think that Java considers its "callables" (method names) to be true objects that can be passed around and referenced with different names. > That's what makes something like: > > ### > >>>>f = sayHello >>>>f() > > hello > ### > > possible: 'f' is a name that's directed to the same function value. The > first statement doesn't do an application: it merely does a variable name > assignment, just like any other assignment we've seen. We can still get > 'f' to fire off by doing the parentheses "application". That cool! I have never done something like that. It would seem like there could be some obscure uses for this (like calling different functions from within a loop, as if the function was an object and we were using polymorphism) but I wonder how often they are used in practice? I have no formal training in programming so I am not familiar with this kind of thing, but isn't this related to something called functional programming? I think I have seen people on this list talk about Lisp having features like this (long time ago so I can't remember, I've been off this list for a long time). [...] > Please feel free to ask more questions about this. I hope this helps! I have one last question -- where do you learn about these kinds of advanced Python concepts, once you've gotten past the understanding of functions and basic data types, etc (other than here)? And where do you see them actually applied in the Real World? Thanks Danny. Erik From magnus@thinkware.se Thu Feb 6 16:26:36 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Thu Feb 6 16:26:36 2003 Subject: [Tutor] capitalize() but only first letter In-Reply-To: <20030206033202.9388.8784.Mailman@mail.python.org> Message-ID: <5.1.0.14.0.20030206213927.02cabb20@www.thinkware.se> Erik Price wrote: > I'm using the capitalize() >method of the Python String type, and although this does capitalize the >first letter of the word, it lowercases all the rest of the letters. I >need to capitalize just the first letter and leave all the other letters >in the word alone. Use regular expressions (RE). >>> import re >>> def upper(matchobj): ... return matchobj.group(0).upper() ... >>> re.sub(r'\b\w', upper, 'thIs is a stRiNG wiTh miXed cAsEs') 'ThIs Is A StRiNG WiTh MiXed CAsEs' What's this? First of all, the RE pattern itself: r'\b\w' r'' means raw string, i.e. don't interpret the \ as starting an escape sequence, just store the string as I typed it. So, while '\t' means "a tab character", r'\t' means "a bacslash followed by a t". So, r'\b\w' is the same as '\\b\\w', but more convenient. \b means word boundry, and \w means alphanumeric character. A word boundry followed by an alphanumeric is the start of a word, right? re.sub(pattern, whatToSubstituteWith, aString) re.sub stands for substitute, so re.sub(r'\b\w', 'X', 'hi there') would return 'Xi Xhere'. But instead of a string to substitute with, we can supply a function. This function will be fed with a RE match object for each RE match in the string. In this case the first character in each word. I wrote def upper(matchobj): return matchobj.group(0).upper() Some RE pattens are quite complex and can extract several different parts of a string at once. These all end up in a "group" each, in this case we just get one group in each match, so we need to extract that from the match object, apply the .upper() method to it, and return it. The re module is written in C, and perhaps not quite as fast as Perl's, but quite reasonable for large volume string manipulation. -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From gp@pooryorick.com Thu Feb 6 19:19:01 2003 From: gp@pooryorick.com (Poor Yorick) Date: Thu Feb 6 19:19:01 2003 Subject: [Tutor] capitalize() but only first letter References: <5.1.0.14.0.20030206213927.02cabb20@www.thinkware.se> Message-ID: <3E42FBAE.8000805@pooryorick.com> Magnus Lycka wrote: > > Use regular expressions (RE). Thanks, for this RE tutorial. I've been trying to digest RE's for quite a while, and little examples like this really help. Poor Yorick gp@pooyorick.com From shalehperry@attbi.com Thu Feb 6 20:22:03 2003 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Thu Feb 6 20:22:03 2003 Subject: [Tutor] adding methods to native types In-Reply-To: <2C5D363E-39D6-11D7-AB64-00039351FE6A@mac.com> References: <2C5D363E-39D6-11D7-AB64-00039351FE6A@mac.com> Message-ID: <200302061721.09460.shalehperry@attbi.com> On Thursday 06 February 2003 05:23, Erik Price wrote: > On Thursday, February 6, 2003, at 12:20 AM, Sean 'Shaleh' Perry wrote: > > easy answer: it has been that way since Python began. > > > > much of python lets you interact with objects without actually using > > methods. > > I think len() is one of those vestiges. > > > > I wonder if it had something to do with trying to ease people into OO > > (Python > > was meant to help those learning programming). > > Okay. So there's nothing wrong with doing: > > class MyList(): > def __init__(self): > self._mylist =3D [] > > def len(self): > return len(self) > > ? > return len(self._mylist) you mean yes using has-a v. is-a would be a valid approach as well. > It feels "dirty" to use the __init__ method since it has those magic > underscores (I feel the same way about using if __name__ =3D=3D > "__main__"). But there is no other name for the constructor, right? > the double underscore methods are needed to implement things. You should= not=20 however see them in common, run of the mill code. Things like __init__ are the way classes are designed and implemented. Y= ou=20 have no choice but to use them. The __name__ =3D=3D "__main__" is indeed= a hack=20 but it has become a standard, expected idiom. From tony@tcapp.com Fri Feb 7 02:11:31 2003 From: tony@tcapp.com (Tony Cappellini) Date: Fri Feb 7 02:11:31 2003 Subject: [Tutor] Looking for Python equivalents of some C functions Message-ID: <5.1.0.14.0.20030206231734.0464cce0@smtp.sbcglobal.net> Are there Python equivalents for the following C functions ? sprintf() fprintf() I didn't see anything suitable in the strings module references. itoa() ltoa() ftoa() // float or double to asciii From shalehperry@attbi.com Fri Feb 7 03:14:01 2003 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Fri Feb 7 03:14:01 2003 Subject: [Tutor] Looking for Python equivalents of some C functions In-Reply-To: <5.1.0.14.0.20030206231734.0464cce0@smtp.sbcglobal.net> References: <5.1.0.14.0.20030206231734.0464cce0@smtp.sbcglobal.net> Message-ID: <200302070013.23532.shalehperry@attbi.com> On Thursday 06 February 2003 23:19, Tony Cappellini wrote: > Are there Python equivalents for the following C functions ? > > sprintf() > fprintf() > import sys sys.stderr.write("My name is %s" % name) # equiv of fprintf(stderr, "My name is %s", name); name =3D "%s, %s" % (last_name, first_name) # equiv of sprintf(name, "%s, %s", last_name, first_name); > I didn't see anything suitable in the strings module references. > > itoa() > ltoa() > ftoa() // float or double to asciii > str(), int(), float() will do that conversions you want. From johnca@ourpla.net Fri Feb 7 05:17:01 2003 From: johnca@ourpla.net (John Abbe) Date: Fri Feb 7 05:17:01 2003 Subject: [Tutor] Sometimes unreferenced!? In-Reply-To: <3E429A16.5000501@ccvcorp.com> References: <3E429A16.5000501@ccvcorp.com> Message-ID: At 9:23 AM -0800 on 2003-02-06, Jeff Shannon typed: >John Abbe wrote: > >>def f(): >> records = [4, 5] >> groupData += records > >>UnboundLocalError: local variable 'groupData' referenced before assignment > >The trick is that the parser examines every variable in a function >as it's reading in the def, and decides at that time whether a >variable is local or global. > >In your first function e(), you modify the object that groupData >points to, by calling its reverse() method. But it's still the same >list object, so there's no re-binding, so groupData is considered a >global name. This means that Python looks it up properly at runtime. > >In your f() function, though, you use += to create a *new* list >(which is the union of groupData and records), and then re-bind >groupData to point to that new list. Here's where things get tricky >-- Python sees the re-binding before running the code, so it >presumes that groupData is a local variable here. >So a new, local name is created that shadows the global groupData. >Now, 'groupData += records' is (loosely) equivalent to 'groupData = >groupData + records', so Python tries to look up the contents of the >(local) groupData variable to add them to the contents of the >'records' variable -- but at this point, the local version of >groupData doesn't point to anything yet. Okay, i understand *that* this is happening (and thanks for the fix), but i don't get why. If the parser can know that groupData is a global variable and thus not choke on groupData.reverse(), then why can't it know that groupData is a global variable when the function tries to look up its contents? Life, John -- All you /\/\ John Abbe "If you don't like the news, need \ / CatHerder go out and make some of your own." is... \/ http://ourpla.net/john/ --Wes Nisker From alan.gauld@bt.com Fri Feb 7 06:32:02 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Fri Feb 7 06:32:02 2003 Subject: [Tutor] My serial prog and prob Message-ID: <7497DCA1C240C042B28F6657ADFD8E097023D7@i2km11-ukbr.domain1.systemhost.net> > I would appreciate any advice on where i am going wrong. > The data comes in as > ' - 2345 4565 - 5678 ' My first guess would be to use a regular exression and re.split() Or maybe re.findall() would be better... You can define a regex to extract anything followed by a group of numbers. Split after the numbers. Then maybe strip() the results and get rid of the space between - and the first digit (assuming its supposed to be a minus?). Finally convert to a number... OTOH they look like they might be fixed length fields (although the last one doesn't quite fit). Did you cut n' paste or is it an approximation? If they are fixed length then slicing/indexing is a better alternative. Alan g. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld/ From alan.gauld@bt.com Fri Feb 7 06:59:01 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Fri Feb 7 06:59:01 2003 Subject: [Tutor] capitalize() but only first letter Message-ID: <7497DCA1C240C042B28F6657ADFD8E097023D8@i2km11-ukbr.domain1.systemhost.net> > I'm still somewhat confused since I would think that the > following tuple uses four throwaway objects > > t = ("first", "second", "third") It does in this case. But if you used the hard wored stringsa in the join() technique they'd also be throwaway there too. But in this case: s1 = 'first' s2 = 'second' s3 = 'third' s4 = '%s %s %s' % (s1,s2,s3) Then only the tuple is temporary, we keep s1,s2,s3 for later use. but s3 = s1 + ' ' + s2 + ' ' + s3 creates 3 temporary strings whilst still keeping s1,s2 and s3. > notation of object and method calls, so Perl had to use an > arrow (->), > which is even uglier than normal Perl code). In fact I rather like the -> notation for objects, to me it is more reminiscent of a message being sent to the object than a dot is. But it's an extra character to typec and bucks the general OO language trend. Alan g. From Don Arnold" Message-ID: <035c01c2cea1$b3628530$b1d1b241@defaultcomp> ----- Original Message ----- From: "Tony Cappellini" To: Sent: Friday, February 07, 2003 1:19 AM Subject: [Tutor] Looking for Python equivalents of some C functions > > > Are there Python equivalents for the following C functions ? > > sprintf() Take a look at http://www.python.org/doc/current/lib/typesseq-strings.html and you'll see that you can use (almost?) all of C's string fromatting operators in Python: >>> a = 'This string has %d %s.' % (5,'words') >>> print a This string has 5 words. > fprintf() This can be done using the print statement: myfile = open('temp') print >> myfile, '%s %d %l' % ('stuff', 10, 28328738273L) > > I didn't see anything suitable in the strings module references. > > itoa() > ltoa() > ftoa() // float or double to asciii These are all covered by the built-in str( ) function: >>> for i in (10, 2343224234234L, 4.52): print 'result = ' + str(i) result = 10 result = 2343224234234 result = 4.52 HTH, Don From alan.gauld@bt.com Fri Feb 7 07:10:11 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Fri Feb 7 07:10:11 2003 Subject: [Tutor] Apply() [function calling depends on end parenthese s] Message-ID: <7497DCA1C240C042B28F6657ADFD8E0974DAB2@i2km11-ukbr.domain1.systemhost.net> > lot different from Java, since I don't think that Java considers its > "callables" (method names) to be true objects that can be > passed around and referenced with different names. It certainly doesn't, which is one reason they had to introduce the dreadful inner class stuff! You define a bunch of inner classes(*) that have a single method then you can instantiate whichever inner class you need then call it's method - yech! And it's still rubbish because the method names have to be the same etc. One reason why for non trivial code C++ often works out shorter than Java despite the hype. At least C++ includes the concept of method pointers! Alan g. (*) Java also allows anonymous inner classes which are directly analagous to Python's lambdas. From Anwar.Lorenzo@gmx.net Fri Feb 7 07:15:02 2003 From: Anwar.Lorenzo@gmx.net (Anwar.Lorenzo@gmx.net) Date: Fri Feb 7 07:15:02 2003 Subject: [Tutor] List exercise Message-ID: <3E441772.17884.AF49B4@localhost> Hi I'm trying to solve the exercise: As an exercise, write a loop that traverses the previous list (['spam!', 1, ['Brie', 'Roquefort', 'Pol le Veq'], [1, 2, 3]]) and prints the length of each element. What happens if you send an integer to len? (exercise from 8.3) from the ebook How To Think Like A Computer Scientist: Learning with Python. I've coded a function to solve this but it doesn't seem to work. IDLE just hangs when I execute this function. Here's my solution: def exerSize(): exer = ['spam!', 1, ['Brie', 'Roquefort', 'Pol le Veq'], [1, 2, 3]] i = 0 while i < len(exer): len(exer[i]) i = i + 1 Thanks in advance! -Anwar From erikprice@mac.com Fri Feb 7 07:50:02 2003 From: erikprice@mac.com (Erik Price) Date: Fri Feb 7 07:50:02 2003 Subject: OT: Re: [Tutor] Apply() [function calling depends on end parenthese s] In-Reply-To: <7497DCA1C240C042B28F6657ADFD8E0974DAB2@i2km11-ukbr.domain1.systemhost.net> Message-ID: <9091F7FE-3A9C-11D7-B368-00039351FE6A@mac.com> On Friday, February 7, 2003, at 07:08 AM, alan.gauld@bt.com wrote: > It certainly doesn't, which is one reason they had to introduce the > dreadful inner class stuff! > > You define a bunch of inner classes(*) that have a single method > then you can instantiate whichever inner class you need then > call it's method - yech! I've never done anything like that in Java, actually. Part of it must be that I'm still a relative newcomer to Java, too. I thought that Java's inner classes were a means of simulating multiple inheritance. (When implementing multiple interfaces won't do the trick because you need some kind of implementation functionality from the parent class.) Because the inner class has access to the enclosing class's members and operations, you can have the inner class inherit from a diff't class than the enclosing class and write the whole thing to do whatever it is you need from both parent classes. And I thought that anonymous inner classes were primarily used for code organization, say you need an event handler for some control X, but you don't use it anywhere else in the application, then why bother making a separate public class just for that one case -- just tuck it inside the class that needs it, etc. I have not had opportunity to use inner classes in the way that you describe (to make dynamic callables), but yes, it does sound like a lot more work than the Python way. Erik -- Erik Price email: erikprice@mac.com jabber: erikprice@jabber.org From erikprice@mac.com Fri Feb 7 07:54:01 2003 From: erikprice@mac.com (Erik Price) Date: Fri Feb 7 07:54:01 2003 Subject: [Tutor] List exercise In-Reply-To: <3E441772.17884.AF49B4@localhost> Message-ID: <287B972E-3A9D-11D7-B368-00039351FE6A@mac.com> On Friday, February 7, 2003, at 07:30 AM, Anwar.Lorenzo@gmx.net wrote: > just hangs when I execute this function. > > Here's my solution: > > def exerSize(): > exer = ['spam!', 1, ['Brie', 'Roquefort', 'Pol le Veq'], [1, 2, 3]] > i = 0 > while i < len(exer): > len(exer[i]) > i = i + 1 Hi Anwar, I think the reason your program hangs is because you have an infinite loop. The "while" loop says "while i is less than the length of exer", and since i is zero, this loop is always true, and never stops. If you were thinking that your i variable would increment on each iteration of the loop (by using "i = i + 1"), the problem is that that line is outside of the loop. So that line only executes after the loop is done iterating, but because it's an infinite loop, it never stops. Try putting that i = i + 1 line inside the while loop and see what your program does. while i < len(exer): len(exer[i]) i = i + 1 # all you have to do is indent it to line up with the previous line Erik -- Erik Price email: erikprice@mac.com jabber: erikprice@jabber.org From alan.gauld@bt.com Fri Feb 7 08:28:02 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Fri Feb 7 08:28:02 2003 Subject: [Tutor] Apply() [function calling depends on end parent hese s] Message-ID: <7497DCA1C240C042B28F6657ADFD8E097023DA@i2km11-ukbr.domain1.systemhost.net> > > It certainly doesn't, which is one reason they had to introduce the > > dreadful inner class stuff! > > > be that I'm still a relative newcomer to Java, too. I thought that > Java's inner classes were a means of simulating multiple > inheritance. Yes, you can use them for that too, that's why I said 'one reason' Inner classes are a horrible way to provide work-arounds for a lot of fundamental flaws in the original language. > And I thought that anonymous inner classes were primarily > used for code organization, say you need an event handler > for some control Which is very often what you use lambdas for in Python. call back functions in Tkinter etc. > then why bother making a separate public class just for > that one case Which is exactly the argument for lambdas - why bother creating a function for a one-off use. > I have not had opportunity to use inner classes in the way that you > describe (to make dynamic callables), but yes, it does sound > like a lot more work than the Python way. Yes, and its the only way to approximate dynamic dispatch in Java. eg Tables of functions where you want to walk down the table calling each function but changing the content of the table between runs, or even as you go! Alan g. From Anwar.Lorenzo@gmx.net Fri Feb 7 08:38:04 2003 From: Anwar.Lorenzo@gmx.net (Anwar.Lorenzo@gmx.net) Date: Fri Feb 7 08:38:04 2003 Subject: [Tutor] List exercise In-Reply-To: <287B972E-3A9D-11D7-B368-00039351FE6A@mac.com> References: <3E441772.17884.AF49B4@localhost> Message-ID: <3E442ADB.4907.FB1D7C@localhost> > > On Friday, February 7, 2003, at 07:30 AM, Anwar.Lorenzo@gmx.net wrote: > > > just hangs when I execute this function. > > > > Here's my solution: > > > > def exerSize(): > > exer = ['spam!', 1, ['Brie', 'Roquefort', 'Pol le Veq'], [1, 2, 3]] > > i = 0 > > while i < len(exer): > > len(exer[i]) > > i = i + 1 > > Hi Anwar, > > I think the reason your program hangs is because you have an infinite > loop. The "while" loop says "while i is less than the length of exer", > and since i is zero, this loop is always true, and never stops. If you > were thinking that your i variable would increment on each iteration of > the loop (by using "i = i + 1"), the problem is that that line is > outside of the loop. So that line only executes after the loop is done > iterating, but because it's an infinite loop, it never stops. > > Try putting that i = i + 1 line inside the while loop and see what your > program does. > > while i < len(exer): > len(exer[i]) > i = i + 1 # all you have to do is indent it to line up with > the previous line > > > > Erik > > > > > > -- > Erik Price > > email: erikprice@mac.com > jabber: erikprice@jabber.org > I've tried indenting that line (i = i + 1) but I got this error: Traceback (most recent call last): File "", line 1, in ? exerSize() File "", line 5, in exerSize len(exer[i]) TypeError: len() of unsized object From Janssen@rz.uni-frankfurt.de Fri Feb 7 09:27:01 2003 From: Janssen@rz.uni-frankfurt.de (Michael Janssen) Date: Fri Feb 7 09:27:01 2003 Subject: [Tutor] List exercise In-Reply-To: <3E442ADB.4907.FB1D7C@localhost> Message-ID: On Fri, 7 Feb 2003 Anwar.Lorenzo@gmx.net wrote: > I've tried indenting that line (i = i + 1) but I got this error: > Traceback (most recent call last): > File "", line 1, in ? > exerSize() > File "", line 5, in exerSize > len(exer[i]) > TypeError: len() of unsized object > now, variable i is incrementing and therefore exer[i] returns it's items from index position 0 till last index of exer. But at least one of this items is an object which isn't sized (as the traceback mentions): this means it's forbidden to run len() about. For Example: integer 10 is unsized, since it doesn't make sence to speak of the length of an integer. To find out, which item is of an unsized type, you could do: 1.) Print every item before run len() over it. Last printed item before traceback is the critical one. while i < len(exer): print exer[i] len(exer) 2.) Enhance this: while i < len(exer): print i, type(exer[i]), exer[i] # gives you more informations len(exer) 3.) Catch the exception, and print information only for the critical item. while i < len(exer): try: len(exer) except TypeError: print i,type(exer[i]),exer[i] 4.) You can - of course - look through your code and find out what type of object did you actually stick into exer. You will find, that you've got an integer in your example code. In the case you want to have a list "exer" with sized an unsized types mixed and also want to get the length of each list-item, you need to put solution 3. into your code and provide a sensible method to handle unsized objects: you can "pass" them or do len(str(exer[i])) or anything else you find suitable. Michael > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From eprice@ptc.com Fri Feb 7 10:45:02 2003 From: eprice@ptc.com (Erik Price) Date: Fri Feb 7 10:45:02 2003 Subject: [Tutor] capitalize() but only first letter In-Reply-To: <5.1.0.14.0.20030206213927.02cabb20@www.thinkware.se> References: <5.1.0.14.0.20030206213927.02cabb20@www.thinkware.se> Message-ID: <3E43D420.10201@ptc.com> Magnus Lycka wrote: > Use regular expressions (RE). > > >>> import re > >>> def upper(matchobj): > ... return matchobj.group(0).upper() > ... > >>> re.sub(r'\b\w', upper, 'thIs is a stRiNG wiTh miXed cAsEs') > 'ThIs Is A StRiNG WiTh MiXed CAsEs' [...] > re.sub(pattern, whatToSubstituteWith, aString) > > re.sub stands for substitute, so re.sub(r'\b\w', 'X', 'hi there') > would return 'Xi Xhere'. But instead of a string to substitute > with, we can supply a function. > > This function will be fed with a RE match object for each RE > match in the string. In this case the first character in each > word. I'm not sure I understand why this works. As I understand it, you're saying: 1. The re.sub() function accepts a string as its second argument 2. The re.sub() function will also accept a function name as its second argument 3. If the re.sub() function is passed a function name as its second argument, it will call that function and pass it a match object argument. Is there some kind of internal type checking done to determine if the argument is a string or a function name, or is this some esoteric feature of Python that I've never heard of at work? Erik From ljholish@speakeasy.net Fri Feb 7 12:21:31 2003 From: ljholish@speakeasy.net (Larry Holish) Date: Fri Feb 7 12:21:31 2003 Subject: [Tutor] List exercise In-Reply-To: <3E441772.17884.AF49B4@localhost> References: <3E441772.17884.AF49B4@localhost> Message-ID: <20030207172114.GA10196@badlands.philberts.org> On Fri, Feb 07, 2003 at 08:30:42PM +0800, Anwar.Lorenzo@gmx.net wrote: > Hi > I'm trying to solve the exercise: > > As an exercise, write a loop that traverses the previous list > (['spam!', 1, ['Brie', 'Roquefort', 'Pol le Veq'], [1, 2, 3]]) and > prints the length of each element. What happens if you send an > integer to len? (exercise from 8.3) > > from the ebook How To Think Like A Computer Scientist: Learning with > Python. > > I've coded a function to solve this but it doesn't seem to work. IDLE > > just hangs when I execute this function. > > Here's my solution: > > def exerSize(): > exer = ['spam!', 1, ['Brie', 'Roquefort', 'Pol le Veq'], [1, 2, 3]] > i = 0 > while i < len(exer): > len(exer[i]) > i = i + 1 The type() builtin may also be useful for this problem: import types if type(mylist) == types.ListType: print 'mylist is a list' -- Larry Holish From dyoo@hkn.eecs.berkeley.edu Fri Feb 7 12:30:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Feb 7 12:30:02 2003 Subject: [Tutor] Apply() [function calling depends on end parentheses] In-Reply-To: <3E42C321.4040201@ptc.com> Message-ID: On Thu, 6 Feb 2003, Erik Price wrote: > > > Danny Yoo wrote: > > [...] > > > The thing that makes functions unique from values, like strings and > > numbers, is that they can be "called" by using those parentheses at > > the end. In technical terms, functions can be "applied" or "called". > > In some programming languages, the term "apply" is prevalent, but in > > Python, it looks like "call" is the term that is most frequently used. > > (Perhaps the 'apply()' builtin should have been renamed as 'call()'... > > but I'm just digressing. *grin*) > > After reading the link you sent earlier in this thread, I noticed that > the term "callable" is found all over the Python docs. So Python is a > lot different from Java, since I don't think that Java considers its > "callables" (method names) to be true objects that can be passed around > and referenced with different names. Yes. In fact, it's very easy in Python to make something "callable": all an object needs is a "__call__" magic method: ### >>> class LabelMaker: ... def __init__(self, prefix): ... self.count = 1 ... self.prefix = prefix ... def __call__(self): ... next_label = "%s%d" % (self.prefix, self.count) ... self.count = self.count = 1 ... return next_label ... >>> header_maker = LabelMaker("header") >>> header_maker() 'header1' >>> header_maker() 'header1' ### *laugh* Doh... that statement in my __call__() was supposed to increment the count, but I wrote a typo: self.count = self.count = 1 rather than: self.count = self.count + 1 but I hope that the idea is coming though, even though the code above has that bug. Anyway, the idea of callable things is very general in Python, so that even class instances can look like functions. There's a builtin called 'callable()' that tells us if something looks callable or not: ### >>> callable(header_maker) 1 >>> callable("hello world") 0 >>> callable(callable) 1 ### > > That's what makes something like: > > > > ### > > > >>>>f = sayHello > >>>>f() > > > > hello > > ### > > > > possible: 'f' is a name that's directed to the same function value. > > The first statement doesn't do an application: it merely does a > > variable name assignment, just like any other assignment we've seen. > > We can still get 'f' to fire off by doing the parentheses > > "application". > > That cool! I have never done something like that. It would seem like > there could be some obscure uses for this (like calling different > functions from within a loop, as if the function was an object and we > were using polymorphism) but I wonder how often they are used in > practice? Tkinter GUI programming uses the idea of passing function values: if we pass a function to someone else, that someone can later call our function. If we make a button, we can tell that button, "If you get pressed, apply my function for me." Here's an example that tries to show this: ### import Tkinter import webbrowser def openPythonOrg(): webbrowser.open("http://python.org/doc/lib") b = Tkinter.Button(text="Press me to open Library Docs", command=openPythonOrg) b.pack() Tkinter.mainloop() ### Hey, instant bookmarks. *grin* It's the key to understanding why we do: b = Tkinter.Button(text="Press me to open Library Docs", command=openPythonOrg) and not: b = Tkinter.Button(text="Press me to open Library Docs", command=openPythonOrg()) Understanding functions --- that is, seeing how these "callable" things can be treated as passable values --- makes the "callback" idea in Tkinter very approachable. > > Please feel free to ask more questions about this. I hope this helps! > > I have one last question -- where do you learn about these kinds of > advanced Python concepts, once you've gotten past the understanding of > functions and basic data types, etc (other than here)? Actually, I picked up a lot of stuff from here on the mailing list. Stick around! *grin* I think "The Structure and Interpretation of Computer Programs" heavily influenced the way I think about programming: http://mitpress.mit.edu/sicp/ Although the book is not targeted specifically toward Python programmers, the ideas in SICP can be applied remarkably well in Python. But I have to admit a strong bias here, since the introductory CS courses at many colleges (including Berkeley) use SICP --- there may be something better out there that I haven't been exposed to yet. > And where do you see them actually applied in the Real World? The most down-to-earth example I can think of (this early in the morning) is list sort()ing. Think of what happens when we pass a comparison function to a list's sort method(): ### >>> def cmp_by_len(a, b): ... return cmp(len(a), len(b)) ... >>> words = "it was the best of times; it was the worst of times".split() >>> words.sort() >>> words ['best', 'it', 'it', 'of', 'of', 'the', 'the', 'times', 'times;', 'was', 'was', 'worst'] >>> words.sort(cmp_by_len) >>> words ['it', 'it', 'of', 'of', 'the', 'the', 'was', 'was', 'best', 'times', 'worst', 'times;'] ### I hope this helps! From hiddenworlds@hotmail.com Fri Feb 7 13:14:02 2003 From: hiddenworlds@hotmail.com (Jerry Brady) Date: Fri Feb 7 13:14:02 2003 Subject: [Tutor] Please remove me Message-ID:


Please remove me from your mailing list

Thank you



Tired of spam? Get advanced junk mail protection with MSN 8. From kyle@runbox.com Fri Feb 7 13:20:09 2003 From: kyle@runbox.com (Kyle Babich) Date: Fri Feb 7 13:20:09 2003 Subject: [Tutor] Learning Tkinter Message-ID: I'm trying to learn Tkinter which I've been putting off for a while but I f= eel it is now necesary. So soley for the purpose of simplicity I pumped my= entire program into a function called track then I added this below it: root =3D Tkinter.Tk() menubar =3D Tkinter.Menu(root) root.config(menu=3Dmenubar) filemenu =3D Tkinter.Menu(menubar) menubar.add_cascade(label=3D'File', menu=3Dfilemenu) filemenu.add_command(label=3D'Exit', command=3Dsys.exit) widget =3D Tkinter.Label(root, track) #Problem- running track within th= e window widget.config(bg=3D'white', fg=3D'black') widget.config(font=3D('courier', 10)) widget.pack(expand=3D'YES', fill=3D'both') root.mainloop() It is generally what I was going for considering it is my first GUI but how= would I run the former command line program that was put into the function= track within the GUI? Thank you, Kyle From jeff@ccvcorp.com Fri Feb 7 15:26:03 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Fri Feb 7 15:26:03 2003 Subject: [Tutor] Sometimes unreferenced!? References: <3E429A16.5000501@ccvcorp.com> Message-ID: <3E4415E2.1070102@ccvcorp.com> John Abbe wrote: > At 9:23 AM -0800 on 2003-02-06, Jeff Shannon typed: > >> The trick is that the parser examines every variable in a function as >> it's reading in the def, and decides at that time whether a variable >> is local or global. > > > Okay, i understand *that* this is happening (and thanks for the fix), > but i don't get why. If the parser can know that groupData is a global > variable and thus not choke on groupData.reverse(), then why can't it > know that groupData is a global variable when the function tries to > look up its contents? Because the parser doesn't know whether you intend the groupData in the function to be the same groupData as the global one. You may be working in a large program, and not even realize that there *is* a global variable by the same name. Python has decided that any variable that is created (i.e. the name is bound/re-bound) in a function is something that might or might not be intentionally different from any similar name in the global scope. So rather than guessing that you want to use the global, and possibly changing something that you don't expect and which will be very difficult to track down, Python throws an exception as a way of asking you to clarify just what your intent is. On the other hand, when you use a name that doesn't exist in the local scope (as in your first function), then Python decides that it's safe to assume that you know that the name exists in a containing (i.e., global) scope, so it looks there. I hope this clarifies things -- I know that it helps *me* a lot to understand just *why* a particular behavior is the way it is, it makes it much easier to remember and to predict other related behaviors... Jeff Shannon Technician/Programmer Credit International From jeff@ccvcorp.com Fri Feb 7 15:40:03 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Fri Feb 7 15:40:03 2003 Subject: [Tutor] List exercise References: <3E441772.17884.AF49B4@localhost> <20030207172114.GA10196@badlands.philberts.org> Message-ID: <3E441949.6010202@ccvcorp.com> Larry Holish wrote: >On Fri, Feb 07, 2003 at 08:30:42PM +0800, Anwar.Lorenzo@gmx.net wrote: > > >>As an exercise, write a loop that traverses the previous list >>(['spam!', 1, ['Brie', 'Roquefort', 'Pol le Veq'], [1, 2, 3]]) and >>prints the length of each element. What happens if you send an >>integer to len? (exercise from 8.3) >> >> > >The type() builtin may also be useful for this problem: > >import types >if type(mylist) == types.ListType: > print 'mylist is a list' > However, lists are not the only thing that have a length. Strings and tuples also have a length, and so do some class instances. In order to deal with all of those using type(), you'd have to have a series of if-clauses for each and every possibility... which you can't properly do, anyhow, because an object might be a class instance that defines its own __len__(), or it might be a subclass of a list, or any of a number of other possibilities. One of the standard Python idioms is that it's easier to ask forgiveness than to ask permission. In other words, try it but be ready to catch an exception. >>> def ExerSize(): ... exer = ['spam!', 1, ['Brie', 'Roquefort', 'Pol le Veq'], [1, 2, 3]] ... i = 0 ... while i < len(exer): ... try: ... print len(exer[i]) ... except TypeError: ... print "Item does not have a length!" ... i = i + 1 ... >>> ExerSize() 5 Item does not have a length! 3 3 >>> Note, also, that there's a better way to examine every item in a list than to use an explicitly incremented index variable. The Python for loop takes any sequence (list, tuple, string, etc) and iterates over each element in that sequence. So the previous code can be re-written like this: >>> def ExerSize(): ... exer = ['spam!', 1, ['Brie', 'Roquefort', 'Pol le Veq'], [1, 2, 3]] ... for item in exer: ... try: ... print len(item) ... except TypeError: ... print "Item does not have a length!" ... >>> ExerSize() 5 Item does not have a length! 3 3 >>> You get exactly the same results, and the code is less confusing and less likely to have odd errors (like the infinite loop due to an indentation error). Jeff Shannon Technician/Programmer Credit International From magnus@thinkware.se Fri Feb 7 15:59:01 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Fri Feb 7 15:59:01 2003 Subject: [Tutor] capitalize() but only first letter In-Reply-To: <3E43D420.10201@ptc.com> References: <5.1.0.14.0.20030206213927.02cabb20@www.thinkware.se> <5.1.0.14.0.20030206213927.02cabb20@www.thinkware.se> Message-ID: <5.1.0.14.0.20030207195702.02afe440@www.thinkware.se> At 10:43 2003-02-07 -0500, Erik Price wrote: >I'm not sure I understand why this works. Why not? The world doesn't HAVE to be complicated just because most other programming languages are! In Python almost everything is a first class object. It's uniform as no other language that I know. We often call this quality orthogonality. The X and Y axis in a ordinary coordinate system is orthogonal, which means that the X value won't change just because you change the Y value of a point and vice versa. This means that you can concern yourself with one thing at a time. In a similar spirit, the way we pass objects to functions doesn't depend on their type in Python. Any object can be passed to a function. (It's another issue whether that function can deal with any object). Any object can be printed. Any object can be compared with any other object and so on. It's very regular. We quickly find our way in Python, because the different parts of the language are so similar and regular. Think about the sprintf, fprintf question earlier. If you can format a string and write to a file, you can write a formatted string to a file in Python. In C you need to know a particular function for that context. It's as if Python was a city with streets going north to south, and avenue going west to east. If houses are addressed like "the corner of Formatting street and Print Avenue", you need to know all the streets to find any address. So if there are 100 streets and 100 avenues, you need to be able to locate 200 things to find any place in the city. C is more like a city where every house has a name of it's own... Just because you know the Print Formatting house doesn't mean that you know where File Formatting house is. It might be close... But you still have 10 000 house names to memorize. In reality, there are much more than two dimensions in prorgamming. On the other hand, not all intersections are meaningful... >As I understand it, you're saying: > >1. The re.sub() function accepts a string as its second argument Yes. >2. The re.sub() function will also accept a function name as its second >argument Well, a function! Either we say "a string or a function", or we say "the name of a string or the name of a function". I don't know why you change perspectives like that. Strings and functions are both objects, just as classes, instances, modules and integers etc. Simple objects like strings and numbers can be stated explicitly like "Hello" or 3.14, but typically we pass objects by providing some kind of name or reference. The reference might be the left hand side of an assignment, as in "a = 5" or it might be a name from a definition like "def f(x): return x*x" or "class A: pass" or it can be the the return value from a function call etc. It's often some kind of name... >3. If the re.sub() function is passed a function name as its second >argument, it will call that function and pass it a match object argument. Yes. > Is there some kind of internal type checking done to determine if the > argument is a string or a function name, Yes, normal Python code can do that, and C as well. > or is this some esoteric feature of Python that I've never heard of at work? No magic. Could hypothetically be something like this... (I'm sure it's not implemented anything like this really, Fredrik Lundh wrote it in C...) def sub(pattern, replacement, text): ... import types while .... : match = ... beforeMatch = ... afterMatch = ... if type(replacement) == types.FunctionType: text = beforeMatch+replacement(match)+afterMAtch else: text = beforeMatch+replacement+afterMatch ... return text -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From antonmuhin at rambler.ru" References: <3E441772.17884.AF49B4@localhost> Message-ID: <13235428693.20030207215544@rambler.ru> Hello Anwar, Friday, February 7, 2003, 3:30:42 PM, you wrote: ALgn> Hi ALgn> I'm trying to solve the exercise: ALgn> As an exercise, write a loop that traverses the previous list ALgn> (['spam!', 1, ['Brie', 'Roquefort', 'Pol le Veq'], [1, 2, 3]]) and ALgn> prints the length of each element. What happens if you send an ALgn> integer to len? (exercise from 8.3) ALgn> from the ebook How To Think Like A Computer Scientist: Learning with ALgn> Python. ALgn> I've coded a function to solve this but it doesn't seem to work. IDLE ALgn> just hangs when I execute this function. ALgn> Here's my solution: ALgn> def exerSize(): ALgn> exer = ['spam!', 1, ['Brie', 'Roquefort', 'Pol le Veq'], [1, 2, 3]] ALgn> i = 0 ALgn> while i < len(exer): ALgn> len(exer[i]) ALgn> i = i + 1 ALgn> Thanks in advance! ALgn> -Anwar BTW: the common idiom in Python for iterating through the list is: for item in exer: # do something For example, your exercise with note by Michael Janssen (see the letter for more details) might look: def printLens(l): for item in l: try: print len(item) except TypeError: print "No len for", item if __name__ == "__main__": printLens(['spam!', 1, ['Brie', 'Roquefort', 'Pol le Veq'], [1, 2, 3]]) -- Best regards, anton mailto:antonmuhin@rambler.ru From benvpatel@yahoo.com Fri Feb 7 20:48:08 2003 From: benvpatel@yahoo.com (Ben Patel) Date: Fri Feb 7 20:48:08 2003 Subject: [Tutor] Question Message-ID: <20030201223212.10349.qmail@web14608.mail.yahoo.com> --0-1924568497-1044138732=:10225 Content-Type: text/plain; charset=us-ascii Hello: I would like to write a program to calculate age of a person based on the birth date entered (in any format). Any help would be appreciated. Thanks in advance ! Ben --------------------------------- Do you Yahoo!? Yahoo! Mail Plus - Powerful. Affordable. Sign up now --0-1924568497-1044138732=:10225 Content-Type: text/html; charset=us-ascii

Hello:

I would like to write a program to calculate age of a person based on the birth date entered (in any format).

Any help would be appreciated.

Thanks in advance !

Ben



Do you Yahoo!?
Yahoo! Mail Plus - Powerful. Affordable. Sign up now --0-1924568497-1044138732=:10225-- From project5@redrival.net Fri Feb 7 20:48:16 2003 From: project5@redrival.net (A) Date: Fri Feb 7 20:48:16 2003 Subject: [Tutor] PIL - line width Message-ID: <20030202225633.112BE3B28@sitemail.everyone.net> Hello everyone, I'm a beginner-level pythoneer and have been lurking on the list for quite some time now, picking up bits of advice. Now I'm working on my first Python project of over 30 lines and I need to draw images. I've got the PIL and I know how to draw with it, but I can't find (in the docs) any way to change the line width. I could draw several lines near each other to accomplish this. This is not just inconvenient, but presents another problem as well: I don't need just horizontal/vertical lines, but also arcs. Drawing two arcs next to each other will not always result in a smooth extra wide arc. Instead, there will be background-colored pixels on the arc which is supposed to be extra wide and solid (presumably due to rounding during the calculation of the pixels which belong to the arc). Any suggestions on how I could solve this issue? Is there a parameter which I missed completely? I have already: - Googled for it, but the post it returned is about 2-3 years old (with a negative answer) and I was hoping something has changed in the mean time. - considered ImageMagick, but the Python wrapper is poorly (or not at all) documented and I already have code using the PIL so I'd rather not switch Andrei _____________________________________________________________ Get email for your site ---> http://www.everyone.net _____________________________________________________________ Select your own custom email address for FREE! Get you@yourchoice.com w/No Ads, 6MB, POP & more! http://www.everyone.net/selectmail?campaign=tag From stjfunai@netzero.com Fri Feb 7 20:48:26 2003 From: stjfunai@netzero.com (stjfunai@netzero.com) Date: Fri Feb 7 20:48:26 2003 Subject: [Tutor] Multithreading with Python on a Windows Machine Message-ID: <20030202.164801.20476.32103@webmail06.lax.untd.com> I tried to run the multithread example that came with Pyro 3.1. The client wouldn't run because apparently the fork function from the os module is not supported on Windows. I'd like to know if there is a comparable Windows-supported function available, or if there is another way to fork child processes. Thanks. From stephan.richter@tufts.edu Fri Feb 7 20:48:45 2003 From: stephan.richter@tufts.edu (Stephan Richter) Date: Fri Feb 7 20:48:45 2003 Subject: [Tutor] Objectifying code In-Reply-To: <5.1.0.14.0.20030204080115.02b85220@www.thinkware.se> References: <5.1.0.14.0.20030124181208.02cffed8@www.thinkware.se> <5.1.0.14.0.20030204080115.02b85220@www.thinkware.se> Message-ID: <200302040256.10651.stephan.richter@tufts.edu> On Tuesday 04 February 2003 02:15, Magnus Lycka wrote: > At 10:47 2003-02-04 +0630, John Abbe wrote: > >Hm, my Python says "TypeError: unsupported operand types for +: 'dict' and > >'dict'" > > Mine too. How silly of me! "When in doubt, refuse the temptation > to guess." I should have known that Python would refuse to do > something unclearly defined like that. The problem is what to do > when you run into the same key in both dicts. > > Of course your approach works. > > I guess I should have done: > > import copy > stringFields = copy.copy(entry) > stringFields['cgiaddr'] = cgiaddr > print x % stringFields > > Or, for a more generic (simply overwriting) merge > > >>> def dictMerge(*dicts): > > ... all = {} > ... for dict in dicts: > ... for key, value in dict.items(): > ... all[key] = value > ... return all > ... > > >>> print dictMerge({1:2,2:3},{2:4,3:4},{'a':'b'}) Shrug, what about dict1.update(dict2)? This function is fast, since it is written in C. Regards, Stephan -- Stephan Richter CBU Physics & Chemistry (B.S.) / Tufts Physics (Ph.D. student) Web2k - Web Software Design, Development and Training From WCOLtd@aol.com Fri Feb 7 20:49:00 2003 From: WCOLtd@aol.com (WCOLtd@aol.com) Date: Fri Feb 7 20:49:00 2003 Subject: [Tutor] importing graphics Message-ID: <6395D199.55ED1E0F.0004FA3D@aol.com> I really want to know how to import something like a circle or a line in python. I would really appreciate help. -Andrew Leister-Frazier (Wcoltd@aol.com) From JH2232@aol.com Fri Feb 7 20:49:07 2003 From: JH2232@aol.com (JH2232@aol.com) Date: Fri Feb 7 20:49:07 2003 Subject: [Tutor] HELP!!!! Message-ID: <46F4E6A3.23880F51.00045597@aol.com> Hi, my name is Lanette, I'm a freshmen at PSU, I am having > difficulty with some programming in python and I thought maybe > you could help. here's my problem > > I need to write a python program, that uses a while loop, that > calculates how many years it will take for someone to become a > millionaire. The program must request from a user an initial > deposit amount and interest rate. > Then I must use the following formula to calculate the amount of > money after n years: amount = initial amount(1+p/100)n > where p = interest rate > n = number of year (raising the expression above to that power > > can u help????? if not thanks > if u can super super super thanks :) From seiji_funai@yahoo.com Fri Feb 7 21:57:02 2003 From: seiji_funai@yahoo.com (Seiji Funai) Date: Fri Feb 7 21:57:02 2003 Subject: [Tutor] Forking Processes on a Windows Machine Message-ID: <20030208025618.97796.qmail@web21308.mail.yahoo.com> I installed Pyro on my Windows computer and tried to run the 'multithread' example that comes with it. It wouldn't run because the fork function (from the os module) is not supported on Windows machines. Is there another way to fork child processes? Please send simple examples if you have them! Thanks. __________________________________________________ Do you Yahoo!? Yahoo! Mail Plus - Powerful. Affordable. Sign up now. http://mailplus.yahoo.com From ramrom@earthling.net Fri Feb 7 22:12:04 2003 From: ramrom@earthling.net (Bob Gailer) Date: Fri Feb 7 22:12:04 2003 Subject: [Tutor] HELP!!!! In-Reply-To: <46F4E6A3.23880F51.00045597@aol.com> Message-ID: <5.2.0.9.0.20030207200952.03042e98@66.28.54.253> --=======68EE105F======= Content-Type: text/plain; x-avg-checked=avg-ok-537E2B4; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit Hi, Lanette: the policy on this list is to NOT solve homework for students, but to assist where you get stuck. Could you show us what you've done so far (either programming or design-wise) and/or let us know where you're stuck. At 11:07 AM 2/7/2003 -0500, you wrote: >Hi, my name is Lanette, I'm a freshmen at PSU, I am having > > difficulty with some programming in python and I thought maybe > > you could help. here's my problem > > > > I need to write a python program, that uses a while loop, that > > calculates how many years it will take for someone to become a > > millionaire. The program must request from a user an initial > > deposit amount and interest rate. > > Then I must use the following formula to calculate the amount of > > money after n years: amount = initial amount(1+p/100)n > > where p = interest rate > > n = number of year (raising the expression above to that power > > > > can u help????? if not thanks > > if u can super super super thanks :) Bob Gailer mailto:ramrom@earthling.net 303 442 2625 --=======68EE105F======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-537E2B4 Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.445 / Virus Database: 250 - Release Date: 1/21/2003 --=======68EE105F=======-- From Anwar.Lorenzo@gmx.net Fri Feb 7 22:43:04 2003 From: Anwar.Lorenzo@gmx.net (Anwar.Lorenzo@gmx.net) Date: Fri Feb 7 22:43:04 2003 Subject: [Tutor] List exercise In-Reply-To: References: <3E442ADB.4907.FB1D7C@localhost> Message-ID: <3E44F0A6.14946.3FFC021@localhost> Thank you guys for all your help. I never knew that simple exercise can be so complex, I'm still very early at learning python I haven't that used the keyword except yet so that's why I can't get a right solution. Anyway do you guys think that "Thinking Like a Computer Scientist:Learning with Python" is the best tutorial for an absolute beginner? Thanks again! -Anwar From hsteiger@comcast.net Sat Feb 8 01:04:24 2003 From: hsteiger@comcast.net (Henry Steigerwaldt) Date: Sat Feb 8 01:04:24 2003 Subject: [Tutor] Question on Regular Expression Help Message-ID: <001f01c24a94$3bd81f70$0201a8c0@eagle> This is a multi-part message in MIME format. --Boundary_(ID_q5KDbCler5Dw4K9hjxsNsQ) Content-type: text/plain; charset=iso-8859-1 Content-transfer-encoding: 7BIT To All: I have spent some time without success, trying to read a line of data containing four numbers and storing each number into a variable. The line that is read is the following, which has been shortened some to remove extra spaces for this example. MX/MN 91 72 90 70 These numbers represent temperatures, and can vary, such as -11, -1, 0, 9 23, 75, 102, etc. So in order to use a regular expression to search for the numbers, I have to check for a dash (-) with up to 2 digits after the dash, and whether their could be up to 3 digits in each number. The problem is that my code cannot extract these numbers to store into the variables t1, t2, t3, and t4. The code does find something because the piece of code below, namely if temp == None: print "temp is MISSING" return result is not accessed. I use a list below because there are a number of files to open and store each file into a variable for later number extraction. My code (with comments is as follows). _________________________ fwc[j] = f_object.read() f_object.seek(0) # reset pointer to beginning of file string = f_object.readline() # read and store one line into variable regexp = re.compile(r"(?P[-]*[1]*[0-9]*)" r"(?P[-]*[1]*[0-9]*)" r"(?P[-]*[1]*[0-9]*)" r"(?P[-]*[1]*[0-9]*)") temp = regexp.search(string) # store entire pattern found into "temp" if temp == None: print "temp is MISSING" return result t1 = temp.group('temp1') # store each number found into a variable t2 = temp.group('temp2') t3 = temp.group('temp3') t4 = temp.group('temp4') __________________________ I have also tried the follow code for the regular expression without success. regexp = re.compile(r"(?P[ ][-]?[1]*[0-9][0-9])" r"(?P[ ][-]?[1]*[0-9][0-9])" r"(?P[ ][-]?[1]*[0-9][0-9])" r"(?P[ ][-]?[1]*[0-9][0-9])") I hope the problem is something simple in the regular expressions I have tried. Thanks for any help provided. Please also send a response to my email address below. Henry Steigerwaldt Hermitage, TN Email: hsteiger@comcast.net --Boundary_(ID_q5KDbCler5Dw4K9hjxsNsQ) Content-type: text/html; charset=iso-8859-1 Content-transfer-encoding: 7BIT
To All:
 
I have spent some time without success, trying to read a line
of data containing four numbers and storing each number into
a variable.
 
The line that is read is the following, which has been shortened
some to remove extra spaces for this example.
 
MX/MN          91          72          90          70        
 
These numbers represent temperatures, and can vary, such as
-11, -1, 0, 9 23, 75, 102, etc. So in order to use a regular expression
to search for the numbers, I have to check for a dash (-) with up to
2 digits after the dash, and whether their could be up to 3 digits in
each number.
 
The problem is that my code cannot extract these numbers to
store into the variables t1, t2, t3, and t4. The code does
find something because the piece of code below, namely
 
   if temp == None:

        print "temp is MISSING"

        return result

is not accessed.

I use a list below because there are a number of files to open

and store each file into a variable for later number extraction.

My code (with comments is as follows).

_________________________

fwc[j] = f_object.read()   

f_object.seek(0)   # reset pointer to beginning of file

string = f_object.readline()    # read and store one line into variable

regexp = re.compile(r"(?P<temp1>[-]*[1]*[0-9]*)"

      r"(?P<temp2>[-]*[1]*[0-9]*)"

      r"(?P<temp3>[-]*[1]*[0-9]*)"

      r"(?P<temp4>[-]*[1]*[0-9]*)")

temp = regexp.search(string)     #  store entire pattern found into "temp"

if temp == None:

     print "temp is MISSING"

     return result

t1 = temp.group('temp1')     # store each number found into a variable

t2 = temp.group('temp2')

t3 = temp.group('temp3')

t4 = temp.group('temp4')

__________________________

I have also tried the follow code for the regular expression

without success.

regexp = re.compile(r"(?P<temp1>[ ][-]?[1]*[0-9][0-9])"

     r"(?P<temp2>[ ][-]?[1]*[0-9][0-9])"

     r"(?P<temp3>[ ][-]?[1]*[0-9][0-9])"

     r"(?P<temp4>[ ][-]?[1]*[0-9][0-9])")

 

I hope the problem is something simple in the regular

expressions I have tried.

 

Thanks for any help provided. Please also send a response

to my email address below.

Henry Steigerwaldt

Hermitage, TN

Email:  hsteiger@comcast.net

 

--Boundary_(ID_q5KDbCler5Dw4K9hjxsNsQ)-- From fredm@smartypantsco.com Sat Feb 8 02:06:01 2003 From: fredm@smartypantsco.com (Alfred Milgrom) Date: Sat Feb 8 02:06:01 2003 Subject: [Tutor] Re: Question on Regular Expression Help Message-ID: <5.1.0.14.0.20030208175712.01ecd410@mail.milgromphoto.com> >> I have spent some time without success, trying to read a line of data containing four numbers and storing each number into a variable. The line that is read is the following, which has been shortened some to remove extra spaces for this example. MX/MN 91 72 90 70 These numbers represent temperatures, and can vary, such as -11, -1, 0, 9 23, 75, 102, etc. So in order to use a regular expression to search for the numbers, I have to check for a dash (-) with up to 2 digits after the dash, and whether their could be up to 3 digits in each number. The problem is that my code cannot extract these numbers to store into the variables t1, t2, t3, and t4. Hi Henry: I don't think it is necessary to use "re", as simple string operations and list comprehension do the job easily. The following code illustrates the ideas: def isnumber(str): digits = '-0123456789' for letter in str: if letter not in digits: return 0 return 1 string = "MX/MN 91 72 90 70 " list = string.split(' ') list = [item for item in list if item and isnumber(item)] if len(list) == 4: t1, t2, t3, t4 = list print t1, t2, t3, t4 else: print "line does not contain four numbers' Hope this helps, Fred Milgrom From missive@hotmail.com Sat Feb 8 04:38:01 2003 From: missive@hotmail.com (Lee Harr) Date: Sat Feb 8 04:38:01 2003 Subject: [Tutor] Re: importing graphics Message-ID: >I really want to know how to import something like a circle or >a line in python. Hi; Not exactly sure what you mean, but this may be of interest to you. I am writing a set of modules which are designed to help people get started with programming, using Python and Pygame. One of the modules is a "turtle-graphics" like thing which would let you very quickly use Python to draw on the screen (lines, circles, and lots of other things too) The latest version is available here: http://savannah.nongnu.org/files/?group=pygsear More information and screenshots here: http://www.nongnu.org/pygsear/ _________________________________________________________________ The new MSN 8: advanced junk mail protection and 2 months FREE* http://join.msn.com/?page=features/junkmail From Don Arnold" <5.1.0.14.0.20030208000512.045af7d0@tcapp.com> Message-ID: <101e01c2cf72$d0075cc0$1a11ba3f@defaultcomp> ----- Original Message ----- From: "Tony Cappellini" To: "Don Arnold" Sent: Saturday, February 08, 2003 2:14 AM Subject: Re: [Tutor] Looking for Python equivalents of some C functions > > >thanks > > > > >>> a = 'This string has %d %s.' % (5,'words') > > >>> print a > >This string has 5 words. > > > >This can be done using the print statement: > > > >myfile = open('temp') > >print >> myfile, '%s %d %l' % ('stuff', 10, 28328738273L) > > >> > I've never seen this operator defined for redirection in any of my python books > It's always listed as the bitshift operator I think it's a fairly recent additon (added in 2.1 or 2.2?). > > Here's what happens when I tried your example > myfile=open("junk.txt","w") > >>> print >> myfile, '%s %d %l' % ('stuff', 10, 28328738273L) > Traceback (most recent call last): > File "", line 1, in ? > ValueError: incomplete format > Shame on me! Apologies to any and all who took this as working code. There is no format specifier for a long int. Just format it as a string: myfile = open('d:/python22/tutor/tony.txt','w') print >> myfile, '%s %d %s' % ('stuff', 10, 28328738273L) myfile.close() myfile = open('d:/python22/tutor/tony.txt','r') for line in myfile.readlines(): print line [--- begin program run --] stuff 10 28328738273 [--- begin program run --] This once again shows that no matter how simple your code looks, you should run it through the interpreter before posting it. You'd think I would've learned that by now! ; ) Sorry for the confusion, Don From magnus@thinkware.se Sat Feb 8 08:31:23 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Sat Feb 8 08:31:23 2003 Subject: [Tutor] Age calculations In-Reply-To: <20030208014844.3189.53401.Mailman@mail.python.org> Message-ID: <5.1.0.14.0.20030208141629.02ab1d20@www.thinkware.se> Ben Patel wrote: >Subject: [Tutor] Question First advice: Write a descriptive subject for your mail. Virtually everything mail on this list is a question or an answer... Ok, off with the list police hat. >I would like to write a program to calculate age of a person based on the >birth date entered (in any format). The mxDateTime package might be useful if you don't want to think too much. You can find it at http://www.egenix.com/ What's really the problem in your opinion? The calculation or the python programming part? -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From Janssen@rz.uni-frankfurt.de Sat Feb 8 08:34:01 2003 From: Janssen@rz.uni-frankfurt.de (Michael Janssen) Date: Sat Feb 8 08:34:01 2003 Subject: [Tutor] List exercise In-Reply-To: <3E44F0A6.14946.3FFC021@localhost> Message-ID: On Sat, 8 Feb 2003 Anwar.Lorenzo@gmx.net wrote: > Anyway do you guys think that "Thinking Like a Computer > Scientist:Learning with Python" is the best tutorial for an absolute > beginner? I prefer writing little real world programs just after getting a glimps on the language core (Chapter 2 of the Python Library Reference to name it). In your case I would assume, you already got enough of the core (hey, you know to define functions - i had to rewrite my first script to put everything into functions :-). I strongly believe that the world isn't short of relativly simple real problems/ tasks. I believe you can put them with python to a useful solution with your thought just on the problems (instead on syntax issues). This way you learn how to think like those computer guys by need. This way you will very probably write code which isn't that good looking even to yourself after you have more experience. On the other side, hey: my first-week-script is yet running and does it useful job! I have learned how to use dictionary three month after I have started programming because I must learn *why* to use them: A script of mine (mis)uses lists and runs incredibly slow. Oh, I've read one or two tutorials and I've read about dictionarys but they seemed to me hard to fill, hard to handle and hard to get items from it back. So I forget them and a perl programmer had to advise me to use "hash arrays" - tooks me an hour to translate this into "dictionary" and I have to relecture the tutorials about dictionarys and the outcome was: my script did it's job in seconds not ineffordable ten minutes. This feeling of "one problem solved" can't be read in tutorials ;-) Michael > > Thanks again! > -Anwar > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From Don Arnold" > ----- Original Message ----- > From: "Tony Cappellini" > To: "Don Arnold" > Sent: Saturday, February 08, 2003 2:14 AM > Subject: Re: [Tutor] Looking for Python equivalents of some C functions > > > > > > >thanks > > > > > > > >>> a = 'This string has %d %s.' % (5,'words') > > > >>> print a > > >This string has 5 words. > > > > > >This can be done using the print statement: > > > > > >myfile = open('temp') > > >print >> myfile, '%s %d %l' % ('stuff', 10, 28328738273L) > > > > >> > > I've never seen this operator defined for redirection in any of my python > books > > It's always listed as the bitshift operator > > I think it's a fairly recent additon (added in 2.1 or 2.2?). > > > > > Here's what happens when I tried your example > > myfile=open("junk.txt","w") > > >>> print >> myfile, '%s %d %l' % ('stuff', 10, 28328738273L) > > Traceback (most recent call last): > > File "", line 1, in ? > > ValueError: incomplete format > > > > Shame on me! Apologies to any and all who took this as working code. There > is no format specifier for a long int. Just format it as a string: > > > myfile = open('d:/python22/tutor/tony.txt','w') > > print >> myfile, '%s %d %s' % ('stuff', 10, 28328738273L) > myfile.close() > > myfile = open('d:/python22/tutor/tony.txt','r') > for line in myfile.readlines(): > print line > > [--- begin program run --] > > stuff 10 28328738273 > > [--- begin program run --] > > > This once again shows that no matter how simple your code looks, you should > run it through the interpreter before posting it. You'd think I would've > learned that by now! ; ) > > Sorry for the confusion, > Don > Even better, I just realized that the %d specifier works with long ints as well as regular integers: >>> print '%015d' % (123456789L) 000000123456789 >>> HTH, Don From Don Arnold" Message-ID: <106d01c2cf7e$b076f490$1a11ba3f@defaultcomp> ----- Original Message ----- From: "Alfred Milgrom" To: ; Sent: Saturday, February 08, 2003 1:02 AM Subject: [Tutor] Re: Question on Regular Expression Help > >> I have spent some time without success, trying to read a line of data > containing four numbers and storing each number into a variable. The line > that is read is the following, which has been shortened some to remove > extra spaces for this example. MX/MN 91 72 90 70 These numbers represent > temperatures, and can vary, such as -11, -1, 0, 9 23, 75, 102, etc. So in > order to use a regular expression to search for the numbers, I have to > check for a dash (-) with up to 2 digits after the dash, and whether their > could be up to 3 digits in each number. The problem is that my code cannot > extract these numbers to store into the variables t1, t2, t3, and t4. > > Hi Henry: > > I don't think it is necessary to use "re", as simple string operations and > list comprehension do the job easily. > > The following code illustrates the ideas: > > def isnumber(str): > digits = '-0123456789' > for letter in str: > if letter not in digits: > return 0 > return 1 > > string = "MX/MN 91 72 90 70 " > list = string.split(' ') > list = [item for item in list if item and isnumber(item)] > if len(list) == 4: > t1, t2, t3, t4 = list > print t1, t2, t3, t4 > else: > print "line does not contain four numbers' You could also let Python decide for you whether or not a string can be interpreted as an integer: >>> def isInt(aString): try: int(aString) return True except: return False >>> for substr in 'mx/mn 23 45 23.45 -456 3945'.split(): print '%s : %d' % (substr, isInt(substr)) mx/mn : 0 23 : 1 45 : 1 23.45 : 0 -456 : 1 3945 : 1 HTH, Don From magnus@thinkware.se Sat Feb 8 11:23:01 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Sat Feb 8 11:23:01 2003 Subject: [Tutor] Re: Question on Regular Expression Help In-Reply-To: <20030208143202.4208.44159.Mailman@mail.python.org> Message-ID: <5.1.0.14.0.20030208162343.02cdae80@www.thinkware.se> Alfred Milgrom wrote: > def isnumber(str): > digits = '-0123456789' > for letter in str: > if letter not in digits: > return 0 > return 1 This will report 1-----4 as being an integer, right? But +42 is not an integer, right? This can be fixed of course. >>> def isnumber(str): ... if str[0] in '+-': ... start = 1 ... else: ... start = 0 ... for c in str[start:]: ... if c not in '0123456789': ... return False ... return True Don Arnold wrote: > >>> def isInt(aString): > try: > int(aString) > return True > except: > return False But note that int(3.14) => 3 ! Is that what you want? Is 3.14 an integer? I think the code below works, but I don't really like it... I'm a bit allergic to comparing floats for equality, even though I think it should work in this particular case. (That is, if you think that something like "2.0000000000000000000000001" should be accepted as an int since it's so close that the floating point mechanism can't see a difference.) >>> def isInt(s): ... try: ... return int(s) == float(s) ... except: ... return False I think import re def isInteger(s): return re.match(r'[+-]?\d+$', s) is a better choice. But of course, it depends on what you mean by an integer. This code finds what it mathematically and integer. It might not fit in a Python int. The same is true for the first version. Anyway, regular expressions are part of a programmers toolbox. Don't avoid them like the plague when they add value. Learn them! From a performance point of view, the try/except version is the faster when the number is really and integer, but the loop version if faster in finding non-integer strings. The regular expression version is the slowest, but I think regular expression might win big if applied to a bigger problem, like finding all integers in a big string with something like re.findall(r'\s([+-]?\d+)\s', s) -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From Don Arnold" Message-ID: <10a101c2cf94$4bc11650$1a11ba3f@defaultcomp> > > Don Arnold wrote: > > >>> def isInt(aString): > > try: > > int(aString) > > return True > > except: > > return False > > But note that int(3.14) => 3 ! Is that what you want? Is 3.14 an integer? > Nope: int(3.14) => 3, but int('3.14') raises an exception as intended. Don From shalehperry@attbi.com Sat Feb 8 12:24:02 2003 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Sat Feb 8 12:24:02 2003 Subject: [Tutor] Question In-Reply-To: <20030201223212.10349.qmail@web14608.mail.yahoo.com> References: <20030201223212.10349.qmail@web14608.mail.yahoo.com> Message-ID: <200302080923.16878.shalehperry@attbi.com> On Saturday 01 February 2003 14:32, Ben Patel wrote: > Hello: > > I would like to write a program to calculate age of a person based on t= he > birth date entered (in any format). > > Any help would be appreciated. > how would you (a person) accomplish this? You ask for the their birth da= te=20 and subtract it from the current year. So, what do you need? their birth date (start simple and just ask for a year, then get fancy) the current date a way to ask for the first item and display the answer The python online docs (or the ones that came with your local install if = any)=20 should be able to answer these. This may not sound like a direct answer. Rather the point is to get you = to=20 think about a problem in this manner so you can solve even bigger problem= s=20 later. Part of programming is being able to consider the problem and bre= ak=20 it into smaller, easier to solve pieces. From shalehperry@attbi.com Sat Feb 8 12:27:03 2003 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Sat Feb 8 12:27:03 2003 Subject: [Tutor] Re: Question on Regular Expression Help In-Reply-To: <5.1.0.14.0.20030208175712.01ecd410@mail.milgromphoto.com> References: <5.1.0.14.0.20030208175712.01ecd410@mail.milgromphoto.com> Message-ID: <200302080926.23788.shalehperry@attbi.com> On Friday 07 February 2003 23:02, Alfred Milgrom wrote: > > string =3D "MX/MN 91 72 90 70 = " > list =3D string.split(' ') > list =3D [item for item in list if item and isnumber(item)] > if len(list) =3D=3D 4: > t1, t2, t3, t4 =3D list > print t1, t2, t3, t4 > else: > print "line does not contain four numbers' > since we are doling out advice, it is bad form to name a variable after a= =20 builtin type. calling one "string", "list", "dict", "dictionary", etc is= =20 asking for trouble. Another item in a similar vein that catches me from = time=20 to time is accidently naming a variable the same name as a builtin functi= on. From magnus@thinkware.se Sat Feb 8 13:00:02 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Sat Feb 8 13:00:02 2003 Subject: [Tutor] Re: Question on Regular Expression Help In-Reply-To: <10a101c2cf94$4bc11650$1a11ba3f@defaultcomp> References: <5.1.0.14.0.20030208162343.02cdae80@www.thinkware.se> Message-ID: <5.1.0.14.0.20030208183402.02a27600@www.thinkware.se> At 11:05 2003-02-08 -0600, Don Arnold wrote: > > But note that int(3.14) => 3 ! Is that what you want? Is 3.14 an integer? > > > >Nope: int(3.14) => 3, but int('3.14') raises an exception as intended. True, but while the loop and re functions will throw a TypeError for a float as input, your version will silently give the wrong answer. With "return int(s) == float(s)" I *think* it will always give the right result. (If we assume that a long is no int.) As a user of a function I certainly prefer an exception to an incorrect response if I use it differently than intended. (This is regardless of whether I wrote it myself or not. ;) In a way it might seem a bit strange that 3.14 is ok as an argument, but "3.14" is not. With a float as an argument, int() takes the role of truncator as well as type converter. With a string input, it will refuse to truncate. But it's not so strange. Floats are basically always approximations, while strings describe exactly what they describe... But I suppose the big issue is that the try: int() version will check for complience with the memory bound Python int type, while the re and loop version will check whether a string is mathematically an integer, i.e. an int or a long. Often, we want to use such values, and in such cases, we will want to convert them to numeric types anyway. In that case it's obviously most conveient to try: int(). Note that python automatically creates longs when you perform operations where ints won't fit in recent versions of Python. So sys.maxint + 1 will no longer raise an OverflowError, but will instead return a long. But int(sys.maxint + 1) will still raise an OverfloError. Ints are faster than longs though, so it might be good to do something like try: x = int(s) except OverflowError: x = long(s) except: # Error handling... -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From dyoo@hkn.eecs.berkeley.edu Sat Feb 8 15:29:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat Feb 8 15:29:02 2003 Subject: [Tutor] Multithreading with Python on a Windows Machine In-Reply-To: <20030202.164801.20476.32103@webmail06.lax.untd.com> Message-ID: On Mon, 3 Feb 2003 stjfunai@netzero.com wrote: > I tried to run the multithread example that came with Pyro 3.1. The > client wouldn't run because apparently the fork function from the os > module is not supported on Windows. I'd like to know if there is a > comparable Windows-supported function available, or if there is another > way to fork child processes. Hi Stjunai, I don't have a Windows system handy with me, but my memory tells me that Python 2.2 does have a fork() for Windows... let me check. Hmm... Ok, so the standard Python install for Windows doesn't appear to have it. However, the Cygwin distribution does appear to include enough Unix functionality to support os.fork(), from conversations on the twisted matrix mailing lists: http://twistedmatrix.com/pipermail/twisted-python/2002-February/000827.html You can find Cygwin here: http://www.cygwin.com/ You might also want to ask your question on the win32 list --- the gurus there may have better advice for you. http://mail.python.org/mailman/listinfo/python-win32 Good luck! From borelan@wanadoo.fr Sat Feb 8 15:40:02 2003 From: borelan@wanadoo.fr (D2) Date: Sat Feb 8 15:40:02 2003 Subject: [Tutor] Python notations References: <7497DCA1C240C042B28F6657ADFD8E097023C1@i2km11-ukbr.domain1.systemhost.net> Message-ID: <3E456AD8.7080308@wanadoo.fr> Thanks for your advice, i began to read it. i won't fail to ask questions if needed. alan.gauld@bt.com a =E9crit: >>for example, when do i use object.method or method(parameters), or >>object.method() or something.method().other_method().something (pan) >>I didn't find something explicit to help me understand the=20 >>way that works. >=20 >=20 > I don't remember if you said you could program in other langages but fr= om > the above I suspect not. Years ago, i just used, DBMS, but i was too involved in administrative=20 and financial tasks to keep in touch with the evolution of programming. I was just looking for an application framework to try some ideas on the=20 web. I found Zope then Python and had been attracted by this language=20 and all the concepts behind it. >=20 > In that case visit the Newbies page on the www.python.org website for=20 > a list of more suitable tutors. Or just visit mine below.... >=20 > Work through it systematically and raise specific questions here=20 > if you find things you don't understand. (If you use mine you can=20 > send mail direct to me too, but there are many more helpers on=20 > this list!) >=20 > Alan g. > Author of the Learn to Program website > http://www.freenetpages.co.uk/hp/alan.gauld/ >=20 >=20 --=20 Andre PZP Enthusiast From joel@prettyhipprogramming.com Sat Feb 8 17:10:04 2003 From: joel@prettyhipprogramming.com (Joel Ricker) Date: Sat Feb 8 17:10:04 2003 Subject: [Tutor] Passing attribute calls to has-a classes In-Reply-To: Message-ID: <000901c2cfbe$ee99fc00$c9e03942@nc.rr.com> Hi all, [Python 2.1] I've been working with the PIL package and ran into a little snag. I wanted to extend their Image type but unfortunately, they use a factory to build the object up. I wasn't sure quite sure I could extend this as is so I just wrapped my own class around it. What I would like to do is take any property calls and send them on to the wrapped object, intercepting the ones I need for the class. My problem is I keep getting in an infinite loop when I do. My code snippet: class MyImage: def __init__(self, fp): self.master = Image.open(fp) def __getattr__(self, name): return self.master.__getattr__(name) #I've also tried getattr(self.master, name) def __setattr__(self, name, value): self.master.__setattr__(name, value) #I've also tried setattr(self.master, name, value) Also, how can I catch calls to methods so that I can pass them on to the object self.master or is this even possible? ie, my = MyImage("image.jpg") my.show() # Since MyImage doesn't have a show() method, I'd like to catch that and try sending in to # self.master and if that still doesn't work, throw an error. Thanks Joel From ramrom@earthling.net Sat Feb 8 17:31:36 2003 From: ramrom@earthling.net (Bob Gailer) Date: Sat Feb 8 17:31:36 2003 Subject: [Tutor] Class as Exception Message-ID: <5.2.0.9.0.20030208152729.0303a798@66.28.54.253> --=======4E682C45======= Content-Type: text/plain; x-avg-checked=avg-ok-2E59145B; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit A couple of times I got the following to work. Now I just get an exception. >>> class n(str):pass >>> raise n, 'tst' Traceback (most recent call last): File "", line 1, in ? TypeError: exceptions must be strings, classes, or instances, not type Why would the same code work, then fail? Bob Gailer mailto:ramrom@earthling.net 303 442 2625 --=======4E682C45======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-2E59145B Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.445 / Virus Database: 250 - Release Date: 1/21/2003 --=======4E682C45=======-- From ramrom@earthling.net Sat Feb 8 18:40:40 2003 From: ramrom@earthling.net (Bob Gailer) Date: Sat Feb 8 18:40:40 2003 Subject: [Tutor] HELP!!!! In-Reply-To: <461C4EF6.45047FDF.00045597@aol.com> Message-ID: <5.2.0.9.0.20030208162457.02ffbe70@66.28.54.253> --=======34EE55F1======= Content-Type: text/plain; x-avg-checked=avg-ok-2E59145B; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit At 06:20 PM 2/8/2003 -0500, you wrote: >Sure, this is what I have so far: >n = 1 >amount = input("What is your initial deposit? ") >p = input("Please enter your interest rate ") >while amount < 1000000: > amount = amount(1 + p/100)**n > n = n + 1 >print n, "years" >print amount > >this is what I get along with this error message: >What is your initial deposit? 1000 >Please enter your interest rate 10 >Traceback (most recent call last): > File "C:\Python22\million.py", line 5, in ? > amount = amount(1 + p/100)**n >TypeError: 'int' object is not callable 1) in amount = amount(1 + p/100)**n the parentheses after amount look like a function call. Amount isn't a function, its an int, so you get the TypeError. If you want multiplication, use an *: amount = amount*(1 + p/100)**n 2) assuming that the user enters an integer for interest, p/100 becomes integer division resulting in 0; amount will never change. So try amount = amount*(1 + p/100.0)**n 3) 1 + p/100.0 is a "loop invariant", meaning that the result is the same each pass through the loop. In this program it does not matter; as programs grow it can help with efficiency to move such calculations outside the loop: rate = 1 + p/100.0 while ... amount = amount*rate**n Also when replying please include tutor@python.org so everyone can see your messages. Also as has been mentioned, use a meaningful subject line. Bob Gailer mailto:ramrom@earthling.net 303 442 2625 --=======34EE55F1======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-2E59145B Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.445 / Virus Database: 250 - Release Date: 1/21/2003 --=======34EE55F1=======-- From shalehperry@attbi.com Sat Feb 8 20:13:40 2003 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Sat Feb 8 20:13:40 2003 Subject: [Tutor] Class as Exception In-Reply-To: <5.2.0.9.0.20030208152729.0303a798@66.28.54.253> References: <5.2.0.9.0.20030208152729.0303a798@66.28.54.253> Message-ID: <200302081711.53180.shalehperry@attbi.com> On Saturday 08 February 2003 14:30, Bob Gailer wrote: > A couple of times I got the following to work. Now I just get an except= ion. > > >>> class n(str):pass > >>> raise n, 'tst' > > Traceback (most recent call last): > File "", line 1, in ? > TypeError: exceptions must be strings, classes, or instances, not type > > Why would the same code work, then fail? > 1) when you want an exception, derive from Exception. class n(Exception)= =2E 2) I believe you are suppose to raise an instance of the exception class,= not=20 the class itself. "raise n(), 'tst'". From joel@prettyhipprogramming.com Sat Feb 8 23:13:01 2003 From: joel@prettyhipprogramming.com (Joel Ricker) Date: Sat Feb 8 23:13:01 2003 Subject: [Tutor] Passing attribute calls to has-a classes In-Reply-To: <000901c2cfbe$ee99fc00$c9e03942@nc.rr.com> Message-ID: <000e01c2cff1$8ed9c6a0$c9e03942@nc.rr.com> Aha, figured it out! : My code snippet: : : class MyImage: : : def __init__(self, fp): : self.master = Image.open(fp) My problem was here, I needed to say: self.__dict__['master'] = Image.open(fp) : def __getattr__(self, name): : return self.master.__getattr__(name) : #I've also tried getattr(self.master, name) and: return getattr(self.master, name) : def __setattr__(self, name, value): : self.master.__setattr__(name, value) : #I've also tried setattr(self.master, name, value) and: return setattr(self.master, name, value) Thanks for listening! :) Joel From dyoo@hkn.eecs.berkeley.edu Sat Feb 8 23:21:04 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat Feb 8 23:21:04 2003 Subject: [Tutor] List exercise In-Reply-To: <3E44F0A6.14946.3FFC021@localhost> Message-ID: On Sat, 8 Feb 2003 Anwar.Lorenzo@gmx.net wrote: > Thank you guys for all your help. I never knew that simple exercise can > be so complex, I'm still very early at learning python I haven't that > used the keyword except yet so that's why I can't get a right solution. Don't be discouraged: if something that you read on Tutor goes way over your head, just feel free to holler for a good explanation. I get the feeling that the subject matter itself may not be complex, although our replies may be. *grin* > Anyway do you guys think that "Thinking Like a Computer Scientist: > Learning with Python" is the best tutorial for an absolute beginner? Dunno. Which one did you feel was the most readable and understandable for you? I thought Thinking Like a Computer Scientist was good, though I'm more partial to Alan Gauld's "Learning to Program". (But that's probably because Alan's active here on the Tutor list. *grin*) All of the tutorials from: http://python.org/doc/Newbies.html are excellent, I think. You can tickle your curiosity by seeing how other folks explain the same concepts: expect to see a variety of explanations, just like on this list. If you have more questions, please feel free to ask! From op73418@mail.telepac.pt Sun Feb 9 07:36:31 2003 From: op73418@mail.telepac.pt (=?iso-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Sun Feb 9 07:36:31 2003 Subject: [Tutor] Class as Exception References: <5.2.0.9.0.20030208152729.0303a798@66.28.54.253> Message-ID: <003d01c2d038$b471fb70$60120dd5@violante> ----- Original Message ----- From: "Bob Gailer" To: Sent: Saturday, February 08, 2003 10:30 PM Subject: [Tutor] Class as Exception > A couple of times I got the following to work. Now I just get an exception. > > >>> class n(str):pass > >>> raise n, 'tst' > Traceback (most recent call last): > File "", line 1, in ? > TypeError: exceptions must be strings, classes, or instances, not type > > Why would the same code work, then fail? > To amplify on S. Perry answer, the line raise n, tst is effectively raise n(tst), that is, if you provide args to the exception, it must be an instance. If no args are given, the class (derived from Exception) is enough. > Bob Gailer > mailto:ramrom@earthling.net > 303 442 2625 All the best, G. Rodrigues From glingl@aon.at Sun Feb 9 11:25:03 2003 From: glingl@aon.at (Gregor Lingl) Date: Sun Feb 9 11:25:03 2003 Subject: [Tutor] importing graphics References: <6395D199.55ED1E0F.0004FA3D@aol.com> Message-ID: <3E4680D2.6070301@aon.at> This is a multi-part message in MIME format. --------------090203060702020800060306 Content-Type: text/plain; charset=us-ascii; format=flowed Content-Transfer-Encoding: 7bit WCOLtd@aol.com schrieb: >I really want to know how to import something like a circle or a line in python. > Hi Andrew! To do what you ask for, you need some Graphics Toolkit. There are many of them for Python. The one, which comes with the original Python Distribution from www.python.org is Tkinter, an interface to Tk ... (from Tcl/Tk). Tkinter is a Toolkit for building graphical user-interfaces (GUIs), which are assembled with widgets (Window-Gadgets such as Buttons, Labels, Sliders etc.). For your intentions the appropriate widget is the Canvas-Widget, which has methods to draw several geometrical objects (such as lines, rectangles, circles etc.) To use Tkinter, unfortunatly you have to study a little ... ;-) Just to let you get an impression I show you a simple script (from M. Lutz's Programming Python, O'Reilly): # demo all basic canvas interfaces from Tkinter import * canvas = Canvas(width=300, height=300, bg='white') # 0,0 is top left corner canvas.pack(expand=YES, fill=BOTH) # increases down, right canvas.create_line(100, 100, 200, 200) # fromX, fromY, toX, toY canvas.create_line(100, 200, 200, 300) # draw shapes for i in range(1, 20, 2): canvas.create_line(0, i, 50, i) canvas.create_oval(10, 10, 200, 200, width=2, fill='blue') canvas.create_arc(200, 200, 300, 100) canvas.create_rectangle(200, 200, 300, 300, width=5, fill='red') canvas.create_line(0, 300, 150, 150, width=10, fill='green') photo=PhotoImage(file='../gifs/guido.gif') canvas.create_image(250, 0, image=photo, anchor=NW) # embed a photo widget = Label(canvas, text='Spam', fg='white', bg='black') widget.pack() canvas.create_window(100, 100, window=widget) # embed a widget canvas.create_text(100, 280, text='Ham') # draw some text mainloop() I've attached it - so you can run it immediately. Alternatively you can type it into IDLE line by line, so you can see what each line does. (But in this case avoid to type in the last line: mainloop() !) A gentle introduction to Tkinter you can find at "Thinking in Tkinter": http://home.att.net/~stephen_ferg/thinking_in_tkinter/index.html This website also contains a list of important links to docs and tutorials for Tkinter. A commented list of links to other GUI - toolkits you can find at: http://phaseit.net/claird/comp.lang.python/python_GUI.html Hope that helps Gregor > >I would really appreciate help. >-Andrew Leister-Frazier >(Wcoltd@aol.com) > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > > --------------090203060702020800060306 Content-Type: text/plain; name="canvas1.py" Content-Transfer-Encoding: 7bit Content-Disposition: inline; filename="canvas1.py" # demo all basic canvas interfaces from Tkinter import * canvas = Canvas(width=300, height=300, bg='white') # 0,0 is top left corner canvas.pack(expand=YES, fill=BOTH) # increases down, right canvas.create_line(100, 100, 200, 200) # fromX, fromY, toX, toY canvas.create_line(100, 200, 200, 300) # draw shapes for i in range(1, 20, 2): canvas.create_line(0, i, 50, i) canvas.create_oval(10, 10, 200, 200, width=2, fill='blue') canvas.create_arc(200, 200, 300, 100) canvas.create_rectangle(200, 200, 300, 300, width=5, fill='red') canvas.create_line(0, 300, 150, 150, width=10, fill='green') photo=PhotoImage(file='../gifs/guido.gif') canvas.create_image(250, 0, image=photo, anchor=NW) # embed a photo widget = Label(canvas, text='Spam', fg='white', bg='black') widget.pack() canvas.create_window(100, 100, window=widget) # embed a widget canvas.create_text(100, 280, text='Ham') # draw some text mainloop() --------------090203060702020800060306-- From gerrit@nl.linux.org Sun Feb 9 12:00:31 2003 From: gerrit@nl.linux.org (Gerrit Holl) Date: Sun Feb 9 12:00:31 2003 Subject: [Tutor] importing graphics In-Reply-To: <3E4680D2.6070301@aon.at> References: <6395D199.55ED1E0F.0004FA3D@aol.com> <3E4680D2.6070301@aon.at> Message-ID: <20030209163701.GA4695@nl.linux.org> Gregor Lingl schreef op zondag 9 februari om 17:25:23 +0000: > WCOLtd@aol.com schrieb: > > >I really want to know how to import something like a circle or a line in > >python. > To use Tkinter, unfortunatly you have to study a little ... ;-) For simple graphics, use the Turtle module: 17:35:32:3:gerrit@stopcontact:~/cvs/python/dist/src$ python Python 2.3a1 (#1, Jan 5 2003, 16:06:30) [GCC 2.96 20000731 (Red Hat Linux 7.3 2.96-110)] on linux2 Type "help", "copyright", "credits" or "license" for more information. 0 >>> import turtle 1 >>> turtle.circle(100) 2 >>> turtle.forward(100) http://www.python.org/dev/doc/devel/lib/module-turtle.html yours, Gerrit. -- Asperger Syndroom - een persoonlijke benadering: http://people.nl.linux.org/~gerrit/ Het zijn tijden om je zelf met politiek te bemoeien: http://www.sp.nl/ From tim@johnsons-web.com Sun Feb 9 12:29:02 2003 From: tim@johnsons-web.com (Tim Johnson) Date: Sun Feb 9 12:29:02 2003 Subject: [Tutor] extracting elements in a sequence Message-ID: <20030209173454.GL1564@johnsons-web.com> Hello All: Is there a builtin way to extract elements in a series as in test = [1,'one',2,'two',3,'three'] extract(test,2) = [1,2,3] or extract(test,3) = [1,'two'] If so, pointers to documentation would be appreciated. -- Tim Johnson http://www.alaska-internet-solutions.com http://www.johnsons-web.com From magnus@thinkware.se Sun Feb 9 12:48:02 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Sun Feb 9 12:48:02 2003 Subject: [Tutor] Class as Exception In-Reply-To: <20030209162503.10151.85621.Mailman@mail.python.org> Message-ID: <5.1.0.14.0.20030209183904.02ab1bd8@www.thinkware.se> Bob Gailer wrote: >A couple of times I got the following to work. Now I just get an exception. > > >>> class n(str):pass > >>> raise n, 'tst' >Traceback (most recent call last): > File "", line 1, in ? >TypeError: exceptions must be strings, classes, or instances, not type > >Why would the same code work, then fail? I don't know, but if you want to create an exception class, it should be an Exception, not a string. Try doing class MyError(Exception): pass instead of subclassing string. Even if you would get it to work in this particular case, you'd just cause a lot of trouble. See http://www.python.org/doc/current/tut/node10.html and http://www.python.org/doc/current/lib/module-exceptions.html -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From shalehperry@attbi.com Sun Feb 9 13:21:07 2003 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Sun Feb 9 13:21:07 2003 Subject: [Tutor] extracting elements in a sequence In-Reply-To: <20030209173454.GL1564@johnsons-web.com> References: <20030209173454.GL1564@johnsons-web.com> Message-ID: <200302091019.08947.shalehperry@attbi.com> On Sunday 09 February 2003 09:34, Tim Johnson wrote: > Hello All: > Is there a builtin way to extract elements in a series > as in > test =3D [1,'one',2,'two',3,'three'] > extract(test,2) > =3D [1,2,3] > or extract(test,3) > =3D [1,'two'] > If so, pointers to documentation would be appreciated. eh? uh? what? why does extract(test, 2) return [1,2,3]? This example just does not par= se=20 for me. From shalehperry@attbi.com Sun Feb 9 13:21:16 2003 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Sun Feb 9 13:21:16 2003 Subject: [Tutor] Class as Exception In-Reply-To: <003d01c2d038$b471fb70$60120dd5@violante> References: <5.2.0.9.0.20030208152729.0303a798@66.28.54.253> <003d01c2d038$b471fb70$60120dd5@violante> Message-ID: <200302091019.54034.shalehperry@attbi.com> On Sunday 09 February 2003 04:42, Gon=E7alo Rodrigues wrote: > To amplify on S. Perry answer, the line > > raise n, tst > > is effectively raise n(tst), that is, if you provide args to the except= ion, > it must be an instance. If no args are given, the class (derived from > Exception) is enough. > thanks, I new there was a reason but could not come up with it. From tbrauch@mindless.com Sun Feb 9 14:06:06 2003 From: tbrauch@mindless.com (Timothy M. Brauch) Date: Sun Feb 9 14:06:06 2003 Subject: [Tutor] urllib help Message-ID: <002101c2d06d$dbac25a0$6600a8c0@tbrauch> I am trying to use urllib to open a webpage. However, I have hit a small problem. The page I want to open is password protected and you have to log in to view it. It's not that big of a problem because I know the username and password (it is my website). I am not sure how to send this data through. Here is an interactive session: Python 2.2.2 (#37, Oct 14 2002, 17:02:34) [MSC 32 bit (Intel)] on win32 Type "copyright", "credits" or "license" for more information. IDLE Fork 0.8 -- press F1 for help >>> import urllib >>> source = urllib.urlopen('http://192.168.0.1') Enter username for server at 192.168.0.1: mylogin Warning: Problem with getpass. Passwords may be echoed. Enter password for admin in DI-614+ at 192.168.0.1: mypassword How can I send mylogin and mypassword? I am trying to write a script that will run on its own, without my intervention to retrieve a file for me. - Tim From tim@johnsons-web.com Sun Feb 9 16:05:52 2003 From: tim@johnsons-web.com (Tim Johnson) Date: Sun Feb 9 16:05:52 2003 Subject: [Tutor] extracting elements in a sequence In-Reply-To: <200302091019.08947.shalehperry@attbi.com> References: <20030209173454.GL1564@johnsons-web.com> <200302091019.08947.shalehperry@attbi.com> Message-ID: <20030209211025.GM1564@johnsons-web.com> * Sean 'Shaleh' Perry [030209 09:36]: > On Sunday 09 February 2003 09:34, Tim Johnson wrote: > > Hello All: > > Is there a builtin way to extract elements in a series > > as in > > test = [1,'one',2,'two',3,'three'] > > extract(test,2) > > = [1,2,3] > > or extract(test,3) > > = [1,'two'] > > If so, pointers to documentation would be appreciated. > > eh? uh? what? > > why does extract(test, 2) return [1,2,3]? This example just does not parse > for me. Sorry to confuse you. Perhaps you would choose a better word. You see the results: One would iterate through the collection, taking (if 2 the first of two, if 3 the first of 3, etc.) I used the word 'extract' because I'm coming from a different language.... HTH -- Tim Johnson http://www.alaska-internet-solutions.com http://www.johnsons-web.com From hsteiger@comcast.net Sun Feb 9 16:09:02 2003 From: hsteiger@comcast.net (Henry Steigerwaldt) Date: Sun Feb 9 16:09:02 2003 Subject: [Tutor] Need mouse cursor readout for text placement in program Message-ID: <000501c24a84$89813500$0201a8c0@eagle> To All: I have been able to generate a canvas and place text on the canvas in Python like I was able to do in Tcl/Tk. But unlike the Tcl/Tk program, I am still unable to produce a mouse readout for easier text placement. A cursor readout allows one to determine precisely the x and y coordinates on the canvas where the mouse is located at any moment in time. In order to place text precisely at certain locations, rather than spend a long time via trial and error, I want to get the x and y values via a mouse cursor readout. Once I know the precise x and y locations, I can then hard code this into the program code for text placement. By the way, just the other day I asked a question and several people quickly responded. Thanks much for a list like this. I just marvel at how easy programming comes to some people. I am NOT ONE OF THEM ! To anyone that responds, please also send a copy to my email address: hsteiger@comcast.net Thanks again and have a good day. Henry Steigerwaldt Hermitage, TN From fredm@smartypantsco.com Sun Feb 9 17:11:03 2003 From: fredm@smartypantsco.com (Alfred Milgrom) Date: Sun Feb 9 17:11:03 2003 Subject: [Tutor] extracting elements in a sequence Message-ID: <5.1.0.14.0.20030210090024.01edeec0@mail.milgromphoto.com> Hi Tim: As far as I know there is no built-in way to extract the nth element out of a list, but it is very simple to write a function to do this for you: def extract (oldlist, spacing): count = 0 newlist = [] for item in oldlist: if count % spacing == 0: newlist.append(item) count = count+1 return newlist oldlist = [1,'one',2,'two',3,'three'] newlist = extract(oldlist, 2) print newlist newlist = extract(oldlist, 3) print newlist (The % operator is the modulo function) Hope this helps you, Alfred Milgrom From tim@johnsons-web.com Sun Feb 9 17:17:02 2003 From: tim@johnsons-web.com (Tim Johnson) Date: Sun Feb 9 17:17:02 2003 Subject: [Tutor] extracting elements in a sequence In-Reply-To: <5.1.0.14.0.20030210090024.01edeec0@mail.milgromphoto.com> References: <5.1.0.14.0.20030210090024.01edeec0@mail.milgromphoto.com> Message-ID: <20030209222200.GN1564@johnsons-web.com> * Alfred Milgrom [030209 13:16]: > Hi Tim: Hello Alfred: > As far as I know there is no built-in way to extract the nth element out of Aha, was just checking... > a list, but it is very simple to write a function to do this for you: > def extract (oldlist, spacing): > count = 0 > newlist = [] > for item in oldlist: > if count % spacing == 0: > newlist.append(item) > count = count+1 > return newlist Yes, I just wrote something similar, but I like yours better. :-) thank you Alfred. regards -tim- > oldlist = [1,'one',2,'two',3,'three'] > newlist = extract(oldlist, 2) > print newlist > newlist = extract(oldlist, 3) > print newlist > > (The % operator is the modulo function) > > Hope this helps you, > Alfred Milgrom -- Tim Johnson http://www.alaska-internet-solutions.com http://www.johnsons-web.com From Kxgin14@cs.com Sun Feb 9 17:31:08 2003 From: Kxgin14@cs.com (Kxgin14@cs.com) Date: Sun Feb 9 17:31:08 2003 Subject: [Tutor] take me off list Message-ID: <9.9935340.2b783046@cs.com> From tim@johnsons-web.com Sun Feb 9 17:49:01 2003 From: tim@johnsons-web.com (Tim Johnson) Date: Sun Feb 9 17:49:01 2003 Subject: [Tutor] Problems 'reloading'/'reimporting' module Message-ID: <20030209225402.GO1564@johnsons-web.com> Hello All: Is it possible to 'reimport' a module in python2.2 without restarting the interpreter? I'm not having any luck in either Linux Konsole or Xemacs python-mode. In Linux Konsole if I make changes to code and do from tlib import * # second time changes are not reflected. If I do reload(tlib) NameError: name 'tlib' is not defined However, if I do this in the python-mode interpreter window, I get what appears to be a successful reload >>> reload(tlib) but changes are not shown. Any help would be appreciated. TIA -- Tim Johnson http://www.alaska-internet-solutions.com http://www.johnsons-web.com From tim@johnsons-web.com Sun Feb 9 18:08:03 2003 From: tim@johnsons-web.com (Tim Johnson) Date: Sun Feb 9 18:08:03 2003 Subject: [Tutor] Problems 'reloading'/'reimporting' module In-Reply-To: <20030209225402.GO1564@johnsons-web.com> References: <20030209225402.GO1564@johnsons-web.com> Message-ID: <20030209231351.GP1564@johnsons-web.com> Found the solution: must use import and reload together. Must also get namespaces straight. :-) Thanks tim * Tim Johnson [030209 14:04]: > Hello All: > Is it possible to 'reimport' a module in > python2.2 without restarting the interpreter? > > I'm not having any luck in either Linux Konsole > or Xemacs python-mode. > > In Linux Konsole if I make changes to code and > do > from tlib import * # second time > changes are not reflected. > > If I do reload(tlib) > NameError: name 'tlib' is not defined > > However, if I do this in the python-mode interpreter > window, I get what appears to be a successful reload > >>> reload(tlib) > > > but changes are not shown. > > Any help would be appreciated. > TIA > -- > Tim Johnson > http://www.alaska-internet-solutions.com > http://www.johnsons-web.com > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Tim Johnson http://www.alaska-internet-solutions.com http://www.johnsons-web.com From erikprice@mac.com Sun Feb 9 18:27:16 2003 From: erikprice@mac.com (Erik Price) Date: Sun Feb 9 18:27:16 2003 Subject: [Tutor] capitalize() but only first letter In-Reply-To: <5.1.0.14.0.20030207195702.02afe440@www.thinkware.se> Message-ID: On Friday, February 7, 2003, at 03:39 PM, Magnus Lycka wrote: > At 10:43 2003-02-07 -0500, Erik Price wrote: >> I'm not sure I understand why this works. > > Why not? The world doesn't HAVE to be complicated just > because most other programming languages are! In Python > almost everything is a first class object. [...] > Could hypothetically be something like this... (I'm sure it's not > implemented anything like this really, Fredrik Lundh wrote it in C...) > > def sub(pattern, replacement, text): > ... > import types > while .... : > match = ... > beforeMatch = ... > afterMatch = ... > if type(replacement) == types.FunctionType: > text = beforeMatch+replacement(match)+afterMAtch > else: > text = beforeMatch+replacement+afterMatch > ... > return text Sorry, I should have been more clear when I said "I'm not sure how this works" -- I wasn't taking issue with the fact that Python lets just about everything be an object, simply curious about how the re.sub() function determined whether it should act upon a string or use a function. Your explanation makes it completely clear -- there's an internal type check that decides which should be done based on what the argument is. Thanks! Erik -- Erik Price email: erikprice@mac.com jabber: erikprice@jabber.org From R. Alan Monroe" I have a project consisting of a main file and two modules. If I want to set up a new third module file establishing some constants, is it safe to re-import it multiple times, once in each file and module? Are there any side-effects to doing that? Basically I want to define state values such as: idle=1 attacking=2 attacked=3 And only have to define them in one place, to eliminate errors where they might be accidentally be defined differently in different modules. Later they will be used as dict keys. a[idle]=[1,2,3] etc. Alan From dyoo@hkn.eecs.berkeley.edu Sun Feb 9 18:43:04 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun Feb 9 18:43:04 2003 Subject: [Tutor] extracting elements in a sequence [push() and pop()] In-Reply-To: <5.1.0.14.0.20030210090024.01edeec0@mail.milgromphoto.com> Message-ID: On Mon, 10 Feb 2003, Alfred Milgrom wrote: > Hi Tim: > > As far as I know there is no built-in way to extract the nth element out > of a list, Hi Alfred, Actually, there is: lists support a pop() method that'll simultaneously "pop" an element off a list, and give that element to us: ### >>> sentence = "this is a test of the emergency broadcast system".split() >>> sentence ['this', 'is', 'a', 'test', 'of', 'the', 'emergency', 'broadcast', 'system'] >>> sentence.pop(3) 'test' >>> sentence ['this', 'is', 'a', 'of', 'the', 'emergency', 'broadcast', 'system'] ### Symmetrically, if we need to do an insertion somewhere in a list, we can use the "push()" method. We can look at more information about these methods here: http://www.python.org/doc/lib/typesseq-mutable.html Hope this helps! From magnus@thinkware.se Sun Feb 9 19:16:51 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Sun Feb 9 19:16:51 2003 Subject: [Tutor] capitalize() but only first letter In-Reply-To: References: <5.1.0.14.0.20030207195702.02afe440@www.thinkware.se> Message-ID: <5.1.0.14.0.20030210005938.02c07430@www.thinkware.se> At 18:39 2003-02-09 -0500, Erik Price wrote: >Sorry, I should have been more clear when I said "I'm not sure how this >works" -- I wasn't taking issue with the fact that Python lets just about >everything be an object, simply curious about how the re.sub() function >determined whether it should act upon a string or use a function. Your >explanation makes it completely clear -- there's an internal type check >that decides which should be done based on what the argument is. To be more precise, the code looks like this: if (PyCallable_Check(template)) { /* sub/subn takes either a function or a template */ filter = template; Py_INCREF(filter); filter_is_callable = 1; } else { /* if not callable, check if it's a literal string */ It's in the pattern_subx function of _sre.c, which you can find in the Python source code. http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/python/python/dist/src/Modules/_sre.c?rev=2.87&content-type=text/vnd.viewcvs-markup -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From erikprice@mac.com Sun Feb 9 20:17:21 2003 From: erikprice@mac.com (Erik Price) Date: Sun Feb 9 20:17:21 2003 Subject: [Tutor] capitalize() but only first letter In-Reply-To: <5.1.0.14.0.20030210005938.02c07430@www.thinkware.se> Message-ID: <2F18018E-3C97-11D7-B24E-00039351FE6A@mac.com> On Sunday, February 9, 2003, at 07:01 PM, Magnus Lycka wrote: > It's in the pattern_subx function of _sre.c, which you can > find in the Python source code. > > http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/python/python/dist/src/ > Modules/_sre.c?rev=2.87&content-type=text/vnd.viewcvs-markup > Thanks for the pointer -- that's neat. I assume that viewcvs.cgi does on-the-fly conversion of source code to syntax-colored HTML? (I've never seen it before.) Sure beats having to download the entire source tree just to look at a file or two. Erik -- Erik Price email: erikprice@mac.com jabber: erikprice@jabber.org From fredm@smartypantsco.com Mon Feb 10 01:01:50 2003 From: fredm@smartypantsco.com (Alfred Milgrom) Date: Mon Feb 10 01:01:50 2003 Subject: [Tutor] extracting elements in a sequence [push() and pop()] Message-ID: <5.1.0.14.0.20030210164932.01ee2bb0@mail.milgromphoto.com> >> As far as I know there is no built-in way to extract the nth element out >> of a list, > Hi Alfred, > Actually, there is: lists support a pop() method that'll simultaneously > "pop" [the nth] element off a list, and give that element to us ... Thanks Danny! That's why I love this list so much. I learn not only from asking questions, or reading answers to other questions but also as a follow-up to what I think I know :) By the way, I think the following is a more elegant way of doing the extract method I posted previously: def extract (oldlist, spacing): return [oldlist[i] for i in range(0,len(oldlist), spacing)] Thanks again, Fred Milgrom From shalehperry@attbi.com Mon Feb 10 01:40:03 2003 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Mon Feb 10 01:40:03 2003 Subject: [Tutor] extracting elements in a sequence In-Reply-To: <20030209211025.GM1564@johnsons-web.com> References: <20030209173454.GL1564@johnsons-web.com> <200302091019.08947.shalehperry@attbi.com> <20030209211025.GM1564@johnsons-web.com> Message-ID: <200302092239.14319.shalehperry@attbi.com> On Sunday 09 February 2003 13:10, Tim Johnson wrote: > * Sean 'Shaleh' Perry [030209 09:36]: > > On Sunday 09 February 2003 09:34, Tim Johnson wrote: > > > Hello All: > > > Is there a builtin way to extract elements in a series > > > as in > > > test =3D [1,'one',2,'two',3,'three'] > > > extract(test,2) > > > =3D [1,2,3] > > > or extract(test,3) > > > =3D [1,'two'] > > > If so, pointers to documentation would be appreciated. > > > > eh? uh? what? > > > > why does extract(test, 2) return [1,2,3]? This example just does not > > parse for me. > > Sorry to confuse you. Perhaps you would choose a better word. > > You see the results: One would iterate through the collection, > > taking (if 2 the first of two, if 3 the first of 3, etc.) > I used the word 'extract' because I'm coming from a different > language.... > ok. "if 2 the first of two". Do you mean the first two items which woul= d be=20 (1, 'one')? The second example of extract(3) returning (1, 'two') is=20 particularly puzzling to me. Why is (1, 2, 3) what you expect from extract(2)? > HTH not really, but we can work it out (-: From w.richert@gmx.net Mon Feb 10 03:18:01 2003 From: w.richert@gmx.net (Willi Richert) Date: Mon Feb 10 03:18:01 2003 Subject: [Tutor] Sun says: Don't use Java, use Python! Message-ID: <200302100916.18123.w.richert@gmx.net> Hi, I've found this link via slashdot: http://www.internalmemos.com/memos/memodetails.php?memo_id=1321 Some thoughts in this article: "...If the Java runtime were as small as that of Python, it is likely that the Java daemon would become popular and could provide basic services to applications written in any number of languages...." "...A study performed by an outside team appears to indicate a rough parity in performance between Java and a common implementation of another OO language called Python (see IEEE Computing, October 2000, "An Empirical Comparison of Seven Programming Languages" by Lutz Prechelt of the University of Karlsruhe). Both platforms are Object Oriented, support web applications, serialization, internet connections and native interfaces. The key difference is that Python is a scripting language. This means there is no compilation to byte code so the Python runtime environment has to do two things in addition to what the Java runtime environment does. It has to perform syntax checks and it must parse the ascii text provided by the programmer. Both of those tasks are performed at compile time by Java and so that capability does not have to be in the JRE." Nice memo, wr From w.richert@gmx.net Mon Feb 10 04:37:21 2003 From: w.richert@gmx.net (Willi Richert) Date: Mon Feb 10 04:37:21 2003 Subject: [Tutor] Sun says: Don't use Java, use Python! Message-ID: <200302101035.46262.mennosimons@gmx.net> Hi, I've found this link via slashdot: http://www.internalmemos.com/memos/memodetails.php?memo_id=1321 Some thoughts in this article: "...If the Java runtime were as small as that of Python, it is likely that the Java daemon would become popular and could provide basic services to applications written in any number of languages...." "...A study performed by an outside team appears to indicate a rough parity in performance between Java and a common implementation of another OO language called Python (see IEEE Computing, October 2000, "An Empirical Comparison of Seven Programming Languages" by Lutz Prechelt of the University of Karlsruhe). Both platforms are Object Oriented, support web applications, serialization, internet connections and native interfaces. The key difference is that Python is a scripting language. This means there is no compilation to byte code so the Python runtime environment has to do two things in addition to what the Java runtime environment does. It has to perform syntax checks and it must parse the ascii text provided by the programmer. Both of those tasks are performed at compile time by Java and so that capability does not have to be in the JRE." Nice memo, wr From scot@possum.in-berlin.de Mon Feb 10 04:49:24 2003 From: scot@possum.in-berlin.de (Scot Stevenson) Date: Mon Feb 10 04:49:24 2003 Subject: [Tutor] Multithreading with Python on a Windows Machine In-Reply-To: References: Message-ID: <200302101048.56132.scot@possum.in-berlin.de> Hello Danny, > I don't have a Windows system handy with me, but my memory tells me that > Python 2.2 does have a fork() for Windows... let me check. Hmm... Ok, > so the standard Python install for Windows doesn't appear to have it. Windows per se doesn't seem to have a fork call, or at least that is what Mark Lutz says in "Programming Python", second edition, p. 89. However, the book, as excellent as it is, is getting rather old in Python terms, so that might have changed. Y, Scot -- Scot W. Stevenson -- scot@possum.in-berlin.de -- Zepernick, Germany From alan.gauld@bt.com Mon Feb 10 05:43:19 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon Feb 10 05:43:19 2003 Subject: [Tutor] Need mouse cursor readout for text placement in progr am Message-ID: <7497DCA1C240C042B28F6657ADFD8E097023E8@i2km11-ukbr.domain1.systemhost.net> > unlike the Tcl/Tk program, I am still unable to produce a > mouse readout for easier text placement. Hmm, I'd like to know how you do that in Tcl/Tk? I've never seen that feature. Can you explain? > Once I know the precise x and y locations, I can then hard > code this into the program code for text placement. Caveat: This is likely to break if your user has different fonts/screen sizes etc set up on their computer. If its just for yourself or you have control of the end user environment its fine. > Thanks much for a list like this. I just marvel at how > easy programming comes to some people. I am > NOT ONE OF THEM ! Its like driving a car, when learning you go slowly and everything seems to happen at once. After a few years you relax and can enjoy the scenery while talking to your passenger and driving at the same time. Programming is essentially the same set of problems coming up time after time but in disguise. The trick is to recognise the problem for what it is then translate the standard answswer into the new context. But first of course you have to experience all of the standard problems so that you can recognise them... This list is a good place to get explanations of those standard formulae. Alan g. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld/ > > To anyone that responds, please also send a copy to > my email address: hsteiger@comcast.net > > Thanks again and have a good day. > > Henry Steigerwaldt > Hermitage, TN > > > > From alan.gauld@bt.com Mon Feb 10 05:47:02 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon Feb 10 05:47:02 2003 Subject: [Tutor] extracting elements in a sequence Message-ID: <7497DCA1C240C042B28F6657ADFD8E0974DAB6@i2km11-ukbr.domain1.systemhost.net> > As far as I know there is no built-in way to extract the nth > element out of a list, but it is very simple to write a function > to do this for you: > def extract (oldlist, spacing): newlist = [] for i in range(0,len(oldlist),spacing): newlist.append(oldlist[i]) return newlist Should do it? Alan g. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld/ From alan.gauld@bt.com Mon Feb 10 05:49:04 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon Feb 10 05:49:04 2003 Subject: [Tutor] Problems 'reloading'/'reimporting' module Message-ID: <7497DCA1C240C042B28F6657ADFD8E097023EA@i2km11-ukbr.domain1.systemhost.net> > In Linux Konsole if I make changes to code and > do > from tlib import * # second time > changes are not reflected. Yet another reason not to use from X import * If you just do import tlib then change tlib and do reload(tlib) it should all work. Alan G. From alan.gauld@bt.com Mon Feb 10 06:57:02 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon Feb 10 06:57:02 2003 Subject: [Tutor] Learning Tkinter Message-ID: <7497DCA1C240C042B28F6657ADFD8E0974DAB7@i2km11-ukbr.domain1.systemhost.net> > root = Tkinter.Tk() > menubar = Tkinter.Menu(root) > root.config(menu=menubar) You'll find Tkinter life much easier if you get used to creating Frames and putting your controls inside them. The frames then become reusable... They also help you layout your GUI much more easily. Frames are kind of like visual classes for Tkinter. > filemenu = Tkinter.Menu(menubar) > menubar.add_cascade(label='File', menu=filemenu) filemenu.add_command(label='Run', command=mymod.main) # <---NEW! > filemenu.add_command(label='Exit', command=sys.exit) > ... > root.mainloop() > > It is generally what I was going for considering it is my > first GUI but how would I run the former command line program > that was put into the function track within the GUI? See the line I added? It should create a menu item called Run that will run your program(called mymod.main here). Your next trick is to get the output displayed somehow... The simplest way is stick a Text widget on the GUI and capture the output of your porogram in a string. Then show the string in the Text widget. Next, if your program takes input capture it in fields on Tkinter - entry fields, radio buttons etc. Create a callback function that calls your function with the parameter values. Like so: def callback(): Mymod.main(entryVal1, entryVal2, radButt1) And call that from the menu instead of calling main() directly Finally, put the output in a tuple and display the elements in more GUI like widgets - labels, scrolling lists, entry fields. All of this is illustrated in the Case Study in my tutor which takes a batch oriented program and puts a GUI on top. HTH, Alan g. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld/ From alan.gauld@bt.com Mon Feb 10 07:07:01 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon Feb 10 07:07:01 2003 Subject: [Tutor] List exercise Message-ID: <7497DCA1C240C042B28F6657ADFD8E0901F850A1@i2km11-ukbr.domain1.systemhost.net> > Anyway do you guys think that "Thinking Like a Computer > Scientist:Learning with Python" is the best tutorial for an absolute > beginner? I'm biased, but really it doesn't matter which one *I* think is best. What matters is which *you* think is best....Different strokes for different folks etc. The good thing about Python is that there are at least 4 good tutors for complete beginners. Thats about 3 more than for most languages. If one doesn't work for you then try one of the others, anything you learn on one will transfer to the others fairly seamlessly so you should cruise through the early stages till you get to the next hurdle. The new approach might make it clearer than the previous one. Do the examples, try modifying them and make sure you understand what changed and why. If stuck as on the list. Have fun. Enjoy, Alan g. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld/ From alan.gauld@bt.com Mon Feb 10 07:19:02 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon Feb 10 07:19:02 2003 Subject: [Tutor] List exercise Message-ID: <7497DCA1C240C042B28F6657ADFD8E0901F850A2@i2km11-ukbr.domain1.systemhost.net> > I prefer writing little real world programs just after > getting a glimps on the language core AS I said in an earlier post, different strokes etc. Most good tutors will provide examples and suggested exercises too. > problems/ tasks. I believe you can put them with python to a > useful solution with your thought just on the problems > ...This way you learn how to think like those computer > guys by need. The only problem with this approach is that learning by experience can teach an awful lot of bad habits that are hard to break. Using a tutorial that teaches good habits early saves a lot of time in the long run because you don't have to unlearn so much. > This way you will very probably write code which isn't that > good looking even to yourself after you have more experience. Exactly so. > my first-week-script is yet running and does it useful job! And this is the counter argument. If it scratches your itch then go for it. But keep reading the tutorials too... > I have learned how to use dictionary three month after I have started > programming because I must learn *why* to use them: Interesting.. Because dictionaries are things we use all the time in real life. Why would you find them so difficult to grasp in a programming context? People from other languages who don't have dictionaries often don't see the need, but someone with no baggage should, I'd think, see the usefulnes straight away? At least thats been my experience when training non programmers in awk(a language that uses dictionaries extensively). Alan g. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld/ From op73418@mail.telepac.pt Mon Feb 10 07:53:02 2003 From: op73418@mail.telepac.pt (=?iso-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Mon Feb 10 07:53:02 2003 Subject: [Tutor] Sun says: Don't use Java, use Python! References: <200302100916.18123.w.richert@gmx.net> Message-ID: <001b01c2d104$106fc530$251a0dd5@violante> ----- Original Message ----- From: "Willi Richert" To: Cc: Sent: Monday, February 10, 2003 8:16 AM Subject: [Tutor] Sun says: Don't use Java, use Python! > Hi, > > I've found this link via slashdot: > http://www.internalmemos.com/memos/memodetails.php?memo_id=1321 > > Some thoughts in this article: > > "...If the Java runtime were as small as that of Python, it is likely that the > Java daemon would become popular and could provide basic services to > applications written in any number of languages...." > > "...A study performed by an outside team appears to indicate a rough parity in > performance between Java and a common implementation of another OO language > called Python (see IEEE Computing, October 2000, "An Empirical Comparison of > Seven Programming Languages" by Lutz Prechelt of the University of > Karlsruhe). Both platforms are Object Oriented, support web applications, > serialization, internet connections and native interfaces. The key difference > is that Python is a scripting language. This means there is no compilation to > byte code so the Python runtime environment has to do two things in addition > to what the Java runtime environment does. It has to perform syntax checks > and it must parse the ascii text provided by the programmer. Both of those > tasks are performed at compile time by Java and so that capability does not > have to be in the JRE." > This is wrong. There *is* compilation to Python bytecode. Have they never heard of .pyc files? This does not bode well... > Nice memo, > wr With my best regards, G. Rodrigues From antonmuhin at rambler.ru" References: <20030209173454.GL1564@johnsons-web.com> Message-ID: <1882848966.20030210155404@rambler.ru> Hello Tim, Sunday, February 9, 2003, 8:34:54 PM, you wrote: TJ> Hello All: TJ> Is there a builtin way to extract elements in a series TJ> as in TJ> test = [1,'one',2,'two',3,'three'] TJ> extract(test,2) TJ> = [1,2,3] TJ> or extract(test,3) TJ> = [1,'two'] TJ> If so, pointers to documentation would be appreciated. Another solution: def extract(seq, step): return [seq[i] for i in range(0, len(seq), step)] -- Best regards, anton mailto:antonmuhin@rambler.ru From op73418@mail.telepac.pt Mon Feb 10 07:55:13 2003 From: op73418@mail.telepac.pt (=?iso-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Mon Feb 10 07:55:13 2003 Subject: [Tutor] Multithreading with Python on a Windows Machine References: <200302101048.56132.scot@possum.in-berlin.de> Message-ID: <002601c2d104$87da72f0$251a0dd5@violante> ----- Original Message ----- From: "Scot Stevenson" To: "Danny Yoo" ; Cc: Sent: Monday, February 10, 2003 9:48 AM Subject: Re: [Tutor] Multithreading with Python on a Windows Machine > Hello Danny, > > > I don't have a Windows system handy with me, but my memory tells me that > > Python 2.2 does have a fork() for Windows... let me check. Hmm... Ok, > > so the standard Python install for Windows doesn't appear to have it. > > Windows per se doesn't seem to have a fork call, or at least that is what Mark > Lutz says in "Programming Python", second edition, p. 89. However, the book, > as excellent as it is, is getting rather old in Python terms, so that might > have changed. > No this has not changed. the fork() call is still a unixism. You *may* want to check the spawn*/exec* family of system calls (module os). They might just do what you want. > Y, Scot > > -- > Scot W. Stevenson -- scot@possum.in-berlin.de -- Zepernick, Germany > All the best, G. Rodrigues From op73418@mail.telepac.pt Mon Feb 10 07:59:07 2003 From: op73418@mail.telepac.pt (=?iso-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Mon Feb 10 07:59:07 2003 Subject: [Tutor] extracting elements in a sequence References: <7497DCA1C240C042B28F6657ADFD8E0974DAB6@i2km11-ukbr.domain1.systemhost.net> Message-ID: <003001c2d104$d88e1620$251a0dd5@violante> ----- Original Message ----- From: To: ; ; Sent: Monday, February 10, 2003 10:45 AM Subject: RE: [Tutor] extracting elements in a sequence > > As far as I know there is no built-in way to extract the nth > > element out of a list, but it is very simple to write a function > > to do this for you: > > > def extract (oldlist, spacing): > newlist = [] > for i in range(0,len(oldlist),spacing): > newlist.append(oldlist[i]) > return newlist > In the coming 2.3 (still in alpha) you may use extended slices, e.g. newlist[::spacing] > Should do it? > > Alan g. All the best, G. Rodrigues From eprice@ptc.com Mon Feb 10 10:50:09 2003 From: eprice@ptc.com (Erik Price) Date: Mon Feb 10 10:50:09 2003 Subject: [Tutor] List exercise In-Reply-To: <7497DCA1C240C042B28F6657ADFD8E0901F850A2@i2km11-ukbr.domain1.systemhost.net> References: <7497DCA1C240C042B28F6657ADFD8E0901F850A2@i2km11-ukbr.domain1.systemhost.net> Message-ID: <3E47C912.4060405@ptc.com> alan.gauld@bt.com wrote: > The only problem with this approach is that learning by experience > can teach an awful lot of bad habits that are hard to break. Using > a tutorial that teaches good habits early saves a lot of time in > the long run because you don't have to unlearn so much. One thing that always helps me is to see the source code of others. This can also teach very bad habits, because the neophyte might make the assumption that the author of some source code would know not to use bad habits (in the situation where the author may have used a bad habit), but if you exercise variety in reading the source code of others, you can hopefully alleviate this. There are books written about avoiding bad habits too, for instance one of the best I've seen is a little pocket guide called "The Elements of Java Style". Admittedly not very relevant to a Python programmer, but maybe the Python Cookbook has a section dedicated to style. (Anyone know?) Erik From alan.gauld@bt.com Mon Feb 10 12:10:04 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon Feb 10 12:10:04 2003 Subject: [Tutor] Re: Question on Regular Expression Help Message-ID: <7497DCA1C240C042B28F6657ADFD8E0901F850AB@i2km11-ukbr.domain1.systemhost.net> > But +42 is not an integer, right? This can be fixed of course. >>> def isnumber(str): ... if str[0] in '+-': ... start = 1 ... else: ... start = 0 Or replace the if/else with: def isnumber(strng) start = strng[0] in '+-' ... for c in strng[start:]: ... if c not in '0123456789': ... return False ... return True But I prefer: > Don Arnold wrote: > >>> def isInt(aString): > try: > int(aString) > return True > except: > return False > >But note that int(3.14) => 3 ! Is that what you want? Is 3.14 an integer? Doesn't matter since we only return a boolean, if the number can be converted to an int it is a number, thats all I care about here... > import re > def isInteger(s): > return re.match(r'[+-]?\d+$', s) I note we've changed the test now to isInteger from isNumber... > From a performance point of view, the try/except version is > the faster when the number is really and integer, It's faster regardless, it just doesn't guarantee the number is an integer. > regular expression version is the slowest, but I think > regular expression might win big if applied to a bigger problem, Yes I agree, that's why I suggested it it to an earliuer poster as the best flexible solution for dealing with strange unformatted input. > re.findall(r'\s([+-]?\d+)\s', s) Just so. Alan G. From alan.gauld@bt.com Mon Feb 10 12:28:13 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon Feb 10 12:28:13 2003 Subject: [Tutor] Sun says: Don't use Java, use Python! Message-ID: <7497DCA1C240C042B28F6657ADFD8E0901F850AD@i2km11-ukbr.domain1.systemhost.net> > ...The key difference is that Python is a scripting language. > This means there is no compilation to byte code ....It has to > perform syntax checks and it must parse the ascii text Interesting but only partially right since most of the time for production code Python will already have compiled its modules to byte code and only the main module remains in ascii text. As to relative speeds I'd tend to agree that Python runs as fast as Java(*) and Perl a little faster. Alan G. (*)Haven't tried gcc v3's native Java compilation yet, I'd expect that to change the ground rules somewhat in Java's favour... From Janssen@rz.uni-frankfurt.de Mon Feb 10 13:02:02 2003 From: Janssen@rz.uni-frankfurt.de (Michael Janssen) Date: Mon Feb 10 13:02:02 2003 Subject: [Tutor] List exercise In-Reply-To: <7497DCA1C240C042B28F6657ADFD8E0901F850A2@i2km11-ukbr.domain1.systemhost.net> Message-ID: On Mon, 10 Feb 2003 alan.gauld@bt.com wrote: > The only problem with this approach is that learning by experience > can teach an awful lot of bad habits that are hard to break. Using > a tutorial that teaches good habits early saves a lot of time in > the long run because you don't have to unlearn so much. When I remember correctly the threads "list exercise" wasn't such a shiny example of good programming style, was it? Taking up bad habits while learning by experience is truely a weightfull argument, but isn't it said that python protects the learner from bad habits? And also, that you can learn python very fast, write usefull code and *grow with* the language? A python learner doesn't start with bad habits (solong s/he doesn't come from a bad habit language ;-); s/he writes somewhat simpleminded code that's all. I don't want to suggest never read a tutorial - but I can't see a need to elaborate about tutorial examples when the real world is that near. Especially when the examples are more complicated than the real world: you wont often get a list of ints, strings, lists all mixed together in a reasonable programm-design, will you? Anybody who comes to the tutor-list claiming that s/he got a internal data structur like: ['spam!', 1, ['Brie', 'Roquefort', 'Pol le Veq'], [1, 2, 3]] would gain some remarks about using dictionaries to count strings (or whatever else might be archived with the above list). It's very interessting - for me as a student of educational sience - how tutorials claim to explain something but tries to accomplish this effort on objects, which are harder than necessary (to say the least). Reading (well-written) existing code is a way out - as Erik Price recently suggests. Michael From alan.gauld@bt.com Mon Feb 10 13:30:09 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon Feb 10 13:30:09 2003 Subject: [Tutor] Re: Question on Regular Expression Help Message-ID: <7497DCA1C240C042B28F6657ADFD8E0901F850AC@i2km11-ukbr.domain1.systemhost.net> > Don Arnold wrote: > > >>> def isInt(aString): > > try: > > int(aString) > > return True > > except: > > return False > > But note that int(3.14) => 3 ! Is that what you want? Is 3.14 an integer? > Oops, I didn't notice it was Don who shifted the target from numbers to integers. In that case my earlier reasoning was wrong. However as he says it does work, just not for the reasons I gave! Alan G. From deirdrehac@lycos.co.uk Mon Feb 10 13:40:03 2003 From: deirdrehac@lycos.co.uk (Deirdre Hackett) Date: Mon Feb 10 13:40:03 2003 Subject: [Tutor] indexing of arrays in numeric Message-ID: <000501c2d133$b0235cc0$0800a8c0@WHOOPI> This is a multi-part message in MIME format. ------=_NextPart_000_0009_01C2CD36.88AD1DD0 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable I downloaded numeric to help me with my array problems.... I either have the data in this format, data =3D ([2345,4567,-6754]) or =20 xin =3D 2345 yin =3D 4567 zin =3D -6754 I created an array of 10 rows and 3 columns, datab =3D zeros((10,3)) I want the 3 values to be along each row but I am having trouble = figuring out how to index the array specifically. for x, in arange(28): put(datab, [x], xin) put(datab, [x+1], yin) put(datab, [x+2], zin) This obviously does not work but I hope it will give you an idea of what = I mean. Not sure how the sequence works. I know that you can say, a =3D arrayrange(9) a.shape =3D (3,3) print a[0,0] #will give you first row, first column,ie first element print a[0] #get first row I want to be able to do this except the opposite way around. Thanks=20 Deirdre ------=_NextPart_000_0009_01C2CD36.88AD1DD0 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
I downloaded numeric to help me with my = array=20 problems....
 
I either have the data in this = format,
    data =3D = ([2345,4567,-6754])
or=20    
    xin =3D = 2345
    yin =3D = 4567
    zin =3D = -6754
 
I created an array of 10 rows and 3=20 columns,
   datab =3D zeros((10,3))
 
I want the 3 values to be along each = row but I am=20 having trouble figuring out how to index the array = specifically.
 
for x, in = arange(28):
   =20 put(datab, [x], xin)
    put(datab, [x+1],=20 yin)
    put(datab, [x+2], zin)
 
This obviously does not work but I hope = it will=20 give you an idea of what I mean.
Not sure how the sequence works. I know = that you=20 can say,
a =3D arrayrange(9)
a.shape =3D (3,3)
print a[0,0] #will give you first row, = first=20 column,ie first element
print a[0]    #get first = row
 
I want to be able to do this except the opposite way around.
Thanks
Deirdre
------=_NextPart_000_0009_01C2CD36.88AD1DD0-- From phthenry@earthlink.net Mon Feb 10 14:40:05 2003 From: phthenry@earthlink.net (Paul Tremblay) Date: Mon Feb 10 14:40:05 2003 Subject: [Tutor] Sun says: Don't use Java, use Python! In-Reply-To: <7497DCA1C240C042B28F6657ADFD8E0901F850AD@i2km11-ukbr.domain1.systemhost.net> References: <7497DCA1C240C042B28F6657ADFD8E0901F850AD@i2km11-ukbr.domain1.systemhost.net> Message-ID: <20030210143718.B1785@localhost.localdomain> On Mon, Feb 10, 2003 at 05:25:04PM -0000, alan.gauld@bt.com wrote: > > ...The key difference is that Python is a scripting language. > > This means there is no compilation to byte code ....It has to > > perform syntax checks and it must parse the ascii text > > Interesting but only partially right since most of the time for > production code Python will already have compiled its modules to > byte code and only the main module remains in ascii text. > > As to relative speeds I'd tend to agree that Python runs as fast > as Java(*) and Perl a little faster. > > Alan G. > So doesn't this mean that if you are planning to distribute a Python script (as I am), that you should distribute it as a module? I hadn't even considered that modules are faster than scripts before reading this thread. Paul -- ************************ *Paul Tremblay * *phthenry@earthlink.net* ************************ From jeff@ccvcorp.com Mon Feb 10 14:49:10 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Mon Feb 10 14:49:10 2003 Subject: [Tutor] Class as Exception References: <5.2.0.9.0.20030208152729.0303a798@66.28.54.253> Message-ID: <3E480204.2060607@ccvcorp.com> Bob Gailer wrote: > A couple of times I got the following to work. Now I just get an > exception. > > >>> class n(str):pass > >>> raise n, 'tst' > Traceback (most recent call last): > File "", line 1, in ? > TypeError: exceptions must be strings, classes, or instances, not type > > Why would the same code work, then fail? Did you derive your exception class from str the times that it worked? By doing so, you're making your class into a new-style object (i.e., a type) instead of an old-style (instance) object. That's what the interpreter is complaining about. As others have said, though, if you want to use a class as an exception, you really ought to be deriving it from Exception (or some other subclass of Exception), not from something like str. Jeff Shannon Technician/Programmer Credit International From phthenry@earthlink.net Mon Feb 10 14:52:02 2003 From: phthenry@earthlink.net (Paul Tremblay) Date: Mon Feb 10 14:52:02 2003 Subject: [Tutor] how to write documentation for a script Message-ID: <20030210145155.D1785@localhost.localdomain> I have written a script that converts RTF to XML. The script is in perl, and I wish to convert it to Python. Is there a way to include documentation within the actual script, as you can in perl? The book I have on Pyton, called *Core Pyton,* states that you put the documentation between quotation marks right after the startup line: #!usr/bin/python " This script converts Microsoft RTF to XML.." However, this only allows for the simplest form of documentation. You can't bold words, make headers, and do other things that you can in perl. I'm not complaining. I just want to make sure that I'm not missing something. I would like my script to have really nice documentation. Thanks Paul -- ************************ *Paul Tremblay * *phthenry@earthlink.net* ************************ From jeff@ccvcorp.com Mon Feb 10 15:00:43 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Mon Feb 10 15:00:43 2003 Subject: [Tutor] Passing attribute calls to has-a classes References: <000e01c2cff1$8ed9c6a0$c9e03942@nc.rr.com> Message-ID: <3E4803FD.3040704@ccvcorp.com> Joel Ricker wrote: >Aha, figured it out! > >: My code snippet: >: >: class MyImage: >: >: def __init__(self, fp): >: self.master = Image.open(fp) > >My problem was here, I needed to say: > > self.__dict__['master'] = Image.open(fp) > >: def __getattr__(self, name): >: return self.master.__getattr__(name) >: #I've also tried getattr(self.master, name) > >and: > return getattr(self.master, name) > >: def __setattr__(self, name, value): >: self.master.__setattr__(name, value) >: #I've also tried setattr(self.master, name, value) > >and: > return setattr(self.master, name, value) > > I would've thought that anywhere in these methods where you're using self.master, you would want to change it to use self.__dict__['master'] -- by using self.master in __getattr__(), you're setting up a potentially infinite loop of recursive __getattr__() calls. [...] def __getattr__(self, name): return getattr(self.__dict__['master'], name) def __setattr__(self, name, value): return setattr(self.__dict__['master'], name, value) I suppose that the change wouldn't be necessary in __setattr__(), because the 'self.master' resolution would pass through your __getattr__() which should return the right object (though using the instance dict directly cuts out an unneeded layer of indirection), but I'd be very surprised if your class actually works with 'self.master' used in __getattr__(). Jeff Shannon Technician/Programmer Credit International From jeff@ccvcorp.com Mon Feb 10 15:01:18 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Mon Feb 10 15:01:18 2003 Subject: [Tutor] Re: Question on Regular Expression Help References: <5.1.0.14.0.20030208162343.02cdae80@www.thinkware.se> Message-ID: <3E47FB36.8090201@ccvcorp.com> Magnus Lycka wrote: > > I think the code below works, but I don't really like it... I'm a bit > allergic to comparing floats for equality, even though I think it > should work in this particular case. [...] > > >>> def isInt(s): > ... try: > ... return int(s) == float(s) > ... except: > ... return False As long as an integer is always exactly representable as a float (that is, a number 2343265.00 can be exactly represented in float format), which I believe to be the case, then this will work. However, the O.P.'s problem didn't specify that it was necessary to find integers, just that it was necessary to find "numbers". In this case, the format of the input file would be the key -- if the numbers there are always given as integer values, then testing whether int(value) throws an exception is enough. If the numbers sometimes have decimal places (or, indeed, even if they are always integers) then testing whether float(value) throws an exception will work. Since the integer-ness (integrity?) of the number is irrelevant, it's not necessary to do both and compare the result. So, my suggestion to the O.P. would be this little snippet: def IsNumber(val): try: float(val) return True except: return False temps = [x for x in inputstring.split() if IsNumber(x)] Now 'temps' is a list of strings which contain only numeric values. Note that we're not saving the numeric value, we're only noting that these strings *can* be converted to numbers -- this will be important later on when actually using the number in question. If we will need them as numbers later, the following code might be more effective: temps = [] for item in inputstring.split(): try: x = float(item) temps.append(x) except: pass Now we have a list of floats. Of course, if we really want integers then int(item) will work just as well as float(item) -- or even int(float(item)), if we want to accept numbers with decimal values but truncate them to integers. Jeff Shannon Technician/Programmer Credit International From ramrom@earthling.net Mon Feb 10 15:03:03 2003 From: ramrom@earthling.net (Bob Gailer) Date: Mon Feb 10 15:03:03 2003 Subject: [Tutor] Class as Exception In-Reply-To: <3E480204.2060607@ccvcorp.com> References: <5.2.0.9.0.20030208152729.0303a798@66.28.54.253> Message-ID: <5.2.0.9.0.20030210125715.01a4f520@66.28.54.253> --=======1BA76B9F======= Content-Type: text/plain; x-avg-checked=avg-ok-39F2189B; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit At 11:48 AM 2/10/2003 -0800, Jeff Shannon wrote: > if you want to use a class as an exception, you really ought to be deriving it from Exception (or some other subclass of Exception) Yep that's what I needed. After reading a good explanation of class-based exceptions in TWC's Python Programming Patterns it came clear. I had been trying to work from the language reference, which is pretty terse. Bob Gailer mailto:ramrom@earthling.net 303 442 2625 --=======1BA76B9F======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-39F2189B Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.445 / Virus Database: 250 - Release Date: 1/21/2003 --=======1BA76B9F=======-- From norvell@houseofspearman.org Mon Feb 10 15:26:45 2003 From: norvell@houseofspearman.org (Norvell Spearman) Date: Mon Feb 10 15:26:45 2003 Subject: [Tutor] Sun says: Don't use Java, use Python! In-Reply-To: <20030210143718.B1785@localhost.localdomain> References: <7497DCA1C240C042B28F6657ADFD8E0901F850AD@i2km11-ukbr.domain1.systemhost.net> <20030210143718.B1785@localhost.localdomain> Message-ID: <20030210202519.GA23743@houseofspearman.org> On Monday, 2003.02.10, 14:37:18 -0500, Paul Tremblay wrote: > So doesn't this mean that if you are planning to distribute a Python > script (as I am), that you should distribute it as a module? I hadn't > even considered that modules are faster than scripts before reading this > thread. According to the Python Tutorial, section 6.1.2, ``Compiled'' Python files, the only thing faster about a compiled file is the speed with which it is loaded. Once loaded, it won't run any faster than the regular script version of the program. -- Norvell Spearman From jeff@ccvcorp.com Mon Feb 10 16:32:05 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Mon Feb 10 16:32:05 2003 Subject: [Tutor] Sun says: Don't use Java, use Python! References: <7497DCA1C240C042B28F6657ADFD8E0901F850AD@i2km11-ukbr.domain1.systemhost.net> <20030210143718.B1785@localhost.localdomain> Message-ID: <3E480933.3000503@ccvcorp.com> Paul Tremblay wrote: >On Mon, Feb 10, 2003 at 05:25:04PM -0000, alan.gauld@bt.com wrote: > > >>>...The key difference is that Python is a scripting language. >>>This means there is no compilation to byte code ....It has to >>>perform syntax checks and it must parse the ascii text >>> >>> >>Interesting but only partially right since most of the time for >>production code Python will already have compiled its modules to >>byte code and only the main module remains in ascii text. >> >> >So doesn't this mean that if you are planning to distribute a Python >script (as I am), that you should distribute it as a module? I hadn't >even considered that modules are faster than scripts before reading this >thread. > > That depends on the script. Remember, the term 'module', when applied to Python files, is simply a statement that the file is used via 'import' in some other file, so distributing a script as a module implies that you have a script file that imports that module and runs some function(s) from it. If it's a short, quick script, then it's probably not going to make enough of a difference to worry about. The simplicity of distributing a single file would be more valuable than the speed gain that you'd get from having the bytecode precompiled. (Precompilation only affects startup speed, *not* actual running speed.) If it's a longer script, then you might get enough of a time savings to make it worthwhile having a second "driver" script, that does nothing but import your main file as a module and run a function from it ('import mymodule; mymodule.run()'). However, if your program is big enough that the startup cost is significant, then odds are that it's big enough that it should be split into more than one module anyhow. Using several small, functionally discrete modules makes a program easier to understand and maintain than having one or two big, bulky, everything-but-the-kitchen-sink modules. So in this case, it's probably best to have three or four or six (or whatever number of subunits your program logically breaks down into) separate modules, and organize all of those into a package. This involves not much more than putting them in their own directory and adding a blank __init__.py file, and some slight changes to your "driver" script ('from mypackage import main; main.run()'). Depending on your distribution requirements, it may or may not be worth the effort to set up a distutils script to install your package on new machines. If it's a pure Python package, then all distutils would be doing is copying it to a subdirectory of [Python-home]\Lib\site-packages, which is easy enough to do manually... Jeff Shannon Technician/Programmer Credit International From ramrom@earthling.net Mon Feb 10 16:48:11 2003 From: ramrom@earthling.net (Bob Gailer) Date: Mon Feb 10 16:48:11 2003 Subject: [Tutor] how to write documentation for a script In-Reply-To: <20030210145155.D1785@localhost.localdomain> Message-ID: <5.2.0.9.0.20030210144400.01a4c960@66.28.54.253> --=======33AF436======= Content-Type: text/plain; x-avg-checked=avg-ok-1B473DD2; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit At 02:51 PM 2/10/2003 -0500, Paul Tremblay wrote: >Is there a way to include documentation within the actual script? The book >I have on Pyton, called *Core Pyton,* states that >you put the documentation between quotation marks right after the startup >line. Any line can be or end with a comment. Just start the comment with #. The "documentation between quotation marks right after the startup line" is a special comment known as a doc string; it becomes a property of the object being documented, and is accessible using objectname.__doc__. Bob Gailer mailto:ramrom@earthling.net 303 442 2625 --=======33AF436======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-1B473DD2 Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.445 / Virus Database: 250 - Release Date: 1/21/2003 --=======33AF436=======-- From jeff@ccvcorp.com Mon Feb 10 17:10:16 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Mon Feb 10 17:10:16 2003 Subject: [Tutor] how to write documentation for a script References: <20030210145155.D1785@localhost.localdomain> Message-ID: <3E482246.1090802@ccvcorp.com> Paul Tremblay wrote: >Is there a way to include documentation within the actual script, as you >can in perl? The book I have on Pyton, called *Core Pyton,* states that >you put the documentation between quotation marks right after the >startup line: > >#!usr/bin/python > >" This script converts Microsoft RTF to XML.." > >However, this only allows for the simplest form of documentation. You >can't bold words, make headers, and do other things that you can in >perl. > I know nothing about how things work for Perl, but Python itself has no facilities for internal documentation to be anything other than plain text. You can use docstrings for the module (like that example above) and for each function, class, method, etc, but they're all plain text. You might, however, want to look into something that's called (IIRC) reStructured Text. I *think* that ActiveState has their hands in this, but I'm not sure -- I remember some discussion of it, and even some attempt to encourage all Python modules to use it for docstrings, but that's about it. (I'd imagine that Google would find it, or you could check the PEP listings on python.org.) What I can say is that it's a plain-text markup scheme, whereby something can be easily readable as plain text but can also be parsed and re-presented in a fancy formatted way with appropriate tools. By using rST, you'd be able to have readable docstrings in your modules, and then use a simple tool to extract that documentation and turn it into prettified HTML (or use Reportlab to crank out a PDF, or whatever...) Jeff Shannon Technician/Programmer Credit International From ramrom@earthling.net Mon Feb 10 17:11:13 2003 From: ramrom@earthling.net (Bob Gailer) Date: Mon Feb 10 17:11:13 2003 Subject: [Tutor] importing constants In-Reply-To: <93154097190.20030209184254@columbus.rr.com> Message-ID: <5.2.0.9.0.20030210150409.02f09680@66.28.54.253> --=======16231CB7======= Content-Type: text/plain; x-avg-checked=avg-ok-1B473DD2; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit At 06:42 PM 2/9/2003 -0500, R. Alan Monroe wrote: >I have a project consisting of a main file and two modules. If I want >to set up a new third module file establishing some constants, is it >safe to re-import it multiple times, once in each file and module? Yes >Are there any side-effects to doing that? No Suggestion: make "constant" names upper case e;g; IDLE = 1. This helps later when reading code to remind you that IDLE is intended to be constant. If you import constants then you must prefix the module name to each constant: constants.IDLE OTOH if you from constants import * then just use the constant name. Bob Gailer mailto:ramrom@earthling.net 303 442 2625 --=======16231CB7======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-1B473DD2 Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.445 / Virus Database: 250 - Release Date: 1/21/2003 --=======16231CB7=======-- From ATrautman@perryjudds.com Mon Feb 10 17:40:55 2003 From: ATrautman@perryjudds.com (Alan Trautman) Date: Mon Feb 10 17:40:55 2003 Subject: [Tutor] importing constants Message-ID: <0BA95581EDA7D611841B00A0C9AD25DD2B59C9@mail.pjinet.com> OTOH if you from constants import * then just use the constant name. Great Idea! I finally see a great reason to use from x import * as all constants across the modules will have the same name with only one file to edit. Thanks Bob From dyoo@hkn.eecs.berkeley.edu Mon Feb 10 17:44:26 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Feb 10 17:44:26 2003 Subject: [Tutor] how to write documentation for a script In-Reply-To: <3E482246.1090802@ccvcorp.com> Message-ID: > >Is there a way to include documentation within the actual script, as > >you can in perl? > > You might, however, want to look into something that's called (IIRC) > reStructured Text. I *think* that ActiveState has their hands in this, There's an explanation on the emerging "StructuredText" format here: http://www.python.org/sigs/doc-sig/stext.html It looks like there is pretty good consensus for the StructuredText approach --- it allows us to combine some kind of markup (emphasis, paragraphs) within docstrings. And StructuredText seems pretty versatile; the Zope Book is written in StructuredText: http://www.zope.org/DocProjects/zope_book_signups/index_html Hope this helps! From abli@freemail.hu Mon Feb 10 17:56:46 2003 From: abli@freemail.hu (Abel Daniel) Date: Mon Feb 10 17:56:46 2003 Subject: [Tutor] how to write documentation for a script In-Reply-To: <20030210145155.D1785@localhost.localdomain> References: <20030210145155.D1785@localhost.localdomain> Message-ID: <20030210225528.GB748@hooloovoo> Paul Tremblay (phthenry@earthlink.net) wrote: > I have written a script that converts RTF to XML. The script is in perl, > and I wish to convert it to Python. > > Is there a way to include documentation within the actual script, as you > can in perl? The book I have on Pyton, called *Core Pyton,* states that > you put the documentation between quotation marks right after the > startup line: You can (or rather should) do similarly for documenting classes and strings. See pep no.257 http://python.org/peps/pep-0257.html > > #!usr/bin/python > > " This script converts Microsoft RTF to XML.." > > However, this only allows for the simplest form of documentation. You > can't bold words, make headers, and do other things that you can in > perl. > > I'm not complaining. I just want to make sure that I'm not missing > something. I would like my script to have really nice documentation. I guess the idea is that fancy markup isn't usefull if you edit the code in a simple text-editor, or when experimenting at the interactive prompt, as such tools cant handle anything more fancy than simple text. So markup is only usefull if you process the code to generate documentation. One such system is http://docutils.sourceforge.net/ "The purpose of the Docutils project is to create a set of tools for processing plaintext documentation into useful formats, such as HTML, XML, and TeX." I didnt try that, but it looks to be using reStructuredText, which can do basic markup. abli abli@freemail.hu From R. Alan Monroe" References: <5.2.0.9.0.20030210150409.02f09680@66.28.54.253> Message-ID: <196241370612.20030210185727@columbus.rr.com> > At 06:42 PM 2/9/2003 -0500, R. Alan Monroe wrote: >>I have a project consisting of a main file and two modules. If I want >>to set up a new third module file establishing some constants, is it >>safe to re-import it multiple times, once in each file and module? > Yes >>Are there any side-effects to doing that? > No Cool. > Suggestion: make "constant" names upper case e;g; IDLE = 1. This helps > later when reading code to remind you that IDLE is intended to be constant. Good idea! Alan From phthenry@earthlink.net Mon Feb 10 19:30:05 2003 From: phthenry@earthlink.net (Paul Tremblay) Date: Mon Feb 10 19:30:05 2003 Subject: [Tutor] how to write documentation for a script In-Reply-To: References: <3E482246.1090802@ccvcorp.com> Message-ID: <20030210192942.E1785@localhost.localdomain> On Mon, Feb 10, 2003 at 02:37:39PM -0800, Danny Yoo wrote: > > > > >Is there a way to include documentation within the actual script, as > > >you can in perl? > > > > You might, however, want to look into something that's called (IIRC) > > reStructured Text. I *think* that ActiveState has their hands in this, > > > There's an explanation on the emerging "StructuredText" format here: > > http://www.python.org/sigs/doc-sig/stext.html > > It looks like there is pretty good consensus for the StructuredText > approach --- it allows us to combine some kind of markup (emphasis, > paragraphs) within docstrings. > > > And StructuredText seems pretty versatile; the Zope Book is written in > StructuredText: > > http://www.zope.org/DocProjects/zope_book_signups/index_html > > Thanks. Structured text looks like a good idea. However, I have spent the last two hours (gRRRR) trying to get the pytondoc utility to work. I am given all sorts of warning errors. Here is the last one I got. My thinking is that the module is too old to work with newer versions of python? Anyone had any success with this? Thanks Paul error messages: DeprecationWarning: the regex module is deprecated; please use the re module import regex, regsub /usr/local/lib/python2.1/regsub.py:15: DeprecationWarning: the regsub module is deprecated; please use re.sub() DeprecationWarning) Error: Couldn't import StructuredText (exceptions.ImportError: No module named ts_regex) -- ************************ *Paul Tremblay * *phthenry@earthlink.net* ************************ From phthenry@earthlink.net Mon Feb 10 20:11:03 2003 From: phthenry@earthlink.net (Paul Tremblay) Date: Mon Feb 10 20:11:03 2003 Subject: [Tutor] Sun says: Don't use Java, use Python! In-Reply-To: <3E480933.3000503@ccvcorp.com> References: <7497DCA1C240C042B28F6657ADFD8E0901F850AD@i2km11-ukbr.domain1.systemhost.net> <20030210143718.B1785@localhost.localdomain> <3E480933.3000503@ccvcorp.com> Message-ID: <20030210200958.G1785@localhost.localdomain> On Mon, Feb 10, 2003 at 12:18:59PM -0800, Jeff Shannon wrote: > Paul Tremblay wrote: > > >So doesn't this mean that if you are planning to distribute a Python > >script (as I am), that you should distribute it as a module? I hadn't > >even considered that modules are faster than scripts before reading this > >thread. > > > > > > That depends on the script. Remember, the term 'module', when applied > to Python files, is simply a statement that the file is used via > 'import' in some other file, so distributing a script as a module > implies that you have a script file that imports that module and runs > some function(s) from it. > > If it's a short, quick script, then it's probably not going to make > enough of a difference to worry about. The simplicity of distributing a > single file would be more valuable than the speed gain that you'd get > from having the bytecode precompiled. (Precompilation only affects > startup speed, *not* actual running speed.) The script will be over 3,000 lines long. In order to parse the RTF, it has to make a dozen or so passes through the file. The reason for so many passes is that RTF is very dense. I had written a successful perl script that parsed RTF in one pass, but the script is almost unreadable. The newer perl script (not the one above) makes a module for each pass through the file. I thought this was bad design, because I had a dozen or so modules. But you are telling me that it is perhaps best to keep the script modular? > > main.run()'). > > Depending on your distribution requirements, it may or may not be worth > the effort to set up a distutils script to install your package on new > machines. If it's a pure Python package, then all distutils would be > doing is copying it to a subdirectory of > [Python-home]\Lib\site-packages, which is easy enough to do manually... > Setting up the distribution is not such an easy task. With the perl script, I thought it would be a piece of cake, but I am really strugging with writing the set-up script. For that reason, I wanted to make sure I knew how to do this with Python *before* the script was finished, and before I ralized that I should have done x, y or z--but realized it was going to be really hard to do so at this point. Paul -- ************************ *Paul Tremblay * *phthenry@earthlink.net* ************************ From dyoo@hkn.eecs.berkeley.edu Mon Feb 10 20:35:04 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Feb 10 20:35:04 2003 Subject: [Tutor] Distutils In-Reply-To: <20030210200958.G1785@localhost.localdomain> Message-ID: > > Depending on your distribution requirements, it may or may not be > > worth the effort to set up a distutils script to install your package > > on new machines. If it's a pure Python package, then all distutils > > would be doing is copying it to a subdirectory of > > [Python-home]\Lib\site-packages, which is easy enough to do > > manually... > > > > Setting up the distribution is not such an easy task. With the perl > script, I thought it would be a piece of cake, but I am really strugging > with writing the set-up script. For that reason, I wanted to make sure I > knew how to do this with Python *before* the script was finished Hi Paul, (By the way, there was an article on Perl's MakeMaker system in a recent edition of The Perl Journal, and the book "Computer Science and Perl Programming" has a section on it in Chapter 42... (hmmm, that number comes up a lot...)) I have some examples of Python scripts that have been "distutil"ed. For example, here's a pathetically puny one: http://hkn.eecs.berkeley.edu/~dyoo/python/__std__/ Organizing a set of modules to distribute to other folks via disutils isn't actually that bad. For the __std__ module above, I organized my code into a package named "__std__". I also cooked up a quicky 'setup.py' file that tells Distutils what I'm packaging: ### from distutils.core import setup setup(name="__std__", version="1.0", author="Danny Yoo", author_email="dyoo@hkn.eecs.berkeley.edu", url="http://hkn.eecs.berkeley.edu/~dyoo/python/__std__/", packages=["__std__"] ) ### I think every keyword parameter in there is optional except for the 'name' and 'packages' keywords... *grin* But if you'd like, I'm sure that someone here can give a deeper introduction into Python's distutils system. But the official docs: http://python.org/dev/doc/devel/dist/dist.html are decent. Anyway, the small effort to 'Distutils' a package is worth it in my mind, because it makes module installation convenient and consistant for others. From jeff@ccvcorp.com Mon Feb 10 20:45:02 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Mon Feb 10 20:45:02 2003 Subject: [Tutor] Sun says: Don't use Java, use Python! References: <7497DCA1C240C042B28F6657ADFD8E0901F850AD@i2km11-ukbr.domain1.systemhost.net> <20030210143718.B1785@localhost.localdomain> <3E480933.3000503@ccvcorp.com> <20030210200958.G1785@localhost.localdomain> Message-ID: <3E485578.2070209@ccvcorp.com> Paul Tremblay wrote: >On Mon, Feb 10, 2003 at 12:18:59PM -0800, Jeff Shannon wrote: > >>If it's a short, quick script, then it's probably not going to make >>enough of a difference to worry about. The simplicity of distributing a >>single file would be more valuable than the speed gain that you'd get >>from having the bytecode precompiled. (Precompilation only affects >>startup speed, *not* actual running speed.) >> >> > >The script will be over 3,000 lines long. In order to parse the RTF, it >has to make a dozen or so passes through the file. The reason for so >many passes is that RTF is very dense. I had written a successful perl >script that parsed RTF in one pass, but the script is almost unreadable. > >The newer perl script (not the one above) makes a module for each pass >through the file. I thought this was bad design, because I had a dozen >or so modules. > >But you are telling me that it is perhaps best to keep the script >modular? > Yes. The more modular it is, the easier it will be to understand what's going on. A module for each pass through the file sounds fairly reasonable, since it's performing a completely different process each time. You might also want to have a separate module for utility functions that are used in more than one pass, if there are any. But rather than simply separating functions by the pass that they're used on, think about your script in units of related functionality. If you're converting RTF to XML, then you want to have the code that parses and makes sense of the RTF separate from the code that creates the XML. Ideally, you should be able to point to each module and name a single task that it performs -- if you need to use "and" more than once in describing a module, then it's a good candidate for splitting into two or more separate modules. Then you can describe the overall control flow of the program in terms of module interactions. "The main module uses the parser module to organize the input, then processes that with the analyzer module. The results of this are used by the configuration module to drive the xml_output module." (I just made all this up, and have absolutely no idea if your code could reasonably be broken down into chunks in that sort of way, but the point is to show that each module should have a separate, easily identifiable task.) That way, you can work on one small subset of the problem at a time (just basic parsing, or just analyzing your parse tree, or just writing XML) and not worry so much about keeping the entire process in your head at once. >Setting up the distribution is not such an easy task. With the perl >script, I thought it would be a piece of cake, but I am really strugging >with writing the set-up script. For that reason, I wanted to make sure I >knew how to do this with Python *before* the script was finished, and >before I ralized that I should have done x, y or z--but realized it was >going to be really hard to do so at this point. > If you can set your program up as a package, or possibly even a nested package with several subpackages (depending on how many layers of task heirarchy you can reasonably separate), then distribution in Python shouldn't be very difficult. If just copying the package directory to a new machine's site-packages doesn't work, then look into distutils -- it's a little daunting at first, but it's really pretty easy to use, especially if your package is all Python. (Things get more complicated if you've got a C extension that needs compiled on the target machine, but it doesn't sound like you're intending to do that.) Jeff Shannon Technician/Programmer Credit International From erikprice@mac.com Mon Feb 10 23:25:04 2003 From: erikprice@mac.com (Erik Price) Date: Mon Feb 10 23:25:04 2003 Subject: [Tutor] Sun says: Don't use Java, use Python! In-Reply-To: <20030210200958.G1785@localhost.localdomain> Message-ID: On Monday, February 10, 2003, at 08:09 PM, Paul Tremblay wrote: > The script will be over 3,000 lines long. In order to parse the RTF, it > has to make a dozen or so passes through the file. The reason for so > many passes is that RTF is very dense. I had written a successful perl > script that parsed RTF in one pass, but the script is almost > unreadable. > > The newer perl script (not the one above) makes a module for each pass > through the file. I thought this was bad design, because I had a dozen > or so modules. > > But you are telling me that it is perhaps best to keep the script > modular? [If I ever had to read your script's source code,] I would say so. One of the things that I do like about Java is that it forces the programmer to split their code up into separate files (similar to what Python does with whitespace and indentation). Each file contains its own public class. It's not exactly convenient for quick work, but that's people generally wouldn't use Java for scripting (after all there's Python!). Every [public] class gets its own file. If I'm reading through your main script and see that you use a class called RtfReader to read and parse RTF code, I might want to read the details of how the RtfReader works -- or I might not. Maybe I just want to see what your main script does for now and go into the details later. This is one of the nice things about modules and splitting up a 3000-line program into modular chunks. Plus, it's a LOT easier to use your RtfReader in another script than it is to search through the source, copy and paste the relevant code, then modify it to work in the new script. A lesson I learned on this very list a long time ago (I think it was Danny Yoo) was to use the "if __name__ == '__main__'" trick. Even for the most simple of things, like the accessor/mutator script I made for generating JavaBeans and posted on this list last week -- I'll probably never use that module for anything else, but in case I do, I can just import the module and refer to the functions. Erik -- Erik Price email: erikprice@mac.com jabber: erikprice@jabber.org From carroll@tjc.com Tue Feb 11 00:28:01 2003 From: carroll@tjc.com (Terry Carroll) Date: Tue Feb 11 00:28:01 2003 Subject: [Tutor] Test if name is defined? Message-ID: Is there a way to test to see if a variable is defined other than with the exception system? I'm creating an object with several attributes based on the content of a huge initialiation file. The file comprises a series of lines, each of which is a tab-separated list of three fields: an identifier for the object, the name of an attribute, and the value of the attribute. I want to put an object into a dictionary only if either the The easiest way for me to handle this is to create an object corresponding to the identifier the first time I see it, and to set an attribute for each line I see, until I see a new object identifier. At that time, I'll want to either discard the object I just created, or else put it into a dictionary indexed by the object ID; in any event, I'll go on to create a new object corresponding to the new object ID I just read in. I only want to keep the object if I read in a value for either the attribute kGB0 or kBigFive attributes (or both) are defined. If Python had a defined() method like Perl (sorry, it's my only point of comparison), I'd do something like this: if defined(current.kGB0) or defined(current.kBigFive): dict[current.ID] = deepcopy(current) I can't do this in Python, can I? -- Terry Carroll | "To have this rare opportunity Santa Clara, CA | is a rare opportunity." carroll@tjc.com | - Houston Rockets' Yao Ming, on being named Modell delendus est | starting center for the 2003 NBA All-Star Game From shalehperry@attbi.com Tue Feb 11 00:53:02 2003 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Tue Feb 11 00:53:02 2003 Subject: [Tutor] Test if name is defined? In-Reply-To: References: Message-ID: <200302102152.15209.shalehperry@attbi.com> On Monday 10 February 2003 21:26, Terry Carroll wrote: > Is there a way to test to see if a variable is defined other than with = the > exception system? > In a recent enough python: def defined(thing): return (thing in locals()) or (thing in globals()) or, old way: def defined(thing): return (locals().has_key(thing)) or (globals().has_key(thing)) From phthenry@earthlink.net Tue Feb 11 01:23:03 2003 From: phthenry@earthlink.net (Paul Tremblay) Date: Tue Feb 11 01:23:03 2003 Subject: [Tutor] Sun says: Don't use Java, use Python! In-Reply-To: References: <20030210200958.G1785@localhost.localdomain> Message-ID: <20030211012215.A12957@localhost.localdomain> On Mon, Feb 10, 2003 at 11:38:58PM -0500, Erik Price wrote: > > On Monday, February 10, 2003, at 08:09 PM, Paul Tremblay wrote: > > >The script will be over 3,000 lines long. In order to parse the RTF, it > >has to make a dozen or so passes through the file. The reason for so > >many passes is that RTF is very dense. I had written a successful perl > >script that parsed RTF in one pass, but the script is almost > >unreadable. > > > >The newer perl script (not the one above) makes a module for each pass > >through the file. I thought this was bad design, because I had a dozen > >or so modules. > > > >But you are telling me that it is perhaps best to keep the script > >modular? > > [If I ever had to read your script's source code,] I would say so. One > of the things that I do like about Java is that it forces the > programmer to split their code up into separate files (similar to what > Python does with whitespace and indentation). Each file contains its > own public class. It's not exactly convenient for quick work, but > that's people generally wouldn't use Java for scripting (after all > there's Python!). > Yes, if you had to read my source code of the original script you would probably send me a nasty email. I knew that I would have to maintain the code; hence, the change to a modular design. However, the new modular design is 3 times as slow! It took 50 seconds to parse a dense file on a slow, 100 MHZ computer. The new modular design took 2 minutes and 20 seconds. Some of the speed factors could definitely be due to my inexperience. Keep in mind that these two comparisons are both with perl scripts. I don't know how Python will fare as far as speed is concerned. My reason for converting the script to Python is: --Python is so darn elegant and easy to read --Since it is so easy to read, others are more likely to take an interest in the project and help out, or simply use it. --I am thinking of converting the code to java after I convert it to Python. I know there is a thing called Jython, but I have no idea if I can readily conert my script to Jython. --My reasoning for java is that Java is much faster than perl or python. Of course, speed can be very tricky. Perl is faster at regexp than any language. However, most of the script reads in one line at a time and uses the substr function in perl, which is the same as slicing in Python. I believe that Java would give the user a huge speed increase. However, this thread originally asserted that java was *not* that much faster. In which case, no need to learn and struggle with java! I agree with your statements about java forcing a programmer to uses classes. I noticed this too, even though I know hardly any java. I guess that accounts for my attraction to Python--it allows you to break code into simple re-usable chunks. Paul -- ************************ *Paul Tremblay * *phthenry@earthlink.net* ************************ From carroll@tjc.com Tue Feb 11 02:13:03 2003 From: carroll@tjc.com (Terry Carroll) Date: Tue Feb 11 02:13:03 2003 Subject: [Tutor] Test if name is defined? In-Reply-To: <200302102152.15209.shalehperry@attbi.com> Message-ID: On Mon, 10 Feb 2003, Sean 'Shaleh' Perry wrote: > On Monday 10 February 2003 21:26, Terry Carroll wrote: > > Is there a way to test to see if a variable is defined other than with the > > exception system? > > > > In a recent enough python: > > def defined(thing): > return (thing in locals()) or (thing in globals())> > > or, old way: > > def defined(thing): > return (locals().has_key(thing)) or (globals().has_key(thing)) Thanks; but that didn't work. I tried: ======== def defined(thing): return (locals().has_key(thing)) or (globals().has_key(thing)) x = 1 if defined(x): print "x is", x if defined(y): print "y is", y ======== and got: ======== Traceback (most recent call last): File "tryit.py", line 10, in ? if defined(y): NameError: name 'y' is not defined ======== Same error with both versions. -- Terry Carroll | "To have this rare opportunity Santa Clara, CA | is a rare opportunity." carroll@tjc.com | - Houston Rockets' Yao Ming, on being named Modell delendus est | starting center for the 2003 NBA All-Star Game From Janssen@rz.uni-frankfurt.de Tue Feb 11 04:26:02 2003 From: Janssen@rz.uni-frankfurt.de (Michael Janssen) Date: Tue Feb 11 04:26:02 2003 Subject: [Tutor] Test if name is defined? In-Reply-To: Message-ID: On Mon, 10 Feb 2003, Terry Carroll wrote: > On Mon, 10 Feb 2003, Sean 'Shaleh' Perry wrote: > > In a recent enough python: > > > > def defined(thing): > > return (thing in locals()) or (thing in globals())> > > > > or, old way: > > > > def defined(thing): > > return (locals().has_key(thing)) or (globals().has_key(thing)) > > Thanks; but that didn't work. > > I tried: > ======== > def defined(thing): > return (locals().has_key(thing)) or (globals().has_key(thing)) > > x = 1 > > if defined(x): > print "x is", x > > if defined(y): > print "y is", y > ======== > > and got: > > ======== > Traceback (most recent call last): > File "tryit.py", line 10, in ? > if defined(y): > NameError: name 'y' is not defined > ======== The magic is: defined("y") instead of y. Your are looking for a name (or rather a key in globals() or locals(). Keys of both dictionaries are strings) not for an object referenced by this name. cmp lib/built-in-funcs.html for globals() and locals() From erikprice@mac.com Tue Feb 11 07:25:02 2003 From: erikprice@mac.com (Erik Price) Date: Tue Feb 11 07:25:02 2003 Subject: [Tutor] Sun says: Don't use Java, use Python! In-Reply-To: <20030211012215.A12957@localhost.localdomain> Message-ID: On Tuesday, February 11, 2003, at 01:22 AM, Paul Tremblay wrote: > However, the new modular design is 3 times as slow! It took 50 seconds > to parse a dense file on a slow, 100 MHZ computer. The new modular > design took 2 minutes and 20 seconds. > > Some of the speed factors could definitely be due to my inexperience. > Keep in mind that these two comparisons are both with perl scripts. I > don't know how Python will fare as far as speed is concerned. I'm not a seasoned Python programmer, but I think that each language has certain features that can be optimized -- in other words, what is fast in Perl might not be fast in Python, or vice versa. This list is a good place to ask about what might be bottlenecks in Python so you can look for them in your code. (But not me, since I really don't know.) > My reason for converting the script to Python is: > > --Python is so darn elegant and easy to read > > --Since it is so easy to read, others are more likely to take an > interest in the project and help out, or simply use it. Have you posted the script on sourceforge or the like? It is a good place to advertise it. Especially if it's written in Python -- I'd be more inclined to check out a Python script than a Perl script simply for the reason you give, that it's very easy to read. Of course, I've seen Python scripts that are still difficult to read, and Perl scripts that are easy. (For instance, just about any Perl script written by Randal Schwartz tends to be very easy to follow, but he is also a paid professional Perl instructor so I should hope so.) > --My reasoning for java is that Java is much faster than perl or > python. Hmm... I can't seem to get a hard and fast answer on this myself. C could be much faster than Perl or Python (depending on the circumstances) but both this list and a Perl mailing list that I am subscribed to have been discussing the controversial document from Sun, which now I'm hearing might not even be legit. Either way, it might be worth rewriting in Java for two reasons: 1. To learn more about Java, 2. to see if Java really is any faster. One thing for sure, the actual process of *writing* Java is slower than Python or Perl. If you're really considering re-writing the code with Java, bear in mind that Java will force you to write it in full object oriented style. Since you are just now working on a Python version and Python allows this, you may wish to try doing something like this in Python. It will be easier to move your program to Java later if it is already laid out as a collection of objects and relationships between objects. > Of course, speed can be very tricky. Perl is faster at regexp than any > language. However, most of the script reads in one line at a time and > uses the substr function in perl, which is the same as slicing in > Python. I believe that Java would give the user a huge speed increase. It might. > However, this thread originally asserted that java was *not* that much > faster. In which case, no need to learn and struggle with java! Java is a pretty big language. There is a lot involved in learning it. If you're only interested in amping out the program's performance, I don't really recommend learning Java just for that, since the speed advantage of Java isn't very well-defined -- C would be a better choice if you want something fast. The problem [that I have] with C is that it's very hard to program [to me]. You have to do a lot of the dirty work yourself, like managing strings as arrays of characters, and memory management. It might not be worth it, but that's entirely up to you. > I agree with your statements about java forcing a programmer to uses > classes. I noticed this too, even though I know hardly any java. I > guess > that accounts for my attraction to Python--it allows you to break code > into simple re-usable chunks. Perl and Python and, I think just about every language, let you break code up into chunks. But I think that because Perl and Python are so "natural" to write, it can be hard to stop yourself from just busting out the code, and think about making a modular design. You can just jump in and before you know it, you've got hundreds of lines of spaghetti. I strongly agree with Jeff Shannon, you might want to stop and think about the different aspects of your program. One way to do this, that I first heard about from Alan Gauld on this very list, is to make a list of the different features that your program does -- then write each feature down on a separate index card, and make a list of the responsibilities of each feature that it needs to be responsible for in order to perform its role as a feature. After you've got every responsibility of your program divided up into the various features, you may have a decent idea of what classes you should use (the features would ideally match a class somehow), and the responsibilities can probably be easily translated into methods. It's called CRC, or Class Responsibility Cards. Hopefully it will be helpful to you. Erik -- Erik Price email: erikprice@mac.com jabber: erikprice@jabber.org From reavey@nep.net Tue Feb 11 08:24:03 2003 From: reavey@nep.net (reavey) Date: Tue Feb 11 08:24:03 2003 Subject: [Tutor] how to write a turtle.py program Message-ID: <3E4A4A9B.5060907@nep.net> I am having fun using turtle.py thru the interpreter. However, the turtle draws and the display box vanishes with a test like: #!/usr/bin/python import turtle turtle.reset() turtle.forward(100) thanks re-v From Janssen@rz.uni-frankfurt.de Tue Feb 11 08:42:01 2003 From: Janssen@rz.uni-frankfurt.de (Michael Janssen) Date: Tue Feb 11 08:42:01 2003 Subject: [Tutor] how to write a turtle.py program In-Reply-To: <3E4A4A9B.5060907@nep.net> Message-ID: On Wed, 12 Feb 2003, reavey wrote: > I am having fun using turtle.py thru the interpreter. > However, the turtle draws and the display box vanishes to keep it open keep the python programm open. Best way is to use -i Parameter: python -i turtle.py ---> python executes the script and go into interactive mode. sys.exit() or ctrl-C terminates. Michael > with a test like: > > #!/usr/bin/python > import turtle > turtle.reset() > turtle.forward(100) > > thanks > re-v > > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From reavey@nep.net Tue Feb 11 09:24:02 2003 From: reavey@nep.net (reavey) Date: Tue Feb 11 09:24:02 2003 Subject: [Tutor] full screen turtle.py Message-ID: <3E4A58BD.2020900@nep.net> is there a way to display a full screen when turtle.py initializes? The first canvas takes up a small portion of the display (around 10%). When I hit the expand button on the canvas it doesn't recenter. The drawing still uses the inititial canvas coordinates. btw: this is not a problem using the interactive interpreter as a turtle.reset() issued after you expand works as expected. thanks re-v From deirdrehac@lycos.co.uk Tue Feb 11 10:14:13 2003 From: deirdrehac@lycos.co.uk (Deirdre Hackett) Date: Tue Feb 11 10:14:13 2003 Subject: [Tutor] Binary to bcd Message-ID: <000a01c2d1e0$15f3bd90$0800a8c0@WHOOPI> This is a multi-part message in MIME format. ------=_NextPart_000_0007_01C2D1E0.138D6BF0 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable My data comes in as: =FA=A1=FAz=EA=E5 =FA=A1=FAz=EA=E2 =FA=A1=FAz=EA=E2 =FA=A1=FAz=EA=E2 =FA=A1=FA{=EA=E4 =20 This is the binary data. It is not life or death but I would like to know is there a relatively = easy way of converting binary to bcd (binary coded decimal).=20 Thanks, Deirdre ------=_NextPart_000_0007_01C2D1E0.138D6BF0 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
My data comes in as:
       =20     =FA=A1=FAz=EA=E5
       =20     =FA=A1=FAz=EA=E2
       =20     =FA=A1=FAz=EA=E2
       =20     =FA=A1=FAz=EA=E2
       =20     =FA=A1=FA{=EA=E4
 
This is the binary data.
It is not life or death but I would = like to know is=20 there a relatively easy way of converting binary to bcd (binary coded = decimal).=20
Thanks,
Deirdre
 
------=_NextPart_000_0007_01C2D1E0.138D6BF0-- From magnus@thinkware.se Tue Feb 11 12:21:01 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Tue Feb 11 12:21:01 2003 Subject: [Tutor] how to write documentation for a script In-Reply-To: <20030210213205.25988.85023.Mailman@mail.python.org> Message-ID: <5.1.0.14.0.20030211174507.02be76d0@www.thinkware.se> At Mon, 10 Feb 2003 14:51:55 -0500, Paul Tremblay wrote: >Is there a way to include documentation within the actual script, as you >can in perl? The book I have on Pyton, called *Core Pyton,* states that >you put the documentation between quotation marks right after the >startup line: Normally, you'd use ''' or """ so that you can embed line feeds in the string. You can put these doc-strings in the beginning of a module, a class or a function/method. What you ask for, a standard for formatting of Python source code documentatin, and tools to extract it, is still a new thing in python, and not yet quite established. There are two things you should look at. PyDoc and DocUtils. The pydoc module and utility is included in Python. If you type >>> import pydoc >>> help(pydoc) you will use pydoc to look at itself... In Windows C:\Python22\Tools\scripts\pydocgui.pyw will start up a web based browser for inspecting python modules, including documentation. I guess it's just another path and .py instead of .pyw in other operating systems. This is a great help to inspect python modules, but it's not really what you look for. As far as I understand, StructuredText has be replaced by reStructuredText (rST). I think support for rST will appear in 2.3, but I'm not sure. It certainly exists though, and can be found in the Docutils web http://docutils.sourceforge.net/index.html See the PEPs http://docutils.sourceforge.net/spec/pep-0256.html and http://docutils.sourceforge.net/spec/pep-0287.html The PEPs are written in rST by the way. Another example of rST use is the python-dev summaries, see http://www.python.org/dev/summary/ where you can see them translated to HTML. For instance, view thew latest summary in HTML and rST: http://www.python.org/dev/summary/2003-01-16_2003-01-31.html http://www.python.org/dev/summary/2003-01-16_2003-01-31.txt I assume pydoc will grok rST in time, but I don't think it does today. An example of a module documented with rST can be found here http://docutils.sourceforge.net/docutils/statemachine.py -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From jeff@ccvcorp.com Tue Feb 11 12:55:46 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Tue Feb 11 12:55:46 2003 Subject: [Tutor] Test if name is defined? References: Message-ID: <3E49376D.2000901@ccvcorp.com> Terry Carroll wrote: >Is there a way to test to see if a variable is defined other than with the >exception system? > >[...] > >I only want to keep the object if I read in a value for either the >attribute kGB0 or kBigFive attributes (or both) are defined. > Well, for one, trying and catching exceptions is a recognized valid method of introspection in Python. The fact that you are using try/except to determine whether something is defined, is *not* a sign of bad design. (Python considers the use of exceptions to be much more normal than some other languages, and it is not reserved only for true error conditions.) Secondly, if what you're trying to determine is whether an *object* has a certain *attribute* defined, then you can use the built-in function hasattr(). Alternatively, if you're working with dictionaries, there's a has_key() method that will tell you whether a certain key already exists in the dictionary. >>> class X: ... def __init__(self): ... self.eggs = 1 ... >>> x = X() >>> hasattr(x, "eggs") 1 >>> hasattr(x, "spam") 0 >>> d = { "spam":1 } >>> d.has_key("spam") 1 >>> d.has_key("eggs") 0 >>> Jeff Shannon Technician/Programmer Credit International From mongo57a@comcast.net Tue Feb 11 13:08:06 2003 From: mongo57a@comcast.net (andy surany) Date: Tue Feb 11 13:08:06 2003 Subject: [Tutor] Understanding cursors or MySQLdb problem Message-ID: <008101c2d1f8$a159b2a0$2502a8c0@emily.ewndsr01.nj.comcast.net> Hello List! I am using MySQLdb to access MySQL from my python program. I have a class that does the following: query='select ax, bx, cx from tablename' a=self.cursor.execute(query) b=self.cursor.fetchall() (next part in a loop...) name=self.cursor.description[i,0] type=self.cursor.description[i,1] print name, type (end of loop) This has been working fine. I return the data back to the calling program, as such: dbinfo=sql.Query() and access it like: data_element1.append(dbinfo.ax[i]) data_element2.append(dbinfo.bx[i]) etc................ This all has worked great! until I changed my query to look like: query='select ax, bx, SUM(cx) from tablename' Now, when I try data_element3.append(dbinfo.SUM(cx[i])) I get the following error: SQL instance has no attribute 'SUM' When I look at 'print name, type', I see: name ax, bx, SUM(cx) type 254, 254, 5 I do note that the SUM introduces a new "type" (which I have no idea what it is.....). So............., do I have a problem understanding cursors? or is this a unique MySQLdb issue, or ????? I know this is kind of lengthy... but any help would be appreciated. Regards, Andy From carroll@tjc.com Tue Feb 11 13:13:26 2003 From: carroll@tjc.com (Terry Carroll) Date: Tue Feb 11 13:13:26 2003 Subject: [Tutor] Test if name is defined? In-Reply-To: <3E49376D.2000901@ccvcorp.com> Message-ID: On Tue, 11 Feb 2003, Jeff Shannon wrote: > Terry Carroll wrote: > > >Is there a way to test to see if a variable is defined other than with the > >exception system? > > > >[...] > > > >I only want to keep the object if I read in a value for either the > >attribute kGB0 or kBigFive attributes (or both) are defined. > > > > Well, for one, trying and catching exceptions is a recognized valid > method of introspection in Python. The fact that you are using > try/except to determine whether something is defined, is *not* a sign of > bad design. Thanks; I understand that, it just gets unweidly when you're trying to test multiple variables, and want to proceed if any one variable is defined. > Secondly, if what you're trying to determine is whether an *object* has > a certain *attribute* defined, then you can use the built-in function > hasattr(). Excellent! > >>> class X: > ... def __init__(self): > ... self.eggs = 1 > ... > >>> x = X() > >>> hasattr(x, "eggs") > 1 > >>> hasattr(x, "spam") > 0 And, most importantly for me, I can still do: >>> hasattr(x,"spam") 0 >>> x.spam = 1 >>> hasattr(x,"spam") 1 This would do what I want. Thanks. I've already changed my approach to add a "valid" flag to the object; it's __init__ially set to 0, but I set it to 1 when I add either the kGB0 or kBigFive; then my test is simply against the flag, rather than for those attribute's definitions. This will work for me because I have a simple "or" condition, but I'll definitely keep hasattr() in mind for the future. Thanks. -- Terry Carroll | "To have this rare opportunity Santa Clara, CA | is a rare opportunity." carroll@tjc.com | - Houston Rockets' Yao Ming, on being named Modell delendus est | starting center for the 2003 NBA All-Star Game From jeff@ccvcorp.com Tue Feb 11 13:15:02 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Tue Feb 11 13:15:02 2003 Subject: [Tutor] Sun says: Don't use Java, use Python! References: <20030210200958.G1785@localhost.localdomain> <20030211012215.A12957@localhost.localdomain> Message-ID: <3E493D39.6090709@ccvcorp.com> Paul Tremblay wrote >However, the new modular design is 3 times as slow! It took 50 seconds >to parse a dense file on a slow, 100 MHZ computer. The new modular >design took 2 minutes and 20 seconds. > >Some of the speed factors could definitely be due to my inexperience. >Keep in mind that these two comparisons are both with perl scripts. I >don't know how Python will fare as far as speed is concerned. > I don't know how Python will compare to Perl for this script either... and neither does anyone else. Speed is affected by too many variables to be very predictable in most cases. However, one nice feature of Python is that it includes a profile module in the standard library, which (once you have that nice modular design) can show you exactly *where* your program is spending all its time, so that you can focus any optimization efforts in only those areas that it will actually do some benefit. There's also the question of how critical speed actually is -- if this is a script that'll be run once or twice a week, sweating over a minute's run-time is not very efficient, but if it's something that will be run often with someone waiting idly for the results, then shaving off speed becomes more important. >My reason for converting the script to Python is: > >--Python is so darn elegant and easy to read > >--Since it is so easy to read, others are more likely to take an >interest in the project and help out, or simply use it. > This ease-of-reading also makes it easier to maintain, which also implies that it'll be easier to optimize it once you've got it running. >--I am thinking of converting the code to java after I convert it >to Python. I know there is a thing called Jython, but I have no idea if >I can readily conert my script to Jython. > I've never used Jython myself, but my understanding is that a pure Python program, that doesn't rely on C extensions and such, will usually run unchanged under Jython. Whether this actually buys you any speed benefit is another matter altogether -- it's unlikely to do so unless you've got a good optimizing JIT compiler for Java... >--My reasoning for java is that Java is much faster than perl or python. >Of course, speed can be very tricky. Perl is faster at regexp than any >language. However, most of the script reads in one line at a time and >uses the substr function in perl, which is the same as slicing in >Python. I believe that Java would give the user a huge speed increase. >However, this thread originally asserted that java was *not* that much >faster. In which case, no need to learn and struggle with java! > As has already been discussed, Java *might* (or might not) provide a speed increase, but it's unlikely to be a huge speed increase in any case. Given the nature of the work you're doing, most of the time that your Python program is spending will likely be in various built-in operations. This means that you'll be in the (C-coded) core, which is mostly pretty well optimized by people who know far more about C than I *ever* will. ;) One other advantage about Python is that, when you have problems, there's people on mailing lists and usenet who are eager to be helpful, whether it's with finding a bug that's crashing your program or just optimizing a segment of code that's running too slowly... or even just discussing opinions about the importance and value of various design considerations. ;) Jeff Shannon Technician/Programmer Credit International From Janssen@rz.uni-frankfurt.de Tue Feb 11 13:55:02 2003 From: Janssen@rz.uni-frankfurt.de (Michael Janssen) Date: Tue Feb 11 13:55:02 2003 Subject: [Tutor] how to write a turtle.py program In-Reply-To: Message-ID: On Tue, 11 Feb 2003, Michael Janssen wrote: > On Wed, 12 Feb 2003, reavey wrote: > > I am having fun using turtle.py thru the interpreter. > > However, the turtle draws and the display box vanishes > > to keep it open keep the python programm open. Best way is to use -i > Parameter: > python -i turtle.py Correction: python -i name_of_your_script.py (which is hopefully not "turtle.py", because "import turtle" would import this script itself). Michael > > ---> python executes the script and go into interactive mode. sys.exit() > or ctrl-C terminates. > > Michael > > > with a test like: > > > > #!/usr/bin/python > > import turtle > > turtle.reset() > > turtle.forward(100) > > > > thanks > > re-v > > > > > > > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From rick@niof.net Tue Feb 11 15:28:03 2003 From: rick@niof.net (Rick Pasotto) Date: Tue Feb 11 15:28:03 2003 Subject: [Tutor] Understanding cursors or MySQLdb problem In-Reply-To: <008101c2d1f8$a159b2a0$2502a8c0@emily.ewndsr01.nj.comcast.net> References: <008101c2d1f8$a159b2a0$2502a8c0@emily.ewndsr01.nj.comcast.net> Message-ID: <20030211202715.GE16227@tc.niof.net> On Tue, Feb 11, 2003 at 01:08:50PM -0500, andy surany wrote: > > This all has worked great! until I changed my query to look like: > > query='select ax, bx, SUM(cx) from tablename' > > Now, when I try data_element3.append(dbinfo.SUM(cx[i])) I get the > following error: > > SQL instance has no attribute 'SUM' Have you tried naming your column? query='select ax, bx, SUM(cx) as cxsum from tablename' -- "Economics is extremely useful as a form of employment for economists." -- John Kenneth Galbraith Rick Pasotto rick@niof.net http://www.niof.net From mongo57a@comcast.net Tue Feb 11 15:39:29 2003 From: mongo57a@comcast.net (andy surany) Date: Tue Feb 11 15:39:29 2003 Subject: [Tutor] Understanding cursors or MySQLdb problem Message-ID: <00a201c2d20d$8b0d2ee0$2502a8c0@emily.ewndsr01.nj.comcast.net> Thank you, thank you, thank you !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! I've spent hours on this.............. Regards, Andy -----Original Message----- From: Rick Pasotto To: tutor@python.org Date: Tuesday, February 11, 2003 3:28 PM Subject: Re: [Tutor] Understanding cursors or MySQLdb problem >On Tue, Feb 11, 2003 at 01:08:50PM -0500, andy surany wrote: >> >> This all has worked great! until I changed my query to look like: >> >> query='select ax, bx, SUM(cx) from tablename' >> >> Now, when I try data_element3.append(dbinfo.SUM(cx[i])) I get the >> following error: >> >> SQL instance has no attribute 'SUM' > >Have you tried naming your column? > >query='select ax, bx, SUM(cx) as cxsum from tablename' > >-- >"Economics is extremely useful as a form of employment for economists." > -- John Kenneth Galbraith > Rick Pasotto rick@niof.net http://www.niof.net > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From tlo@aw.sgi.com Tue Feb 11 16:04:03 2003 From: tlo@aw.sgi.com (Terence Lo) Date: Tue Feb 11 16:04:03 2003 Subject: [Tutor] multiple "to" recipients using smtplib Message-ID: <003701c2d211$2bf0bef0$ca411dc6@ms.aliaswavefront.com> Hi there, I have a python n00b question. How do I specify multiple 'to' recipients using smtplib. I've tried the following code snippet but only the first email recipient (user1@somewhere.com) receives the email and not the second. I've also tried setting toaddrs = ["user1@somehwere.com", "user2@somere.com"] but this doesn't work either. Any idea what the heck I'm doing wrong? Thanks, TL ---------------------------------------------------------------------------- ----------------------------------- import smtplib toaddrs = "user1@somewhere.com, user2@somewhere.com" fromaddr = "me@me.com" msg="This is the message" server = smtplib.SMTP('mail.mymailserver.com') server.sendmail(fromaddr, toaddrs, msg) server.quit() From glingl@aon.at Tue Feb 11 17:41:27 2003 From: glingl@aon.at (Gregor Lingl) Date: Tue Feb 11 17:41:27 2003 Subject: [Tutor] full screen turtle.py References: <3E4A58BD.2020900@nep.net> Message-ID: <3E497B82.80600@aon.at> This is a multi-part message in MIME format. --------------010101010100010208010001 Content-Type: text/plain; charset=us-ascii; format=flowed Content-Transfer-Encoding: 7bit reavey schrieb: > is there a way to display a full screen when turtle.py initializes? As a default-canvas is created the first time when you call an arbitrary turtle-graphics function, there is no way to pass information about its size to the canvas. But: (1) There is the possibility to create turtle-objects on your own Tkinter-Canvas which may have any size you want. more precisely, you have to create an object of the RawPen class, which goes like this: >>> from Tkinter import Canvas >>> cv = Canvas(width=800, height=600) >>> cv.pack() >>> t = RawPen(cv) >>> t.forward(100) you may reset the size of cv with something like: >>> cv["width"]=400 >>> cv["height"] = 500 and recenter t by calling t.reset (which works essentially the same way you used when resizing the default-canvas manually) (2) Another way to accomplish what you want ist do decide to rewrite the reset-function of the turtle-module in order to pass information about the size of the canvas. (If these arguments are not given, it works the old way): First you have to change the reset-method of RawPen (approx line 40): def reset(self, width = None, height = None): canvas = self._canvas if width: canvas["width"] = width if height: canvas["height"] = height self._canvas.update() # .... and so on. as before Then you have to modify the reset - function (approx line 350): def reset(width=None, height=None): _getpen().reset(width,height) I've attached a modified turtle.py With these changes the following will be possible: >>> from turtle import * >>> reset(800,600) >>> forward(50) >>> reset(200,200) Regards, Gregor P.S. I didn't extensively test these changes, so maybe there will be some unwanted side-effects, especially when using RawPen. Maybe I'll have a look at this sometimes later ... > > The first canvas takes up a small portion of the display (around 10%). > When I hit the expand button on the canvas it doesn't recenter. > The drawing still uses the inititial canvas coordinates. > > btw: this is not a problem using the interactive interpreter as a > turtle.reset() > issued after you expand works as expected. > > thanks > re-v > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > --------------010101010100010208010001 Content-Type: text/plain; name="turtle.py" Content-Transfer-Encoding: 8bit Content-Disposition: inline; filename="turtle.py" # LogoMation-like turtle graphics from math import * # Also for export import Tkinter class Error(Exception): pass class RawPen: def __init__(self, canvas): self._canvas = canvas self._items = [] self._tracing = 1 self._arrow = 0 self._set_fullcircle(360.0) # alter self.degrees() Aufruf self.reset() # Das ist die alte degrees - Funktion # doch ohne Standardwert def _set_fullcircle(self, fullcircle): self._fullcircle = fullcircle self._invradian = pi / (fullcircle * 0.5) # nur noetig, wenn nicht eh schon Gradmass eingestellt def degrees(self): if self._fullcircle == 360.0: return self._set_fullcircle(360.0) self._angle = self._angle / self._invradian # nur noetig wenn nicht eh schon Bogenmass eingestellt def radians(self): # Die folgende Anweisung koennte unterbleiben, da # in diesem Fall self._invradian den Wert 1 hat. # Finde es so aber klarer if self._fullcircle == 2.0*pi: return self._angle = self._angle * self._invradian self._set_fullcircle(2.0*pi) def reset(self, width = None, height = None): canvas = self._canvas if width: canvas["width"] = width if height: canvas["height"] = height self._canvas.update() width = canvas.winfo_width() height = canvas.winfo_height() if width <= 1: width = canvas['width'] if height <= 1: height = canvas['height'] self._origin = float(width)/2.0, float(height)/2.0 self._position = self._origin self._angle = 0.0 self._drawing = 1 self._width = 1 self._color = "black" self._filling = 0 self._path = [] self._tofill = [] self.clear() canvas._root().tkraise() def clear(self): self.fill(0) canvas = self._canvas items = self._items self._items = [] for item in items: canvas.delete(item) self._delete_turtle() self._draw_turtle() def tracer(self, flag): self._tracing = flag if not self._tracing: self._delete_turtle() self._draw_turtle() def forward(self, distance): x0, y0 = start = self._position x1 = x0 + distance * cos(self._angle*self._invradian) y1 = y0 - distance * sin(self._angle*self._invradian) self._goto(x1, y1) def backward(self, distance): self.forward(-distance) def left(self, angle): self._angle = (self._angle + angle) % self._fullcircle self._draw_turtle() def right(self, angle): self.left(-angle) def up(self): self._drawing = 0 def down(self): self._drawing = 1 def width(self, width): self._width = float(width) def color(self, *args): if not args: raise Error, "no color arguments" if len(args) == 1: color = args[0] if type(color) == type(""): # Test the color first try: id = self._canvas.create_line(0, 0, 0, 0, fill=color) except Tkinter.TclError: raise Error, "bad color string: %s" % `color` self._set_color(color) return try: r, g, b = color except: raise Error, "bad color sequence: %s" % `color` else: try: r, g, b = args except: raise Error, "bad color arguments: %s" % `args` assert 0 <= r <= 1 assert 0 <= g <= 1 assert 0 <= b <= 1 x = 255.0 y = 0.5 self._set_color("#%02x%02x%02x" % (int(r*x+y), int(g*x+y), int(b*x+y))) def _set_color(self,color): self._color = color self._draw_turtle() def write(self, arg, move=0): x, y = start = self._position x = x-1 # correction -- calibrated for Windows item = self._canvas.create_text(x, y, text=str(arg), anchor="sw", fill=self._color) self._items.append(item) if move: x0, y0, x1, y1 = self._canvas.bbox(item) self._goto(x1, y1) self._draw_turtle() def fill(self, flag): if self._filling: path = tuple(self._path) smooth = self._filling < 0 if len(path) > 2: item = self._canvas._create('polygon', path, {'fill': self._color, 'smooth': smooth}) self._items.append(item) self._canvas.lower(item) if self._tofill: for item in self._tofill: self._canvas.itemconfigure(item, fill=self._color) self._items.append(item) self._path = [] self._tofill = [] self._filling = flag if flag: self._path.append(self._position) def circle(self, radius, extent=None): if extent is None: extent = self._fullcircle x0, y0 = self._position xc = x0 - radius * sin(self._angle * self._invradian) yc = y0 - radius * cos(self._angle * self._invradian) # weil self._angle eventuell im Bogenmass vorliegt: # 90.0 ----> self._fullcircle / 4 if radius >= 0.0: start = self._angle - self._fullcircle / 4 else: start = self._angle + self._fullcircle / 4 extent = -extent ## start und extent für den Bogen werden ## c_start und arc_extent zugewiesen ## weil sie für Canvas.create_arc unbedingt ## im Gradmass angegeben werden muessen if self._fullcircle == 2 * pi: arc_start = start * 180.0 / pi arc_extent = extent * 180.0 / pi else: arc_start = start arc_extent = extent if self._filling: if abs(extent) >= self._fullcircle: item = self._canvas.create_oval(xc-radius, yc-radius, xc+radius, yc+radius, width=self._width, outline="") self._tofill.append(item) item = self._canvas.create_arc(xc-radius, yc-radius, xc+radius, yc+radius, style="chord", start=arc_start, extent=arc_extent, width=self._width, outline="") self._tofill.append(item) if self._drawing: if abs(extent) >= self._fullcircle: item = self._canvas.create_oval(xc-radius, yc-radius, xc+radius, yc+radius, width=self._width, outline=self._color) self._items.append(item) # print xc-radius,yc-radius,xc+radius,yc+radius # print start, extent, self._width, self._color item = self._canvas.create_arc(xc-radius, yc-radius, xc+radius, yc+radius, style="arc", start=arc_start, extent=arc_extent, width=self._width, outline=self._color) self._items.append(item) angle = start + extent x1 = xc + abs(radius) * cos(angle * self._invradian) y1 = yc - abs(radius) * sin(angle * self._invradian) self._angle = (self._angle + extent) % self._fullcircle self._position = x1, y1 if self._filling: self._path.append(self._position) self._draw_turtle() def goto(self, *args): if len(args) == 1: try: x, y = args[0] except: raise Error, "bad point argument: %s" % `args[0]` else: try: x, y = args except: raise Error, "bad coordinates: %s" % `args[0]` x0, y0 = self._origin self._goto(x0+x, y0-y) def _goto(self, x1, y1): x0, y0 = start = self._position self._position = map(float, (x1, y1)) if self._filling: self._path.append(self._position) if self._drawing: if self._tracing: dx = float(x1 - x0) dy = float(y1 - y0) distance = hypot(dx, dy) nhops = int(distance) item = self._canvas.create_line(x0, y0, x0, y0, width=self._width, capstyle="round", fill=self._color) try: for i in range(1, 1+nhops): x, y = x0 + dx*i/nhops, y0 + dy*i/nhops self._canvas.coords(item, x0, y0, x, y) self._draw_turtle((x,y)) self._canvas.update() self._canvas.after(10) # in case nhops==0 self._canvas.coords(item, x0, y0, x1, y1) self._canvas.itemconfigure(item, arrow="none") except Tkinter.TclError: # Probably the window was closed! return else: item = self._canvas.create_line(x0, y0, x1, y1, width=self._width, capstyle="round", fill=self._color) self._items.append(item) self._draw_turtle() def _draw_turtle(self,position=[]): if not self._tracing: return if position == []: position = self._position x,y = position distance = 8 dx = distance * cos(self._angle*self._invradian) dy = distance * sin(self._angle*self._invradian) self._delete_turtle() self._arrow = self._canvas.create_line(x-dx,y+dy,x,y, width=self._width, arrow="last", capstyle="round", fill=self._color) self._canvas.update() def _delete_turtle(self): if self._arrow != 0: self._canvas.delete(self._arrow) self._arrow = 0 ## Extensions by g.l. def pos(self): x, y = self._position ox,oy = self._origin return x - ox, oy - y def heading(self): return self._angle def _vector_to(self, *args): if len(args) == 2: x, y = args else: arg = args[0] if isinstance(arg, RawPen): x, y = arg.pos() else: x, y = arg x0, y0 = self.pos() return x - x0, y - y0 def towards(self, *args): vx, vy = self._vector_to(*args) return (atan2(vy,vx) / self._invradian) % self._fullcircle def setheading(self,angle): self._angle = angle % self._fullcircle self._draw_turtle() _root = None _canvas = None _pen = None class Pen(RawPen): def __init__(self): global _root, _canvas if _root is None: _root = Tkinter.Tk() _root.wm_protocol("WM_DELETE_WINDOW", self._destroy) if _canvas is None: # XXX Should have scroll bars _canvas = Tkinter.Canvas(_root, background="white") _canvas.pack(expand=1, fill="both") RawPen.__init__(self, _canvas) def _destroy(self): global _root, _canvas, _pen root = self._canvas._root() if root is _root: _pen = None _root = None _canvas = None root.destroy() def _getpen(): global _pen if not _pen: _pen = Pen() return _pen def degrees(): _getpen().degrees() def radians(): _getpen().radians() def reset(width=None, height=None): _getpen().reset(width,height) def clear(): _getpen().clear() def tracer(flag): _getpen().tracer(flag) def forward(distance): _getpen().forward(distance) def backward(distance): _getpen().backward(distance) def left(angle): _getpen().left(angle) def right(angle): _getpen().right(angle) def up(): _getpen().up() def down(): _getpen().down() def width(width): _getpen().width(width) def color(*args): apply(_getpen().color, args) def write(arg, move=0): _getpen().write(arg, move) def fill(flag): _getpen().fill(flag) def circle(radius, extent=None): _getpen().circle(radius, extent) def goto(*args): apply(_getpen().goto, args) ## Extensions by g.l. def pos(): return _getpen().pos() def heading(): return _getpen().heading() def towards(*args): return apply(_getpen().towards, args) def setheading(angle): _getpen().setheading(angle) def demo(): reset() tracer(1) up() backward(100) down() # draw 3 squares; the last filled width(3) for i in range(3): if i == 2: fill(1) for j in range(4): forward(20) left(90) if i == 2: color("maroon") fill(0) up() forward(30) down() width(1) color("black") # move out of the way tracer(0) up() right(90) forward(100) right(90) forward(100) right(180) down() # some text write("startstart", 1) write("start", 1) color("red") # staircase for i in range(5): forward(20) left(90) forward(20) right(90) # filled staircase fill(1) for i in range(5): forward(20) left(90) forward(20) right(90) fill(0) # more text write("end") if __name__ == '__main__': _root.mainloop() if __name__ == '__main__': # demo() pass --------------010101010100010208010001-- From glingl@aon.at Tue Feb 11 18:05:19 2003 From: glingl@aon.at (Gregor Lingl) Date: Tue Feb 11 18:05:19 2003 Subject: [Tutor] how to write a turtle.py program References: Message-ID: <3E497E5B.9000607@aon.at> Michael Janssen schrieb: >>to keep it open keep the python programm open. Best way is to use -i >>Parameter: >>python -i turtle.py >> >> > >Correction: python -i name_of_your_script.py .... > >Michael > > >>---> python executes the script and go into interactive mode. sys.exit() >>or ctrl-C terminates. >> >> >>>#!/usr/bin/python >>>import turtle >>>turtle.reset() >>>turtle.forward(100) >>> >>> Other ways to accomplish this are: (1) The standard Tkinter - way: add the statement turtle.Tkinter.mainloop() as last line of you script. Closing the turtle-Window then terminates the program (2) If the script doesn't expect to handle events (mouse clicks etc...) you may add a simple raw_input() as last statement of your script. Hitting Enter at the MSDOS-shell window (or xterm?) will terminate your program. Regards, Gregor >>>thanks >>>re-v >>> >>> >>> >>> >>>_______________________________________________ >>>Tutor maillist - Tutor@python.org >>>http://mail.python.org/mailman/listinfo/tutor >>> >>> >>> >>_______________________________________________ >>Tutor maillist - Tutor@python.org >>http://mail.python.org/mailman/listinfo/tutor >> >> >> > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > > From purplebo@babylonia.flatirons.org Tue Feb 11 18:21:11 2003 From: purplebo@babylonia.flatirons.org (Chris Avery) Date: Tue Feb 11 18:21:11 2003 Subject: [Tutor] fibonacci Message-ID: <1045006038.19574.2.camel@adele> Hello all. How would one go about writing a program that computes the fibonacci sequence? Thanks, Chris From alan.gauld@bt.com Tue Feb 11 18:36:13 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Tue Feb 11 18:36:13 2003 Subject: [Tutor] List exercise Message-ID: <7497DCA1C240C042B28F6657ADFD8E0974DABB@i2km11-ukbr.domain1.systemhost.net> > On Mon, 10 Feb 2003 alan.gauld@bt.com wrote: > > The only problem with this approach is that learning by experience > > can teach an awful lot of bad habits that are hard to break. Using > > a tutorial that teaches good habits early saves a lot of time > When I remember correctly the threads "list exercise" wasn't > such a shiny example of good programming style, was it? But that wasn't a tutorial teaching, it was a bunch of folks on this list presenting different solutions to a problem. Hopefully a pre written tutorial would resolve those issues before commitying to 'print'. > Taking up bad habits while learning by experience is truely a > weightfull argument, but isn't it said that python protects the > learner from bad habits? If itb is its wrong. Python encourages good programming style but it allows bad habits too. Consider how many times the use of exec/eval comes up from beginners who think they've found a solution to a problem. Yet exec/eval are hardly ever the best way of dealing with the problem at hand. > and *grow with* the language? A python learner doesn't start with bad > habits (solong s/he doesn't come from a bad habit language ;-); s/he > writes somewhat simpleminded code that's all. If they are following a structured training path that should be the case, but if they are just learning the basics then going off to do their own thing the potential is there for lots of bad habits to form. > I don't want to suggest never read a tutorial - but I can't > see a need to elaborate about tutorial examples when the real > world is that near. I am ambivalent about exercises etc, if you have a real problem to solve do that instead! But if your imagination can't come up with a pertinent example then the tutors offer an alternative. > wont often get a list of ints, strings, lists all mixed together in a > reasonable programm-design, will you? Actually yes you will. A real world order record is typically exactly that. Or a real world bank account, or... Of course is we move to OOP we use classes but the data internal to the class will be a mixture of types. Classes are just specialised containers after all. > Anybody who comes to the tutor-list claiming that s/he got a > internal data structur like: > ['spam!', 1, ['Brie', 'Roquefort', 'Pol le Veq'], [1, 2, 3]] We might question whether it needs to be that way. One of the best programming habits is to structure the data before structuring the code. In fact the code should reflect the data structure... But there is nothing intrinsically wriong with it as it stands if that is the real nature of the data A name = string An account number = integer A list of order items = 3 strings A corresponding list of prices = 3 numbers The last two should maybe be a single dictionary, but maybe the 3 numbers represent something else - a list of employees involved in the transaction say... > It's very interesting - for me as a student of educational > sience - how tutorials claim to explain something but tries to accomplish > this effort on objects, which are harder than necessary (to say the least). Not sure what you mean here? Do you mean objects are harder than necessary(if so in what way?) or do you mean the tutors are harder than necessary? Or both? > Reading (well-written) existing code is a way out - as Erik > Price recently suggests. Thats true. However well written code at the level of the pythion library say, will be extremely difficult for a beginner to comprehend. Thats where Useless Python plays an invaluable (and unique) role within the Python community. Alan G > > Michael > > From alan.gauld@bt.com Tue Feb 11 18:43:50 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Tue Feb 11 18:43:50 2003 Subject: [Tutor] Sun says: Don't use Java, use Python! Message-ID: <7497DCA1C240C042B28F6657ADFD8E0901F850B2@i2km11-ukbr.domain1.systemhost.net> > > production code Python will already have compiled its modules to > > byte code and only the main module remains in ascii text. > > > So doesn't this mean that if you are planning to distribute a Python > script (as I am), that you should distribute it as a module? For production Python - and I stress I do very little production code in Python, I use it for prototyping prior to Java or C++ - I would write the main script like: ######################## import myrealmodule if __name__ == "__main__": myrealmodule.run() ######################### Then I distribute the compiled .pyc files for realmodule and any other modules that it uses. That way the genuinely interpreted code is minimised. Alan G. From alan.gauld@bt.com Tue Feb 11 18:53:00 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Tue Feb 11 18:53:00 2003 Subject: [Tutor] Sun says: Don't use Java, use Python! Message-ID: <7497DCA1C240C042B28F6657ADFD8E0901F850B3@i2km11-ukbr.domain1.systemhost.net> > According to the Python Tutorial, section 6.1.2, ``Compiled'' Python > files, the only thing faster about a compiled file is the speed with > which it is loaded. Once loaded, it won't run any faster than the > regular script version of the program. Thats true because Python always runs compiled code. However 'loading' includes the compilation of the code and if its a long file that can be significant. If the code comprises an infinite loop (like a server program) then once running the two forms will be identical. If its a single shot batch program the 'loading' time of the top script can be significant part of the total runtime. So as ever the answer to whether it helps to compile first is "it depends" Alan G From alan.gauld@bt.com Tue Feb 11 19:01:36 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Tue Feb 11 19:01:36 2003 Subject: [Tutor] importing constants Message-ID: <7497DCA1C240C042B28F6657ADFD8E0901F850B4@i2km11-ukbr.domain1.systemhost.net> > OTOH if you > from constants import * > then just use the constant name. > > Great Idea! I finally see a great reason to use from x import * as all > constants across the modules will have the same name But the usual caveats apply. If you pick a constant name thats already in use you get a name collision. However being all uppercase lessens the risk somewhat - except that Python library constants are also uppercase... Personally I'd recommend sticking to import constants x = constants.FOO It keeps things clearer. Alan G From alan.gauld@bt.com Tue Feb 11 19:09:10 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Tue Feb 11 19:09:10 2003 Subject: [Tutor] Sun says: Don't use Java, use Python! Message-ID: <7497DCA1C240C042B28F6657ADFD8E0901F850B5@i2km11-ukbr.domain1.systemhost.net> > The script will be over 3,000 lines long. Wooooh! Way too long. Break it into modules. I use the import/execute trick if my main module is a few hundred lines, but many hundreds and certainly thousands means you should put it in modules. Provided you can group the functions into some kind of logical grouping then it should help long term maintenance > In order to parse the RTF, it has to make a dozen or so > passes through the file. The RTF file I assume? Therefore the code is oinside a loop? In which case the compilation of the entire module will already be done. > The newer perl script (not the one above) makes a module for each pass > through the file. I thought this was bad design, because I had a dozen > or so modules. Assuming you mean a different function (perl sub?) then thats fine, put them in modules. I assume you don't mean thast your script is dynamically creating code modules and executing them as it goes? Now that would be interesting code!! Alan G From alan.gauld@bt.com Tue Feb 11 19:18:02 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Tue Feb 11 19:18:02 2003 Subject: [Tutor] Sun says: Don't use Java, use Python! Message-ID: <7497DCA1C240C042B28F6657ADFD8E0901F850B6@i2km11-ukbr.domain1.systemhost.net> > of the things that I do like about Java is that it forces the > programmer to split their code up into separate files > ....Each file contains its own public class. Thats one of the many things I dislike abut Java. The unit of reuse is not the class but what Boochj calls the class *category* (a package in UML, except package can mean other things too) A category is a group of coupled classes where they are all required to produce the reuse function. These categhories should ideally be implemented in a single file to make redistribution and configuration control easier. Javba breaks that model and thereby introduces major headaches in configuration management when categories get reused across projects. However I won't say any more about Java today - its bad for my bloodpressure! Alan G From alan.gauld@bt.com Tue Feb 11 19:42:00 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Tue Feb 11 19:42:00 2003 Subject: [Tutor] Sun says: Don't use Java, use Python! Message-ID: <7497DCA1C240C042B28F6657ADFD8E0901F850B7@i2km11-ukbr.domain1.systemhost.net> > --My reasoning for java is that Java is much faster than perl > or python. Then your reasoning is flawed. Java in some situations can be faster than Python and rarely faster than Perl. But never *much* faster.(Unless you use a native machine code compiler...) If you really need top speed you will need to go to C++ or C. Best approach is write it in Python, find which bits are slow, speed the up by better code design, then and only then rewrite the slow bits in C. > language. However, most of the script reads in one line at a time and > uses the substr function in perl, which is the same as slicing in > Python. I believe that Java would give the user a huge speed > increase. Why? The file I/O routines are all in the operating system regardless of which language and ultimately the file exists as magnetic particles on a mechanical disk being read by an electro-magnet! > However, this thread originally asserted that java was *not* that much > faster. In which case, no need to learn and struggle with java! If you were doing sophisticated math modelling Java might work for you but in this case I doubt you'd see more than 10-20% improvement, if that. Alan G From alan.gauld@bt.com Tue Feb 11 19:45:03 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Tue Feb 11 19:45:03 2003 Subject: [Tutor] Sun says: Don't use Java, use Python! Message-ID: <7497DCA1C240C042B28F6657ADFD8E0901F850B8@i2km11-ukbr.domain1.systemhost.net> > If you're really considering re-writing the code with Java, bear in > mind that Java will force you to write it in full object oriented > style. No, not at all, it will only force you to wrap your functional code in a class structure. But if you make the methods static you don't even need to create an object at all, just call the method as if it was a function. This is how a lot of Java tutors start off teaching Java! Java is not object oriented it is class oriented. Alan g From wesc@fuzzyorange.com Tue Feb 11 19:49:03 2003 From: wesc@fuzzyorange.com (Wesley Chun) Date: Tue Feb 11 19:49:03 2003 Subject: [Tutor] ANN: BayPIGgies mtg Wed Feb 12 7:30pm In-Reply-To: Message-ID: BayPIGgies: Silicon Valley-San Francisco Bay Area Python Users Group When: February 12, 2002 @ 7:30pm Where: Stanford University, Palo Alto, CA Agenda: Python, threads, e-mail, HTTP, spam :-) Speaker: Dennis Reinhardt "Python technology in a threaded internet application" The Python technology underpinning a new spam management program is described. The program uses Python threading with independent threads of control for acquiring POP3 email, delivering that email to client, and for user control via integrated http server. Threads are spawned dynamically. Most of the code is written at the socket level. The approach taken to allow an embedded single executable install and live update will be described. # Call For Talks: We are actively seeking speakers for BayPIGgies! If you would like to give a talk at one of our 2003 meetings (any Python related topic), contact us to coordinate! more info including directions: http://www.baypiggies.net hope 2 c u tomorrow nite! -wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall PTR, =A9 2001 http://starship.python.net/crew/wesc/cpp/ Silicon Valley-San Francisco Bay Area Python Users Group (BayPIGgies) http://baypiggies.net wesley.j.chun :: wesc at deirdre.org or wesc at fuzzyorange.com cyberweb.consulting : henderson, nv : cyberweb at rocketmail.com http://www.roadkill.com/~wesc/cyberweb/ From missive@hotmail.com Tue Feb 11 20:25:04 2003 From: missive@hotmail.com (Lee Harr) Date: Tue Feb 11 20:25:04 2003 Subject: [Tutor] how to write a turtle.py program Message-ID: >I am having fun using turtle.py thru the interpreter. You might also like working with pygsear. It is a graphics library I am writing which uses Python and Pygame, and it includes a turtle graphics module. I mostly work with it from the command line, but it does come with a demo script which shows off a bunch of drawings I made. You could also make your drawing in a script and put a myTurtle.save('picture.bmp') at the end to capture the output. Latest version is here: http://savannah.nongnu.org/files/?group=pygsear More information and screenshots here: http://www.nongnu.org/pygsear/ _________________________________________________________________ Add photos to your e-mail with MSN 8. Get 2 months FREE*. http://join.msn.com/?page=features/featuredemail From dyoo@hkn.eecs.berkeley.edu Tue Feb 11 20:50:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Feb 11 20:50:02 2003 Subject: [Tutor] fibonacci In-Reply-To: <1045006038.19574.2.camel@adele> Message-ID: On 11 Feb 2003, Chris Avery wrote: > Hello all. > > How would one go about writing a program that computes the fibonacci > sequence? Hi Chris, Counterquestion: what is the fibonacci sequence? *grin* But seriously speaking: pretend that none of us on the list know what the "fibonacci sequence" is, and try explaining it to us. Since concrete examples help clear our head, it might also be helpful to show us what the first few terms of these sequence are. You may find that explaining it to a human can help you figure out how to program a computer how to do it! From erikprice@mac.com Tue Feb 11 20:56:34 2003 From: erikprice@mac.com (Erik Price) Date: Tue Feb 11 20:56:34 2003 Subject: [Tutor] Sun says: Don't use Java, use Python! In-Reply-To: <7497DCA1C240C042B28F6657ADFD8E0901F850B6@i2km11-ukbr.domain1.systemhost.net> Message-ID: <68039EEE-3E2E-11D7-B6B5-00039351FE6A@mac.com> On Tuesday, February 11, 2003, at 07:15 PM, alan.gauld@bt.com wrote: > A category is a group of coupled classes where they are all > required to produce the reuse function. These categhories should > ideally be implemented in a single file to make redistribution > and configuration control easier. Javba breaks that model and A single file... you mean like a JAR file? :) Erik -- Erik Price email: erikprice@mac.com jabber: erikprice@jabber.org From erikprice@mac.com Tue Feb 11 20:57:13 2003 From: erikprice@mac.com (Erik Price) Date: Tue Feb 11 20:57:13 2003 Subject: [Tutor] Sun says: Don't use Java, use Python! In-Reply-To: <7497DCA1C240C042B28F6657ADFD8E0901F850B8@i2km11-ukbr.domain1.systemhost.net> Message-ID: On Tuesday, February 11, 2003, at 07:42 PM, alan.gauld@bt.com wrote: >> If you're really considering re-writing the code with Java, bear in >> mind that Java will force you to write it in full object oriented >> style. > > > No, not at all, it will only force you to wrap your functional code > in a class structure. But if you make the methods static you don't > even need to create an object at all, just call the method as if > it was a function. This is how a lot of Java tutors start off > teaching Java! > > Java is not object oriented it is class oriented. True. I forgot about this, I seem to recall that it was you who first explained this to me here on this list back in the summer. Erik: "What I have heard is that in Java everything is an object." Alan: "Not so. In Java, everything is a class." I've taken issue with that very fact, that many Java tutors start off by putting a bunch of procedural code into the main method of a class. It isn't a good way to start off. Erik -- Erik Price email: erikprice@mac.com jabber: erikprice@jabber.org From hsteiger@comcast.net Tue Feb 11 20:58:19 2003 From: hsteiger@comcast.net (Henry Steigerwaldt) Date: Tue Feb 11 20:58:19 2003 Subject: [Tutor] Accessing the Web using Python Message-ID: <000501c24a72$2ed9fb80$0201a8c0@eagle> To All: I am trying to understand why the process of accessing a Web site sometimes fails. I am attempting to get data from the following Web site: http://isl715.nws.noaa.gov/tdl/forecast/fwc.txt If you go there you will notice that this site contains a VERY LONG list of data. The code I am using in a small program I am working on is this: ______________________________________________ import urllib fwcURL = "http://isl715.nws.noaa.gov/tdl/forecast/fwc.txt" try: print "Going to Web for data" fwcall = urllib.urlopen(fwcURL).read() print "Successful" print "Will now print all of the data to screen" print "fwcall = ", fwcall except: print "Could not obtain data from Web" ______________________________________________ Using this code the previous day, I had absolutely no problem getting the data. However yesterday using the same code, most of the time this site could not be accessed at all. When I could not get anything back from this site using the above code, I tried going to the site using Microsoft Internet Explorer (I am using a windows PC). And I immediately got access to the site. I also noticed that a few times I would be able to access the site (i.e. the "Successful" would print to the screen), but each time absolutely NOTHING would be stored in the "fwcall" variable, unlike successful times when all the text information WAS stored in the variable. Does anyone know what the heck is going on here? Is there a way to have more positive results obtaining data from the Web using some other Python coding, or is it sometimes just hit and miss? I just tried this same code tonight and once again it works great! I am really puzzled by all this. When one writes a program to access the Web, as long as the site accessed is not "down," one should anticipate always being able to get the data. Is there a better and hence much more successful way to do what I want? Please also send any response to my email. Thanks much! Henry Steigerwaldt Hermitage, TN Email: hsteiger@comcast.net From micforster@yahoo.com Tue Feb 11 21:05:02 2003 From: micforster@yahoo.com (Mic Forster) Date: Tue Feb 11 21:05:02 2003 Subject: [Tutor] fibonacci In-Reply-To: Message-ID: <20030212020104.31410.qmail@web13408.mail.yahoo.com> --- Danny Yoo wrote: > Counterquestion: what is the fibonacci sequence? > *grin* > > > But seriously speaking: pretend that none of us on > the list know what the > "fibonacci sequence" is, and try explaining it to > us. Since concrete > examples help clear our head, it might also be > helpful to show us what the > first few terms of these sequence are. > > You may find that explaining it to a human can help > you figure out how to > program a computer how to do it! > Danny, That's not bad advice. I have been told before that if you cannot explain a scientific theory to a 6 year old, and make them understand, then it is not much of a theory. The same could be said of computer programming. __________________________________________________ Do you Yahoo!? Yahoo! Shopping - Send Flowers for Valentine's Day http://shopping.yahoo.com From reavey@nep.net Tue Feb 11 21:19:03 2003 From: reavey@nep.net (reavey) Date: Tue Feb 11 21:19:03 2003 Subject: [Tutor] how to write an algorithm for sequence Message-ID: <3E4B005E.9070105@nep.net> I'm stumped. I made up this sequence and I can't figure out a method. the sequence is 1,5,7,15,19,35, 43, 75... thanks re-v From reavey@nep.net Tue Feb 11 21:46:18 2003 From: reavey@nep.net (reavey) Date: Tue Feb 11 21:46:18 2003 Subject: [Tutor] pygsear prob mandrake 8.2 Message-ID: <3E4B064A.6020003@nep.net> I continue to have a problem with the package. the ./test.py command returns error sh: python 2.2 : command not found the set-up returns the same error tahnks re-v From op73418@mail.telepac.pt Tue Feb 11 21:46:29 2003 From: op73418@mail.telepac.pt (=?iso-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Tue Feb 11 21:46:29 2003 Subject: [Tutor] how to write an algorithm for sequence References: <3E4B005E.9070105@nep.net> Message-ID: <002201c2d241$99fd3290$47160dd5@violante> ----- Original Message ----- From: "reavey" To: Sent: Thursday, February 13, 2003 2:18 AM Subject: [Tutor] how to write an algorithm for sequence > I'm stumped. I made up this sequence and I can't figure out a method. > the sequence is 1,5,7,15,19,35, 43, 75... What is your question, exactly? The formula that suposedly reproduces the above sequence? That is a mathematics question, not a Python programming one. And without more input there is not much anyone can say - there are infinite (and a very high cardinal) functions on the integers reproducing the above. > thanks > re-v > All the best, G. Rodrigues From dyoo@hkn.eecs.berkeley.edu Tue Feb 11 22:05:03 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Feb 11 22:05:03 2003 Subject: [Tutor] Accessing the Web using Python In-Reply-To: <000501c24a72$2ed9fb80$0201a8c0@eagle> Message-ID: On Fri, 23 Aug 2002, Henry Steigerwaldt wrote: > import urllib > > fwcURL = "http://isl715.nws.noaa.gov/tdl/forecast/fwc.txt" > > try: > print "Going to Web for data" > fwcall = urllib.urlopen(fwcURL).read() > print "Successful" > print "Will now print all of the data to screen" > print "fwcall = ", fwcall > except: > print "Could not obtain data from Web" > ______________________________________________ > Using this code the previous day, I had absolutely no problem > getting the data. However yesterday using the same code, > most of the time this site could not be accessed at all. [some text cut] > I also noticed that a few times I would be able to access the site (i.e. > the "Successful" would print to the screen), but each time absolutely > NOTHING would be stored in the "fwcall" variable, unlike successful > times when all the text information WAS stored in the variable. Hi Henry, We may need some more information; at the moment, the code is obscuring some information that exceptions can provide. Let's enable some more diagnostics. Can you change the except block to something like: ### except: print "Could not obtain data from Web" traceback.print_exc() ### You'll probably need to import the 'traceback' module for this. The additional line, that "traceback.print_exc()", will print out more information about the excetion itself, and should give us insight into what exactly is causing the magic to fizzle. > I just tried this same code tonight and once again it works great! I am > really puzzled by all this. When one writes a program to access the Web, > as long as the site accessed is not "down," one should anticipate always > being able to get the data. It actually depends on the service that the web site provides! For example, the National Center for Biotechnology Information (NCBI) provides a set of valuable online programs and services for biologists: http://www.ncbi.nlm.nih.gov/ But, despite the electronic nature of NCBI, there is a kind of scarcity involved here: namely, they need to maintain a service that's available to scientists in a timely fashion, and some of the services they provide are computationally very expensive. What to do? NCBI has a cap, a kind of rate limiter, that limits how many requests they handle from a single computer at a time. That is, NCBI will block web requests of anyone who tries to abuse their public resource. As an example, here's what their guidelines dictate: """ Do not overload NCBI's systems. Users intending to send numerous queries and/or retrieve large numbers of records from Entrez should comply with the following: * Run retrieval scripts on weekends or between 9 PM and 5 AM ET weekdays for any series of more than 100 requests. * Make no more than one request every 3 seconds. """ And they are serious. I accidently ran a program once that hammered their systems. It is not a Good Thing when your computer is blacklisted from a national public resource. *cough* But that's NCBI; I don't know if the National Weather Service applies a similar rate-limiter on their services. So let's see what the traceback.print_exc() gives us in your program above, and we'll work from there. Good luck! From dyoo@hkn.eecs.berkeley.edu Tue Feb 11 22:13:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Feb 11 22:13:02 2003 Subject: [Tutor] how to write an algorithm for sequence In-Reply-To: <3E4B005E.9070105@nep.net> Message-ID: On Wed, 12 Feb 2003, reavey wrote: > I'm stumped. I made up this sequence and I can't figure out a method. > the sequence is 1,5,7,15,19,35, 43, 75... Hi Reavey, This isn't quite Python either, but I'll give it a shot. *grin* Hmmm... I don't see anything immediate from the sequence above either. But have you tried the method of differences? Here's how it works: take each pair of numbers, subtract them, and see if a pattern emerges. ### >>> def differences(seq): ... for i in range(0, len(seq)-1): ... print seq[i+1] - seq[i], ... >>> differences([1, 5, 7, 15, 19, 35, 43, 75]) 4 2 8 4 16 8 32 ### Let's arrange it so that it's easier to see what's going on: 1 5 7 15 19 35 43 75 4 2 8 4 16 8 32 Interesting. All of the individual "differences" are even, first of all. Wait: Reavey, I do see some sort of pattern here. Do you see it too now? Good luck to you! From reavey@nep.net Tue Feb 11 22:36:15 2003 From: reavey@nep.net (reavey) Date: Tue Feb 11 22:36:15 2003 Subject: [Fwd: Re: [Tutor] how to write an algorithm for sequence] Message-ID: <3E4B11D2.503@nep.net> --------------000805030907060407000008 Content-Type: text/plain; charset=us-ascii; format=flowed Content-Transfer-Encoding: 7bit -------- Original Message -------- Subject: Re: [Tutor] how to write an algorithm for sequence Date: Wed, 12 Feb 2003 22:28:08 -0500 From: reavey To: Danny Yoo References: Yes. I wrote this as a power of two sequence. I can see how to get the next number, however the algorithm is baffling. Thanks re-v Danny Yoo wrote: >On Wed, 12 Feb 2003, reavey wrote: > > > >>I'm stumped. I made up this sequence and I can't figure out a method. >>the sequence is 1,5,7,15,19,35, 43, 75... >> >> > >Hi Reavey, > > >This isn't quite Python either, but I'll give it a shot. *grin* > >Hmmm... I don't see anything immediate from the sequence above either. > > >But have you tried the method of differences? Here's how it works: take >each pair of numbers, subtract them, and see if a pattern emerges. > >### > > >>>>def differences(seq): >>>> >>>> >... for i in range(0, len(seq)-1): >... print seq[i+1] - seq[i], >... > > >>>>differences([1, 5, 7, 15, 19, 35, 43, 75]) >>>> >>>> >4 2 8 4 16 8 32 >### > > >Let's arrange it so that it's easier to see what's going on: > > > 1 5 7 15 19 35 43 75 > 4 2 8 4 16 8 32 > > > >Interesting. All of the individual "differences" are even, first of all. >Wait: Reavey, I do see some sort of pattern here. Do you see it too now? > > > >Good luck to you! > > > > --------------000805030907060407000008 Content-Type: text/html; charset=us-ascii Content-Transfer-Encoding: 7bit

-------- Original Message --------
Subject: Re: [Tutor] how to write an algorithm for sequence
Date: Wed, 12 Feb 2003 22:28:08 -0500
From: reavey <reavey@nep.net>
To: Danny Yoo <dyoo@hkn.eecs.berkeley.edu>
References: <Pine.LNX.4.44.0302111904390.28496-100000@hkn.eecs.berkeley.edu>


Yes. I wrote this as a power of two sequence. I can see how to get the next number, however
the algorithm is baffling.
Thanks
re-v

Danny Yoo wrote:
On Wed, 12 Feb 2003, reavey wrote:

  
I'm stumped. I made up this sequence and I can't figure out a method.
the sequence is 1,5,7,15,19,35, 43, 75...
    

Hi Reavey,


This isn't quite Python either, but I'll give it a shot.  *grin*

Hmmm... I don't see anything immediate from the sequence above either.


But have you tried the method of differences?  Here's how it works: take
each pair of numbers, subtract them, and see if a pattern emerges.

###
  
def differences(seq):
        
...     for i in range(0, len(seq)-1):
...         print seq[i+1] - seq[i],
...
  
differences([1, 5, 7, 15, 19, 35, 43, 75])
        
4 2 8 4 16 8 32
###


Let's arrange it so that it's easier to see what's going on:


    1   5   7   15   19   35   43   75
      4   2   8    4   16    8    32



Interesting.  All of the individual "differences" are even, first of all.
Wait: Reavey, I do see some sort of pattern here.  Do you see it too now?



Good luck to you!


  

--------------000805030907060407000008-- From dyoo@hkn.eecs.berkeley.edu Tue Feb 11 23:10:11 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Feb 11 23:10:11 2003 Subject: [Tutor] how to write an algorithm for sequence [puzzling over a sequence] In-Reply-To: Message-ID: On Tue, 11 Feb 2003, Danny Yoo wrote: > > > On Wed, 12 Feb 2003, reavey wrote: > > > I'm stumped. I made up this sequence and I can't figure out a method. > > the sequence is 1,5,7,15,19,35, 43, 75... > > Hi Reavey, > > > This isn't quite Python either, but I'll give it a shot. *grin* > > Hmmm... I don't see anything immediate from the sequence above either. That was a fun puzzle. I've got it. *grin* If you don't want to ruin it for yourself, do not read the message below. *** spoiler space ahead *** *** spoiler space *** If we take the original sequence: [1, 5, 7, 15, 19, 35, 43, 75] and we'd like to figure out a way to predict the next number, a good way to start is to take differences between adjacent elements: ### >>> def differences(seq): ... for i in range(0, len(seq)-1): ... print seq[i+1] - seq[i], ... >>> differences([1, 5, 7, 15, 19, 35, 43, 75]) 4 2 8 4 16 8 32 ### Pattern recognition time. If we look at this in a twisty enough way, we won't be able to resist seeing a pattern emerging.... if we write the sequence in a zigzaggy sort of fashion. Let's write the entries on the "even" indices on the top, and the "odd" entries on the bottom: 4 2 8 4 16 8 32 ---> 4 8 16 32 2 4 8 And this should strike a chord: the sequence of differences is just a shuffling of the powers of 2 against itself! ### >>> def shuffle(s1, s2): ... pairs = zip(s1, s2) ... results = [] ... for p in pairs: ... results.append(p[0]) ... results.append(p[1]) ... return results ... >>> powers_of_two = [2**n for n in range(10)] >>> l1 = powers_of_two[2:] >>> l2 = powers_of_two[1:] >>> shuffle(l1, l2) [4, 2, 8, 4, 16, 8, 32, 16, 64, 32, 128, 64, 256, 128, 512, 256] ### Success! But why should we pay so much attention to differences? Because, if we can figure out how the differences work, we can figure out how the original sequence works. Let's see why. As a concrete example, we see that the next difference that's coming up after 32 is 16. [4, 2, 8, 4, 16, 8, 32, 16, ...] ^^^^ So we plug 16 at the bottom of our little "differences" diagram we drew up before: 1 5 7 15 19 35 43 75 4 2 8 4 16 8 32 [plug in 16] ==> 1 5 7 15 19 35 43 75 4 2 8 4 16 8 32 16 Now the next number on the top, our original sequence, is easy to calculate: ### >>> 75 + 16 91 ### Let's say this in formal mathy language. First, we'll label the top row the "sequence" row, and let's label the bottom the "difference" row. Now, since we've named them, let's say the relationship between the two rows: sequence(0) = 1 ## the first number in the sequences row is ## always 1. sequence(n) = sequence(n-1) + difference(n-1) ## And any other number is just the ## the number to the left, plus ## the difference number on the right ## side. Here is a formula I'll conjure up that gives us the "n'th" difference number: ### >>> def secretFormula(n): ... return ((-1)**n + 1) * 2**((n+2)/2) ... >>> [secretFormula(n) for n in range(10)] [4, 0, 8, 0, 16, 0, 32, 0, 64, 0] >>> def secretFormula2(n): return secretFormula(n-3) ... >>> [secretFormula2(n) for n in range(10)] [0.0, 2.0, 0.0, 4, 0, 8, 0, 16, 0, 32] >>> def d(n): ... return int(secretFormula(n) + secretFormula2(n)) ... >>> [d(n) for n in range(10)] [4, 2, 8, 4, 16, 8, 32, 16, 64, 32] ### And with this, we're pretty much set: ### >>> def sequence(n): ... if n == 0: return 1 ... return sequence(n-1) + d(n-1) ... >>> sequence(0) 1 >>> sequence(1) 5 >>> sequence(2) 7 >>> [sequence(n) for n in range(10)] [1, 5, 7, 15, 19, 35, 43, 75, 91, 155] ### We can continue going on, but I think I'll stop here. But now I've got a hankering to start reading Concrete Mathematics again. *grin* Hope this helps! From monte4python@yahoo.com Tue Feb 11 23:17:13 2003 From: monte4python@yahoo.com (=?iso-8859-1?q?Monte=20Carlo?=) Date: Tue Feb 11 23:17:13 2003 Subject: [Tutor] mailing list Message-ID: <20030212041510.29425.qmail@web20705.mail.yahoo.com> --0-1355911442-1045023310=:28656 Content-Type: text/plain; charset=iso-8859-1 Content-Transfer-Encoding: 8bit --------------------------------- With Yahoo! Mail you can get a bigger mailbox -- choose a size that fits your needs --0-1355911442-1045023310=:28656 Content-Type: text/html; charset=iso-8859-1 Content-Transfer-Encoding: 8bit



With Yahoo! Mail you can get a bigger mailbox -- choose a size that fits your needs
--0-1355911442-1045023310=:28656-- From montana@buc99.bsd.st Tue Feb 11 23:38:06 2003 From: montana@buc99.bsd.st (montana) Date: Tue Feb 11 23:38:06 2003 Subject: [Tutor] Substitution question... Message-ID: <200302120434.h1C4YVR4001253@buc99.bsd.st> Hi Everyone- I Would like to open a list of files an re-write them all to new filenams. I know how to do this with a for loop and then open each file for reading and then writing them to a new file name. My question deals more with substitution in the filenames. For insatnce: I know that all of the files contain five letters followed by a number that couls be 1or 2 digits followed by .html. --> xxxxx1.html or xxxxx12.html What I would like to do is lopp off the 'xxxxx' and replace with 'yyy' so the previous example would end up with yyy1.html and yyy12.html. (of course the '1' and '12' could be any number that is between 1 and 2 digits long) How can I accomplish this easily. Thanks. SA :) From purplebo@babylonia.flatirons.org Wed Feb 12 00:41:01 2003 From: purplebo@babylonia.flatirons.org (Chris Avery) Date: Wed Feb 12 00:41:01 2003 Subject: [Tutor] fibonacci In-Reply-To: References: Message-ID: Of course, my apologies. The Fibonacci sequence is the sequence of numbers each of which, after the second, is the sum of the two previous ones. 0, 1, 1, 2, 3, 5, 8, 13, 21,..., Sorry about the confusion. Chris On Tue, 11 Feb 2003, Danny Yoo wrote: > > > On 11 Feb 2003, Chris Avery wrote: > > > Hello all. > > > > How would one go about writing a program that computes the fibonacci > > sequence? > > Hi Chris, > > > Counterquestion: what is the fibonacci sequence? *grin* > > > But seriously speaking: pretend that none of us on the list know what the > "fibonacci sequence" is, and try explaining it to us. Since concrete > examples help clear our head, it might also be helpful to show us what the > first few terms of these sequence are. > > You may find that explaining it to a human can help you figure out how to > program a computer how to do it! > > -- +++++++++++++++++++ Chris Avery, KC0OBP +++++++++++++++++++ From shalehperry@attbi.com Wed Feb 12 01:10:02 2003 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Wed Feb 12 01:10:02 2003 Subject: [Tutor] Substitution question... In-Reply-To: <200302120434.h1C4YVR4001253@buc99.bsd.st> References: <200302120434.h1C4YVR4001253@buc99.bsd.st> Message-ID: <200302112209.21051.shalehperry@attbi.com> On Tuesday 11 February 2003 20:34, montana wrote: > > What I would like to do is lopp off the 'xxxxx' and replace with 'yyy' = so > the previous example would end up with yyy1.html and yyy12.html. > > (of course the '1' and '12' could be any number that is between 1 and 2 > digits long) > > How can I accomplish this easily. > sounds like a regular expression to the rescue! import re my_re =3D re.compile(r'^.+?(\d+)\.html$') new_name =3D 'bob' filename =3D 'sean12.html' print my_re.sub('%s\\1.html' % new_name, name) bob12.html is the output. The regex translates to: 'start at the beginning of the string. Find a g= roup=20 of characters (don't care which) followed by a group of numbers and ".htm= l". =20 Store the group of numbers'. The sub() call replaces the string with the new_name followed by the grou= p of=20 numbers found and ".html" again. From Ike Hall Wed Feb 12 01:30:03 2003 From: Ike Hall (Ike Hall) Date: Wed Feb 12 01:30:03 2003 Subject: [Tutor] fibonacci References: <20030212020104.31410.qmail@web13408.mail.yahoo.com> Message-ID: <000d01c2d260$3bd19700$bf27e183@chief> Actually, the Fibonacci Sequence is quite simple, its 1,1,2,3,5,8,13,.... each number is the sum of the previous 2.... writing a program to do this would be simple as well... def fib(index): first=1 second=1 for i in range(index): new=first+second first=second second=new return new then this function would give the nth number in a fibonacci sequence ----- Original Message ----- From: "Mic Forster" To: Sent: Tuesday, February 11, 2003 8:01 PM Subject: Re: [Tutor] fibonacci > > --- Danny Yoo wrote: > > Counterquestion: what is the fibonacci sequence? > > *grin* > > > > > > But seriously speaking: pretend that none of us on > > the list know what the > > "fibonacci sequence" is, and try explaining it to > > us. Since concrete > > examples help clear our head, it might also be > > helpful to show us what the > > first few terms of these sequence are. > > > > You may find that explaining it to a human can help > > you figure out how to > > program a computer how to do it! > > > > > Danny, > > That's not bad advice. I have been told before that if > you cannot explain a scientific theory to a 6 year > old, and make them understand, then it is not much of > a theory. The same could be said of computer programming. > > __________________________________________________ > Do you Yahoo!? > Yahoo! Shopping - Send Flowers for Valentine's Day > http://shopping.yahoo.com > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From dyoo@hkn.eecs.berkeley.edu Wed Feb 12 02:31:01 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Feb 12 02:31:01 2003 Subject: [Tutor] fibonacci In-Reply-To: <000d01c2d260$3bd19700$bf27e183@chief> Message-ID: On Wed, 12 Feb 2003, Ike Hall wrote: > Actually, the Fibonacci Sequence is quite simple, > > its 1,1,2,3,5,8,13,.... > > each number is the sum of the previous 2.... > > writing a program to do this would be simple as well... > > def fib(index): > first=1 > second=1 > for i in range(index): > new=first+second > first=second > second=new > return new > > then this function would give the nth number in a fibonacci sequence Are you sure? This is not a flippant question: there's a subtle off-by-one bug in this implementation, so that fib(0) breaks, and every other value is off an index. (In the last statement of the block, I think the code can be repaired by returning 'first', rather than 'new'.) Even the simplest of programs need testing. I've been bitten way too much by silly typos to trust myself... *grin*. Good luck! From antonmuhin at rambler.ru" References: <200302120434.h1C4YVR4001253@buc99.bsd.st> Message-ID: <186945850.20030212103921@rambler.ru> Hello montana, Wednesday, February 12, 2003, 7:34:31 AM, you wrote: m> Hi Everyone- m> I Would like to open a list of files an re-write them all to new filenams. I know how to do this with a for loop and then open each file for reading and then writing them to a new file name. My m> question deals more with substitution in the filenames. For insatnce: m> I know that all of the files contain five letters followed by a number that couls be 1or 2 digits followed by .html. --> xxxxx1.html or xxxxx12.html m> What I would like to do is lopp off the 'xxxxx' and replace with 'yyy' so the previous example would end up with yyy1.html and yyy12.html. m> (of course the '1' and '12' could be any number that is between 1 and 2 digits long) m> How can I accomplish this easily. m> Thanks. m> SA m> :) If your files' names has such a strict structutre you described above, you might even keep away from regexp's: name = "xxxxx12" name[:5] will produce "xxxxx", while name[5:]---"12" Therefore to substitute you may write: newName = "yyy" + name[5:] BTW, if you need just to copy or rename files, you might be better with os.rename and shutil.* functions. -- Best regards, anton mailto:antonmuhin@rambler.ru From antonmuhin at rambler.ru" References: <20030212020104.31410.qmail@web13408.mail.yahoo.com> <000d01c2d260$3bd19700$bf27e183@chief> Message-ID: <931519965.20030212104855@rambler.ru> Hello Ike, Wednesday, February 12, 2003, 9:30:26 AM, you wrote: IH> writing a program to do this would be simple as well... IH> def fib(index): IH> first=1 IH> second=1 IH> for i in range(index): IH> new=first+second IH> first=second IH> second=new IH> return new IH> then this function would give the nth number in a fibonacci sequence There might be a small bug: fib(1) calculates to 2 that is not 1st fib (of course, it depends on how you count it :). Here I'd like suggest slightly modified variant: def fib(n, first = 1, second = 1): if n == 1: return first elif n == 2: return second else: for i in range(n - 2): first, second = second, first + second return second -- Best regards, anton mailto:antonmuhin@rambler.ru From dyoo@hkn.eecs.berkeley.edu Wed Feb 12 02:59:05 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Feb 12 02:59:05 2003 Subject: [Tutor] Accessing the Web using Python (fwd) Message-ID: Let me forward to the rest of the list, so that the rest of us know what the situation is. (Also, please don't call me Mr. Yoo. Just "Danny" is fine. Dear gosh, am I that old already? *grin*) Best of wishes to you! ---------- Forwarded message ---------- Date: Fri, 23 Aug 2002 03:19:35 -0500 From: Henry Steigerwaldt To: Danny Yoo Subject: Re: [Tutor] Accessing the Web using Python Mr. Yoo: I think you are on to something here. I just realized that after I get the data a couple of times like a just did earlier tonight, the access then stops. I'll bet a program monitors how many times someone comes into the site. If they do so too often in a short period of time, then they freeze them out for a time. I'll bet that is it. I had just finished making a while loop and trying to access that site over and over and over again to see if I could get in. It must have looped through 30 times! WOW! I'll stop that immediately! I would assume that is what hackers have done to try and cause a site to crash. If this is the problem and it sounds like it is, I'll just get the data later (or tomorrow) when I can again get into the site, store it to a file, and THEN do more work on my program by using the data stored on my PC. I'll try your suggestion in a few minutes. Thanks. Henry Steigerwaldt ----- Original Message ----- From: "Danny Yoo" To: "Henry Steigerwaldt" Cc: Sent: Tuesday, February 11, 2003 10:04 PM Subject: Re: [Tutor] Accessing the Web using Python > > > On Fri, 23 Aug 2002, Henry Steigerwaldt wrote: > > > > import urllib > > > > fwcURL = "http://isl715.nws.noaa.gov/tdl/forecast/fwc.txt" > > > > try: > > print "Going to Web for data" > > fwcall = urllib.urlopen(fwcURL).read() > > print "Successful" > > print "Will now print all of the data to screen" > > print "fwcall = ", fwcall > > except: > > print "Could not obtain data from Web" > > ______________________________________________ > > Using this code the previous day, I had absolutely no problem > > getting the data. However yesterday using the same code, > > most of the time this site could not be accessed at all. > > [some text cut] > > > I also noticed that a few times I would be able to access the site (i.e. > > the "Successful" would print to the screen), but each time absolutely > > NOTHING would be stored in the "fwcall" variable, unlike successful > > times when all the text information WAS stored in the variable. > > > > Hi Henry, > > > We may need some more information; at the moment, the code is obscuring > some information that exceptions can provide. Let's enable some more > diagnostics. Can you change the except block to something like: > > ### > except: > print "Could not obtain data from Web" > traceback.print_exc() > ### > > You'll probably need to import the 'traceback' module for this. The > additional line, that "traceback.print_exc()", will print out more > information about the excetion itself, and should give us insight into > what exactly is causing the magic to fizzle. > > > > > > I just tried this same code tonight and once again it works great! I am > > really puzzled by all this. When one writes a program to access the Web, > > as long as the site accessed is not "down," one should anticipate always > > being able to get the data. > > > It actually depends on the service that the web site provides! For > example, the National Center for Biotechnology Information (NCBI) provides > a set of valuable online programs and services for biologists: > > http://www.ncbi.nlm.nih.gov/ > > > But, despite the electronic nature of NCBI, there is a kind of scarcity > involved here: namely, they need to maintain a service that's available to > scientists in a timely fashion, and some of the services they provide are > computationally very expensive. What to do? > > > NCBI has a cap, a kind of rate limiter, that limits how many requests they > handle from a single computer at a time. That is, NCBI will block web > requests of anyone who tries to abuse their public resource. As an > example, here's what their guidelines dictate: > > > """ > Do not overload NCBI's systems. Users intending to send numerous > queries and/or retrieve large numbers of records from Entrez should > comply with the following: > > * Run retrieval scripts on weekends or between 9 PM and 5 AM ET > weekdays for any series of more than 100 requests. > > * Make no more than one request every 3 seconds. > """ > > > And they are serious. I accidently ran a program once that hammered their > systems. It is not a Good Thing when your computer is blacklisted from a > national public resource. *cough* > > > > But that's NCBI; I don't know if the National Weather Service applies a > similar rate-limiter on their services. So let's see what the > traceback.print_exc() gives us in your program above, and we'll work from > there. > > > > Good luck! > > From dyoo@hkn.eecs.berkeley.edu Wed Feb 12 03:18:03 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Feb 12 03:18:03 2003 Subject: [Tutor] fibonacci In-Reply-To: Message-ID: On Tue, 11 Feb 2003, Chris Avery wrote: > Of course, my apologies. > > The Fibonacci sequence is the sequence of numbers each of which, after the > second, is the sum of the two previous ones. > > 0, 1, 1, 2, 3, 5, 8, 13, 21,..., Ok, this sounds clear enough. Let's try it: ### def fibonacci(n): """The Fibonacci sequence is the sequence of numbers each of which, after the second, is the sum of the two previous ones.""" return fibonacci(n-1) + fibonacci(n-2) ### The above definition won't work, of course. But's it's darn close to being correct (if not efficient). Can you think of a reason why it's broken, and if there's a good way to fix it? > Sorry about the confusion. No problem; don't worry about it. The problem is a lot clearer now. Gotta go to sleep now. Good night! From janos.juhasz@VELUX.com Wed Feb 12 03:48:03 2003 From: janos.juhasz@VELUX.com (janos.juhasz@VELUX.com) Date: Wed Feb 12 03:48:03 2003 Subject: [Tutor] fibonacci Message-ID: Dear All, I have cut it from the activepython help, because of its beauty: # Fibonacci numbers module def fib(n): # write Fibonacci series up to n a, b =3D 0, 1 while b < n: print b, a, b =3D b, a+b def fib2(n): # return Fibonacci series up to n result =3D [] a, b =3D 0, 1 while b < n: result.append(b) a, b =3D b, a+b return result I know it needs a little modification, but it is uses that nice feature= of python that isn't available most of other programing languages. I mean, assign values for lists. Which languages support so well the list? Best regards, ----------------------- Juh=E1sz J=E1nos IT department = From fredm@smartypantsco.com Wed Feb 12 03:53:01 2003 From: fredm@smartypantsco.com (Alfred Milgrom) Date: Wed Feb 12 03:53:01 2003 Subject: [Tutor] fibonacci Message-ID: <5.1.0.14.0.20030212193948.02d50b70@mail.milgromphoto.com> The solutions presented so far calculate the nth value of the fibonacci sequence, and certainly Danny Yoo's pseudo-code definition only needs one (and a bit) additional line to make it work. However if the sequence is required, rather than the value of the nth element in the sequence, the following code makes good use of Python's lists and the ability to index from the end: def fibonacci(n): a = [0,1] if n<3: return a[:n] else: for i in range (2, n): a.append(a[-1]+a[-2]) return a print fibonacci(15) >>> [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377] Just as an exercise, I was unable to create a one-line recursive fibonacci generator, but the following works correctly for all values of n greater than 2. def fib(n): return (n<5)*(n-2) or fib(n-1) + fib(n-2) print fib(15) >>> 377 Fred Milgrom From Janssen@rz.uni-frankfurt.de Wed Feb 12 05:07:08 2003 From: Janssen@rz.uni-frankfurt.de (Michael Janssen) Date: Wed Feb 12 05:07:08 2003 Subject: [Tutor] List exercise In-Reply-To: <7497DCA1C240C042B28F6657ADFD8E0974DABB@i2km11-ukbr.domain1.systemhost.net> Message-ID: On Tue, 11 Feb 2003 alan.gauld@bt.com wrote: > > [Michael Janssen] > > When I remember correctly the threads "list exercise" wasn't > > such a shiny example of good programming style, was it? > > But that wasn't a tutorial teaching, it was a bunch of folks on this > list presenting different solutions to a problem. Hopefully a > pre written tutorial would resolve those issues before commitying > to 'print'. Oh I'm sorry for that: I've indeed looked for the tutorial (Think like those guys with computers section 8.3) and I believe the list exercise taken from this part of the tutorial isn't a shiny example of good programming style. The help of the list was a work in progress (I like Wiki for example and I like work in progress) and it was nice, straight, complete, helpful. Never comes to my mind to blame tutor@python.org ;-) Michael The rest of our little discussion is IMO subject to different opinions. Below follows a correction of my inappopriate english. > > It's very interesting - for me as a student of educational > > sience - how tutorials claim to explain something but tries to accomplish > > this effort on objects, which are harder than necessary (to say the > least). > > Not sure what you mean here? Do you mean objects are harder than > necessary(if so in what way?) or do you mean the tutors are harder > than necessary? Or both? tutorials (change objects to subjects :-). It's their way to give examples with pitfalls. When you want to show something clearly you possibly end description and make an example; when you want to give a problem to solve, you set up a pitfall. Both together make the learner think s/he has missed the clarification. From glingl@aon.at Wed Feb 12 05:40:03 2003 From: glingl@aon.at (Gregor Lingl) Date: Wed Feb 12 05:40:03 2003 Subject: [Tutor] fibonacci References: Message-ID: <3E4A2495.7060306@aon.at> This is a multi-part message in MIME format. --------------090705010405060909080500 Content-Type: text/plain; charset=us-ascii; format=flowed Content-Transfer-Encoding: 7bit Chris Avery schrieb: >Of course, my apologies. > >The Fibonacci sequence is the sequence of numbers each of which, after the >second, is the sum of the two previous ones. > >0, 1, 1, 2, 3, 5, 8, 13, 21,..., > > > ... and if you like to *see* them, run the following (or the attached) script: from turtle import * def fibotree(n, length=110, angle=45, factor=0.62): if n == 0: return forward(length) if n > 2: left(angle) fibotree(n-2, length*factor) right(angle) right(angle) fibotree(n-1, length*factor) left(angle) backward(length) reset() left(90) up();backward(120);down() fibotree(10) It makes you also see them grow and think about them ... Regards, Gregor --------------090705010405060909080500 Content-Type: text/plain; name="fibotree.py" Content-Transfer-Encoding: 7bit Content-Disposition: inline; filename="fibotree.py" from turtle import * def fibotree(n, length=110, angle=45, factor=0.62): if n == 0: return forward(length) if n > 2: left(angle) fibotree(n-2, length*factor) right(angle) right(angle) fibotree(n-1, length*factor) left(45) backward(length) reset() left(90) up();backward(120);down() fibotree(10) --------------090705010405060909080500-- From Janssen@rz.uni-frankfurt.de Wed Feb 12 05:56:56 2003 From: Janssen@rz.uni-frankfurt.de (Michael Janssen) Date: Wed Feb 12 05:56:56 2003 Subject: [Tutor] multiple "to" recipients using smtplib In-Reply-To: <003701c2d211$2bf0bef0$ca411dc6@ms.aliaswavefront.com> Message-ID: On Tue, 11 Feb 2003, Terence Lo wrote: > Hi there, > I have a python n00b question. How do I specify multiple 'to' recipients > using smtplib. I've tried the following code snippet but only the first > email recipient (user1@somewhere.com) receives the email and not the second. > I've also tried setting > toaddrs = ["user1@somehwere.com", "user2@somere.com"] but this doesn't work > either. Any idea what the heck I'm doing wrong? Using a string for two addresses is wrong. A single address can be a string (and smtplib will automatcally put it in a list with one element). toaddrs = ["user1@somehwere.com", "user2@somere.com"] is correct and should have worked. Are you sure it didn't? Spellchecked and so on? Michael > import smtplib > > toaddrs = "user1@somewhere.com, user2@somewhere.com" > fromaddr = "me@me.com" > msg="This is the message" > > server = smtplib.SMTP('mail.mymailserver.com') > > server.sendmail(fromaddr, toaddrs, msg) realize that this Message havn't got a Subject: nor To: (or CC:) header. You must put them at the head of msg (and two newlines before starting with the body) > server.quit() From woiski@dem.feis.unesp.br Wed Feb 12 06:40:04 2003 From: woiski@dem.feis.unesp.br (Emanuel R Woiski) Date: Wed Feb 12 06:40:04 2003 Subject: [Tutor] how to write an algorithm for sequence [puzzling over a sequence] References: Message-ID: <3E4A3271.7020606@dem.feis.unesp.br> --------------040807080007070703050706 Content-Type: text/plain; charset=us-ascii; format=flowed Content-Transfer-Encoding: 7bit I guess the sequence is such as: a[0] = 1 if n > 0 a[n] = a[n-1] + 2**(n + 3)/2 odd n a[n] = a[n-1] + 2**n/2 even n regards woiski Danny Yoo escreveu: >On Tue, 11 Feb 2003, Danny Yoo wrote: > > > >>On Wed, 12 Feb 2003, reavey wrote: >> >> >> >>>I'm stumped. I made up this sequence and I can't figure out a method. >>>the sequence is 1,5,7,15,19,35, 43, 75... >>> >>> >>Hi Reavey, >> >> >>This isn't quite Python either, but I'll give it a shot. *grin* >> >>Hmmm... I don't see anything immediate from the sequence above either. >> >> > > >That was a fun puzzle. I've got it. *grin* > > >If you don't want to ruin it for yourself, do not read the message below. > > >*** spoiler space ahead *** > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > >*** spoiler space *** > >If we take the original sequence: > > [1, 5, 7, 15, 19, 35, 43, 75] > >and we'd like to figure out a way to predict the next number, a good way >to start is to take differences between adjacent elements: > >### > > >>>>def differences(seq): >>>> >>>> >... for i in range(0, len(seq)-1): >... print seq[i+1] - seq[i], >... > > >>>>differences([1, 5, 7, 15, 19, 35, 43, 75]) >>>> >>>> >4 2 8 4 16 8 32 >### > > >Pattern recognition time. If we look at this in a twisty enough way, we >won't be able to resist seeing a pattern emerging.... if we write the >sequence in a zigzaggy sort of fashion. > > >Let's write the entries on the "even" indices on the top, and the "odd" >entries on the bottom: > > >4 2 8 4 16 8 32 ---> > > 4 8 16 32 > 2 4 8 > >And this should strike a chord: the sequence of differences is just a >shuffling of the powers of 2 against itself! > > >### > > >>>>def shuffle(s1, s2): >>>> >>>> >... pairs = zip(s1, s2) >... results = [] >... for p in pairs: >... results.append(p[0]) >... results.append(p[1]) >... return results >... > > >>>>powers_of_two = [2**n for n in range(10)] >>>>l1 = powers_of_two[2:] >>>>l2 = powers_of_two[1:] >>>>shuffle(l1, l2) >>>> >>>> >[4, 2, 8, 4, 16, 8, 32, 16, 64, 32, 128, 64, 256, 128, 512, 256] >### > > >Success! But why should we pay so much attention to differences? >Because, if we can figure out how the differences work, we can figure out >how the original sequence works. Let's see why. As a concrete example, >we see that the next difference that's coming up after 32 is 16. > >[4, 2, 8, 4, 16, 8, 32, 16, ...] > ^^^^ > >So we plug 16 at the bottom of our little "differences" diagram we drew up >before: > > 1 5 7 15 19 35 43 75 > 4 2 8 4 16 8 32 > >[plug in 16] ==> > > > 1 5 7 15 19 35 43 75 > 4 2 8 4 16 8 32 16 > > >Now the next number on the top, our original sequence, is easy to >calculate: > >### > > >>>>75 + 16 >>>> >>>> >91 >### > > >Let's say this in formal mathy language. First, we'll label the top row >the "sequence" row, and let's label the bottom the "difference" row. >Now, since we've named them, let's say the relationship between the two >rows: > > sequence(0) = 1 ## the first number in the sequences row is > ## always 1. > > > sequence(n) = sequence(n-1) + difference(n-1) > > ## And any other number is just the > ## the number to the left, plus > ## the difference number on the right > ## side. > > > > >Here is a formula I'll conjure up that gives us the "n'th" difference >number: > >### > > >>>>def secretFormula(n): >>>> >>>> >... return ((-1)**n + 1) * 2**((n+2)/2) >... > > >>>>[secretFormula(n) for n in range(10)] >>>> >>>> >[4, 0, 8, 0, 16, 0, 32, 0, 64, 0] > > >>>>def secretFormula2(n): return secretFormula(n-3) >>>> >>>> >... > > >>>>[secretFormula2(n) for n in range(10)] >>>> >>>> >[0.0, 2.0, 0.0, 4, 0, 8, 0, 16, 0, 32] > > >>>>def d(n): >>>> >>>> >... return int(secretFormula(n) + secretFormula2(n)) >... > > >>>>[d(n) for n in range(10)] >>>> >>>> >[4, 2, 8, 4, 16, 8, 32, 16, 64, 32] >### > > > >And with this, we're pretty much set: > >### > > >>>>def sequence(n): >>>> >>>> >... if n == 0: return 1 >... return sequence(n-1) + d(n-1) >... > > >>>>sequence(0) >>>> >>>> >1 > > >>>>sequence(1) >>>> >>>> >5 > > >>>>sequence(2) >>>> >>>> >7 > > >>>>[sequence(n) for n in range(10)] >>>> >>>> >[1, 5, 7, 15, 19, 35, 43, 75, 91, 155] >### > > >We can continue going on, but I think I'll stop here. But now I've got a >hankering to start reading Concrete Mathematics again. *grin* > > >Hope this helps! > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > > --------------040807080007070703050706 Content-Type: text/html; charset=us-ascii Content-Transfer-Encoding: 7bit I guess the sequence is such as:
a[0] = 1
if n > 0
a[n] = a[n-1] + 2**(n + 3)/2    odd n
a[n] = a[n-1] + 2**n/2       even n

regards

woiski

Danny Yoo escreveu:
On Tue, 11 Feb 2003, Danny Yoo wrote:

  
On Wed, 12 Feb 2003, reavey wrote:

    
I'm stumped. I made up this sequence and I can't figure out a method.
the sequence is 1,5,7,15,19,35, 43, 75...
      
Hi Reavey,


This isn't quite Python either, but I'll give it a shot.  *grin*

Hmmm... I don't see anything immediate from the sequence above either.
    


That was a fun puzzle.  I've got it.  *grin*


If you don't want to ruin it for yourself, do not read the message below.


*** spoiler space ahead ***










































*** spoiler space ***

If we take the original sequence:

    [1, 5, 7, 15, 19, 35, 43, 75]

and we'd like to figure out a way to predict the next number, a good way
to start is to take differences between adjacent elements:

###
  
def differences(seq):
        
...     for i in range(0, len(seq)-1):
...         print seq[i+1] - seq[i],
...
  
differences([1, 5, 7, 15, 19, 35, 43, 75])
        
4 2 8 4 16 8 32
###


Pattern recognition time.  If we look at this in a twisty enough way, we
won't be able to resist seeing a pattern emerging.... if we write the
sequence in a zigzaggy sort of fashion.


Let's write the entries on the "even"  indices on the top, and the "odd"
entries on the bottom:


4 2 8 4 16 8 32 --->

                    4   8   16   32
                      2   4    8

And this should strike a chord: the sequence of differences is just a
shuffling of the powers of 2 against itself!


###
  
def shuffle(s1, s2):
        
...     pairs = zip(s1, s2)
...     results = []
...     for p in pairs:
...         results.append(p[0])
...         results.append(p[1])
...     return results
...
  
powers_of_two = [2**n for n in range(10)]
l1 = powers_of_two[2:]
l2 = powers_of_two[1:]
shuffle(l1, l2)
        
[4, 2, 8, 4, 16, 8, 32, 16, 64, 32, 128, 64, 256, 128, 512, 256]
###


Success!  But why should we pay so much attention to differences?
Because, if we can figure out how the differences work, we can figure out
how the original sequence works.  Let's see why.  As a concrete example,
we see that the next difference that's coming up after 32 is 16.

[4, 2, 8, 4, 16, 8, 32, 16, ...]
                       ^^^^

So we plug 16 at the bottom of our little "differences" diagram we drew up
before:

    1   5   7   15   19   35   43   75
      4   2   8    4   16    8    32

[plug in 16] ==>


    1   5   7   15   19   35   43   75
      4   2   8    4   16    8    32  16


Now the next number on the top, our original sequence, is easy to
calculate:

###
  
75 + 16
        
91
###


Let's say this in formal mathy language.  First, we'll label the top row
the "sequence" row, and let's label the bottom the "difference" row.
Now, since we've named them, let's say the relationship between the two
rows:

    sequence(0) = 1           ## the first number in the sequences row is
                              ## always 1.


    sequence(n) = sequence(n-1) + difference(n-1)

                              ## And any other number is just the
                              ## the number to the left, plus
                              ## the difference number on the right
                              ## side.




Here is a formula I'll conjure up that gives us the "n'th" difference
number:

###
  
def secretFormula(n):
        
...     return ((-1)**n + 1) * 2**((n+2)/2)
...
  
[secretFormula(n) for n in range(10)]
        
[4, 0, 8, 0, 16, 0, 32, 0, 64, 0]
  
def secretFormula2(n): return secretFormula(n-3)
        
...
  
[secretFormula2(n) for n in range(10)]
        
[0.0, 2.0, 0.0, 4, 0, 8, 0, 16, 0, 32]
  
def d(n):
        
...     return int(secretFormula(n) + secretFormula2(n))
...
  
[d(n) for n in range(10)]
        
[4, 2, 8, 4, 16, 8, 32, 16, 64, 32]
###



And with this, we're pretty much set:

###
  
def sequence(n):
        
...     if n == 0: return 1
...     return sequence(n-1) + d(n-1)
...
  
sequence(0)
        
1
  
sequence(1)
        
5
  
sequence(2)
        
7
  
[sequence(n) for n in range(10)]
        
[1, 5, 7, 15, 19, 35, 43, 75, 91, 155]
###


We can continue going on, but I think I'll stop here.  But now I've got a
hankering to start reading Concrete Mathematics again.  *grin*


Hope this helps!


_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


  

--------------040807080007070703050706-- From alan.gauld@bt.com Wed Feb 12 07:48:01 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Wed Feb 12 07:48:01 2003 Subject: [Tutor] Sun says: Don't use Java, use Python! Message-ID: <7497DCA1C240C042B28F6657ADFD8E0901F850B9@i2km11-ukbr.domain1.systemhost.net> > > ideally be implemented in a single file to make redistribution > > and configuration control easier. Javba breaks that model and > > A single file... you mean like a JAR file? Nope coz the jar is the unit of distribution not the unit of implementation. If somebody makes a change to a single class high is part of a category they have to issue a new Jar containing all of the classes in the original. We then have multiple Jars some with A B C and some with A B and C+. It becomes hard to know what has changed, what the impact is etc. If A B and C are in a single source file we can be sure that the .obj(or library) is consistent in its internal class versions. Alan g. From alan.gauld@bt.com Wed Feb 12 07:51:02 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Wed Feb 12 07:51:02 2003 Subject: [Tutor] Sun says: Don't use Java, use Python! Message-ID: <7497DCA1C240C042B28F6657ADFD8E0901F850BA@i2km11-ukbr.domain1.systemhost.net> > > Erik: "What I have heard is that in Java everything is an object." > Alan: "Not so. In Java, everything is a class." > Probably. Its my main philosophical gripe with Java. It is badly done from a pure OOP point of view. > by putting a bunch of procedural code into the main method of > a class. It isn't a good way to start off. Absolutely! But it is an acceptable Java idiom unfortunately. cf the math operations... BTW I have no problem with providing the ability to create functions (a la Python) but lets not pretend that wrapping them in a class has anything to do with OOP! Alan G. From erikprice@mac.com Wed Feb 12 08:08:01 2003 From: erikprice@mac.com (Erik Price) Date: Wed Feb 12 08:08:01 2003 Subject: [Tutor] Sun says: Don't use Java, use Python! In-Reply-To: <7497DCA1C240C042B28F6657ADFD8E0901F850B9@i2km11-ukbr.domain1.systemhost.net> Message-ID: On Wednesday, February 12, 2003, at 07:45 AM, alan.gauld@bt.com wrote: >>> ideally be implemented in a single file to make redistribution >>> and configuration control easier. Javba breaks that model and >> >> A single file... you mean like a JAR file? > > Nope coz the jar is the unit of distribution not the unit of > implementation. If somebody makes a change to a single class > high is part of a category they have to issue a new Jar > containing all of the classes in the original. We then have > multiple Jars some with A B C and some with A B and C+. > It becomes hard to know what has changed, what the impact is etc. > If A B and C are in a single source file we can be sure that > the .obj(or library) is consistent in its internal class versions. Hm... I'm not trying to be argumentative, but it would seem to me that you could have this problem with any kind of versioned distributed product. How does putting A B and C into a single source file ensure that the person who made the modification has tested that it is binary compatible with the rest of the package? It seems to me that the JAR provides the convenience of a single file to distribute, but the cleanliness of separating out classes into separate files (even into hierarchies). If the code really is production code, then I would hope that the developers would be using an ant script to compile and assemble the JAR which incorporates a test bed to ensure that everything inside the JAR is to spec etc. Sure, there is a lot of room for error here, but I think the same is true of a Python module. Don't get me wrong! It probably sounds like I'm pooping on Python. I'm really not, I like Python. But, even though I have limited experience with Java, I think it has some really nice features for making distributable code. I'm open-minded to hear about alternative strategies for this, though. I've never written code for public distribution myself (only for the two companies I've worked for), so any thoughts or comments on this subject are welcome. Especially since I am working on a [personal] project as we speak that I intend to make freely available when it is ready. Erik -- Erik Price email: erikprice@mac.com jabber: erikprice@jabber.org From erikprice@mac.com Wed Feb 12 08:14:22 2003 From: erikprice@mac.com (Erik Price) Date: Wed Feb 12 08:14:22 2003 Subject: [Tutor] Sun says: Don't use Java, use Python! In-Reply-To: <7497DCA1C240C042B28F6657ADFD8E0901F850B2@i2km11-ukbr.domain1.systemhost.net> Message-ID: <9A2548F4-3E8D-11D7-88ED-00039351FE6A@mac.com> On Tuesday, February 11, 2003, at 06:40 PM, alan.gauld@bt.com wrote: > For production Python - and I stress I do very little production code > in Python, I use it for prototyping prior to Java or C++ - Do you use Jython at all (in prototyping for Java)? Have you any thoughts about Jython? Erik -- Erik Price email: erikprice@mac.com jabber: erikprice@jabber.org From alan.gauld@bt.com Wed Feb 12 08:34:01 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Wed Feb 12 08:34:01 2003 Subject: [Tutor] Sun says: Don't use Java, use Python! Message-ID: <7497DCA1C240C042B28F6657ADFD8E0974DABC@i2km11-ukbr.domain1.systemhost.net> > > containing all of the classes in the original. We then have > > multiple Jars some with A B C and some with A B and C+. > > It becomes hard to know what has changed, what the impact is etc. I didn't explain this well, sorry. I meant let's assume C is modified but because of dependencies B needs to be modified to cope with the changes in C. So the Jar file *should* contain A B+ and C+ but accidentally gets shipped with only A B and C+ This kind of consistency error can and does happen and is very hard to detect if you don't have the original source files(in fact even if you do, because the modified B is in the source repository but the old B is in the JAR! If A B and C are all in one source file then this can't happen. Of course the file gets very big which is where tradeoff comes in. In C++ and some other languages(Modula etc) we can separate declaration from implementation and so keep the class declarations in one file and the implementations in separate ones - the best of both worlds. > How does putting A B and C into a single source file ensure > that the person who made the modification has tested that it > is binary compatible with the rest of the package? Provided they test the JAR and not the compiled source then its fine. Unfortunately experience tells me that very often developers test the source files then create a JAR and ship it. If the JAR creation step doesn't, for whatever reason, pick up the right source version then an error results. From hard experience with several vendors we have become very wary of JAR releases! > production code, then I would hope that the developers would be using > an ant script to compile and assemble the JAR which > incorporates a test bed to ensure that everything inside the JAR > is to spec etc. You would hope so, but sadly you might be wrong... > there is a lot of room for error here, but I think the same > is true of a Python module. Sure but Python lets you choose your poison. Java dictates it. > strategies for this, though. I've never written code for public > distribution myself (only for the two companies I've worked for), I'm usually a customer, and suffer the pain. Weget far fewer of these kinds of issues from the C++ suppliers than from the Java guys.(Sometimes they are even the same vendor!) C++'s header, body approach requires more upfront work but provides a powerful error catching mechanism IMHO. Alan g. From alan.gauld@bt.com Wed Feb 12 08:38:09 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Wed Feb 12 08:38:09 2003 Subject: [Tutor] Sun says: Don't use Java, use Python! Message-ID: <7497DCA1C240C042B28F6657ADFD8E0901F850BE@i2km11-ukbr.domain1.systemhost.net> > Do you use Jython at all (in prototyping for Java)? Have you any > thoughts about Jython? Tried it but it broke my JRE engine used by IE for one of our in house applications so I had to take it out again! Alan g From karthik@james.hut.fi Wed Feb 12 09:31:01 2003 From: karthik@james.hut.fi (Karthikesh Raju) Date: Wed Feb 12 09:31:01 2003 Subject: [Tutor] viewing images In-Reply-To: <20030212114004.26734.81941.Mailman@mail.python.org> Message-ID: Hi, i am trying to view matrices as images (just like the imagesc in matlab). NumTut (which comes with numeric) has something close to it, but whenever i import it, the whole python slows down.... it veryoften dumps core. Anybody aware of a simple yet effective view.py (similar to the lines of view.py)...... Any other suggestions, Best regards karthik ----------------------------------------------------------------------- Karthikesh Raju, email: karthik@james.hut.fi Researcher, http://www.cis.hut.fi/karthik Helsinki University of Technology, Tel: +358-9-451 5389 Laboratory of Comp. & Info. Sc., Fax: +358-9-451 3277 Department of Computer Sc., P.O Box 5400, FIN 02015 HUT, Espoo, FINLAND ----------------------------------------------------------------------- From brad.reisfeld@colostate.edu Wed Feb 12 09:32:51 2003 From: brad.reisfeld@colostate.edu (Brad Reisfeld) Date: Wed Feb 12 09:32:51 2003 Subject: [Tutor] checksum of dictionary Message-ID: Hi, I have a time-consuming function that operates on a large dictionary. Before I call this function, I'd like to confirm that the dictionary has changed since the last time I called the function. To check for a change, I am thinking of calculating a checksum on the dictionary. My initial approach is something like >>> import marshal >>> import md5 >>> d={'a':1,'b':2} >>> md5.new(marshal.dumps(d)).hexdigest() '2854ff50b105cab3a4ca3d71c76834a7' >>> d['c']=3 >>> md5.new(marshal.dumps(d)).hexdigest() '8c3213334c7311d387aceb59610cfeff' >>> del d['b'] >>> md5.new(marshal.dumps(d)).hexdigest() 'b9063f0f5409882e9a3474b70dc9d090' >>> d['b']=3 >>> md5.new(marshal.dumps(d)).hexdigest() '9af630eec20336c8842637893833baec' >>> d['b']=2 >>> md5.new(marshal.dumps(d)).hexdigest() '8c3213334c7311d387aceb59610cfeff' Is a checksum a reasonable approach? Is there a better or more economical way to check a large dictionary for changes? Thanks. -Brad From amd@atlas.ucpel.tche.br Wed Feb 12 10:38:25 2003 From: amd@atlas.ucpel.tche.br (Aurelio Magalhaes Dias) Date: Wed Feb 12 10:38:25 2003 Subject: [Tutor] fibonacci In-Reply-To: <000d01c2d260$3bd19700$bf27e183@chief> References: <20030212020104.31410.qmail@web13408.mail.yahoo.com> <000d01c2d260$3bd19700$bf27e183@chief> Message-ID: Hi all, Well I think the sequence starts from zero ... 0,1,1,2,3,5,8,13,... so fib(0) =3D 0; fib(1) =3D 1; fib(2) =3D 1 ... Isn't it ? Bye, Aur=E9lio. ----------------------------------------- Aur=E9lio Magalh=E3es Dias Ci=EAncia da Computa=E7=E3o UCPel - RS - Brasil ----------------------------------------- On Wed, 12 Feb 2003, Ike Hall wrote: > Actually, the Fibonacci Sequence is quite simple, > > its 1,1,2,3,5,8,13,.... > From alan.gauld@bt.com Wed Feb 12 10:56:25 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Wed Feb 12 10:56:25 2003 Subject: [Tutor] List exercise Message-ID: <7497DCA1C240C042B28F6657ADFD8E0901F850C1@i2km11-ukbr.domain1.systemhost.net> > tutorials (change objects to subjects :-). It's their way to > give examples with pitfalls. When you want to show something clearly you > possibly end description and make an example; when you want to give a problem to > solve, you set up a pitfall. Both together make the learner think s/he has > missed the clarification. OK, Interesting point. I now need to revisit my tutor to see if/when I fall into that trap. I guess that is a bigger problem with paper books since web tutor authors get copious feedback(trust me on this! :-) and have opportunity to fix ambiguities progressively. Paper authors have to await the print schedules of their publisher - which are driven by sales volume not technical accuracy! Thanks for clarifying, Alan G From eprice@ptc.com Wed Feb 12 11:18:17 2003 From: eprice@ptc.com (Erik Price) Date: Wed Feb 12 11:18:17 2003 Subject: [Tutor] Sun says: Don't use Java, use Python! In-Reply-To: <7497DCA1C240C042B28F6657ADFD8E0974DABC@i2km11-ukbr.domain1.systemhost.net> References: <7497DCA1C240C042B28F6657ADFD8E0974DABC@i2km11-ukbr.domain1.systemhost.net> Message-ID: <3E4A7225.2010902@ptc.com> alan.gauld@bt.com wrote: > This kind of consistency error can and does happen and is very > hard to detect if you don't have the original source files(in > fact even if you do, because the modified B is in the source > repository but the old B is in the JAR! If A B and C are all > in one source file then this can't happen. Of course the file > gets very big which is where tradeoff comes in. I see your point about this. You're right. However, if you're using ant, then the general practice is to do an "ant clean" (to remove the current build altogether) and then do an "ant dist" (to rebuild the build and then package it into a jar). This would ensure that all the source files are up to date. It is my understanding that ant is being used widely in Java development, not just in J2EE webapp development (which is what I use ant for). > In C++ and some > other languages(Modula etc) we can separate declaration from > implementation and so keep the class declarations in one file > and the implementations in separate ones - the best of both worlds. [...] > C++'s header, body approach requires more upfront work but > provides a powerful error catching mechanism IMHO. Yes, this is also how Objective-C does it. There is a file.h with the declarations/prototypes and a file.m which implements the class. It is not something I have used before (since I have never used C++) but I kind of like it. Erik From gp@pooryorick.com Wed Feb 12 11:29:16 2003 From: gp@pooryorick.com (Poor Yorick) Date: Wed Feb 12 11:29:16 2003 Subject: [Tutor] Decision matrix Message-ID: <3E4A765F.1000105@pooryorick.com> The following question will expose the fact that I am mathematically challenged, but here goes... I have a function which takes a string as a paramater. Each letter in the string represents a switch, and each unique combination of letters should result in a different function being called, like so: STRING FUNCTION r function1 rd function2 rds function3 d function4 ds function5 s function6 I've toyed with a series of if statements and considered constructing a bitwise variable with which to index a dictionary of functions, and am now looking for suggestions. What would be the most eloquent way to code this sort of decision matrix in Python? Poor Yorick gp@pooryorick.com From eprice@ptc.com Wed Feb 12 11:44:02 2003 From: eprice@ptc.com (Erik Price) Date: Wed Feb 12 11:44:02 2003 Subject: [Tutor] Decision matrix In-Reply-To: <3E4A765F.1000105@pooryorick.com> References: <3E4A765F.1000105@pooryorick.com> Message-ID: <3E4A798A.4000806@ptc.com> Poor Yorick wrote: > > STRING FUNCTION > > r function1 > rd function2 > rds function3 > d function4 > ds function5 > s function6 > > I've toyed with a series of if statements and considered constructing a > bitwise variable with which to index a dictionary of functions, and am > now looking for suggestions. What would be the most eloquent way to > code this sort of decision matrix in Python? Maybe I'm not entirely clear on what you're trying to do, but I'm curious as to why you haven't tried the dictionary of functions approach. It seems like you have a one-to-one mapping with each of these. |>>> def func1(): |... return 1 |... |>>> def func2(): |... return 2 |... |>>> def func3(): |... return 3 |... |>>> funcs = { 'r':func1, 'rd':func2, 'rds':func3 } |>>> for i in funcs.keys(): |... print "%s : %i" % (i, funcs[i]()) |... |rd: 2 |r : 1 |rds : 3 |>>> Erik PS: Special thanks to the sages on this list for showing me how functions are just another kind of object and can be referenced/called in this fashion. From drewp@bigasterisk.com Wed Feb 12 12:31:02 2003 From: drewp@bigasterisk.com (Drew Perttula) Date: Wed Feb 12 12:31:02 2003 Subject: [Tutor] checksum of dictionary In-Reply-To: Your message of "Wed, 12 Feb 2003 07:31:26 MST." Message-ID: <200302121729.h1CHTus19681@bang.houseoflove> > Hi, > I have a time-consuming function that operates on a large dictionary. Before > I call this function, I'd like to confirm that the dictionary has changed > since the last time I called the function. > To check for a change, I am thinking of calculating a checksum on the > dictionary. Nowadays you can subclass the dictionary to make one that notices any changes. If you're purely concerned about setitem and delitem calls, you could just override those. If you want to catch update(), etc, you might like http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/117236, which is a dict interface defined in terms of getitem/setitem/delitem/keys. It's great for constructing custom dict-like objects that use custom code for all 20-or-so of the standard dict methods. Obviously, watching dict accesses would be tremendously more efficient than walking the whole dict every time you need to see if it changed. -Drew From brad.reisfeld@colostate.edu Wed Feb 12 13:45:03 2003 From: brad.reisfeld@colostate.edu (Brad Reisfeld) Date: Wed Feb 12 13:45:03 2003 Subject: [Tutor] checksum of dictionary In-Reply-To: <200302121729.h1CHTus19681@bang.houseoflove> Message-ID: Hi Drew, Thanks for the feedback. Actually, the dictionary in question is already a subclass of dict. It seems as if using setitem/delitem might be overkill for this since all I really care about is a gross state change in the dictionary between 'expensive' calls to my function. In other words, my scenario is 1. create large dict 2. call function on dict 3. perhaps add elements to dict 4. perhaps add elements to dict 5. call function on dict (only if dict is not the same as in step 1). 6. ... I thought that marshaling the dict would be fairly inexpensive (I could be wrong); that was the basis for my checksum idea. -Brad > -----Original Message----- > From: Drew Perttula [mailto:drewp@bigasterisk.com] > Sent: Wednesday, February 12, 2003 10:30 AM > To: Brad Reisfeld > Cc: tutor@python.org > Subject: Re: [Tutor] checksum of dictionary > > > > > Hi, > > I have a time-consuming function that operates on a large > dictionary. Before > > I call this function, I'd like to confirm that the dictionary > has changed > > since the last time I called the function. > > To check for a change, I am thinking of calculating a checksum on the > > dictionary. > > Nowadays you can subclass the dictionary to make one that notices any > changes. If you're purely concerned about setitem and delitem calls, you > could just override those. If you want to catch update(), etc, you might > like http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/117236, which > is a dict interface defined in terms of getitem/setitem/delitem/keys. It's > great for constructing custom dict-like objects that use custom code > for all 20-or-so of the standard dict methods. > > Obviously, watching dict accesses would be tremendously more efficient > than walking the whole dict every time you need to see if it changed. > > -Drew > From aschmidt@fredericksburg.com Wed Feb 12 13:58:22 2003 From: aschmidt@fredericksburg.com (aschmidt@fredericksburg.com) Date: Wed Feb 12 13:58:22 2003 Subject: [Tutor] Digest Authentication with URLLIB2 Message-ID: <200302121853.h1CIr2GQ014746@sws002.fredericksburg.com> This is a multi-part message in MIME format. --bound1045075977 Content-Type: text/plain Content-Transfer-Encoding: 7bit I need some examples of how to incorporate digest authentication into a Python script. Right now, I use urllib to handle the passing of the url and the return of the data...a huge block of tab delimited data. But the group where I get the data is changing their access methods and say they will be requiring digest authentication before being able to call that url now. Any ideas or examples, or links and pointers to such things elsewhere is much appreciated. Thanks Allen --bound1045075977-- From Ike Hall Wed Feb 12 14:45:01 2003 From: Ike Hall (Ike Hall) Date: Wed Feb 12 14:45:01 2003 Subject: [Tutor] fibonacci References: Message-ID: <000701c2d2cf$26d0da40$bf27e183@chief> Hi, yeah, I realized that when after I sent it...dont drink and code... Ike ----- Original Message ----- From: "Danny Yoo" To: "Ike Hall" Cc: "Mic Forster" ; Sent: Wednesday, February 12, 2003 1:30 AM Subject: Re: [Tutor] fibonacci > > > On Wed, 12 Feb 2003, Ike Hall wrote: > > > Actually, the Fibonacci Sequence is quite simple, > > > > its 1,1,2,3,5,8,13,.... > > > > each number is the sum of the previous 2.... > > > > writing a program to do this would be simple as well... > > > > def fib(index): > > first=1 > > second=1 > > for i in range(index): > > new=first+second > > first=second > > second=new > > return new > > > > then this function would give the nth number in a fibonacci sequence > > > Are you sure? > > This is not a flippant question: there's a subtle off-by-one bug in this > implementation, so that fib(0) breaks, and every other value is off an > index. > > (In the last statement of the block, I think the code can be repaired by > returning 'first', rather than 'new'.) > > > Even the simplest of programs need testing. I've been bitten way too much > by silly typos to trust myself... *grin*. > > > Good luck! > From ramrom@earthling.net Wed Feb 12 15:39:02 2003 From: ramrom@earthling.net (Bob Gailer) Date: Wed Feb 12 15:39:02 2003 Subject: [Tutor] Sun says: Don't use Java, use Python! In-Reply-To: <3E4A7225.2010902@ptc.com> References: <7497DCA1C240C042B28F6657ADFD8E0974DABC@i2km11-ukbr.domain1.systemhost.net> <7497DCA1C240C042B28F6657ADFD8E0974DABC@i2km11-ukbr.domain1.systemhost.net> Message-ID: <5.2.0.9.0.20030212133638.019ee620@66.28.54.253> --=======55AC6B92======= Content-Type: text/plain; x-avg-checked=avg-ok-6CB73CC4; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit Could we move this (now) non-Python and non-tutorial topic to another venue? Bob Gailer mailto:ramrom@earthling.net 303 442 2625 --=======55AC6B92======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-6CB73CC4 Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.445 / Virus Database: 250 - Release Date: 1/21/2003 --=======55AC6B92=======-- From eprice@ptc.com Wed Feb 12 15:49:02 2003 From: eprice@ptc.com (Erik Price) Date: Wed Feb 12 15:49:02 2003 Subject: [Tutor] Digest Authentication with URLLIB2 In-Reply-To: <200302121853.h1CIr2GQ014746@sws002.fredericksburg.com> References: <200302121853.h1CIr2GQ014746@sws002.fredericksburg.com> Message-ID: <3E4A9F6E.4020608@ptc.com> aschmidt@fredericksburg.com wrote: > I need some examples of how to incorporate digest authentication into a Python script. Right now, I use urllib to handle the passing of the url and the return of the data...a huge block of tab delimited data. > > But the group where I get the data is changing their access methods and say they will be requiring digest authentication before being able to call that url now. > > Any ideas or examples, or links and pointers to such things elsewhere is much appreciated. I SFTW'd and found this nice, simple explanation of what digest authentication is: http://frontier.userland.com/stories/storyReader$2159 And then I found mention of digest authentication in the documentation of the urllib2 module: http://www.python.org/doc/current/lib/module-urllib2.html I didn't try it (no time, have my own project I'm working on), but it looks like what you're supposed to do is this: 1. make the initial request for the resource 2. the server responds with the nonce (read the first URL above if you're not familiar with this) 3. You create a HTTPPasswordMgr object 4. You call the add_password() method of the HTTPPasswordMgr object and pass in the data for building a password. 5. You pass the HTTPPasswordMgr to a HTTPDigestAuthHandler object and then call handle_authentication_request() and pass in the relevant parameters. It's pretty confusing to me. Hopefully someone else on the list can shed better light on this one. Erik From flash1210@hotmail.com Wed Feb 12 17:19:03 2003 From: flash1210@hotmail.com (Frank Holmes) Date: Wed Feb 12 17:19:03 2003 Subject: [Tutor] please remove me Message-ID: Please remove me from the python mailing list _________________________________________________________________ Protect your PC - get McAfee.com VirusScan Online http://clinic.mcafee.com/clinic/ibuy/campaign.asp?cid=3963 From SWidney@ci.las-vegas.nv.us Wed Feb 12 17:19:24 2003 From: SWidney@ci.las-vegas.nv.us (Scott Widney) Date: Wed Feb 12 17:19:24 2003 Subject: [Tutor] fibonacci Message-ID: <0E5508EBA1620743B409A2B8365DE16FDC8376@sovereign.ci.las-vegas.nv.us> > I have cut it from the activepython help, because of its beauty: > > # Fibonacci numbers module > > def fib(n): # write Fibonacci series up to n > a, b = 0, 1 > while b < n: > print b, > a, b = b, a+b > > def fib2(n): # return Fibonacci series up to n > result = [] > a, b = 0, 1 > while b < n: > result.append(b) > a, b = b, a+b > return result > And if you want to see the first n items in the list of fibonacci numbers: >>> def fib3(index): ... result = [] ... a, b = 0, 1 ... while len(result) < index: ... result.append(b) ... a, b = b, a+b ... return result ... >>> fib3(10) [1, 1, 2, 3, 5, 8, 13, 21, 34, 55] >>> fib3(20) [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765] >>> Regards, Scott From alan.gauld@bt.com Wed Feb 12 18:15:02 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Wed Feb 12 18:15:02 2003 Subject: [Tutor] Decision matrix Message-ID: <7497DCA1C240C042B28F6657ADFD8E0901F850C3@i2km11-ukbr.domain1.systemhost.net> > each unique combination of letters > should result in a different function being called, like so: unique string corresponds to value. Sounds like the definition of a dictionary to me... Functions = { "r": function1, "rd": function2, etc... "s": function6 } Instead of if seq == "R": function1() elif seq == "rd": function2() etc... do Functions[seq]() > What would be the most eloquent way to > code this sort of decision matrix in Python? Does that work for you? Alan G From missive@hotmail.com Wed Feb 12 20:54:21 2003 From: missive@hotmail.com (Lee Harr) Date: Wed Feb 12 20:54:21 2003 Subject: [Tutor] pygsear prob mandrake 8.2 Message-ID: >I continue to have a problem with the package. the ./test.py command >returns error >sh: python 2.2 : command not found Hmm, I have only tried any of this with 2.2, but I guess you could try changing the test.py script to this: # test.py import os os.environ['PYTHONPATH'] = os.getcwd() os.system('python examples/simple.py') # change python2.2 to python # end test.py Do you already have Pygame1.5 installed? >the set-up returns the same error So, when you try python setup.py install you get the same error about not finding python2.2? That does not make sense to me. I do not see any reference to version 2.2 in the setup, and I've accidentally installed in to my python2.1 lib by accident a number of times :0) _________________________________________________________________ The new MSN 8: smart spam protection and 2 months FREE* http://join.msn.com/?page=features/junkmail From gp@pooryorick.com Thu Feb 13 03:29:11 2003 From: gp@pooryorick.com (Poor Yorick) Date: Thu Feb 13 03:29:11 2003 Subject: [Tutor] Decision matrix References: <7497DCA1C240C042B28F6657ADFD8E0901F850C3@i2km11-ukbr.domain1.systemhost.net> Message-ID: <3E4B57B2.8060607@pooryorick.com> alan.gauld@bt.com wrote: >>eac >> > >Sounds like the definition of a dictionary to me... > Two problems with using a dictionary: 1. I would like the flags to be accepted in any order. 2. If I come up with other flags in the future, I would like to deal with them in the most simple possible manner. Adding an exponentially larger number of permutations as dictionary keys doesn't seem like a good method. The solution I've been thinking of today is to code a list of possible functions for each flag and then find the intersection of the lists indicated by the flags passed into the function. Here is a pseudocode example: def fList(path, mode): '''return a list of files, folders, or both, optionally including subdirectories''' #flag tuples f = (Files, FilesS, FilesDirs, FilesDirsS) d = (Dirs, DirsS, FilesDirs, FilesDirsS) r = (DirsS, FilesS, FilesDirsS) choice = Intersection(f, d, r) return choice(path) Poor Yorick gp@pooryorick.com From siddharth178@hotmail.com Thu Feb 13 07:21:03 2003 From: siddharth178@hotmail.com (siddharth karandikar) Date: Thu Feb 13 07:21:03 2003 Subject: [Tutor] basic Qs Message-ID: hello, i am new to the world of Python, so i would like to ask some basic questions ?? which books OR docs to refere ?? ( i am not new to programming but new to Python ) which editor / IDE is best for Python ?? i would also like to know the performance comparison between following - shell scripts - perl - PYTHON in terms of memory requirement, speed etc. waiting for reply ... :) _________________________________________________________________ The new MSN 8: smart spam protection and 2 months FREE* http://join.msn.com/?page=features/junkmail From erikprice@mac.com Thu Feb 13 07:48:01 2003 From: erikprice@mac.com (Erik Price) Date: Thu Feb 13 07:48:01 2003 Subject: [Tutor] Decision matrix In-Reply-To: <3E4B57B2.8060607@pooryorick.com> Message-ID: <34EB0560-3F53-11D7-BADE-00039351FE6A@mac.com> On Thursday, February 13, 2003, at 03:30 AM, Poor Yorick wrote: > Two problems with using a dictionary: > > 1. I would like the flags to be accepted in any order. > 2. If I come up with other flags in the future, I would like to deal > with them in the most simple possible manner. Adding an exponentially > larger number of permutations as dictionary keys doesn't seem like a > good method. Hey Yorick, I was thinking that this is what you originally meant in your first post: that calling a combination of flags will call that combination of functions. If I am wrong, stop me right here because the rest of this email assumes that this is what you meant. The thing is, your example you posted to the tutor the other day seemed to suggest otherwise. In your sample, you were using a combination of the flags to call a specific function. In other words, if flag A was for func1, flag B for func2, and flag C for func3, you were saying that flag ABC should call func4, instead of calling each of func1, func2, and func3. Am I correct? I guess I'm having a hard time nailing down exactly what you want. If I am correct, though, and you are saying that you *do* want to call the combination of functions indicated by the passed-in flags (and not an entirely different function), then I have an idea: |>>> def func1(): |... return "func1 called" |... |>>> def func2(): |... return "func2 called" |... |>>> def func3(): |... return "func3 called" |... |>>> funclist = { |... "a":func1, |... "b":func2, |... "c":func3 |... } |>>> |>>> user_input = "acb" |>>> |>>> for flag in user_input: |... print "Now calling %s: '%s'" % (flag, funclist[flag]()) |... |Now calling a: 'func1 called' |Now calling c: 'func3 called' |Now calling b: 'func2 called' |>>> Note that it even preserves the order of the flags in the user_input string! Essentially, since a string can be handled as a list of characters[1], you can just parse the string to extract the flags and then call the appropriate function in the dictionary based on the character in your string. In fact, it would probably be a lot better to write a function ("parse_flags") to do this for you. Even if the flags were more than one character long (i.e., "help", "run", "debug"), you could probably write the function to examine the user input to pick out the words, and call the appropriate function in the dictionary using the word as the key. This works for you in two ways: 1) You don't have to come up with every possible combination of flags and define a new function which calls the other functions. If I am not mistaken, that is what you were initially suggesting to do. This keeps your dictionary very straightforward, and it doesn't grow exponentially as you had feared 2) You use the appropriate data structure for the job -- a dictionary. Really, a flag is nothing more than a "key" to some other value, whether it be a function or a string or a number or whatever. When you have keys in a group, you should probably be using a dictionary at some level. Of course, if I've been totally mistaken about what you wanted to do, then I apologize and you can disregard this idea. Erik [1] Is a string really a list of characters, or does it just allow you to treat it as one? Anyone know? > > The solution I've been thinking of today is to code a list of possible > functions for each flag and then find the intersection of the lists > indicated by the flags passed into the function. Here is a pseudocode > example: > > def fList(path, mode): > '''return a list of files, folders, or both, optionally including > subdirectories''' > #flag tuples > f = (Files, FilesS, FilesDirs, FilesDirsS) > d = (Dirs, DirsS, FilesDirs, FilesDirsS) > r = (DirsS, FilesS, FilesDirsS) > choice = Intersection(f, d, r) > return choice(path) > > > Poor Yorick > gp@pooryorick.com > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Erik Price email: erikprice@mac.com jabber: erikprice@jabber.org From erikprice@mac.com Thu Feb 13 07:52:03 2003 From: erikprice@mac.com (Erik Price) Date: Thu Feb 13 07:52:03 2003 Subject: [Tutor] basic Qs In-Reply-To: Message-ID: On Thursday, February 13, 2003, at 07:20 AM, siddharth karandikar wrote: > i am new to the world of Python, so i would like to ask some basic > questions ?? > > which books OR docs to refere ?? > ( i am not new to programming but new to Python ) If you already know how to program, perhaps you just need a quick tutorial and a language reference? I think "Python Essential Reference" by David Beazley (sp?) is a decent book, but I don't have my copy on me (it's at work). > which editor / IDE is best for Python ?? I use BBEdit on MacOS X at home and jEdit on Windows at work. > i would also like to know the performance comparison between following > - shell scripts > - perl > - PYTHON "It all depends." I've been reading an interesting interview with the creator of Python lately, it is at http://www.artima.com/intv/strongweak.html Note that it is split into several parts. Erik -- Erik Price email: erikprice@mac.com jabber: erikprice@jabber.org From chimera4@fastmail.fm Thu Feb 13 08:37:06 2003 From: chimera4@fastmail.fm (william) Date: Thu Feb 13 08:37:06 2003 Subject: [Tutor] What is the use of voidresp()? Message-ID: <20030213133430.93754438A2@server2.fastmail.fm> Hi, I am currently trying to do an app that accesses ftp servers and downloads parts of a file. I have a function that does basically what ftplib.retrbinary() does, but it breaks the connection when the required segment has been downloaded. I am basing my function on retrbinary code, but I am puzzled as to what voidresp() does at the end of the retrbinary function. From what I can gather, it merely checks server response. But why do we need to do that at the end of the connection? Anyway, I found out an exception will be raised, because the server responded with error 451 which is 'Transfer aborted. Broken pipe' Which is not an error for me because I wanted to abort the transfer. So should I just leave out the voidresp() check, or should I just use a try-except block to handle the exception and check whether its 451, and if not, reraise the exception? By the way, are there any other conditions which might lead to error 451 that I should be concerned with? Thanks in advance. -- http://fastmail.fm - Choose from over 50 domains or use your own From ramrom@earthling.net Thu Feb 13 10:16:01 2003 From: ramrom@earthling.net (Bob Gailer) Date: Thu Feb 13 10:16:01 2003 Subject: [Tutor] Decision matrix In-Reply-To: <3E4B57B2.8060607@pooryorick.com> References: <7497DCA1C240C042B28F6657ADFD8E0901F850C3@i2km11-ukbr.domain1.systemhost.net> Message-ID: <5.2.0.9.0.20030213080021.025063b8@66.28.54.253> --=======2A0C1575======= Content-Type: text/plain; x-avg-checked=avg-ok-60876147; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit Let's step back and look at the functionality desired: if r get subdirectories if f process files if d process directories Sounds like 2 functions, one for files, one for directories, and another to expand the subdirectories, each returning a list. How about: def fList(path, mode): if 'r' in mode: path = GetSubDirectories(path) if 'f' in mode: files = Files(path) if 'd' in mode: directories = Dirs(path) if the results of doing both Files and Dirs needs to be presented in some order other than all files followed by all directories, arrange the 2 lists in the desired order. At 01:30 AM 2/13/2003 -0700, Poor Yorick wrote: >1. I would like the flags to be accepted in any order. >2. If I come up with other flags in the future, I would like to deal >with them in the most simple possible manner. Adding an exponentially >larger number of permutations as dictionary keys doesn't seem like a >good method. > >The solution I've been thinking of today is to code a list of possible >functions for each flag and then find the intersection of the lists >indicated by the flags passed into the function. Here is a pseudocode >example: > >def fList(path, mode): > '''return a list of files, folders, or both, optionally including >subdirectories''' > #flag tuples > f = (Files, FilesS, FilesDirs, FilesDirsS) > d = (Dirs, DirsS, FilesDirs, FilesDirsS) > r = (DirsS, FilesS, FilesDirsS) > choice = Intersection(f, d, r) > return choice(path) Bob Gailer mailto:ramrom@earthling.net 303 442 2625 --=======2A0C1575======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-60876147 Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.445 / Virus Database: 250 - Release Date: 1/21/2003 --=======2A0C1575=======-- From magnus@thinkware.se Thu Feb 13 11:01:03 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Thu Feb 13 11:01:03 2003 Subject: [Tutor] checksum of dictionary In-Reply-To: <20030213133706.16409.63291.Mailman@mail.python.org> Message-ID: <5.1.0.14.0.20030213165120.02cdada0@www.thinkware.se> At Wed, 12 Feb 2003 09:29:56 -0800, Drew Perttula wrote in response to: > > I have a time-consuming function that operates on a large dictionary. > Before > > I call this function, I'd like to confirm that the dictionary has changed > > since the last time I called the function. > > To check for a change, I am thinking of calculating a checksum on the > > dictionary. > >Nowadays you can subclass the dictionary to make one that notices any >changes. If you're purely concerned about setitem and delitem calls, you >could just override those. If you want to catch update(), etc, you might >like http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/117236, which >is a dict interface defined in terms of getitem/setitem/delitem/keys. It's >great for constructing custom dict-like objects that use custom code >for all 20-or-so of the standard dict methods. But notice that no such fix will see changes in mutable data in the dictionary. >>> class D(dict): ... def __setitem__(self, k, v): ... print "New key %s and value %s" % (k, v) ... dict.__setitem__(self, k, v) ... >>> d = D() >>> d[1] = 1 New key 1 and value 1 >>> d[1] = [] New key 1 and value [] >>> d[1].append(1) # No dict change >>> d[1].append(2) >>> d {1: [1, 2]} >>> d[1].append(2) >>> d[1].append(2) >>> d {1: [1, 2, 2, 2]} -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From eprice@ptc.com Thu Feb 13 11:16:09 2003 From: eprice@ptc.com (Erik Price) Date: Thu Feb 13 11:16:09 2003 Subject: [Tutor] checksum of dictionary In-Reply-To: <5.1.0.14.0.20030213165120.02cdada0@www.thinkware.se> References: <5.1.0.14.0.20030213165120.02cdada0@www.thinkware.se> Message-ID: <3E4BC3B9.3060609@ptc.com> Magnus Lycka wrote: >> Nowadays you can subclass the dictionary to make one that notices any >> changes. If you're purely concerned about setitem and delitem calls, you >> could just override those. If you want to catch update(), etc, you might >> like http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/117236, >> which >> is a dict interface defined in terms of getitem/setitem/delitem/keys. >> It's >> great for constructing custom dict-like objects that use custom code >> for all 20-or-so of the standard dict methods. > > > But notice that no such fix will see changes in mutable data in the > dictionary. I didn't even think of this myself, though I was thinking that rather than subclass dict, it might be better to create a custom class that contains its own instance of a dictionary, and instead of directly accessing the dictionary, the class provides set and get methods for setting and getting the data. Of course, within these methods is the logic for testing whether or not the dict has been modified (perhaps by using an enumeration or boolean flag). Drawbacks, however: 1) You can't use convenient dictionary syntax, you have to use the specified accessor/mutator methods. (Probably not that big a deal.) 2) I'm not sure of how this works in Python, but my guess is that if you have some code that wants an object of type "dict", then this new object won't do the trick, since it composes a dict but does not inherit from one. Is this in fact how Python works, anybody? Since it's dynamically typed, I'm not sure how much type really matters anyway, but in library code it might be something to consider. In Java there would probably be some interface that the new class could implement so that it can be considered the same type as the dict, yet without actually having to inherit from dict, but that is Java and this is Python, and perhaps types just aren't as significant. I'm trying to be a more knowledgeable Python programmer so if someone has a pointer to more information on the significance of types in Python... :) Erik From eprice@ptc.com Thu Feb 13 11:47:05 2003 From: eprice@ptc.com (Erik Price) Date: Thu Feb 13 11:47:05 2003 Subject: Interfaces in Python (was: [Tutor] checksum of dictionary) In-Reply-To: <3E4BC3B9.3060609@ptc.com> References: <5.1.0.14.0.20030213165120.02cdada0@www.thinkware.se> <3E4BC3B9.3060609@ptc.com> Message-ID: <3E4BCBBF.2030400@ptc.com> Erik Price wrote: > Is this in fact how Python works, anybody? Since it's dynamically > typed, I'm not sure how much type really matters anyway, but in library > code it might be something to consider. > > In Java there would probably be some interface that the new class could > implement so that it can be considered the same type as the dict, yet > without actually having to inherit from dict, but that is Java and this > is Python, and perhaps types just aren't as significant. I'm trying to > be a more knowledgeable Python programmer so if someone has a pointer to > more information on the significance of types in Python... :) Looks like I just found one: http://www.artima.com/intv/pycontract.html Van Rossum seems to suggest that there are plenty of problems that can emerge at runtime with a strongly typed language, such as when an object is of the appropriate type but does not behave in line with the intent of the method it is being passed to. That in this situation, the only thing that will help you is the docs, which is why documentation is so crucial to any object. So, the documentation is actually a better advisor to the behavior of an object than any protocol or interface could be (in spite of the fact that protocols and interfaces are very important to languages like Objective-C or Java). I take it to mean that in Python, concerning oneself with types is just not an issue. If the object does what you want, then use it. So then is it useless to write code like this: # the foo method expects a bar object as its argument def foo(baz): if not instanceof(bar, baz): raise Exception Or is that something that people who are concerned with robust/secure code do in fact do? I suppose I should spend more time reading the source code of widely-distributed Python software to see how the "pros" do it. To be honest, in the published interview, Van Rossum doesn't provide a very strong argument against strongly-typed languages with well-defined interfaces, so I was wondering if anyone has any other tips on this topic? Thanks, Erik From jeff@ccvcorp.com Thu Feb 13 12:51:49 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Thu Feb 13 12:51:49 2003 Subject: [Tutor] Decision matrix Message-ID: <3E4BDA45.1080404@ccvcorp.com> Whoops, I'd intended to reply to the list as well, and only sent this to Poor Yorick. --Jeff S. -------- Original Message -------- Subject: Re: [Tutor] Decision matrix Date: Thu, 13 Feb 2003 09:46:08 -0800 From: Jeff Shannon To: Poor Yorick References: <7497DCA1C240C042B28F6657ADFD8E0901F850C3@i2km11-ukbr.domain1.systemhost.net> <3E4B57B2.8060607@pooryorick.com> Poor Yorick wrote: > alan.gauld@bt.com wrote: > > >Sounds like the definition of a dictionary to me... > > > Two problems with using a dictionary: > > 1. I would like the flags to be accepted in any order. > 2. If I come up with other flags in the future, I would like to deal > with them in the most simple possible manner. Adding an exponentially > larger number of permutations as dictionary keys doesn't seem like a > good method. If you want each unique set of flags to call a single (probably unique) function, regardless of the order of those flags, you can always sort your flags before searching the dictionary. This avoids the permutation explosion, and it's probably a lot simpler than your proposed Intersection() function. flags = raw_input() lflags = list(flags) lflags.sort() flags = ''.join(lflags) result = Functions[flags]() In order to find the intersection of a set of lists, you'll have to traverse each list once for each item in the first list, which (if you have a large number of flags) can grow to be a *lot* of list traversal. Dictionary searching is much faster than list traversal, and is done in constant time regardless of the size of the dict (where list traversal is proportional to the size of the list). Another possible issue with your Intersection() idea -- how are you intending to verify that a given set of flags always resolves to a *single* function? With only a few flags, you can eyeball and match up, but when you've got a dozen flags, each of which has half a dozen potential functions, it'll become almost impossible to ensure that no group of flags will resolve to more than one function -- especially if someone later needs to modify the list of flags. This will be a maintenance nightmare. A dict, on the other hand, will make it very easy to see what function will be called by a given combination of flags, and there's no worries about accidentally selecting more than one function. Almost any time you're looking to select one item out of a set of items based on some arbitrary parameter, a dictionary is the way to go. The only trick is figuring out what the most efficient key scheme will be... Jeff Shannon Technician/Programmer Credit International From jeff@ccvcorp.com Thu Feb 13 13:04:02 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Thu Feb 13 13:04:02 2003 Subject: [Tutor] Decision matrix References: <34EB0560-3F53-11D7-BADE-00039351FE6A@mac.com> Message-ID: <3E4BDD4C.2050508@ccvcorp.com> Erik Price wrote: > > [1] Is a string really a list of characters, or does it just allow you > to treat it as one? Anyone know? Not quite -- a string is a *sequence* of characters. Lists and tuples are also sequences. There's similarities, but also differences. For instance, any sequence can be used in a for loop. However, lists are the only (built-in) sequence that can be sorted. It is pretty easy to convert between these sequences, however. >>> mystring = "eggsandspam" >>> mylist = list(mystring) >>> mylist ['e', 'g', 'g', 's', 'a', 'n', 'd', 's', 'p', 'a', 'm'] >>> mytuple = tuple(mystring) >>> mytuple ('e', 'g', 'g', 's', 'a', 'n', 'd', 's', 'p', 'a', 'm') >>> mytuple = tuple(mylist) >>> mytuple ('e', 'g', 'g', 's', 'a', 'n', 'd', 's', 'p', 'a', 'm') >>> myotherstring = ''.join(mytuple) >>> myotherstring 'eggsandspam' >>> myotherotherstring = ''.join(mylist) >>> myotherotherstring 'eggsandspam' >>> Converting a (non-string) sequence to a string is a little bit different from converting to a list or tuple, but the principle is still there. You might ask why you can't just use the string constructor function, str(), to convert to a string, in the same way that you use the list() and tuple() constructors. Well, the answer is that you *can*, but the results may not be quite what you want: >>> str(mylist) "['e', 'g', 'g', 's', 'a', 'n', 'd', 's', 'p', 'a', 'm']" >>> It creates a string representation of the list, rather than a string containing the elements of the list. The request "make a string out of this list" is somewhat ambiguous in this case, and Python has chosen to resolve that ambiguity in a practical way -- especially since the string.join() method would be desirable anyhow, and the list that you're asking to convert might not contain only characters. Jeff Shannon Technician/Programmer Credit International From eprice@ptc.com Thu Feb 13 13:26:07 2003 From: eprice@ptc.com (Erik Price) Date: Thu Feb 13 13:26:07 2003 Subject: [Tutor] Decision matrix In-Reply-To: <3E4BDD4C.2050508@ccvcorp.com> References: <34EB0560-3F53-11D7-BADE-00039351FE6A@mac.com> <3E4BDD4C.2050508@ccvcorp.com> Message-ID: <3E4BE161.3090207@ptc.com> Jeff Shannon wrote: > > > Erik Price wrote: > >> >> [1] Is a string really a list of characters, or does it just allow you >> to treat it as one? Anyone know? > > > > Not quite -- a string is a *sequence* of characters. Lists and tuples > are also sequences. There's similarities, but also differences. For > instance, any sequence can be used in a for loop. However, lists are > the only (built-in) sequence that can be sorted. It is pretty easy to > convert between these sequences, however. Oh, I didn't know that. Thanks for the clarification. Followup question: which sequence is used for strings? Or does it not matter. Erik From Deirdre Hackett" This is a multi-part message in MIME format. ------=_NextPart_000_00F5_01C2D38E.745C0680 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Can someone tell me the proper way to use the binascii module. I want to = convert binary to ascii. Any small example will do. Thanks=20 Deirdre ------=_NextPart_000_00F5_01C2D38E.745C0680 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
Can someone tell me the proper way to = use the=20 binascii module. I want to convert binary to ascii.
 
Any small example will do.
Thanks
Deirdre
 
------=_NextPart_000_00F5_01C2D38E.745C0680-- From jeff@ccvcorp.com Thu Feb 13 13:49:21 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Thu Feb 13 13:49:21 2003 Subject: [Tutor] Decision matrix References: <34EB0560-3F53-11D7-BADE-00039351FE6A@mac.com> <3E4BDD4C.2050508@ccvcorp.com> <3E4BE161.3090207@ptc.com> Message-ID: <3E4BE852.7090807@ccvcorp.com> Erik Price wrote: > Jeff Shannon wrote: > >> Not quite -- a string is a *sequence* of characters. Lists and >> tuples are also sequences. There's similarities, but also differences. > > > Oh, I didn't know that. Thanks for the clarification. Followup > question: which sequence is used for strings? Or does it not matter. The string sequence is used for strings. ;) Strings are a sequence all on their own, which is why you can do things like: >>> for char in "I am a string!": ... print char, ord(char) ... I 73 32 a 97 m 109 32 a 97 32 s 115 t 116 r 114 i 105 n 110 g 103 ! 33 >>> In any situation that requires a sequence, you can use a string. It's only situations that require the specific features of a different type of sequence (like, say, the ability to sort, which can only be done on lists) that you need to convert from one to the other. Jeff Shannon Technician/Programmer Credit International From eprice@ptc.com Thu Feb 13 13:54:18 2003 From: eprice@ptc.com (Erik Price) Date: Thu Feb 13 13:54:18 2003 Subject: [Tutor] Decision matrix In-Reply-To: <3E4BE852.7090807@ccvcorp.com> References: <34EB0560-3F53-11D7-BADE-00039351FE6A@mac.com> <3E4BDD4C.2050508@ccvcorp.com> <3E4BE161.3090207@ptc.com> <3E4BE852.7090807@ccvcorp.com> Message-ID: <3E4BE966.4070901@ptc.com> Jeff Shannon wrote: > The string sequence is used for strings. ;) Strings are a sequence all > on their own, which is why you can do things like: > > >>> for char in "I am a string!": > ... print char, ord(char) Oh. So then, it's similar to an interface or protocol? As in, you can perform X with a sequence, and of course the implementation of the sequence will do the work of figuring out how to handle the situation? (I started a concurrent thread on this very topic earlier today.) Erik From op73418@mail.telepac.pt Thu Feb 13 14:01:01 2003 From: op73418@mail.telepac.pt (=?iso-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Thu Feb 13 14:01:01 2003 Subject: [Tutor] checksum of dictionary References: <5.1.0.14.0.20030213165120.02cdada0@www.thinkware.se> <3E4BC3B9.3060609@ptc.com> Message-ID: <002201c2d393$1c54d4d0$05100dd5@violante> ----- Original Message ----- From: "Erik Price" To: "Magnus Lycka" Cc: Sent: Thursday, February 13, 2003 4:11 PM Subject: Re: [Tutor] checksum of dictionary > > > Magnus Lycka wrote: > > >> Nowadays you can subclass the dictionary to make one that notices any > >> changes. If you're purely concerned about setitem and delitem calls, you > >> could just override those. If you want to catch update(), etc, you might > >> like http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/117236, > >> which > >> is a dict interface defined in terms of getitem/setitem/delitem/keys. > >> It's > >> great for constructing custom dict-like objects that use custom code > >> for all 20-or-so of the standard dict methods. > > > > > > But notice that no such fix will see changes in mutable data in the > > dictionary. > > I didn't even think of this myself, though I was thinking that rather > than subclass dict, it might be better to create a custom class that > contains its own instance of a dictionary, and instead of directly > accessing the dictionary, the class provides set and get methods for > setting and getting the data. Of course, within these methods is the > logic for testing whether or not the dict has been modified (perhaps by > using an enumeration or boolean flag). > > Drawbacks, however: > > 1) You can't use convenient dictionary syntax, you have to use the > specified accessor/mutator methods. (Probably not that big a deal.) > You can. Check the magic __getitem__, __setitem__, __delitem__ methods. > 2) I'm not sure of how this works in Python, but my guess is that if you > have some code that wants an object of type "dict", then this new object > won't do the trick, since it composes a dict but does not inherit from one. > It depends. If the code is pythonically written then it just expects an onject with a dict-like interface/protocol/whatever you wanna call it (e.g. __getitem__, etc.). If the code does type checking (isinstance, etc.) then well, it does not work. But in all honesty, how many times do you need a *real* dictionary intead of something that just acts like one? Very few indeed. Check the cookbook, either the book or online, on Easier-to-ask-forgiveness-than-permission. It is a very pythonic way to do interface-checking. You check that the object passed has the needed attributes, e.g. def bogusfunction(obj): #Are you sufficiently dict-like? try: obj.__getitem__ except AttributeError: raise TypeError("Hey buster, I can't work with you!") #Proceed with code. You can get more accurate checkings (checking signatures fir examples) using the inspect module. > Is this in fact how Python works, anybody? Since it's dynamically > typed, I'm not sure how much type really matters anyway, but in library > code it might be something to consider. > > In Java there would probably be some interface that the new class could > implement so that it can be considered the same type as the dict, yet > without actually having to inherit from dict, but that is Java and this > is Python, and perhaps types just aren't as significant. I'm trying to > be a more knowledgeable Python programmer so if someone has a pointer to > more information on the significance of types in Python... :) > > > Erik Look above. With my best regards, G. Rodrigues From op73418@mail.telepac.pt Thu Feb 13 14:03:14 2003 From: op73418@mail.telepac.pt (=?iso-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Thu Feb 13 14:03:14 2003 Subject: Interfaces in Python (was: [Tutor] checksum of dictionary) References: <5.1.0.14.0.20030213165120.02cdada0@www.thinkware.se> <3E4BC3B9.3060609@ptc.com> <3E4BCBBF.2030400@ptc.com> Message-ID: <002801c2d393$504f4220$05100dd5@violante> ----- Original Message ----- From: "Erik Price" To: Sent: Thursday, February 13, 2003 4:45 PM Subject: Interfaces in Python (was: [Tutor] checksum of dictionary) > > > Erik Price wrote: [snip] > > > Or is that something that people who are concerned with robust/secure > code do in fact do? I suppose I should spend more time reading the > source code of widely-distributed Python software to see how the "pros" > do it. > > To be honest, in the published interview, Van Rossum doesn't provide a > very strong argument against strongly-typed languages with well-defined > interfaces, so I was wondering if anyone has any other tips on this topic? > See my reply to your other post. > > > Thanks, > > Erik > All the best, G. Rodrigues From eprice@ptc.com Thu Feb 13 14:19:06 2003 From: eprice@ptc.com (Erik Price) Date: Thu Feb 13 14:19:06 2003 Subject: [Tutor] checksum of dictionary In-Reply-To: <002201c2d393$1c54d4d0$05100dd5@violante> References: <5.1.0.14.0.20030213165120.02cdada0@www.thinkware.se> <3E4BC3B9.3060609@ptc.com> <002201c2d393$1c54d4d0$05100dd5@violante> Message-ID: <3E4BEE90.8010101@ptc.com> Gon=E7alo Rodrigues wrote: > It depends. If the code is pythonically written then it just expects an > onject with a dict-like interface/protocol/whatever you wanna call it (= e.g. > __getitem__, etc.). [...] > If the code does type checking (isinstance, etc.) then well, it does no= t > work. But in all honesty, how many times do you need a *real* dictionar= y > intead of something that just acts like one? Very few indeed. >=20 > Check the cookbook, either the book or online, on > Easier-to-ask-forgiveness-than-permission. It is a very pythonic way to= do > interface-checking. You check that the object passed has the needed > attributes, e.g. [I didn't know that the cookbook was online. Thanks, I will hunt it down= .] > def bogusfunction(obj): > #Are you sufficiently dict-like? > try: > obj.__getitem__ > except AttributeError: > raise TypeError("Hey buster, I can't work with you!") > #Proceed with code. >=20 > You can get more accurate checkings (checking signatures fir examples) = using > the inspect module. Ah. It becomes so much clearer to me now. This is what people mean=20 when they say that it is okay in Python to throw exceptions even in=20 non-exceptional circumstances. So this is the Pythonic approach? I much like it. It lets you use any=20 object as long as it implements the necessary method. Or rather, it=20 lets you use any object as long as it doesn't raise a TypeError. Thanks Gon=E7alo. That helps me understand a lot. Erik From op73418@mail.telepac.pt Thu Feb 13 15:45:02 2003 From: op73418@mail.telepac.pt (=?iso-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Thu Feb 13 15:45:02 2003 Subject: [Tutor] checksum of dictionary References: <5.1.0.14.0.20030213165120.02cdada0@www.thinkware.se> <3E4BC3B9.3060609@ptc.com> <002201c2d393$1c54d4d0$05100dd5@violante> <3E4BEE90.8010101@ptc.com> Message-ID: <000501c2d3a1$aed930e0$05100dd5@violante> ----- Original Message ----- From: "Erik Price" To: "Gonçalo Rodrigues" Cc: Sent: Thursday, February 13, 2003 7:14 PM Subject: Re: [Tutor] checksum of dictionary [snip] > > So this is the Pythonic approach? I much like it. It lets you use any > object as long as it implements the necessary method. Or rather, it > lets you use any object as long as it doesn't raise a TypeError. > The important thing is that the code raises an exception. It's a way of saying: I can't work with you. I chose to raise TypeError because according to the docs: TypeError: Raised when a built-in operation or function is applied to an object of inappropriate type. The associated value is a string giving details about the type mismatch. But notice that even this type of initial checking may not be needed. For example (A) def bogusfunction(obj): #This raises an exception if obj has no __getitem__. bogusvar = obj[0] The advantage of doing an intial check like: (B) > def bogusfunction(obj): > #Are you sufficiently dict-like? > try: > obj.__getitem__ > except AttributeError: > raise TypeError("Hey buster, I can't work with you!") > #Proceed with code. is that of you have a lot of operations, in the (A) case some could succed and some fail, partially altering the object and possibly leaving it in an "inconsistent state". With (B) you make some initial checks and while things can still go wrong it much less likely so. An this leads me to the one point that I forgot to mention: to produce robust code you have to test it. Check the unittest module. All the best, G. Rodrigues From SWidney@ci.las-vegas.nv.us Thu Feb 13 15:51:04 2003 From: SWidney@ci.las-vegas.nv.us (Scott Widney) Date: Thu Feb 13 15:51:04 2003 Subject: [Tutor] checksum of dictionary Message-ID: <0E5508EBA1620743B409A2B8365DE16FDC8382@sovereign.ci.las-vegas.nv.us> > [I didn't know that the cookbook was online. > Thanks, I will hunt it down.] > Let me save you the safari; the cookbook is maintained by David Ascher at ActiveState. Here's the link: http://aspn.activestate.com/ASPN/Cookbook/Python Enjoy! Scott From dyoo@hkn.eecs.berkeley.edu Thu Feb 13 16:57:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Feb 13 16:57:02 2003 Subject: [Tutor] basic Qs [tutorial / text editors / performance characteristics] In-Reply-To: Message-ID: On Thu, 13 Feb 2003, Erik Price wrote: > On Thursday, February 13, 2003, at 07:20 AM, siddharth karandikar > wrote: > > > i am new to the world of Python, so i would like to ask some basic > > questions ?? > > > > which books OR docs to refere ?? > > ( i am not new to programming but new to Python ) > > If you already know how to program, perhaps you just need a quick > tutorial and a language reference? Hi Siddharth, You may want to try the official Python tutorial at: http://python.org/doc/tut/ Since you already have programming experience, I don't have so many qualms recommending it for you. If you have questions, please feel free to bring them up on the Tutor list; we're here to help each other learn Python. By the way, what kind of programming background do you have already? We may be able to point you toward more appropriate material that takes better advantage of your experience. > I think "Python Essential Reference" by David Beazley (sp?) is a decent > book, but I don't have my copy on me (it's at work). > > > which editor / IDE is best for Python ?? > > I use BBEdit on MacOS X at home and jEdit on Windows at work. There's a list of text editors that integrate themselves well with Python on the PythonWiki: http://www.python.org/cgi-bin/moinmoin/PythonEditors I personally use Emacs with the 'python-mode' extensions, and it fits comfortably for me. I've also heard very good things about Vim's integration with Python. Let's defuse the holy war fast: A good bet is to use the text editor that you're most comfortable with already. (Unless that's Microsoft Notepad; if so, switch to something else, for your own sake. *grin*). > > i would also like to know the performance comparison between following > > - shell scripts > > - perl > > - PYTHON > > "It all depends." Siddharth, there's a page that's been partitioned off the Documentation page on Python.org that provides some comparisons between Python and other languages: http://python.org/doc/Comparisons.html But take these with a grain of salt: there's a good reason why they're linked up from Python.org. *grin* There's another site that might interest you: Doug Bagley has taken an empirical appraoch, and written a pretty comprehensive test suite of programs for many languages: http://www.bagley.org/~doug/shootout/ Please feel free to ask more questions about Python. Good luck! From dyoo@hkn.eecs.berkeley.edu Thu Feb 13 16:59:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Feb 13 16:59:02 2003 Subject: [Tutor] please remove me [you can unsubscribe yourself] In-Reply-To: Message-ID: On Wed, 12 Feb 2003, Frank Holmes wrote: > > Please remove me from the python mailing list Hi Frank, I forgot if I responded to you already; please forgive me for being late about this. Frank, you can unsubscribe yourself by visiting that page you used to first subscribe to Tutor. Here's a link to that page: http://mail.python.org/mailman/listinfo/tutor There's a form below that'll let you edit your mailing list options, and from there, you should be able to unsubscribe. If you run into any problems while unsubscribing, please feel free to directly contact the mailing list administrators on the email address "tutor-admin@python.org". From pwallace@rightnow.com Thu Feb 13 19:34:02 2003 From: pwallace@rightnow.com (Wallace, Pippin) Date: Thu Feb 13 19:34:02 2003 Subject: [Tutor] Question about IDE's like PythonWin Message-ID: This message is in MIME format. Since your mail reader does not understand this format, some or all of this message may not be legible. ------_=_NextPart_001_01C2D3C0.88FF00B0 Content-Type: text/plain; charset="iso-8859-1" Hello Grand list, I am just starting out with programming and am using Linux vim and PythonWin to work through examples in Alan's book. What I really find helpful is when I type a function in PythonWin a pop-up window appears with a drop-down list of function options to choose from. For example if I type . then a window appears with append, count, extend, index, insert, pop, etc in it to choose from and once an option is chosen and a pren is typed a usage display appears which details how to use the function. My question is are there IDE's that have this function for Linux? Regards, Ted ------_=_NextPart_001_01C2D3C0.88FF00B0 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Question about IDE's like PythonWin

Hello Grand list,

I am just starting out with = programming and am using Linux vim and PythonWin to work through = examples in Alan's book.  What I really find helpful is when I = type a function in PythonWin a pop-up window appears with a drop-down = list of function options to choose from.  For example if I type = <listname>. then a window appears with append, count, extend, = index, insert, pop, etc in it to choose from and once an option is = chosen and a pren is typed a usage display appears which details how to = use the function.

My question is are there IDE's that = have this function for Linux?

Regards,

Ted


------_=_NextPart_001_01C2D3C0.88FF00B0-- From jeff@ccvcorp.com Thu Feb 13 20:05:01 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Thu Feb 13 20:05:01 2003 Subject: [Tutor] Decision matrix References: <34EB0560-3F53-11D7-BADE-00039351FE6A@mac.com> <3E4BDD4C.2050508@ccvcorp.com> <3E4BE161.3090207@ptc.com> <3E4BE852.7090807@ccvcorp.com> <3E4BE966.4070901@ptc.com> Message-ID: <3E4C4079.9090008@ccvcorp.com> Erik Price wrote: > > Jeff Shannon wrote: > >> The string sequence is used for strings. ;) Strings are a sequence >> all on their own, which is why you can do things like: >> >> >>> for char in "I am a string!": >> ... print char, ord(char) > > > Oh. So then, it's similar to an interface or protocol? As in, you > can perform X with a sequence, and of course the implementation of the > sequence will do the work of figuring out how to handle the situation? > (I started a concurrent thread on this very topic earlier today.) Yes. Python has quite a number of informal protocols, and any object that supports certain actions is said to conform to that protocol. For instance, you'll find many references in the docs to "file-like objects" -- Python doesn't care whether it's *actually* a file object or not, as long as it has write(), read(), readlines() (and sometimes seek() and tell(), etc) methods. In fact, there's a library object (StringIO) that wraps a file-like interface around a normal (presumably long) string. There's also a sequence protocol, which involves responding appropriately to indexing, slicing, iteration, and the like. You can even write your own sequences -- just create a class that defines __getitem__(), __setitem__(), __len__(), etc. -- just as you can write your own file-like objects and your own dict-like objects. Jeff Shannon Technician/Programmer Credit International From GREENDAY31087@aol.com Thu Feb 13 22:17:02 2003 From: GREENDAY31087@aol.com (GREENDAY31087@aol.com) Date: Thu Feb 13 22:17:02 2003 Subject: [Tutor] ms notepad Message-ID: <73.2d726412.2b7db992@aol.com> --part1_73.2d726412.2b7db992_boundary Content-Type: text/plain; charset="US-ASCII" Content-Transfer-Encoding: 7bit I have heard that notepad is not a good text editor and I would like to know why. What are the disadvantages? What would be a better choice for me? What does that choice depend on? Thanks in advance! -Wayne --part1_73.2d726412.2b7db992_boundary Content-Type: text/html; charset="US-ASCII" Content-Transfer-Encoding: quoted-printable    I have heard that notepad is not a good t= ext editor and I would like to know why. What are the disadvantages? What wo= uld be a better choice for me? What does that choice depend on?

Thanks in advance!
-Wayne
--part1_73.2d726412.2b7db992_boundary-- From erikprice@mac.com Thu Feb 13 22:20:03 2003 From: erikprice@mac.com (Erik Price) Date: Thu Feb 13 22:20:03 2003 Subject: [Tutor] Decision matrix In-Reply-To: <3E4C4079.9090008@ccvcorp.com> Message-ID: <2BBA1979-3FCD-11D7-BADE-00039351FE6A@mac.com> On Thursday, February 13, 2003, at 08:03 PM, Jeff Shannon wrote: > Yes. Python has quite a number of informal protocols, and any object > that supports certain actions is said to conform to that protocol. > For instance, you'll find many references in the docs to "file-like > objects" -- Python doesn't care whether it's *actually* a file object > or not, as long as it has write(), read(), readlines() (and sometimes > seek() and tell(), etc) methods. In fact, there's a library object > (StringIO) that wraps a file-like interface around a normal > (presumably long) string. There's also a sequence protocol, which > involves responding appropriately to indexing, slicing, iteration, and > the like. You can even write your own sequences -- just create a > class that defines __getitem__(), __setitem__(), __len__(), etc. -- > just as you can write your own file-like objects and your own > dict-like objects. I see. So these are protocols that have come up via convention, i.e. there is no standard by which to implement the protocol? They have just come about from familiarity? Or is there somewhere in the StdLib that specifies how implementations of, say, file-like objects should behave. Erik -- Erik Price email: erikprice@mac.com jabber: erikprice@jabber.org From shalehperry@attbi.com Thu Feb 13 22:33:01 2003 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Thu Feb 13 22:33:01 2003 Subject: [Tutor] ms notepad In-Reply-To: <73.2d726412.2b7db992@aol.com> References: <73.2d726412.2b7db992@aol.com> Message-ID: <200302131932.10021.shalehperry@attbi.com> On Thursday 13 February 2003 19:16, GREENDAY31087@aol.com wrote: > I have heard that notepad is not a good text editor and I would like= to > know why. What are the disadvantages? What would be a better choice for= me? > What does that choice depend on? > > Thanks in advance! > -Wayne notepad is a perfectly fine text editor. It is a poor editor for a progr= ammer=20 though. A good one knows what language you are writing in and adapts=20 accordingly. Every programmer I know has one editor they prefer above any other so you= are=20 bound to get a different opinion from every person you ask. They key the= =20 editor should assist you in your task, not stand there idle (or get in th= e=20 way). Think of it this way. When you write a paper for school do you use notep= ad? =20 Or do you use a word processor with things like spell check, support for=20 layouts, etc? Why should coding be different? I spend most of my time w= hile=20 at work changing and writing code so anything I can do to optimize that t= ime=20 is worth it. From siddharth178@hotmail.com Thu Feb 13 22:41:02 2003 From: siddharth178@hotmail.com (siddharth) Date: Thu Feb 13 22:41:02 2003 Subject: [Tutor] basic Qs [tutorial / text editors / performance characteristics] References: Message-ID: thanks for such quick response :) i know Java in detail and currently i am working as 'software engineer' i do know other langs like c c++ etc. what will be good starting point for me ?? any suggestions ? i would also like to know whats the main adv. and disadv. of using lists and tuples ?? ( tuples are some what confusing me ) ----- Original Message ----- From: "Danny Yoo" To: "Erik Price" Cc: "siddharth karandikar" ; Sent: Friday, February 14, 2003 3-25 AM Subject: Re: [Tutor] basic Qs [tutorial / text editors / performance characteristics] > > > On Thu, 13 Feb 2003, Erik Price wrote: > > > On Thursday, February 13, 2003, at 07:20 AM, siddharth karandikar > > wrote: > > > > > i am new to the world of Python, so i would like to ask some basic > > > questions ?? > > > > > > which books OR docs to refere ?? > > > ( i am not new to programming but new to Python ) > > > > If you already know how to program, perhaps you just need a quick > > tutorial and a language reference? > > > Hi Siddharth, > > > You may want to try the official Python tutorial at: > > http://python.org/doc/tut/ > > Since you already have programming experience, I don't have so many qualms > recommending it for you. If you have questions, please feel free to bring > them up on the Tutor list; we're here to help each other learn Python. > > By the way, what kind of programming background do you have already? We > may be able to point you toward more appropriate material that takes > better advantage of your experience. > > > > > > I think "Python Essential Reference" by David Beazley (sp?) is a decent > > book, but I don't have my copy on me (it's at work). > > > > > which editor / IDE is best for Python ?? > > > > I use BBEdit on MacOS X at home and jEdit on Windows at work. > > There's a list of text editors that integrate themselves well with Python > on the PythonWiki: > > http://www.python.org/cgi-bin/moinmoin/PythonEditors > > I personally use Emacs with the 'python-mode' extensions, and it fits > comfortably for me. I've also heard very good things about Vim's > integration with Python. > > Let's defuse the holy war fast: A good bet is to use the text editor that > you're most comfortable with already. (Unless that's Microsoft Notepad; > if so, switch to something else, for your own sake. *grin*). > > > > > > > i would also like to know the performance comparison between following > > > - shell scripts > > > - perl > > > - PYTHON > > > > "It all depends." > > Siddharth, there's a page that's been partitioned off the Documentation > page on Python.org that provides some comparisons between Python and other > languages: > > http://python.org/doc/Comparisons.html > > But take these with a grain of salt: there's a good reason why they're > linked up from Python.org. *grin* There's another site that might > interest you: Doug Bagley has taken an empirical appraoch, and written a > pretty comprehensive test suite of programs for many languages: > > http://www.bagley.org/~doug/shootout/ > > > > Please feel free to ask more questions about Python. Good luck! > From phthenry@earthlink.net Thu Feb 13 22:49:03 2003 From: phthenry@earthlink.net (Paul Tremblay) Date: Thu Feb 13 22:49:03 2003 Subject: [Tutor] where to put data files Message-ID: <20030213224721.B4961@localhost.localdomain> I have a script that needs to read from a data file, and I want to know the best location for the data file. Right now, I have this line in my setup.py: data_files=[('data', ['char_set'])], This means that in a normal installation, the setup scipt will make a directory /usr/local/data, and put the char_set file there. The file consits of encoding schemes. Would it be better to put the data in /etc? Also, should I use a relative path? I guess if I use a relative path, then each time the script runs, it will have to check for the location of the data directoy: path = sys.path char_dir = "" found_char_dir =0 for dir in path: data_dir = os.join (dir, "data") if isdir(data_dir): char_dir = data_dir found_char_dir=1 last if not found_char_dir: print "no character data found. Scipt will not exit" sys.exit(1) ## code untested ! this is just to illustrate what I mean I'm looking for the most standard place for such a data file, a place that will work on different operating systems. Thanks Paul PS Thanks for the pointers and links in making a setup.py script. Python's documentatin was pretty decent, and after only 2 or 3 hours, I had a nice script written that worked perfectly. Nice. -- ************************ *Paul Tremblay * *phthenry@earthlink.net* ************************ From shalehperry@attbi.com Thu Feb 13 23:03:02 2003 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Thu Feb 13 23:03:02 2003 Subject: [Tutor] where to put data files In-Reply-To: <20030213224721.B4961@localhost.localdomain> References: <20030213224721.B4961@localhost.localdomain> Message-ID: <200302132001.43852.shalehperry@attbi.com> On Thursday 13 February 2003 19:47, Paul Tremblay wrote: > I have a script that needs to read from a data file, and I want to know > the best location for the data file. > > Right now, I have this line in my setup.py: > > data_files=3D[('data', ['char_set'])], > > This means that in a normal installation, the setup scipt will make a > directory /usr/local/data, and put the char_set file there. > > The file consits of encoding schemes. > > Would it be better to put the data in /etc? > according to the FHS (File Hierarchy Standards) used by Linux distributio= ns=20 data that is architecture neutral and usable by multiple installations=20 belongs in /usr/share// (or in your case=20 /usr/local/share/). /etc is for configuration data that you expect the sysadmin to want to=20 change/add/remove/whatever. > Also, should I use a relative path? I guess if I use a relative path, > then each time the script runs, it will have to check for the location > of the data directoy: > you should probably use a full path that is easy to change. So if a user= =20 wants to instll your program in say /opt/program/ they can. From phthenry@earthlink.net Fri Feb 14 01:07:00 2003 From: phthenry@earthlink.net (Paul Tremblay) Date: Fri Feb 14 01:07:00 2003 Subject: [Tutor] where to put data files In-Reply-To: <200302132001.43852.shalehperry@attbi.com> References: <20030213224721.B4961@localhost.localdomain> <200302132001.43852.shalehperry@attbi.com> Message-ID: <20030214010531.C4961@localhost.localdomain> On Thu, Feb 13, 2003 at 08:01:43PM -0800, Sean 'Shaleh' Perry wrote: > according to the FHS (File Hierarchy Standards) used by Linux distributions > data that is architecture neutral and usable by multiple installations > belongs in /usr/share// (or in your case > /usr/local/share/). > > /etc is for configuration data that you expect the sysadmin to want to > change/add/remove/whatever. I didn't know this. This is helpful. > > > Also, should I use a relative path? I guess if I use a relative path, > > then each time the script runs, it will have to check for the location > > of the data directoy: > > > > you should probably use a full path that is easy to change. So if a user > wants to instll your program in say /opt/program/ they can. But how do I do this? The line that will look for the character file will be in the actual script. When the user installs the modules, script, and data file, the installer will somewhow have to read the path and change a line in the main script. In other words, if the user chooses /opt/program, the script will be put in /opt/program/bin, the modules will be put in /opt/program/lib/python2.x/site-packages/rtf2xml/*, and the data file will be put in /opt/program/rtf_data/rtf_char_set. In one of the modules: read_obj = open(path_to_char_set) ## now read each line in and form a hash How do I insure that path will always find the actual charater file? Thanks Paul -- ************************ *Paul Tremblay * *phthenry@earthlink.net* ************************ From jjhegde@konark.ncst.ernet.in Fri Feb 14 02:12:02 2003 From: jjhegde@konark.ncst.ernet.in (Jayprasad J. Hegde) Date: Fri Feb 14 02:12:02 2003 Subject: [Tutor] how to write an algorithm for sequence In-Reply-To: <3E4B005E.9070105@nep.net> References: <3E4B005E.9070105@nep.net> Message-ID: <20030214070717.GA4770@ncst.ernet.in> On Wed, Feb 12, 2003 at 09:18:06PM -0500, reavey wrote: > I'm stumped. I made up this sequence and I can't figure out a method. > the sequence is 1,5,7,15,19,35, 43, 75... I don't know what python has to do with this question. Anyway, here is an analysis and a possible solution to the problem: If you look at the problem closely, there are two sequences interleaved to make one seemingly complicated sequence. You can make use of this observation for solving the problem. The given series: 1,5,7,15,19,35, 43, 75... series #1: 1 7 19 43... series #2: 5 15 35 75... The first series grows like this: x + (prevDiff * 2) where prevDiff's initial value is 6 and x is the previous term in this series The second series grows like this: x + (prevDiff * 2) --- (yes, the same formula again) Here, prevDiff's initial value is 10 and 'x' is the previous term in this series I'm including the code here. Hope it helps. I find that the sequence you have given is less by a couple of elements. Sometimes these missing elements prove crucial to identifying a pattern in a problem. Anyway, I am also writing the output for verification of the desired sequence. 1 5 7 15 19 35 43 75 91 155 187 315 379 635 763 1275 1531 2555 3067 5115 regards - JJH ######### the code ############# SEQUENCELENGTH = 20 prevDiff1 = 6 prevTerm1 = 1 prevDiff2 = 10 prevTerm2 = 5 print prevTerm1, prevTerm2, for i in range (SEQUENCELENGTH - 2): i = i + 1 if (i % 2 == 0): currTerm2 = prevTerm2 + prevDiff2 prevTerm2 = currTerm2 prevDiff2 = prevDiff2 * 2 print currTerm2, else: currTerm1 = prevTerm1 + prevDiff1 prevTerm1 = currTerm1 prevDiff1 = prevDiff1 * 2 print currTerm1, print -- BOFH excuse #362: Plasma conduit breach (defun JJHdetails () (format t "~&~A~&~A~&~A" "Jayprasad J Hegde, Staff Scientist, KBCS, NCST" "Gulmohar Cross Road 9, Juhu, Mumbai 400049." "tel: +91-22-26201606x373")) From jjhegde@konark.ncst.ernet.in Fri Feb 14 03:22:02 2003 From: jjhegde@konark.ncst.ernet.in (Jayprasad J. Hegde) Date: Fri Feb 14 03:22:02 2003 Subject: [Tutor] fibonacci In-Reply-To: <5.1.0.14.0.20030212193948.02d50b70@mail.milgromphoto.com> References: <5.1.0.14.0.20030212193948.02d50b70@mail.milgromphoto.com> Message-ID: <20030214081702.GA4885@ncst.ernet.in> On Wed, Feb 12, 2003 at 07:51:33PM +1100, Alfred Milgrom wrote: [ snip ] > > Just as an exercise, I was unable to create a one-line recursive fibonacci > generator, but the following works correctly for all values of n greater > than 2. > > def fib(n): > return (n<5)*(n-2) or fib(n-1) + fib(n-2) I would not recommend creating a second order (containing two recursive elements e.g. "fib (n - 1)" and "fib (n - 2)" ) recursive function like this. It would be best if you can find... 1. a recursive function with a single recursive element, or 2. sticking to an iterative variant. regards - JJH -- (defun JJHdetails () (format t "~&~A~&~A~&~A" "Jayprasad J Hegde, KBCS, NCST" "Gulmohar Cross Road 9, Juhu, Mumbai 400049." "tel: +91-22-26201606x373")) From glingl@aon.at Fri Feb 14 07:24:02 2003 From: glingl@aon.at (Gregor Lingl) Date: Fri Feb 14 07:24:02 2003 Subject: [Tutor] fibonacci References: <5.1.0.14.0.20030212193948.02d50b70@mail.milgromphoto.com> <20030214081702.GA4885@ncst.ernet.in> Message-ID: <3E4CDFF3.2070308@aon.at> Jayprasad J. Hegde schrieb: >On Wed, Feb 12, 2003 at 07:51:33PM +1100, Alfred Milgrom wrote: >[ snip ] > > >>Just as an exercise, I was unable to create a one-line recursive fibonacci >>generator, but the following works correctly for all values of n greater >>than 2. >> >>def fib(n): >> return (n<5)*(n-2) or fib(n-1) + fib(n-2) >> >> > >I would not recommend creating a second order (containing two recursive elements e.g. "fib (n - 1)" and "fib (n - 2)" ) recursive function like this. >It would be best if you can find... >1. a recursive function with a single recursive element, or >2. sticking to an iterative variant. > > Ok. Somtimes one has a lot of work to do and nevertheless wastes time for some questionable - if not useless - task. So I arrived at this: def fib1liner(n, f=[0,1]): return(n+1>len(f))and[(lambda x:f.append(f[-2]+f[-1]))(i)for i in range(n+1-len(f))]and 0 or f[n] I would not have posted it here if it had not a remarkable property ;-) it is about a factor 50 faster than the (also iterative) classic from the tutorial (as already posted in this thread) : def fib(n): a,b=0,1 for i in range(n): a,b=b,a+b return a from the turorial. This can be seen using: from time import clock def test(afib, n = 500): a = clock() for i in range(n): x = afib(i) b = clock() print b-a print x to measure the time for calculating the first 1000 fibonacci numbers (I use Python 2.2, which converts automtically to longints if needed): >>> test(fib) 3.64362016859 26863810024485359386146727202142923967616609318986952340123175997617981700247881689338369654483356564191827856161443356312976673642210350324634850410377680367334151172899169723197082763985615764450078474174626 >>> test(fib1liner) 0.0725899317958 26863810024485359386146727202142923967616609318986952340123175997617981700247881689338369654483356564191827856161443356312976673642210350324634850410377680367334151172899169723197082763985615764450078474174626 Isn't this nice? (If you don't have to care about use of memory on your machine ;-) ) Gregor P.S.: ... and look, with time fib1liner becomes even faster: >>> test(fib1liner) 0.0172815211761 26863810024485359386146727202142923967616609318986952340123175997617981700247881689338369654483356564191827856161443356312976673642210350324634850410377680367334151172899169723197082763985615764450078474174626 >>> From alan.gauld@bt.com Fri Feb 14 07:26:09 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Fri Feb 14 07:26:09 2003 Subject: [Tutor] basic Qs Message-ID: <7497DCA1C240C042B28F6657ADFD8E0901F850CB@i2km11-ukbr.domain1.systemhost.net> > which books OR docs to refere ?? > ( i am not new to programming but new to Python ) In that case try Beasley's Essential Python Reference or Mark Lutz Programming Python. If you are on Windows try Mark Hammonds Win32 Python book(O'Reilly) > which editor / IDE is best for Python ?? The one that works for you. I use IDLE sometimes and vim mostly. > i would also like to know the performance comparison between following > - shell scripts > - perl > - PYTHON Perl and Python will nearly always beat a shell script A fast Perl program translated line by line to Python will usually show Perl to be fastest. A fast Python program translated to Perl may show Python to be fastest. A basic problem implemented optimally in either language will be similar in performance in most cases (certainly within an order of magnitude, usually within a factor of 2). [ IMHO It's probably easier to convert bottlenecks in Python to C for real performance when necessary than it is in Perl. But with SWIG to help that's maybe not such a big issue... ] > in terms of memory requirement, About the same so far as I can tell. Alan g. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld/ From erikprice@mac.com Fri Feb 14 07:27:01 2003 From: erikprice@mac.com (Erik Price) Date: Fri Feb 14 07:27:01 2003 Subject: [Tutor] where to put data files In-Reply-To: <20030214010531.C4961@localhost.localdomain> Message-ID: <6341F082-4019-11D7-BADE-00039351FE6A@mac.com> On Friday, February 14, 2003, at 01:05 AM, Paul Tremblay wrote: > But how do I do this? The line that will look for the character file > will be in the actual script. When the user installs the modules, > script, and data file, the installer will somewhow have to read the > path > and change a line in the main script. > > In other words, if the user chooses /opt/program, the script will be > put > in /opt/program/bin, the modules will be put in > /opt/program/lib/python2.x/site-packages/rtf2xml/*, and the data file > will be put in /opt/program/rtf_data/rtf_char_set. > > In one of the modules: > > read_obj = open(path_to_char_set) > ## now read each line in and form a hash > > How do I insure that path will always find the actual charater file? Sometimes people distribute a "meta-script" with their programs which assists with the installation process. It is usually a very simple script called "configure" and the user can pass arguments like this: $ ./configure --target=/opt/program [followed by add'l args as necessary] What the configure script does is entirely dependent on how it was written, but often it will write the user's input to a properties file of some sort. This properties file is then consulted by the build tool (such as make or ant) to rewrite the constants representing paths and other configurable information, so that when the program is compiled, it "knows" where it is. In other words, the point of the configure script is to rewrite some of the source code to customize it for the user's environment. You could do something similar even though Python doesn't use a build tool, and in fact, perhaps someone already has. You can write a very simple "installer" script that accepts a few arguments to determine where the user wants to put the file, and then the installer can copy the files to the locations you specify in the script. The "installer" script can also re-write the file paths so that the script will work from wherever it is placed. Hint: this will be a lot easier to do if you keep the file paths and other information in a submodule file (say, one called "rtf2xml.constants"). I'm sure that there are other people with more experience distributing software on this list who can come up with some other ideas. Erik -- Erik Price email: erikprice@mac.com jabber: erikprice@jabber.org From op73418@mail.telepac.pt Fri Feb 14 07:28:01 2003 From: op73418@mail.telepac.pt (=?iso-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Fri Feb 14 07:28:01 2003 Subject: [Tutor] basic Qs [tutorial / text editors / performance characteristics] References: Message-ID: <003701c2d425$5ba120c0$19180dd5@violante> ----- Original Message ----- From: "siddharth" To: Sent: Friday, February 14, 2003 3:53 AM Subject: Re: [Tutor] basic Qs [tutorial / text editors / performance characteristics] > thanks for such quick response :) > > i know Java in detail and currently i am working as 'software engineer' > i do know other langs like c c++ etc. > > what will be good starting point for me ?? any suggestions ? > Just hack away at the tutorial that comes with Python. Since you already have experience, most likely you'll get on par with Python in no time. Do you have any specific needs? > i would also like to know whats the main adv. and disadv. of using lists and > tuples ?? ( tuples are some what confusing me ) > > tuples are like lists, except you can't mutate them. With a list you can do: >>> a = [1, 2, 3] >>> a.append(4) >>> print a [1, 2, 3, 4] >>> a[0] = "Changed!" >>> print a ['Changed!', 2, 3, 4] With a tuple, once it is created you can't mutate, e.g. if you try to do the same >>> b = (1, 2, []) >>> b.append(4) Traceback (most recent call last): File "", line 1, in ? AttributeError: 'tuple' object has no attribute 'append' >>> b[0] = "Changed!" Traceback (most recent call last): File "", line 1, in ? TypeError: object doesn't support item assignment And to give you some food for thought here goes: >>> b[2].append("Changed!") >>> print b (1, 2, ['Changed!']) >>> Of course, we have not mutated the tuple *itself*. We have mutated the last object it referenced, the tuple stayed the same, e.g. has the same number of elements, the elements it has are the same (in the sense of identity, not equality), etc. Hope it helps, G. Rodrigues From alan.gauld@bt.com Fri Feb 14 07:50:02 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Fri Feb 14 07:50:02 2003 Subject: Interfaces in Python (was: [Tutor] checksum of dictionary) Message-ID: <7497DCA1C240C042B28F6657ADFD8E0901F850CC@i2km11-ukbr.domain1.systemhost.net> > So then is it useless to write code like this: > > # the foo method expects a bar object as its argument > def foo(baz): > if not instanceof(bar, baz): > raise Exception > Absolutely it would be more sensible to write something like: # the foo method expects an object supporting the readline() call def foo(bar): return bar.readline() and of course it should be a doc string rather than a comment! :-) > Or is that something that people who are concerned with robust/secure > code do in fact do? How does it make it any more robust? If the object supports the entire interface used by the function internals then its going to be robust. Rather than an if check you should in production code wrap the function implenetaion with a try/except: def foo(bar): try: return bar.readline() except AttributeError: # Do whatever seems sensible... raise > very strong argument against strongly-typed languages with > well-defined interfaces, so I was wondering if anyone has any other tips > on this topic? As a vociferous proponent of strongly typed languages(pre Python) I am surprised how well Pythons run time approach works. I certainly don't see any more faults in my Python code that in my C++ code, and I write a lot less. Interestingly the few objective studies that exist suggest that regardless of language, for any given programmer there is a pretty constant ratio of bugs to lines of code. Therefore the best way to reduce bugs is reduce the lines of code needed! Python achieves just that... Alan G. From siddharth178@hotmail.com Fri Feb 14 07:52:01 2003 From: siddharth178@hotmail.com (siddharth karandikar) Date: Fri Feb 14 07:52:01 2003 Subject: [Tutor] basic Qs [tutorial / text editors / performance characteristics] Message-ID: doing following with lists -> >>>a = [1, 2, 3, 4, 5] >>>b = a # <--- what does this actually means >>>b.append(6) >>>a [1, 2, 3, 4, 5, 6] # <-- is a and b are references of the same list object ? how to create new objects from other object ??? something like new instance with data of other object. ( is object is right word to use ) _________________________________________________________________ Help STOP SPAM with the new MSN 8 and get 2 months FREE* http://join.msn.com/?page=features/junkmail From op73418@mail.telepac.pt Fri Feb 14 08:06:01 2003 From: op73418@mail.telepac.pt (=?iso-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Fri Feb 14 08:06:01 2003 Subject: [Tutor] basic Qs [tutorial / text editors / performance characteristics] References: Message-ID: <001501c2d42a$9c3921a0$19180dd5@violante> ----- Original Message ----- From: "siddharth karandikar" To: Sent: Friday, February 14, 2003 12:50 PM Subject: Re: [Tutor] basic Qs [tutorial / text editors / performance characteristics] > > doing following with lists -> > > >>>a = [1, 2, 3, 4, 5] > > >>>b = a # <--- what does this actually means > b and a are different *names* for the same list. Think of a and b as references to objects and you won't be far off. Notice though, that Python dereferences automatically => there are no pointers in Python. > >>>b.append(6) > > >>>a > [1, 2, 3, 4, 5, 6] # <-- is a and b are references of > the same list object ? > Since b and a reference the same list b.append(6) or a.append(6) are effectively the same. > > > how to create new objects from other object ??? > something like new instance with data of other object. ( is object is right > word to use ) > > Ok you want a *copy* of a, right? A different object but with equal contents. There are various ways. Here goes the simplest: b = list(a) Here goes another: b = [] for elem in a: b.append(elem) Hope it helps, G. Rodrigues From siddharth178@hotmail.com Fri Feb 14 08:08:02 2003 From: siddharth178@hotmail.com (siddharth karandikar) Date: Fri Feb 14 08:08:02 2003 Subject: [Tutor] java talking python Message-ID: i see that its possible to write classes in python, which can be used as an appication's business logic from other python code. is it possible to use those classes defined in Python from Java classes ?? is webapp development possible in python ?? can webapps written using java, servlets, jsp etc. can be replaced with python code ?? _________________________________________________________________ MSN 8 with e-mail virus protection service: 2 months FREE* http://join.msn.com/?page=features/virus From pcarey@lexmark.com Fri Feb 14 08:17:12 2003 From: pcarey@lexmark.com (pcarey@lexmark.com) Date: Fri Feb 14 08:17:12 2003 Subject: [Tutor] Slightly OT: public/private class members Message-ID: Hello. I'm only in my second C++ class at the local university, but I've been using Python for a while. We are just now beginning to create C++ programs that use classes. My prof says "99% of all data members of a class should be private" in a quasi-brainwashed kind of way. My question is thus: when/why would data members/methods need to be private? I know python has adopted a "we're all consenting adults" point of view (cannot remember where I read that). I rather like that point of view, and dislike creating all these "get & set" methods to fetch/set data members from an object. So, what's the need/use for private members? Sorry if this is OT, but I've not really heard any good arguments that support "privatizing" all data members...but then again, I'm pretty much a CS rookie. TIA, Pete From jerry@j3iss.com Fri Feb 14 08:33:35 2003 From: jerry@j3iss.com (Jerry Jorgenson) Date: Fri Feb 14 08:33:35 2003 Subject: [Tutor] Slightly OT: public/private class members Message-ID: > So, what's the need/use for private members? Private members help avoid side effects. If you can't call a variable/class/data from outside the local scope, then you must act on it (them) with the defined methods, so bugs are (theoretically) easier to find and harder to create. On this subject, why can't Python enforce variable names ( e.g. use strict), and why are all variables global in scope. These to "features" are why I don't use Python much. Jerry Jerry Jorgenson jerry@j3iss.com http://www.j3iss.com/ 972-897-1166 (Cell) 972-209-0191 (Page) From missive@hotmail.com Fri Feb 14 09:13:38 2003 From: missive@hotmail.com (Lee Harr) Date: Fri Feb 14 09:13:38 2003 Subject: [Tutor] Re: where to put data files Message-ID: >I have a script that needs to read from a data file, and I want to know >the best location for the data file. > >Right now, I have this line in my setup.py: > > data_files=[('data', ['char_set'])], > I asked basically this same question on comp.lang.python a few weeks back and never received any response. Best I can tell, the best way to do this is still up in the air in the Python community. What I do (and what at least some others do) is put the data in the directory with your library modules. I got this code from Pygame: class smart_install_data(install_data): def run(self): #need to change self.install_dir to the actual library dir install_cmd = self.get_finalized_command('install') self.install_dir = getattr(install_cmd, 'install_lib') return install_data.run(self) Then in the setup() function, I use: ... cmdclass={'install_data': smart_install_data}, data_files=[['pygsear/libdata/images', ['pygsear/libdata/images/None.png', 'pygsear/libdata/images/turtle.png']]] ... You can see how this works in Pygame or pygsear: http://pygame.org/ http://savannah.nongnu.org/files/?group=pygsear _________________________________________________________________ The new MSN 8: advanced junk mail protection and 2 months FREE* http://join.msn.com/?page=features/junkmail From jerry@j3iss.com Fri Feb 14 09:15:01 2003 From: jerry@j3iss.com (Jerry Jorgenson) Date: Fri Feb 14 09:15:01 2003 Subject: [Tutor] Slightly OT: public/private class members Message-ID: > Variables created within function or class definitions are invariably local > in scope *except* they are declared global (using the correspondig keyword.) Thanks, Gregor I guess because you can't declare variables (a new one appears with every typo) they seem global. > P.S.: Certainly you will see more on this topic here soon Cool!! Jerry Jerry Jorgenson jerry@j3iss.com http://www.j3iss.com/ 972-897-1166 (Cell) 972-209-0191 (Page) From op73418@mail.telepac.pt Fri Feb 14 09:37:02 2003 From: op73418@mail.telepac.pt (=?iso-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Fri Feb 14 09:37:02 2003 Subject: [Tutor] Slightly OT: public/private class members References: Message-ID: <001601c2d437$6ff1e9d0$19180dd5@violante> ----- Original Message ----- From: "Jerry Jorgenson" To: Sent: Friday, February 14, 2003 1:31 PM Subject: Re: [Tutor] Slightly OT: public/private class members > > So, what's the need/use for private members? > > Private members help avoid side effects. If you can't call a > variable/class/data from outside the local scope, then you > must act on it (them) with the defined methods, so bugs are > (theoretically) easier to find and harder to create. > > On this subject, why can't Python enforce variable names ( e.g. > use strict), and why are all variables global in scope. These > to "features" are why I don't use Python much. Uh? Variables declared within function scope are local to that scope and cannot leak to the outside environment(*). Unless you explicitly declare them as global, that is. And what does strict (Perlicism?) do? > Jerry > (*) Actually, I believe there are ways to get at them, but they are black & evil as black & evil magic gets. With my best regards, G. Rodrigues From jerry@j3iss.com Fri Feb 14 09:51:54 2003 From: jerry@j3iss.com (Jerry Jorgenson) Date: Fri Feb 14 09:51:54 2003 Subject: [Tutor] Slightly OT: public/private class members Message-ID: > And what does strict (Perlicism?) do? strict enforces declaration of variables before usage. So use strict; makes you issue a my $variableName; statement so the if you accidentally type $myVar or $myvariable later on, an error will occur, rather than a new variable being created. This is great for code maintainability, especially when you cut and paste functions from other code. Jerry Jerry Jorgenson jerry@j3iss.com http://www.j3iss.com/ 972-897-1166 (Cell) 972-209-0191 (Page) From op73418@mail.telepac.pt Fri Feb 14 10:32:02 2003 From: op73418@mail.telepac.pt (=?iso-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Fri Feb 14 10:32:02 2003 Subject: [Tutor] Slightly OT: public/private class members References: Message-ID: <000b01c2d43e$ec20f940$19180dd5@violante> ----- Original Message ----- From: "Jerry Jorgenson" To: Sent: Friday, February 14, 2003 2:49 PM Subject: Re: [Tutor] Slightly OT: public/private class members > > And what does strict (Perlicism?) do? > > strict enforces declaration of variables before usage. So > > use strict; > > makes you issue a > > my $variableName; > > statement so the if you accidentally type $myVar or $myvariable later on, > an error will occur, rather than a new variable being created. This is > great for code maintainability, especially when you cut and paste functions > from other code. > That's what I thought. In Python >= 2.2 there is a similar mechanism but for *instance attributes*: __slots__. >>> class test(object): ... __slots__ = ['myattribute'] ... def __init__(self, attribute): ... self.myattribute = attribute ... >>> a = test(8) >>> a.myattribute 8 >>> a.x = 1 Traceback (most recent call last): File "", line 1, in ? AttributeError: 'test' object has no attribute 'x' > Jerry > With my best regards, G. Rodrigues From dyoo@hkn.eecs.berkeley.edu Fri Feb 14 10:39:30 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Feb 14 10:39:30 2003 Subject: [Tutor] Text script (fwd) Message-ID: Hi Tim, You accidently sent your question to the administrative address "tutor-admin@python.org", so it only reached the list admins. Since you probably meant to send this to the list at "tutor@python.org", I'll forward it there for your convenience. I hope this helps! ---------- Forwarded message ---------- Date: Fri, 14 Feb 2003 10:17:26 -0500 From: Tim & Brenda Morton To: tutor-admin@python.org Subject: Text script Greetings, I am new to programming and recently became interested because of a software idea I have. I write books and html files that often have Bible references in them [such as, Genesis 3:15; Matthew 4:5; etc.]. What I would like to do is have the entire verse popup in an html file [or compiled html file (.chm)] during a "mouseover" of the reference. I have found a Javascript that will do the mouseover/popup part and using a search and replace with regular expressions I am able to wrap the Javascript around the references in the text. The problem is I have to manually copy and paste the verse contents into the javascript for the link for each reference. I have to look at the reference in the html, find the reference in a Bible database using another program, copy the entire verse or verses, and then paste them into the Javascript and do a little formating. This is very tedious and time consuming. I was advised that a scripting program like Python could automate this process for me, so I downloaded Python 2.2.2 for Windows. The problem is I really don't know where to start. I have a Bible database with one verse per line and can adapt it so each verse will begin with the same reference as found in the html files. This should make it easy to find the corresponding verse from the reference, but I don't know how to load the files into Python and tell it how to do what I want. Can any of you help me get started? Tim Morton From alan.gauld@bt.com Fri Feb 14 10:41:14 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Fri Feb 14 10:41:14 2003 Subject: [Tutor] fibonacci Message-ID: <7497DCA1C240C042B28F6657ADFD8E0974DABE@i2km11-ukbr.domain1.systemhost.net> > > Just as an exercise, I was unable to create a one-line > recursive fibonacci > > generator, but the following works correctly for all values > of n greater than 2. > > > > def fib(n): > > return (n<5)*(n-2) or fib(n-1) + fib(n-2) The first bit of this seems convoluted to me, I thought it might be clearer thusly(and it works below 2!): >>> def fib(n): ... return (( n>1 ) and ( fib(n-1)+fib(n-2) )) or (n==1) ... >>> for n in range(7): print fib(n), ... 0 1 1 2 3 5 8 Assumes you agree that fib(0) == 0 Only slight modification if you think fib(0) == 1 Mind you using short circuit evaluation tricks for conditionals is never very clear! > I would not recommend creating a second order (containing two > recursive elements e.g. "fib (n - 1)" and "fib (n - 2)" ) I'm curious, why not? (Aside from performance maybe which is just as true with any recursive solution.) Alan g. From SWidney@ci.las-vegas.nv.us Fri Feb 14 10:42:12 2003 From: SWidney@ci.las-vegas.nv.us (Scott Widney) Date: Fri Feb 14 10:42:12 2003 Subject: [Tutor] basic Qs [tutorial / text editors / performance chara cteristics] Message-ID: <0E5508EBA1620743B409A2B8365DE16FDC838D@sovereign.ci.las-vegas.nv.us> > Ok you want a *copy* of a, right? A different object but with equal > contents. There are various ways. Here goes the simplest: > > b = list(a) > > Here goes another: > > b = [] > for elem in a: > b.append(elem) There's also list slicing: >>> b = a[:] and the copy module: >>> import copy >>> b = copy.copy(a) also, use: >>> import copy >>> b = copy.deepcopy(a) for nested lists. Enjoy! Scott From morton1611@citynet.net Fri Feb 14 10:46:16 2003 From: morton1611@citynet.net (Tim & Brenda Morton) Date: Fri Feb 14 10:46:16 2003 Subject: [Tutor] Need Python script Message-ID: <004101c2d43f$c01f4c60$40b17541@desktop> This is a multi-part message in MIME format. ------=_NextPart_000_003E_01C2D415.D3AFA2E0 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Greetings, I am new to programming and recently became interested because of a = software idea I have. I write books and html files that often have Bible = references in them [such as, Genesis 3:15; Matthew 4:5; etc.]. What I = would like to do is have the entire verse popup in an html file [or = compiled html file (.chm)] during a "mouseover" of the reference. I have = found a Javascript that will do the mouseover/popup part and using a = search and replace with regular expressions I am able to wrap the = Javascript around the references in the text. The problem is I have to = manually copy and paste the verse contents into the javascript for the = link for each reference. I have to look at the reference in the html, = find the reference in a Bible database using another program, copy the = entire verse or verses, and then paste them into the Javascript and do a = little formating. This is very tedious and time consuming.=20 I was advised that a scripting program like Python could automate this = process for me, so I downloaded Python 2.2.2 for Windows. The problem is = I really don't know where to start. I have a Bible database with one = verse per line and can adapt it so each verse will begin with the same = reference as found in the html files. This should make it easy to find = the corresponding verse from the reference, but I don't know how to load = the files into Python and tell it how to do what I want. Can any of you = help me get started?=20 Tim Morton ------=_NextPart_000_003E_01C2D415.D3AFA2E0 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
Greetings,
 
I am new to programming and recently became interested because of a = software idea I have. I write books and html files that often = have=20 Bible references in them [such as, Genesis 3:15; Matthew 4:5; etc.]. = What I=20 would like to do is have the entire verse popup in an html file [or = compiled=20 html file (.chm)] during a "mouseover" of the reference. I have found a=20 Javascript that will do the mouseover/popup part and using a search and = replace=20 with regular expressions I am able to wrap the Javascript around the = references=20 in the text. The problem is I have to manually copy and paste the verse = contents=20 into the javascript for the link for each reference. I have to look at = the=20 reference in the html, find the reference in a Bible database using = another=20 program, copy the entire verse or verses, and then paste them into the=20 Javascript and do a little formating. This is very tedious and time=20 consuming. 
 
I was advised that a scripting program like Python could automate = this=20 process for me, so I downloaded Python 2.2.2 for Windows. The problem is = I=20 really don't know where to start. I have a Bible database with one verse = per=20 line and can adapt it so each verse will begin with the same = reference=20 as found in the html files. This should make it easy to find = the=20 corresponding verse from the reference, but I don't know how = to load=20 the files into Python and tell it how to do what I want. Can any of = you=20 help me get started?
 
Tim Morton
------=_NextPart_000_003E_01C2D415.D3AFA2E0-- From dyoo@hkn.eecs.berkeley.edu Fri Feb 14 10:47:04 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Feb 14 10:47:04 2003 Subject: [Tutor] basic Qs [copy module] In-Reply-To: <001501c2d42a$9c3921a0$19180dd5@violante> Message-ID: > > how to create new objects from other object ??? > > > > something like new instance with data of other object. ( is object is > > right word to use ) > > > Ok you want a *copy* of a, right? A different object but with equal > contents. There are various ways. Here goes the simplest: > > b = list(a) > > Here goes another: > > b = [] > for elem in a: > b.append(elem) There's also a module meant to make copies of a Python object: it's the 'copy' module: http://www.python.org/doc/lib/module-copy.html The functions in the 'copy' module provide a consistant way of copying an object, and works on class instances as well as lists. Hope this helps! From dyoo@hkn.eecs.berkeley.edu Fri Feb 14 10:54:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Feb 14 10:54:02 2003 Subject: [Tutor] java talking python In-Reply-To: Message-ID: On Fri, 14 Feb 2003, siddharth karandikar wrote: > i see that its possible to write classes in python, which can be used as > an appication's business logic from other python code. > > is it possible to use those classes defined in Python from Java classes > ?? > > is webapp development possible in python ?? Hi Siddharth, Yes; the Jython project aims to provide an implementation of Python in Java, with the benefit that Jython programs can take full advantage of the gargantuan Java library. Have you bumped into Useless Python yet? Useless Python contains a collection of tutorials, and one of them shows a sample Jython program that uses Java's "Swing" library: http://uselesspython.com/Jython_Swing_Basics.html Take a look: you'll be pleasantly surprised, I think. *grin* > can webapps written using java, servlets, jsp etc. can be replaced with > python code ?? Yes. Oh, here's the link to Jython: http://jython.org/ Web development using Jython is a slightly specialised topic; many of us on Tutor may not have as much experience with it as we'd like. If you're interested in Jython and servlet development, you may want to ask questions on the Jython-users mailing list: http://lists.sourceforge.net/lists/listinfo/jython-users Good luck to you! From alan.gauld@bt.com Fri Feb 14 11:12:02 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Fri Feb 14 11:12:02 2003 Subject: [Tutor] basic Qs [tutorial / text editors / performance chara cteristics] Message-ID: <7497DCA1C240C042B28F6657ADFD8E0901F850D2@i2km11-ukbr.domain1.systemhost.net> > >>>a > [1, 2, 3, 4, 5, 6] # <-- is a and b are references of > the same list object ? Yes, all variables in Python are just names referring to objects. Specifically they are dictionary keys... > how to create new objects from other object ??? Make a copy. There is a copy module with deepcopy functions etc For simple lists you can useslicing: L1 = [1,2,3] L2 = L1[:] # a copy of L1's contents > ( is object right word to use ) Yes, very pythonic to refer to things as objects. If you need to distinguish between OOP objects and Python internal objects use object instance. Usually the context is enough to tell what you mean. Alan g. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld/ From alan.gauld@bt.com Fri Feb 14 11:16:02 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Fri Feb 14 11:16:02 2003 Subject: [Tutor] java talking python Message-ID: <7497DCA1C240C042B28F6657ADFD8E0901F850D3@i2km11-ukbr.domain1.systemhost.net> > is it possible to use those classes defined in Python from > Java classes ?? Not easily. But using Jython you can freely mix Java and Python classes/objects because Jython translates Python code into Java byte code. Thus in Jython you can build a GUI in AWT or SWING then build the application using Python classes and link them together. > is webapp development possible in python ?? Absolutely, see the cgi , urllib and html, xml etc modules Also various frameworks exist for ASP style programming And Zope exists as a full Web application server where the web application code is Pyton http://www.zope.org > can webapps written using java, servlets, jsp etc. can be > replaced with python code ?? Yes. Alan G From alan.gauld@bt.com Fri Feb 14 11:24:06 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Fri Feb 14 11:24:06 2003 Subject: [Tutor] Slightly OT: public/private class members Message-ID: <7497DCA1C240C042B28F6657ADFD8E0901F850D4@i2km11-ukbr.domain1.systemhost.net> > My prof says "99% of all data members of a class should > be private" in a quasi-brainwashed kind of way. I'd probably argue that it should be more like 75% with the other 25% as protected... > when/why would data members/methods need to be private? Its called information hiding. In good OOP the data is there to suppoort the methods so you should never need to access it directly. Making it private enforces that and leads to greater safety in that only the class owner can manipulate the data and external classes won't then get broken if the owner decides to replace anv array with a list say. The methods using the data stay the same. > adopted a "we're all consenting adults" point of view Yes but does allow for private names too using a magic __xxx naming convention. > all these "get & set" methods to fetch/set data members from > an object. You shouldn't have to write lots of getXXX setXXX methods only the ones where the data really does need to be exposed - which should be rare. If you are doing that your design is almost certainly not object oriented. (I know Java does this be defaiult but I will restrain myself from saying any more about Javas design!) > So, what's the need/use for private members? To protect the guilty from themselves. > Sorry if this is OT, but I've not really heard any good arguments that > support "privatizing" all data members...but then again, I'm > pretty much a CS rookie. You're reading the wrong books in that case! Try OOSC by Meyer or Grady Booch's OOA&D. Both cover the pros/cons of private vv public members. [ BTW Its less of an issue in Python since Python data is much more robust to change than strictly typed languages like Java/C_++ - cf the earlier discussion about typing and static type checking in Python vv C++ ] Alan g. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld/ From alan.gauld@bt.com Fri Feb 14 11:30:35 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Fri Feb 14 11:30:35 2003 Subject: [Tutor] Slightly OT: public/private class members Message-ID: <7497DCA1C240C042B28F6657ADFD8E0901F850D5@i2km11-ukbr.domain1.systemhost.net> > On this subject, why can't Python enforce variable names ( e.g. > use strict), Sorry, what does that mean exactly? Do you mean why doesn't python insist in declaring variables before you use them? I think thats what VB does with strict? Or is it a Perl thing?... Anyway what do you mean? Why would it help? > and why are all variables global in scope. They aren't. Whatever gave you that idea? Python has 3 levels of scope: builtins, module or file(what the docs call global) and local(inside a function). Also classes define a kind of local scope too. See the namespaces topic in my tutor for more info. Alan g. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld/ From alan.gauld@bt.com Fri Feb 14 11:33:02 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Fri Feb 14 11:33:02 2003 Subject: [Tutor] Slightly OT: public/private class members Message-ID: <7497DCA1C240C042B28F6657ADFD8E0901F850D6@i2km11-ukbr.domain1.systemhost.net> > > And what does strict (Perlicism?) do? > > strict enforces declaration of variables before usage. So > > use strict; > > makes you issue a > > my $variableName; > > statement so the if you accidentally type $myVar or > $myvariable later on, an error will occur, rather than a > new variable being created. Ah, I see. OK that is a nice feature that VB can turn on too. For production code it would be nice, for short scripts overkill. A 'use strict' equivalent might be a good idea. Alan g From eprice@ptc.com Fri Feb 14 11:35:03 2003 From: eprice@ptc.com (Erik Price) Date: Fri Feb 14 11:35:03 2003 Subject: [Tutor] Slightly OT: public/private class members In-Reply-To: References: Message-ID: <3E4D1A79.6070304@ptc.com> pcarey@lexmark.com wrote: > Hello. > I'm only in my second C++ class at the local university, but I've been > using Python for a while. We are just now beginning to create C++ programs > that use classes. My prof says "99% of all data members of a class should > be private" in a quasi-brainwashed kind of way. My question is thus: > when/why would data members/methods need to be private? I know python has > adopted a "we're all consenting adults" point of view (cannot remember > where I read that). I rather like that point of view, and dislike creating > all these "get & set" methods to fetch/set data members from an object. > > So, what's the need/use for private members? It ensures that client code only accesses or changes data in your object through methods that you have explicitly provided. You can ensure that objects are immutable in this fashion, you can ensure that only one instance of an object is every created in this fashion (singleton w/public factory method and private constructor). A good example is just recently, on this very list, someone wanted to create a list (or dictionary? I forget) that they could tell when it had been recently modified, so that they could avoid iterating over the list unnecessarily. (Or something like that.) Here is the class: class TimeSensitiveList(): def __init__(self): self._private_list = [] self._private_modified = false def _private_check_is_modified(self): "Determine if the list has been modified since last access" return self._private_modified def append(self, item): "append an item to the list" self._private_modified = true return self._private_list.append(item) def some_complex_function(self): "perform some complex function only if the list has been modified" if not self._private_modified: do some complex function self._private_modified = false # reset the flag Actually, in the OP's case it was a dictionary, not a list, and the thread is called "Checksum of a dictionary". But you can see how, if the private methods (prefixed by "_private_" in my example) are uncallable from the client code, and assuming that the programmer has been careful, there is no way to access the data in the dictionary without tripping the "modified" flag. That's the idea and reasoning behind it. It is especially important when you are distributing code that may be used by others, which you will have to be responsible for maintaining, because if at a later date you decide to change the class (for performance enhancements or something), then you will want to make sure that the class still works with any client code that is making use of it. This means that you should leave the public API alone (since that is what client code is depending on not to change) and only modify the private methods. Since no client code could possibly be dependent on the private methods (they're private, after all), you can do whatever you need to those. One of the tips from Joshua Bloch's "Effective Java" (an incredible book IMHO if you are a Java programmer) is to try to keep as many of your members private as possible, because for every member you make public, you are now responsible for maintaining one more facet of your class. In other words, private members help encapsulate the logic of a class so that it is a "black box" that is not tampered with by client code. Erik From ramrom@earthling.net Fri Feb 14 11:37:23 2003 From: ramrom@earthling.net (Bob Gailer) Date: Fri Feb 14 11:37:23 2003 Subject: [Tutor] fibonacci In-Reply-To: <3E4CDFF3.2070308@aon.at> References: <5.1.0.14.0.20030212193948.02d50b70@mail.milgromphoto.com> <20030214081702.GA4885@ncst.ernet.in> Message-ID: <5.2.0.9.0.20030214082206.025089e8@66.28.54.253> --=======185173EC======= Content-Type: text/plain; x-avg-checked=avg-ok-4FDF15CC; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit At 01:24 PM 2/14/2003 +0100, Gregor Lingl wrote: >def fib1liner(n, f=[0,1]): > return(n+1>len(f))and[(lambda x:f.append(f[-2]+f[-1]))(i)for i in > range(n+1-len(f))]and 0 or f[n] Thanks for a really great example of what can be done using and, or, comprehension. FWIW this can be simplified to: def fib1liner(n, f=[0,1]): return n>1 and[(lambda:f.append(f[-2]+f[-1]))()for i in range(n-1)]and 0 or f[n] Bob Gailer mailto:ramrom@earthling.net 303 442 2625 --=======185173EC======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-4FDF15CC Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.454 / Virus Database: 253 - Release Date: 2/10/2003 --=======185173EC=======-- From eprice@ptc.com Fri Feb 14 11:40:04 2003 From: eprice@ptc.com (Erik Price) Date: Fri Feb 14 11:40:04 2003 Subject: [Tutor] Slightly OT: public/private class members In-Reply-To: <7497DCA1C240C042B28F6657ADFD8E0901F850D6@i2km11-ukbr.domain1.systemhost.net> References: <7497DCA1C240C042B28F6657ADFD8E0901F850D6@i2km11-ukbr.domain1.systemhost.net> Message-ID: <3E4D1B7E.5000706@ptc.com> alan.gauld@bt.com wrote: >>>And what does strict (Perlicism?) do? >> >>strict enforces declaration of variables before usage. So >> >>use strict; >> >>makes you issue a >> >>my $variableName; >> >>statement so the if you accidentally type $myVar or >>$myvariable later on, an error will occur, rather than a >>new variable being created. > > > Ah, I see. OK that is a nice feature that VB can turn on too. > For production code it would be nice, for short scripts overkill. > A 'use strict' equivalent might be a good idea. Another feature of "use strict" in Perl is that it restricts the scope of variables to the file that they are declared within, so that if you include multiple files, you don't have namespaces getting trodden over. This is something that Python handles quite nicely by default -- you can only import other names into the current namespace explicitly. So, while Python doesn't require you to declare all your variables ahead of time (though you are always welcome to do so by intializing them to some dummy value like null or an empty string), the namespace preservation feature of "use strict" is built right into the language. NB I use "use strict" in every Perl script I write (except the occasional oneliner). It is good practice, even for short scripts. Erik From jerry@j3iss.com Fri Feb 14 11:58:08 2003 From: jerry@j3iss.com (Jerry Jorgenson) Date: Fri Feb 14 11:58:08 2003 Subject: [Tutor] Slightly OT: public/private class members Message-ID: > Ah, I see. OK that is a nice feature that VB can turn on too. I wouldn't know about VB :-) > For production code it would be nice, for short scripts overkill. Short scripts have a tendancy to evolve into production code, so I use this feature (in Perl) for all the code I write, even the short ones (my code tends to look like "textbook" code). Jerry Jerry Jorgenson jerry@j3iss.com http://www.j3iss.com/ 972-897-1166 (Cell) 972-209-0191 (Page) From glingl@aon.at Fri Feb 14 12:13:24 2003 From: glingl@aon.at (Gregor Lingl) Date: Fri Feb 14 12:13:24 2003 Subject: [Tutor] fibonacci References: <5.1.0.14.0.20030212193948.02d50b70@mail.milgromphoto.com> <20030214081702.GA4885@ncst.ernet.in> <5.2.0.9.0.20030214082206.025089e8@66.28.54.253> Message-ID: <3E4D23A7.8050908@aon.at> Bob Gailer schrieb: > At 01:24 PM 2/14/2003 +0100, Gregor Lingl wrote: > >> def fib1liner(n, f=[0,1]): >> return(n+1>len(f))and[(lambda x:f.append(f[-2]+f[-1]))(i)for i in >> range(n+1-len(f))]and 0 or f[n] > > > Thanks for a really great example of what can be done using and, or, > comprehension. FWIW this can be simplified to: > > def fib1liner(n, f=[0,1]): > return n>1 and[(lambda:f.append(f[-2]+f[-1]))()for i in > range(n-1)]and 0 or f[n] > Thanks for you compression - concerning the lambda expression. However, your oneliner is not exactly eqivalent to the original: with every call for n > 1 it computes n-1 new fibonacci numbers, while the original version uses the fact, that f - as a mutable object - after every call remains changed. so after you have computed fib1liner(20), f contains all fibonacci-numbers up to the 20th. Every following call with n<20 needs not to compute anything new. Advantages: (1) no unnecessary computing time (2) no unnecessary memory used Gregor P.S. What does FWIW mean? > > Bob Gailer > mailto:ramrom@earthling.net > 303 442 2625 > >------------------------------------------------------------------------ > > >--- >Outgoing mail is certified Virus Free. >Checked by AVG anti-virus system (http://www.grisoft.com). >Version: 6.0.454 / Virus Database: 253 - Release Date: 2/10/2003 > > From glingl@aon.at Fri Feb 14 12:23:19 2003 From: glingl@aon.at (Gregor Lingl) Date: Fri Feb 14 12:23:19 2003 Subject: [Tutor] fibonacci References: <7497DCA1C240C042B28F6657ADFD8E0974DABE@i2km11-ukbr.domain1.systemhost.net> Message-ID: <3E4D25D1.8020107@aon.at> alan.gauld@bt.com schrieb: >>>... >>> > > >>I would not recommend creating a second order (containing two >>recursive elements e.g. "fib (n - 1)" and "fib (n - 2)" ) >> >> > >I'm curious, why not? >(Aside from performance maybe which is just as true with any >recursive solution.) > > This definitely has to be seen more differentiating ... (YKWIM?) Consider def fib1(n, a=0, b=1): if n == 0: return a else: return fib1( n-1, b, a+b) and def fib2(n): if n < 2: return n else: return fib2(n-2) + fib2(n-1) Launching >>> for i in range(30): print fib(i) with fib beeing fib1 or fib2 you can literally see the difference. For instance: fib1(24) needs 24 recursive calls (because this version is eqivalent to a simple for-loop), while fib2(24) needs more than 150000 recursive calls, the number of recursive calls growing (approx) geometrically with n. So it certainly will be definitly *impossible* to compute fib2(100), while my previously posted fib1liner computes the first 1000 Fibonacci numbers in far less than 1 second. Convincing? Gregor >Alan g. > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > > From Don Arnold" <20030214081702.GA4885@ncst.ernet.in> <5.2.0.9.0.20030214082206.025089e8@66.28.54.253> <3E4D23A7.8050908@aon.at> Message-ID: <073d01c2d44e$a1afb620$ddd1b241@defaultcomp> ----- Original Message ----- From: "Gregor Lingl" To: "Bob Gailer" Cc: Sent: Friday, February 14, 2003 11:13 AM Subject: Re: [Tutor] fibonacci > Bob Gailer schrieb: > > > At 01:24 PM 2/14/2003 +0100, Gregor Lingl wrote: > > > >> def fib1liner(n, f=[0,1]): > >> return(n+1>len(f))and[(lambda x:f.append(f[-2]+f[-1]))(i)for i in > >> range(n+1-len(f))]and 0 or f[n] > > > > > > Thanks for a really great example of what can be done using and, or, > > comprehension. FWIW this can be simplified to: > > > > def fib1liner(n, f=[0,1]): > > return n>1 and[(lambda:f.append(f[-2]+f[-1]))()for i in > > range(n-1)]and 0 or f[n] > > > Thanks for you compression - concerning the lambda expression. > However, your oneliner is not exactly eqivalent to the original: > with every call for n > 1 it computes n-1 new fibonacci numbers, while > the original > version uses the fact, that f - as a mutable object - after every call > remains changed. > so after you have computed fib1liner(20), f contains all > fibonacci-numbers up to the 20th. > Every following call with n<20 needs not to compute anything new. > Advantages: (1) no unnecessary computing time > (2) no unnecessary memory used > > Gregor > > P.S. What does FWIW mean? > The one-liner may be waaay over my head, but FWIW == For What It's Worth. Don From alan.gauld@bt.com Fri Feb 14 12:40:10 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Fri Feb 14 12:40:10 2003 Subject: [Tutor] Slightly OT: public/private class members Message-ID: <7497DCA1C240C042B28F6657ADFD8E0974DABF@i2km11-ukbr.domain1.systemhost.net> > Short scripts have a tendancy to evolve into production code, so I > use this feature (in Perl) for all the code I write, even the short > ones (my code tends to look like "textbook" code). Very true, I probably should have said one-off scripts. I write a lot of code that gets used to demonstrate something and then is never seen again. BTW There is one down side to pre declaration of variables (aside from extra typing!) which hasn't been mentioned which is the tendency to leave 'orphaned' names. ie declarations where the variable was originally used but then the code changed and its no longer needed but the declaration gets left behind. I've seen studies that suggest one such variable exists for every 200 lines of C/C++. However the code bloat is hardly massive and I suspect a good optimiser would remove it anyhow. Alan g. From alan.gauld@bt.com Fri Feb 14 12:42:06 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Fri Feb 14 12:42:06 2003 Subject: [Tutor] fibonacci Message-ID: <7497DCA1C240C042B28F6657ADFD8E0974DAC0@i2km11-ukbr.domain1.systemhost.net> > >>I would not recommend creating a second order (containing two > >>recursive elements e.g. "fib (n - 1)" and "fib (n - 2)" ) > >I'm curious, why not? > >(Aside from performance maybe which is just as true with any > >recursive solution.) > > > > > This definitely has to be seen more differentiating ... (YKWIM?) > > fib1(24) needs 24 recursive calls (because this version is > eqivalent to a simple for-loop), > while fib2(24) needs more than 150000 recursive calls, the number > of recursive calls growing (approx) geometrically with n. OK, so the reason is performance which is nearly always bad compared to iterative solutions (unless your language supports tail end recursion.) Plus the fact that with 2 recursions you get geometric progression which is rather like saying you should never use nested loops... there's no good reason other than performance. > So it certainly will be definitly *impossible* to compute fib2(100), Using Python certainly, if we had stackless Python it might very well be possible since, I believe, it doesn't suffer Pythons restrictions on recursion. OTOH it would take an awful long time! > Convincing? I knew it was slow (I'd already tried fib(50) before posting!) The bit I was actually trying to highlight when I posted my solution wasn't the recursive bit at all but the rather clumsy termination test that Alfred was originally using. Alan G. From jeff@ccvcorp.com Fri Feb 14 13:30:02 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Fri Feb 14 13:30:02 2003 Subject: [Tutor] Decision matrix References: <2BBA1979-3FCD-11D7-BADE-00039351FE6A@mac.com> Message-ID: <3E4D355A.9040704@ccvcorp.com> Erik Price wrote: > > On Thursday, February 13, 2003, at 08:03 PM, Jeff Shannon wrote: > >> Yes. Python has quite a number of informal protocols, and any object >> that supports certain actions is said to conform to that protocol. [...] > > > I see. So these are protocols that have come up via convention, i.e. > there is no standard by which to implement the protocol? They have > just come about from familiarity? > > Or is there somewhere in the StdLib that specifies how implementations > of, say, file-like objects should behave. Well, the specification of how file-like objects should behave is, in essence, the standard file object. In Python, protocols are just a fancy way of saying "If it walks like a duck, and quacks like a duck, then it's a duck." Python doesn't care whether it's a naturally-born barnyard duck or a cybernetic Terminator-duck, as long as it looks and acts in the way that is expected. So if you want an object that'll imitate a file, and be usable where files are usable, then you look at what files do, and make an object that does the same things. In general, you can look at the Python docs to see what methods files have, and write the same methods yourself. There are some cases where it'd be nice to have more complete protocol docs, though. For example, there's a few common operations on lists, but to have a fully list-like object you also need to support len(), and slicing, and a few other assorted details. It'd be nice to have a complete list of those details, and any magic methods needed to implement them. I seem to remember some discussion quite a while ago on c.l.py (back when I had time to read that ;) ) about formalizing a number of protocols, and there may even have been a PEP submitted, but I don't recall any real resolution to the discussion... Jeff Shannon Technician/Programmer Credit International From dyoo@hkn.eecs.berkeley.edu Fri Feb 14 13:33:00 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Feb 14 13:33:00 2003 Subject: [Tutor] fibonacci [caching] In-Reply-To: <3E4D25D1.8020107@aon.at> Message-ID: > def fib2(n): > if n < 2: > return n > else: > return fib2(n-2) + fib2(n-1) Hi Gregor, The above defintion of the fibonacci function is always used as the prototypical example of abusive recursion. However, there is a programming technique called "caching" that will greatly improve the performance of something like the recursive fibonacci function. ### """Demonstration of a simple caching technique.""" import weakref class Cache: def __init__(self, f): self.f = f self.cache = {} def __call__(self, *args): if not self.cache.has_key(args): self.cache[args] = self.f(*args) return self.cache[args] def fib2(n): if n < 2: return n return fib2(n-2) + fib2(n-1) fib2 = Cache(fib2) ### Let's see how this might work: ### >>> def measureFib(n): ... start = time.time() ... result = fib2(n) ... stop = time.time() ... print "fib2(%s) == %s, taking %s" % (n, result, stop-start) ... >>> measureFib(100) fib2(100) == 354224848179261915075, taking 0.00286304950714 >>> measureFib(100) fib2(100) == 354224848179261915075, taking 4.19616699219e-05 ### This version of fib2() performs much better than the original; in fact, it's almost as fast as the iterative solutions! (Although it does take up more space.) So for this specific example, at least, there are perfectly good ways to get excellent performance as well as clean code. This technique of caching is often called "memoization", and there's a reference to it in the Python Cookbook: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52201 Hope this helps! From jerry@j3iss.com Fri Feb 14 13:55:20 2003 From: jerry@j3iss.com (Jerry Jorgenson) Date: Fri Feb 14 13:55:20 2003 Subject: [Tutor] Re: [Offlist] Slightly OT: public/private class members Message-ID: > Yes, Perl has the "my" keyword before the declaration. I imagine that > this might not get implemented without a fundamental change to the > Python syntax (such as allowing variables to be declared without being > initialized -- might be kind of weird looking and confusing, though). I should say that I also use the my as documentation for the variable. That is, they look like this: my (@octets) = @_; # List of octects my $octet; # Octet to process my $octetOut; # Return expanded octet my $restOfLine; # Discription of ip address my $sortKey; # Concatenated, expanded ipaddress my @answers; # holds the results my @hostEntries; # Holds a record of data from /etc/hosts My hope is that with the additional comments at the begining of the function/subroutine/program the next person to work on the code will have a clue (including me). Jerry Jerry Jorgenson jerry@j3iss.com http://www.j3iss.com/ 972-897-1166 (Cell) 972-209-0191 (Page) From glingl@aon.at Fri Feb 14 15:25:12 2003 From: glingl@aon.at (Gregor Lingl) Date: Fri Feb 14 15:25:12 2003 Subject: [Tutor] fibonacci [caching] References: Message-ID: <3E4D4F56.3050505@aon.at> Hi Danny, thanks for your very clear and *beautiful* Pythonic explanation. Moreover I understand very well, that there are people, especially seasoned pythonistas, who refuse to read code like the obfuscated one I posted several postings before to this thread: fib1liner Maybe sometimes this will be used as a "prototypical example of abusing Python" --- in my opinion it certainly is! However, I'd like to stress, that it does just what your example does, except that the fibonaccis are stored in a list - which I thiok is ok when defining a function whose domain is the set of the nonnegative integers. Consider it to be a curiosity.And let's keep in mind, that even Guido dislikes lambda. ;-) Danny Yoo schrieb: >>def fib2(n): >> if n < 2: >> return n >> else: >> return fib2(n-2) + fib2(n-1) >> >> > >Hi Gregor, > > >The above defintion of the fibonacci function is always used as the >prototypical example of abusive recursion. However, there is a >programming technique called "caching" that will greatly improve the >performance of something like the recursive fibonacci function. > > >### >"""Demonstration of a simple caching technique.""" > >import weakref > >class Cache: > def __init__(self, f): > self.f = f > self.cache = {} > > def __call__(self, *args): > if not self.cache.has_key(args): > self.cache[args] = self.f(*args) > return self.cache[args] > >def fib2(n): > if n < 2: > return n > return fib2(n-2) + fib2(n-1) > >fib2 = Cache(fib2) >### > > > >Let's see how this might work: > >### > > >>>>def measureFib(n): >>>> >>>> >... start = time.time() >... result = fib2(n) >... stop = time.time() >... print "fib2(%s) == %s, taking %s" % (n, result, stop-start) >... > > >>>>measureFib(100) >>>> >>>> >fib2(100) == 354224848179261915075, taking 0.00286304950714 > > >>>>measureFib(100) >>>> >>>> >fib2(100) == 354224848179261915075, taking 4.19616699219e-05 >### > > > >This version of fib2() performs much better than the original; in fact, >it's almost as fast as the iterative solutions! (Although it does take up >more space.) So for this specific example, at least, there are perfectly >good ways to get excellent performance as well as clean code. > > >This technique of caching is often called "memoization", and there's a >reference to it in the Python Cookbook: > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52201 > > > >Hope this helps! > > > > > From glingl@aon.at Fri Feb 14 16:29:02 2003 From: glingl@aon.at (Gregor Lingl) Date: Fri Feb 14 16:29:02 2003 Subject: [Tutor] fibonacci [caching] References: Message-ID: <3E4D5FAA.8060800@aon.at> And what about this? def fib(n, cache={0:0, 1:1}): if not n in cache: cache[n] = fib(n-2) + fib(n-1) return cache[n] Gregor > > From pversteegen@gcnetmail.net Fri Feb 14 16:40:02 2003 From: pversteegen@gcnetmail.net (Pete Versteegen) Date: Fri Feb 14 16:40:02 2003 Subject: [Tutor] Printing Message-ID: Hi pythonians, I'm wrestling with a formatting issue: >>> x=['h','e','l','l','o'] >>> for i in range(0, len(x)): ... print x[i], ... h e l l o I can't figure out how do I print this without the spaces between the letters? Thanks! From jeff@ccvcorp.com Fri Feb 14 17:20:02 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Fri Feb 14 17:20:02 2003 Subject: [Tutor] Printing References: Message-ID: <3E4D6B5A.7090406@ccvcorp.com> Pete Versteegen wrote: >Hi pythonians, > >I'm wrestling with a formatting issue: > >>>>x=['h','e','l','l','o'] >>>>for i in range(0, len(x)): >>>> >>>> >... print x[i], >... >h e l l o > > If you need more fine-grained control of output than you can get from print, then use sys.stdout.write(). >>> import sys >>> for x in ['h', 'e', 'l', 'l', 'o']: ... sys.stdout.write(x) ... hello >>> Where print does a variety of convenient formatting tricks that make it convenient for common usages, sys.stdout.write() provides raw access to the normal output stream. Jeff Shannon Technician/Programmer Credit International From bsieber@sieber-edv.net Fri Feb 14 17:31:04 2003 From: bsieber@sieber-edv.net (B. Sieber) Date: Fri Feb 14 17:31:04 2003 Subject: [Tutor] IDLEfork Message-ID: <200302142328.03031.bsieber@sieber-edv.net> --------------Boundary-00=_07LBDCQRNF662NNR8AF5 Content-Type: text/plain; charset="us-ascii" Content-Transfer-Encoding: quoted-printable Hi, is this the right place for this question?: I installed Python 2.3a1. I start IDLE by 'python idle.py' and the shell=20 window is open in the background. When I want to save an idle session I d= o=20 not get a file. In the shell window I get this error message: ------------------------------------------------------- Exception in Tkinter callback Traceback (most recent call last): File "/usr/local/lib/python2.3/lib-tk/Tkinter.py", line 1306, in __call= __ return apply(self.func, args) File "/usr/local/lib/python2.3/site-packages/idlelib/IOBinding.py", lin= e=20 273, in save self.save_as(event) File "/usr/local/lib/python2.3/site-packages/idlelib/IOBinding.py", lin= e=20 282, in save_as filename =3D self.asksavefile() File "/usr/local/lib/python2.3/site-packages/idlelib/IOBinding.py", lin= e=20 441, in asksavefile return self.savedialog.show(initialdir=3Ddir, initialfile=3Dbase) File "/usr/local/lib/python2.3/lib-tk/tkCommonDialog.py", line 54, in s= how s =3D self._fixresult(w, s) File "/usr/local/lib/python2.3/lib-tk/tkFileDialog.py", line 58, in=20 _fixresult path, file =3D os.path.split(result) File "/usr/local/lib/python2.3/posixpath.py", line 65, in split i =3D p.rfind('/') + 1 AttributeError: '_tkinter.Tcl_Obj' object has no attribute 'rfind' --------------------------------------------------------------------- Thank you=20 Bernhard --------------Boundary-00=_07LBDCQRNF662NNR8AF5 Content-Type: text/plain; charset="us-ascii"; name="error.txt" Content-Transfer-Encoding: 7bit Content-Disposition: attachment; filename="error.txt" Exception in Tkinter callback Traceback (most recent call last): File "/usr/local/lib/python2.3/lib-tk/Tkinter.py", line 1306, in __call__ return apply(self.func, args) File "/usr/local/lib/python2.3/site-packages/idlelib/IOBinding.py", line 273, in save self.save_as(event) File "/usr/local/lib/python2.3/site-packages/idlelib/IOBinding.py", line 282, in save_as filename = self.asksavefile() File "/usr/local/lib/python2.3/site-packages/idlelib/IOBinding.py", line 441, in asksavefile return self.savedialog.show(initialdir=dir, initialfile=base) File "/usr/local/lib/python2.3/lib-tk/tkCommonDialog.py", line 54, in show s = self._fixresult(w, s) File "/usr/local/lib/python2.3/lib-tk/tkFileDialog.py", line 58, in _fixresult path, file = os.path.split(result) File "/usr/local/lib/python2.3/posixpath.py", line 65, in split i = p.rfind('/') + 1 AttributeError: '_tkinter.Tcl_Obj' object has no attribute 'rfind' --------------Boundary-00=_07LBDCQRNF662NNR8AF5-- From bsieber@sieber-edv.net Fri Feb 14 17:31:13 2003 From: bsieber@sieber-edv.net (B. Sieber) Date: Fri Feb 14 17:31:13 2003 Subject: [Tutor] IDLEfork Message-ID: <200302142328.03031.bsieber@sieber-edv.net> --------------Boundary-00=_R2LBYQR2UIUQSX5RVQ57 Content-Type: text/plain; charset="us-ascii" Content-Transfer-Encoding: quoted-printable Hi, is this the right place for this question?: I installed Python 2.3a1. I start IDLE by 'python idle.py' and the shell=20 window is open in the background. When I want to save an idle session I d= o=20 not get a file. In the shell window I get this error message: ------------------------------------------------------- Exception in Tkinter callback Traceback (most recent call last): File "/usr/local/lib/python2.3/lib-tk/Tkinter.py", line 1306, in __call= __ return apply(self.func, args) File "/usr/local/lib/python2.3/site-packages/idlelib/IOBinding.py", lin= e=20 273, in save self.save_as(event) File "/usr/local/lib/python2.3/site-packages/idlelib/IOBinding.py", lin= e=20 282, in save_as filename =3D self.asksavefile() File "/usr/local/lib/python2.3/site-packages/idlelib/IOBinding.py", lin= e=20 441, in asksavefile return self.savedialog.show(initialdir=3Ddir, initialfile=3Dbase) File "/usr/local/lib/python2.3/lib-tk/tkCommonDialog.py", line 54, in s= how s =3D self._fixresult(w, s) File "/usr/local/lib/python2.3/lib-tk/tkFileDialog.py", line 58, in=20 _fixresult path, file =3D os.path.split(result) File "/usr/local/lib/python2.3/posixpath.py", line 65, in split i =3D p.rfind('/') + 1 AttributeError: '_tkinter.Tcl_Obj' object has no attribute 'rfind' --------------------------------------------------------------------- Thank you=20 Bernhard --------------Boundary-00=_R2LBYQR2UIUQSX5RVQ57 Content-Type: text/plain; charset="us-ascii"; name="error.txt" Content-Transfer-Encoding: 7bit Content-Disposition: attachment; filename="error.txt" Exception in Tkinter callback Traceback (most recent call last): File "/usr/local/lib/python2.3/lib-tk/Tkinter.py", line 1306, in __call__ return apply(self.func, args) File "/usr/local/lib/python2.3/site-packages/idlelib/IOBinding.py", line 273, in save self.save_as(event) File "/usr/local/lib/python2.3/site-packages/idlelib/IOBinding.py", line 282, in save_as filename = self.asksavefile() File "/usr/local/lib/python2.3/site-packages/idlelib/IOBinding.py", line 441, in asksavefile return self.savedialog.show(initialdir=dir, initialfile=base) File "/usr/local/lib/python2.3/lib-tk/tkCommonDialog.py", line 54, in show s = self._fixresult(w, s) File "/usr/local/lib/python2.3/lib-tk/tkFileDialog.py", line 58, in _fixresult path, file = os.path.split(result) File "/usr/local/lib/python2.3/posixpath.py", line 65, in split i = p.rfind('/') + 1 AttributeError: '_tkinter.Tcl_Obj' object has no attribute 'rfind' --------------Boundary-00=_R2LBYQR2UIUQSX5RVQ57-- From dyoo@hkn.eecs.berkeley.edu Fri Feb 14 18:01:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Feb 14 18:01:02 2003 Subject: [Tutor] fibonacci [caching] [What's the precedence of "not foo in bar"?] In-Reply-To: <3E4D5FAA.8060800@aon.at> Message-ID: On Fri, 14 Feb 2003, Gregor Lingl wrote: > And what about this? > > def fib(n, cache={0:0, 1:1}): > if not n in cache: > cache[n] = fib(n-2) + fib(n-1) > return cache[n] Hi Gregor, I feel a little uncomfortable with the 'not n in cache' part: the reason is because it takes a little effort deciding if Python will interpret it as: (not n) in cache ## Version 1 or not (n in cache) ## Version 2 There is a distinct difference between the meanings! Which way will it go? Let's test it by deliberately writing a fork in the road. text_expression = not "foo" in {0 : 'zero', "foo" : "bar"} This expression is specifically tailored to show which fork Python takes. What do you think this test expression evaluates to? Anyway, because of the potential confusion, we'll often use: x not in L rather than not x in L because it's just not really productive to play these precedence games, even though it can be fun. *grin* From pversteegen@gcnetmail.net Fri Feb 14 18:08:15 2003 From: pversteegen@gcnetmail.net (Pete Versteegen) Date: Fri Feb 14 18:08:15 2003 Subject: [Tutor] Printing In-Reply-To: <3E4D6B5A.7090406@ccvcorp.com> Message-ID: Thanks Jeff, I also found just now that I can do it as follows: >>> import string >>> x=['h','e','l','l','o'] >>> text = string.join(x,"") >>> print text hello On 2/14/03 5:19 PM, "Jeff Shannon" wrote: > > Pete Versteegen wrote: > >> Hi pythonians, >> >> I'm wrestling with a formatting issue: >> >>>>> x=['h','e','l','l','o'] >>>>> for i in range(0, len(x)): >>>>> >>>>> >> ... print x[i], >> ... >> h e l l o >> >> > > If you need more fine-grained control of output than you can get from > print, then use sys.stdout.write(). > >>>> import sys >>>> for x in ['h', 'e', 'l', 'l', 'o']: > ... sys.stdout.write(x) > ... > hello >>>> > > Where print does a variety of convenient formatting tricks that make it > convenient for common usages, sys.stdout.write() provides raw access to > the normal output stream. > > Jeff Shannon > Technician/Programmer > Credit International > > > From gapetard@stsams.org Fri Feb 14 18:38:01 2003 From: gapetard@stsams.org (Bob Rea) Date: Fri Feb 14 18:38:01 2003 Subject: [Tutor] Need Python script In-Reply-To: <004101c2d43f$c01f4c60$40b17541@desktop> References: <004101c2d43f$c01f4c60$40b17541@desktop> Message-ID: <200302141835.35287.gapetard@stsams.org> On Friday 14 February 2003 10:42 am, Tim & Brenda Morton=20 wrote: > I was advised that a scripting program like Python could > automate this process for me, so I downloaded Python > 2.2.2 for Windows. The problem is I really don't know > where to start. I have a Bible database with one verse > per line and can adapt it so each verse will begin with > the same reference as found in the html files. This > should make it easy to find the corresponding verse from > the reference, but I don't know how to load the files > into Python and tell it how to do what I want. Can any of > you help me get started? Ur, Tim, I would look for an html page that looks up bible=20 verses and see if you can use it. Might be easier than=20 reinventing the wheel. Unless you want to do it for the=20 experience. --=20 Bob Rea mailto:gapetard@stsams.org http://www.petard.us What do you say to Jesus when he comes again? Where have you been. You said you were coming right back. From hsteiger@comcast.net Fri Feb 14 21:18:04 2003 From: hsteiger@comcast.net (Henry Steigerwaldt) Date: Fri Feb 14 21:18:04 2003 Subject: [Tutor] Question on tell() function and error produced Message-ID: <000b01c24cd0$f1603d80$0201a8c0@eagle> To All: Can anyone tell me how to use the tell( ) function when accessing data on the Web? I know how to use it when reading a file from the hard drive, but I get an error using it after reading text via the Web and then trying to use it on that particular "file object." Part of the code I am using follows. ________________________________ from Tkinter import * import os from time import gmtime import re import string import urllib fwcURL = "http://isl715.nws.noaa.gov/tdl/forecast/fwc.txt" try: f_object = urllib.urlopen(fwcURL) fwcall = f_object.read() location = f_object.tell() print location except: print "Could not obtain data from Web" return __________________________ Here is the error I am getting and I am not sure how to prevent it: __________ Traceback (most recent call last): File "C:\python_pgms\plot_guidance\plot_guidance_fm_web.py", line 123, in Main location = f_object.tell() AttributeError: addinfourl instance has no attribute 'tell' _____________________ How can I prevent this error? I guess I could save the data to a file, then open the file and read it, THEN use the tell ( ) (and for that matter the seek( ) ) function like I am accustomed to doing successfully in the past. But I should be able to use it as is on the file object. Thanks much. Henry Steigerwaldt Hermitage, TN Email: hsteiger@comcast.net From prog" This is a multi-part message in MIME format. --_bc9b200652f9d6d2be977d49ee84f7d3e Content-Type: text/plain; charset="Big5" Content-Transfer-Encoding: base64 SSBhbSB1c2luZyBQeXRob25XaW4gYW5kIHdvdWxkIGxpa2UgdG8gbWFrZSBzb21lIHB5dGhvbiBj Z2kncy4gIA0KaXMgdGhlcmUgYSBwb3NzaWJpbGl0eSB0aGF0IGEgY2dpIGNhbiBydW4gb24gYSBs b2NhbCBXaW5kb3dzIHdoaWNoDQppcyBOT1QgYSB3ZWIgc2VydmVyPw0KDQpGb3IgZXhhbXBsZSwg d2hlbiB5b3UgdHlwZToNCg0KIGM6L3B5dGhvbi9teWNvdW50ZXIuY2dpIA0KDQppbiB0aGUgYWRk cmVzcyBib3ggb2YgdGhlIElFLCB0aGUgSUUgdHJpZ2dlcnMgdGhlIHB5dGhvbiBvciB3aGF0ZXZl cg0KbWFjaG5pc20gYW5kIGV4ZWN1dGVzIHRoZSBjZ2kgYW5kIGRpc3BsYXkgdGhlICdwcmludCAu Li4nIHRvIGJhY2sgdG8NCnRoZSBicm93c2VyPw0KDQpUaHggaW4gYWR2YW5jZS4NCg0KUGFuCgoK PT09PT09PT09PT09PT09PT09PT09PQ0Kfn5+fn4gYmUgc2hhcGVsZXNzIH5+fn5+DQoNClJ1bnN1 biBQYW4sIFBoRA0KRGVwdC4gb2YgRWNvbG9neSAmIEV2b2x1dGlvbg0KVS4gb2YgQ2hpY2Fnbywg VVNBDQo9PT09PT09PT09PT09PT09PT09PT09Cg== --_bc9b200652f9d6d2be977d49ee84f7d3e Content-Type: text/html; charset="Big5" Content-Transfer-Encoding: base64 PGh0bWw+CjxoZWFkPgo8bWV0YSBodHRwLWVxdWl2PSJDb250ZW50LVR5cGUiIGNvbnRlbnQ9InRl eHQvaHRtbDsgY2hhcnNldD1CaWc1Ij4KPC9oZWFkPgo8Ym9keT4KSSBhbSB1c2luZyBQeXRob25X aW4gYW5kIHdvdWxkIGxpa2UgdG8gbWFrZSBzb21lIHB5dGhvbiBjZ2kncy4gIA08YnI+CmlzIHRo ZXJlIGEgcG9zc2liaWxpdHkgdGhhdCBhIGNnaSBjYW4gcnVuIG9uIGEgbG9jYWwgV2luZG93cyB3 aGljaA08YnI+CmlzIE5PVCBhIHdlYiBzZXJ2ZXI/DTxicj4KDTxicj4KRm9yIGV4YW1wbGUsIHdo ZW4geW91IHR5cGU6DTxicj4KDTxicj4KIGM6L3B5dGhvbi9teWNvdW50ZXIuY2dpIA08YnI+Cg08 YnI+CmluIHRoZSBhZGRyZXNzIGJveCBvZiB0aGUgSUUsIHRoZSBJRSB0cmlnZ2VycyB0aGUgcHl0 aG9uIG9yIHdoYXRldmVyDTxicj4KbWFjaG5pc20gYW5kIGV4ZWN1dGVzIHRoZSBjZ2kgYW5kIGRp c3BsYXkgdGhlICdwcmludCAuLi4nIHRvIGJhY2sgdG8NPGJyPgp0aGUgYnJvd3Nlcj8NPGJyPgoN PGJyPgpUaHggaW4gYWR2YW5jZS4NPGJyPgoNPGJyPgpQYW48YnI+CgoKPT09PT09PT09PT09PT09 PT09PT09PTxiciAvPg0Kfn5+fn4gYmUgc2hhcGVsZXNzIH5+fn5+PGJyIC8+DQo8YnIgLz4NClJ1 bnN1biBQYW4sIFBoRDxiciAvPg0KRGVwdC4gb2YgRWNvbG9neSAmIEV2b2x1dGlvbjxiciAvPg0K VS4gb2YgQ2hpY2FnbywgVVNBPGJyIC8+DQo9PT09PT09PT09PT09PT09PT09PT09CjwvYm9keT48 L2h0bWw+Cg== --_bc9b200652f9d6d2be977d49ee84f7d3e-- From jeff@ccvcorp.com Fri Feb 14 21:38:04 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Fri Feb 14 21:38:04 2003 Subject: [Tutor] Question on tell() function and error produced References: <000b01c24cd0$f1603d80$0201a8c0@eagle> Message-ID: <3E4DA7E2.1000801@ccvcorp.com> Henry Steigerwaldt wrote: >To All: > >Can anyone tell me how to use the tell( ) function when >accessing data on the Web? > >I know how to use it when reading a file from the hard drive, >but I get an error using it after reading text via the Web and >then trying to use it on that particular "file object." > I believe that the file-like object that urllib provides does not support tell(), nor seek(). This is due to underlying limitations of using a data stream as a file -- there's no truly meaningful concept of "position" in a data stream. Similarly, seek() and tell() don't -- can't -- work on sockets. >I guess I could save the data to a file, >then open the file and read it, THEN use the tell ( ) (and for that >matter the seek( ) ) function like I am accustomed to doing >successfully in the past. But I should be able to use it as is on the >file object. > If you really need seek() and tell(), then you'll have to save the data to a disk file. Remember, urllib and such don't provide an actual file object, just a "file-like" object. This is one of the relatively few ways that it doesn't (can't) completely mimic a true file object. (Of all file methods, seek() and tell() are the ones most often left unimplemented in file-like objects, most often because they hold no meaning to the form of the underlying data that the file-like object is wrapping.) Jeff Shannon Technician/Programmer Credit International From fredm@smartypantsco.com Sat Feb 15 00:38:01 2003 From: fredm@smartypantsco.com (Alfred Milgrom) Date: Sat Feb 15 00:38:01 2003 Subject: [Tutor] Printing Message-ID: <5.1.0.14.0.20030215163318.01ee0100@mail.milgromphoto.com> > I also found just now that I can do it as follows: >>> import string >>> x=['h','e','l','l','o'] >>> text = string.join(x,"") >>> print text hello You actually now don't need to import string with the more recent versions of Python. You can do it as >>> x=['h','e','l','l','o'] >>> print ''.join(x) hello Best of luck, Fred Milgrom From charlie@begeistert.org Sat Feb 15 06:32:01 2003 From: charlie@begeistert.org (Charlie Clark) Date: Sat Feb 15 06:32:01 2003 Subject: [Tutor] re: always declaring variables In-Reply-To: <20030214223113.4665.57375.Mailman@mail.python.org> References: <20030214223113.4665.57375.Mailman@mail.python.org> Message-ID: <20030215123205.714.1@.1045306321.fake> On 2003-02-14 at 23:31:13 [+0100], tutor-request@python.org wrote: > > Yes, Perl has the "my" keyword before the declaration. I imagine that > > this might not get implemented without a fundamental change to the > > Python syntax (such as allowing variables to be declared without being > > initialized -- might be kind of weird looking and confusing, though). > > I should say that I also use the my as documentation for the variable. > That is, they look like this: > > my (@octets) = @_; # List of octects > my $octet; # Octet to process > my $octetOut; # Return expanded octet > my $restOfLine; # Discription of ip address my $sortKey; > # Concatenated, expanded ipaddress my @answers; # holds the > results > > my @hostEntries; # Holds a record of data from /etc/hosts > > My hope is that with the additional comments at the begining of the > function/subroutine/program the next person to work on the code will have > a clue (including me). "heavens to murgotroyd" where will that lead to? Naming conventions come up quite often as does commenting and inline documentation. They are often very interesting discussions with nuggets from the gurus. A rule of thumb is that good pythonic code is largely self-explanatory. The consensus seems to be use names that mean something and relate to each other; ie. "octet" and "restofline" are IMHO not a good pair. But I don't think commenting variable names is helpful anyway; I for one constantly recycle names or transform variables which easily breaks such declarations. I also now make extensive use of locally scoped variables where it makes sense for me: orthogonally similar functions. I think it's more important to explain what particular parts are going to try to do, ie. a brief commentary at the start of the module as to what it aims to do and comments, descriptions of all functions, class methods. Functions can carry an optional description and can easily be queried as to what variables they expect. More than that doesn't tend to get maintained anyway and it's optimistic at best or naive at worst to expect it. Charlie From charlie@begeistert.org Sat Feb 15 06:48:01 2003 From: charlie@begeistert.org (Charlie Clark) Date: Sat Feb 15 06:48:01 2003 Subject: [Tutor] re. printing In-Reply-To: <20030214223113.4665.57375.Mailman@mail.python.org> References: <20030214223113.4665.57375.Mailman@mail.python.org> Message-ID: <20030215124733.835.2@.1045306321.fake> On 2003-02-14 at 23:31:13 [+0100], tutor-request@python.org wrote: > >>>x=['h','e','l','l','o'] > >>>for i in range(0, len(x)): ... > >h e l l o ... > If you need more fine-grained control of output than you can get from > print, then use sys.stdout.write(). > > >>> import sys > >>> for x in ['h', 'e', 'l', 'l', 'o']: > ... sys.stdout.write(x) > ... > hello I'm not going to argue with Jeff on this but I'm not sure if the solution is really appropriate. But I would point out his implicit correction of your loop. Being able loop directly over sequences is a really nice thing in Python. We always print strings or string representations of objects, bearing that in mind it often makes more sense to convert objects explicitly into strings before printing them. The archetypal conversion of a list to a string is by using the join() method of string objects. The syntax takes a while to get used to because you apply the method to a separator (any kind of string even an empty one) and pass it a sequence as a paramter. >>> print "".join(x) will give you what you want You can also make use of substitution for greater control >>> print "first half '%s%s%s' second half '%s%s'" %tuple(x) first half 'hel' second half 'lo' I'll leave it to the gurus to explain why you have to convert the list to a tuple to do the substitution / string formatting. I think string substitution is actually something else using the evil $ and is staring us in the face in the form of future Python versions Charlie From antonmuhin at rambler.ru" References: <7497DCA1C240C042B28F6657ADFD8E0974DAC0@i2km11-ukbr.domain1.systemhost.net> Message-ID: <623012341.20030215151301@rambler.ru> Hello everybody, Oneliner was really chalenging. Here some oneliners with time comparisons: from __future__ import generators from time import clock import unittest def fib0(n, x0 = 0, x1 = 1): """Almost classical fibs""" for i in range(n): x0, x1 = x1, x0 + x1 return x0 def fib1(n, x0 = 0, x1 = 1, n0 = 0): """Incorrect one-liner: try fib1(2, -1, 1) to see the bug ternary operator hotly discussed now would be good for one-liners :) """ return ((n0 < n) and fib1(n, x1, x0 + x1, n0 + 1)) or x0 def fib1b(n, x0 = 0, x1 = 1, n0 = 0): """Fixed varinat of the previous one-liner""" return (((n0 < n) and (fib1b(n, x1, x0 + x1, n0 + 1),)) or (x0,))[0] def fib2(n, x0 = 0, x1 = 1): """Functional variant, too many lambdas and () though""" return ((reduce(lambda f, g: (lambda x: f(g(x))), [lambda p: (p[1], p[0] + p[1])]*n, lambda p: p))((x0, x1)))[0] """Some notes: 1. lambda f, g: (lambda x: f(g(x))) --- functions' composition 2. [lambda p: (p[1], p[0] + p[1])]*n --- n of fib's steps """ def fib2b(n, x0 = 0, x1 = 1): """Another functional variant""" return ((reduce( lambda f, g: (lambda x, y: f(*g(x, y))), [lambda x, y: (y, x + y)]*n, lambda x, y: (x, y)))(x0, x1))[0] # Technical stuff def allFibs(): def isFib(name, obj): return callable(obj) and name.startswith("fib") g = globals().copy() for name, obj in g.iteritems(): if isFib(name, obj): yield obj def main(): def clockFunction(f, n = 239): t0 = clock() for i in range(n): f(i) return clock() - t0 print "*** Clock functions ****************" clock() stat = [(clockFunction(f), f.func_name) for f in allFibs()] stat.sort() for t, name in stat: print "%s\t%.5f" % (name, t) class FibsTestCase(unittest.TestCase): def setUp(self): self.__fibs = [obj for obj in allFibs()] self.__paragon = fib0 self.__n = 239 def __fibTest(self, x0, x1): for f in self.__fibs: for i in range(self.__n): self.assertEqual( f(i, x0, x1), self.__paragon(i, x0, x1), "Function %s(%d, %d, %d): oops..." % (f.func_name, i, x0, x1) ) def testStandardFibs(self): self.__fibTest(1, 1) def testMoreSophisticatedFibs(self): self.__fibTest(-1, 1) if __name__ == "__main__": main() unittest.main() -- Best regards, anton mailto:antonmuhin@rambler.ru From jerry@j3iss.com Sat Feb 15 09:42:01 2003 From: jerry@j3iss.com (Jerry Jorgenson) Date: Sat Feb 15 09:42:01 2003 Subject: [Tutor] always declaring variables In-Reply-To: <20030215123205.714.1@.1045306321.fake> References: <20030214223113.4665.57375.Mailman@mail.python.org> <20030215123205.714.1@.1045306321.fake> Message-ID: <20030215084026.4927509d.jerry@j3iss.com> On Sat, 15 Feb 2003 12:32:05 +0100 Charlie Clark wrote: > The consensus seems to be use names that mean something and relate to > each other; ie. "octet" and "restofline" are IMHO not a good pair. But I > don't In this case, I'm reading several host files, I only care about the ip-address and it's octets in the begining of the line. The remainder really is "the rest of the line", and nothing happens to it except that it gets printed later, so it makes a great deal of sense in this context. > think commenting variable names is helpful anyway; I for one constantly > recycle names or transform variables which easily breaks such > declarations. I also now make extensive use of locally scoped variables > where it makes sense for me: orthogonally similar functions. > > I think it's more important to explain what particular parts are going > to try to do, ie. a brief commentary at the start of the module as to > what it aims to do and comments, descriptions of all functions, class > methods. Functions can carry an optional description and can easily be > queried as to what variables they expect. More than that doesn't tend to > get maintained anyway and it's optimistic at best or naive at worst to > expect it. Yes, I put comments in as you suggest (in fact, I think I mention this in an earlier post), but since this is a Python newsgroup, I've tried to keep the Perl examples to a minimum just to illustrate the point that I was making (if I was a better Python programmer, then I would post some Python examples, but hey, that's why I'm in this newsgroup). Generally, I don't find a problem with maintaining the variable comments, because if you change the meaning of the variables, you are changing the fuction and likely using new variable names anyway. What I have noticed is that my co-workers like to work on my code, they say it's much easier for them to modify. As usual YMMV. (I've always hated the $i $j $k kind of variables with just an explaination, of what the code segment does, I'd much rather see $widgetCount, $productionLimit, $costConstant with a definition of what a widget is, what production you are talking about, and what makes up the cost). Jerry -- Jerry Jorgenson jerry@j3iss.com http://www.j3iss.com/ From phthenry@earthlink.net Sat Feb 15 12:05:03 2003 From: phthenry@earthlink.net (Paul Tremblay) Date: Sat Feb 15 12:05:03 2003 Subject: [Tutor] tabs or spaces (the endless debate!) Message-ID: <20030215120346.A6592@localhost.localdomain> Sorry if this question causes an endless debate--as I have seen it do on the vim mailing list. I want to know if I should use tabs or spaces when indenting. I use vim, and have been using the autoindent feature. If I type if var==5: then vim atomatically inserts a tab of 8 spaces for the next line: if var==5: pass #do something However, 8 spaces is quite a bit of space. To improve the excessive space problem, I told vim to change the amount of space in a tab from 8 to 5. I then ran a script and found I got a strange out of index message which I had already checked for. It turns out that vim had screwed up the indenting so that what had been part of an 'if' statment was no longer part of it. Because of this, I am suddenly inclined towards spaces. I plan to distribue my module, and I see that tabs could cause the whole thing to break. So can someone sum up the pros and cons of tabs versus spaces? Also, if I do decide on spaces, how do I make vim automatically insert 5 spaces, rather than a tab space of 8. (I know this is really a vim question, but I figure that there are bound to be some vim users who know this question cold.) Thanks Paul -- ************************ *Paul Tremblay * *phthenry@earthlink.net* ************************ From tim.one@comcast.net Sat Feb 15 12:29:01 2003 From: tim.one@comcast.net (Tim Peters) Date: Sat Feb 15 12:29:01 2003 Subject: [Tutor] tabs or spaces (the endless debate!) In-Reply-To: <20030215120346.A6592@localhost.localdomain> Message-ID: [Paul Tremblay] > ... > I want to know if I should use tabs or spaces when indenting. The standard for the Python library is 4 spaces per indent level, and no hard tab characters period (whether in leading whitespace or comments or anywhere else). Tools/scripts/reindent.py rewrites Python source to that standard, and is routinely run over the Python development tree. > ... > So can someone sum up the pros and cons of tabs versus spaces? For code that will never escape your personal machine, it doesn't matter, provided only that you never mix tabs with spaces in a single file. For distributed code, hard tabs cause needless headaches for people who don't use exactly the same tools that you use. > Also, if I do decide on spaces, how do I make vim automatically insert 5 > spaces, rather than a tab space of 8. (I know this is really a vim > question, but I figure that there are bound to be some vim users who > know this question cold.) I'm sure that's so, but I'm not one of them . A quick search via Google suggested that Python vim users do :set expandtab tabstop=4 shiftwidth=4 but it's all gibberish to me. From erikprice@mac.com Sat Feb 15 14:47:06 2003 From: erikprice@mac.com (Erik Price) Date: Sat Feb 15 14:47:06 2003 Subject: [Tutor] tabs or spaces (the endless debate!) In-Reply-To: <20030215120346.A6592@localhost.localdomain> Message-ID: <4081A09C-4120-11D7-8699-00039351FE6A@mac.com> On Saturday, February 15, 2003, at 12:03 PM, Paul Tremblay wrote: > So can someone sum up the pros and cons of tabs versus spaces? This is my summary: I like indenting my code in 4-space increments. I like spaces b/c diff't software displays tabs differently (some are 4 char widths wide, some are 8), but spaces are the final arbiter. This is what The Man has to say about it: http://python.org/doc/essays/styleguide.html Erik -- Erik Price email: erikprice@mac.com jabber: erikprice@jabber.org From R. Alan Monroe" References: Message-ID: <191659440284.20030215150517@columbus.rr.com> > hard tabs cause needless headaches for people who don't > use exactly the same tools that you use. I will take your word for it, but why is this the case? In my mind, a tab character is a fixed, known ascii character around the world. Everyone knows what it is, and if you indent with one, you KNOW that line is to be indented once. With two, you know definitively that line is to be indented twice, etc. With spaces, they may be damaged during transport from mail program to mail program, and nobody sets their editor for the same number of spaces. The tab just seems more explicit and safer. Alan From erikprice@mac.com Sat Feb 15 16:03:01 2003 From: erikprice@mac.com (Erik Price) Date: Sat Feb 15 16:03:01 2003 Subject: [Tutor] tabs or spaces (the endless debate!) In-Reply-To: <191659440284.20030215150517@columbus.rr.com> Message-ID: On Saturday, February 15, 2003, at 03:05 PM, R. Alan Monroe wrote: >> hard tabs cause needless headaches for people who don't >> use exactly the same tools that you use. > > I will take your word for it, but why is this the case? In my mind, a > tab character is a fixed, known ascii character around the world. > Everyone knows what it is, and if you indent with one, you KNOW that > line is to be indented once. With two, you know definitively that line > is to be indented twice, etc. With spaces, they may be damaged during > transport from mail program to mail program, and nobody sets their > editor for the same number of spaces. The tab just seems more > explicit and safer. > Because if you write your code to wrap at 79 chars (which is a good idea for readability) then whether a tab is 4 or 8 chars matters (and diff't environments use diff't sizes for tabs). Erik -- Erik Price email: erikprice@mac.com jabber: erikprice@jabber.org From R. Alan Monroe" References: Message-ID: <83663899366.20030215161936@columbus.rr.com> > Because if you write your code to wrap at 79 chars (which is a good > idea for readability) then whether a tab is 4 or 8 chars matters (and In my opinion, this is more a legacy problem. On all the major platforms we have editors that can display long lines using scroll bars or methods of scrolling. This isn't vi on vt220 any more :^) > diff't environments use diff't sizes for tabs). So? It's purely cosmetic. The content remains true. Anyway, I don't think there's a single "right" answer to this question. I have always used real tabs up until now, but I'm trying spaces on my latest project just for comparison. :^) Alan From dman@dman.ddts.net Sat Feb 15 16:26:03 2003 From: dman@dman.ddts.net (Derrick 'dman' Hudson) Date: Sat Feb 15 16:26:03 2003 Subject: [Tutor] Re: tabs or spaces (the endless debate!) In-Reply-To: <20030215120346.A6592@localhost.localdomain> References: <20030215120346.A6592@localhost.localdomain> Message-ID: <20030215212521.GA6012@dman.ddts.net> --cWoXeonUoKmBZSoM Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Sat, Feb 15, 2003 at 12:03:46PM -0500, Paul Tremblay wrote: | Sorry if this question causes an endless debate=20 What endless debate? Use spaces and all will be good. :-). | I want to know if I should use tabs or spaces when indenting. Spaces. Always. (except in Makefiles, but they're evil anyways ;-)) | I use vim, and have been using the autoindent feature. If I type Good. | if var=3D=3D5: |=20 | then vim atomatically inserts a tab of 8 spaces for the next line: Sorta. If 'et' is false, vim inserts a combination of tabs and spaces such that the indentation level is n*'shiftwidth' (where n is the current level of indentation). | if var=3D=3D5: | pass #do something |=20 | However, 8 spaces is quite a bit of space. I agree. | To improve the excessive space problem, I told vim to change the | amount of space in a tab from 8 to 5.=20 Wrong solution, see below. | I then ran a script and found I got a strange out of index message which | I had already checked for. It turns out that vim had screwed up the | indenting so that what had been part of an 'if' statment was no longer | part of it.=20 vim did what it was told to do. However, python (and some other equipment, both software and hardware) read a tab as equivalent to 8 spaces. Don't try to change this. Instead use spaces where you want a different spacing level. | Because of this, I am suddenly inclined towards spaces. I plan to | distribue my module, and I see that tabs could cause the whole thing to | break. Yep. | So can someone sum up the pros and cons of tabs versus spaces? Guido did : http://www.python.org/peps/pep-0008.html Never mix tabs and spaces. The most popular way of indenting Python is with spaces only. | Also, if I do decide on spaces, how do I make vim automatically insert 5 | spaces, rather than a tab space of 8. (I know this is really a vim | question, but I figure that there are bound to be some vim users who | know this question cold.) All the goodies are here : http://dman.ddts.net/~dman/config_docs/dot-vimrc In short: augroup Python au! au FileType python set sts=3D5 sw=3D5 et ts=3D8 ai si cin tw=3D78 fo=3D= croq2 hls au FileType python set comments=3Db:#=20 " override C preprocessor indenting au FileType python inoremap # X# augroup END -D --=20 A perverse man stirs up dissension, and a gossip separates close friends. Proverbs 16:28 =20 http://dman.ddts.net/~dman/ --cWoXeonUoKmBZSoM Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iEYEARECAAYFAj5OsEEACgkQO8l8XBKTpRTtXwCfe3DKWNJMRH+TKeJleC+4nDq2 K3IAoI/vfAAVxabQ5P2YqCFluSF3ujcZ =SZpv -----END PGP SIGNATURE----- --cWoXeonUoKmBZSoM-- From dman@dman.ddts.net Sat Feb 15 16:34:02 2003 From: dman@dman.ddts.net (Derrick 'dman' Hudson) Date: Sat Feb 15 16:34:02 2003 Subject: [Tutor] Re: tabs or spaces (the endless debate!) In-Reply-To: <191659440284.20030215150517@columbus.rr.com> References: <191659440284.20030215150517@columbus.rr.com> Message-ID: <20030215213324.GB6012@dman.ddts.net> --xXmbgvnjoT4axfJE Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Sat, Feb 15, 2003 at 03:05:17PM -0500, R. Alan Monroe wrote: | > hard tabs cause needless headaches for people who don't | > use exactly the same tools that you use. |=20 | I will take your word for it, but why is this the case? In my mind, a | tab character is a fixed, known ascii character around the world. | Everyone knows what it is, This much is true. | and if you indent with one, you KNOW that | line is to be indented once. With two, you know definitively that line | is to be indented twice, etc. Well, sorta. Suppose you set up your editor so that a tab is 5 spaces, but your indentation level is 7 characters. For the first indentation your editor will insert 1 tab and 2 spaces. For the second, 2 tabs and 4 spaces. Now suppose I set my editor to the same 7-character indentation level, however tabs are 8 characters wide. In that differing environment, mixing of the tabs and spaces is a real problem (even in C code, where it makes it extremely difficult for the programmer to follow the code). | With spaces, they may be damaged during transport from mail program | to mail program, That's a misconfiguration of your mail program, then. My mail program won't mangle any spaces or other characters. | and nobody sets their editor for the same number of spaces. This is a configuration issue regardless of what character(s) you use. Everyone on a given project needs to use the same indentation (and line wrapping) style. | The tab just seems more explicit and safer. If you use only tabs and never mix spaces with them, then it is functional but still causes some discomfort or havoc for different environments. You mention that vim (and other tools) can scroll long lines. That's true, but it doesn't help me read the code if it doesn't fit on the screen. -D --=20 Dishonest money dwindles away, but he who gathers money little by little makes it grow. Proverbs 13:11 =20 http://dman.ddts.net/~dman/ --xXmbgvnjoT4axfJE Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iEYEARECAAYFAj5OsiQACgkQO8l8XBKTpRTBUACgg6QsyW+ELOzzGxXcka3nmN9k 3loAoKiiUa6yq6648XyC1xeNIFdy6P3r =er7w -----END PGP SIGNATURE----- --xXmbgvnjoT4axfJE-- From Jmllr891@cs.com Sat Feb 15 16:56:01 2003 From: Jmllr891@cs.com (Jmllr891@cs.com) Date: Sat Feb 15 16:56:01 2003 Subject: [Tutor] working w/ processes? Message-ID: <001101c2d53d$1ff27560$58bc8018@ne1.client2.attbi.com> ------=_NextPart_000_000E_01C2D513.36222EE0 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable I know that it is possible under *nix operating systems, but is it possible=20= to access and/or kill currently running processes under MS Windows with Pyth= on? ------=_NextPart_000_000E_01C2D513.36222EE0 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
I know that it is possible u= nder=20 *nix operating systems, but is it possible to access and/or kill currently=20 running processes under MS Windows with Python?
------=_NextPart_000_000E_01C2D513.36222EE0-- From phthenry@earthlink.net Sat Feb 15 19:21:01 2003 From: phthenry@earthlink.net (Paul Tremblay) Date: Sat Feb 15 19:21:01 2003 Subject: [Tutor] Re: tabs or spaces (the endless debate!) In-Reply-To: <20030215212521.GA6012@dman.ddts.net> References: <20030215120346.A6592@localhost.localdomain> <20030215212521.GA6012@dman.ddts.net> Message-ID: <20030215192018.B6592@localhost.localdomain> On Sat, Feb 15, 2003 at 04:25:22PM -0500, Derrick 'dman' Hudson wrote: [snip] > > Guido did : > http://www.python.org/peps/pep-0008.html > > Never mix tabs and spaces. The most popular way of indenting > Python is with spaces only. This was nice, since I had other questions about naming conventions. > > | Also, if I do decide on spaces, how do I make vim automatically insert 5 > | spaces, rather than a tab space of 8. (I know this is really a vim > | question, but I figure that there are bound to be some vim users who > | know this question cold.) > > All the goodies are here : > http://dman.ddts.net/~dman/config_docs/dot-vimrc > > In short: > > augroup Python > au! > au FileType python set sts=5 sw=5 et ts=8 ai si cin tw=78 fo=croq2 hls > > au FileType python set comments=b:# > " override C preprocessor indenting > au FileType python inoremap # X# > augroup END > Ah, nice! Comments and all. Thanks everyone for your help. -- ************************ *Paul Tremblay * *phthenry@earthlink.net* ************************ From lbrannma@cablespeed.com Sat Feb 15 21:02:02 2003 From: lbrannma@cablespeed.com (Lance) Date: Sat Feb 15 21:02:02 2003 Subject: [Tutor] newbie - python update on Mandrake 9.0? Message-ID: <000b01c2d563$15d51580$f228eb42@MYNEWBOX> Hi All, I'm a newbie to Linux and chose Mandrake 9.0. My Mandrake installation puts libpython in /usr/lib. I want to download the Python 2.2 tarball. Should I download it to /usr/bin and run ./configure and make install from /usr/bin? Any suggestions will be greatly appreciated.. including whether I must change or add any environment variables in profile or bashrc. Thanks, Lance From lbrannma@cablespeed.com Sat Feb 15 21:35:02 2003 From: lbrannma@cablespeed.com (Lance) Date: Sat Feb 15 21:35:02 2003 Subject: [Tutor] newbie - python update on Mandrake 9.0? References: <000b01c2d563$15d51580$f228eb42@MYNEWBOX> Message-ID: <010401c2d567$ae6be6d0$f228eb42@MYNEWBOX> re my earlier question.... I installed the latest Python to /home/myname.... but wasn't sure how to modify the paths in profile or bashrc. Hence, typing Python started the one that came with Mandrake, not the latest Python. Also.... I was confused because the Python that ships with Mandrake doesn't have all the directories of the latest release. Thanks, Lance ----- Original Message ----- From: "Lance" To: "Tutor" Sent: Saturday, February 15, 2003 6:28 PM Subject: [Tutor] newbie - python update on Mandrake 9.0? > Hi All, > > I'm a newbie to Linux and chose Mandrake 9.0. My Mandrake installation puts > libpython in /usr/lib. > > I want to download the Python 2.2 tarball. Should I download it to /usr/bin > and run ./configure and make install from /usr/bin? Any suggestions will be > greatly appreciated.. including whether I must change or add any environment > variables in profile or bashrc. > > Thanks, > Lance > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > > From erikprice@mac.com Sat Feb 15 23:34:02 2003 From: erikprice@mac.com (Erik Price) Date: Sat Feb 15 23:34:02 2003 Subject: [Tutor] tabs or spaces (the endless debate!) In-Reply-To: <83663899366.20030215161936@columbus.rr.com> Message-ID: On Saturday, February 15, 2003, at 04:19 PM, R. Alan Monroe wrote: >> Because if you write your code to wrap at 79 chars (which is a good >> idea for readability) then whether a tab is 4 or 8 chars matters (and > > In my opinion, this is more a legacy problem. On all the major > platforms we have editors that can display long lines using scroll > bars or methods of scrolling. This isn't vi on vt220 any more :^) So when you print your code, you print it in landscape orientation on 11"x17" paper? I'm pretty sure it is a violation of most coding standards (including the Guido recommendation I linked to earlier) to exceed 80 characters per line, regardless of what your editor is capable of doing. Feel free to do it with your own stuff, but shared code should take into account many different viewing formats (and yes I do occasionally read code in 80 char-columned term windows). > So? It's purely cosmetic. The content remains true. Hmm... if code formatting was purely cosmetic then I doubt that that Python would have been designed to require a specific whitespace-sensitive formatting. There's more to code formatting than meets the eye. :) > Anyway, I don't think there's a single "right" answer to this > question. I have always used real tabs up until now, but I'm trying > spaces on my latest project just for comparison. :^) I agree with you, there is no universal answer, the only "right" answer would be the one in the code style guide you or your team is using. Erik -- Erik Price email: erikprice@mac.com jabber: erikprice@jabber.org From Don Arnold" Message-ID: <01ad01c2d582$95357ad0$7310ba3f@defaultcomp> ----- Original Message ----- From: prog To: tutor-request@python.org ; tutor@python.org Sent: Friday, February 14, 2003 8:36 PM Subject: [Tutor] Run python cgi in local Windows??? >>I am using PythonWin and would like to make some python cgi's. >>is there a possibility that a cgi can run on a local Windows which >>is NOT a web server? >> >>For example, when you type: >> >>c:/python/mycounter.cgi >> >>in the address box of the IE, the IE triggers the python or whatever >>machnism and executes the cgi and display the 'print ...' to back to >>the browser? >>Thx in advance. >>Pan Actually, Python comes with a mini-webserver in the CGIHttpServer module. Here's how you can set it up from the command prompt: 1. Create a home directory for your server. md \myserver 2. Make a cgi-bin subdirectory off the home directory. cd \myserver md cgi-bin 3. Copy the file CGIHttpServer.py to the home directory. cd \myserver copy \python22\Lib\CGIHttpServer.py 4. Put your cgi scripts in the cgi-bin directory. 5. Change to the home directory and run CGIHttpServer.py Pointing your browser at http://localhost:8000/cgi-bin/somescript.py will now execute the cgi script somescript.py. This is a relatively simple server, and I believe it doesn't handle the POST request. If you need that functionality, you might want to go to www.imatix.com and download their xitami web server. It's fast, easy to install, and runs Python cgi scripts quite nicely. HTH, Don From glingl@aon.at Sun Feb 16 15:12:02 2003 From: glingl@aon.at (Gregor Lingl) Date: Sun Feb 16 15:12:02 2003 Subject: [Tutor] How to solve it ... Message-ID: <3E4FF08C.6050306@aon.at> This is a multi-part message in MIME format. --------------020800090302020309090203 Content-Type: text/plain; charset=us-ascii; format=flowed Content-Transfer-Encoding: 7bit Hi Pythonistas, now for something completely different ... The following problem is taken from "Spektrum der Wissenschaft", Feb. 2003 (which is the German edition of Scientific American): Coded entry To cut costs for a doorguard who asks silly mathematical riddles, the union of mathematical logicians has devised a sophisticated locking apparatus for their union's home. The lock of the door is controlled by four simple switches, which are arranged in a square. The door opens if all the switches are "on" or if all of them are "off". When a member arrives to enter, the door always is locked, which means that some switches are in the on position and some are off. No one who wants to enter can see the switches or touch them directly. Instead, there are four buttons on the door, labelled "P", "D", "1" and "2". If you press "P", a pair of two switches in a horizontal or vertical row is randomly selected. If you press "D" a pair of diagonally arranged switches is randomly selected. After this selection has taken place, pushing button "1" randomly selects one of the previously selected switches and changes its position. Contrary to that, pushing "2" switches both of them. The sequence "letter, digit" may be repeated until the door opens (or you lose patience). Find the shortest complete code which opens the door with certainty, regardless of the original position of the four switches. How would you solve this with Python (- just for your amusement)? I append a quick script which simulates the behaviour of this lock - if you consider it helpful for grasping the problem to have something like this at hand. Gregor --------------020800090302020309090203 Content-Type: text/plain; name="lock.py" Content-Transfer-Encoding: 7bit Content-Disposition: inline; filename="lock.py" """Simulation to explore the behaviour of the lock from the following problem (taken from Spektrum der Wissenschaft 2/2003): Coded entry To cut costs for a doorguard who asks silly mathematical riddles, the union of mathematical logicians has devised a sophisticated locking apparatus for their union's home. The lock of the door is controlled by four simple switches, which are arranged in a square. The door opens if all the switches are "on" or if all of them are "off". When a member arrives to enter, the door always is locked, which means that some switches are in the on position and some are off. No one who wants to enter can see the switches or touch them directly. Instead, there are four buttons on the door, labelled "P", "D", "1" and "2". If you press "P", a pair of two switches in a horizontal or vertical row is randomly selected. If you press "D" a pair of diagonally arranged switches is randomly selected. After this selection has taken place, pushing button "1" randomly selects one of the previously selected switches and changes its position. Contrary to that, pushing "2" switches both of them. The sequence "letter, digit" may be repeated until the door opens (or you lose patience). Find the shortest complete code which opens the door with certainty, regardless of the original position of the four switches. Author: Gregor Lingl, glingl@aon.at Date: 16. 2. 2003 Filename: lock.py """ from Tkinter import Button, Canvas, Frame, Label, Tk from Tkconstants import * from random import randrange,choice import sys class Lock(Canvas): """Implement graphical representation of 4-switch-lock along with (1) methods to change its state (2) memory to store sequence of operations (3) method to repeat the operations of the stored sequence""" def __init__(self,root,**args): """Create graphical elements""" Canvas.__init__(self,root, **args) # self.switches = [0,0,0,0] self.memory = "" self.replay = 0 self.squares=[self.create_rectangle( 45, 45,175,175, width=15), self.create_rectangle(225, 45,355,175, width=15), self.create_rectangle( 45,225,175,355, width=15), self.create_rectangle(225,225,355,355, width=15)] self.txt = self.create_text( 200, 200, font=("Courier",16,"bold"), anchor=CENTER, fill="white", text="") self.reset() def reset(self): """Reset lock to a random closed state""" self.selected = () self.switched = () self.settext("") self.switches = [randrange(2), randrange(2), randrange(2), randrange(2)] while self.isopen(): self.switches[randrange(4)] = randrange(2) self.update() def update(self): """Update graphical representation according to state of switches and current selection or recent changes as well as state of the lock""" for i in range(4): sq = self.squares[i] if self.switches[i]: self.itemconfig(sq,fill = "yellow") else: self.itemconfig(sq,fill = "blue") if i in self.selected: self.itemconfig(sq, outline = "gray") elif i in self.switched: self.itemconfig(sq, outline = "white") else: self.itemconfig(sq, outline = "black") if self.isopen(): self["background"] = "green" else: self["background"] = "red" Canvas.update(self) if self.replay: self.after(1500) def select(self, switches): """Mark a pair of *switches* as selected""" self.selected = switches self.switched = () self.update() def switch(self, count): """Perform switching of *count* switches of the current selection""" if count == 1: self.switched = (choice(self.selected),) else: self.switched = self.selected for switch in self.switched: self.switches[switch] = not self.switches[switch] self.selected = () self.update() def isopen(self): """Return state of the lock""" return self.switches in [ [0,0,0,0], [1,1,1,1] ] def settext(self, txt, append = 0): """Helper method: display actions in replay-mode""" tx = self.itemcget(self.txt,"text") if append: self.itemconfig(self.txt, text = tx + txt) else: self.itemconfig(self.txt, text = txt) def p(self): """Select a pair of switches in a row or a column""" self.select(choice([(0,1),(2,3),(0,2),(1,3)])) if not self.replay: self.memory += "P" def d(self): """Select a pair of switches arranged diagonally""" self.select(choice([(0,3),(1,2)])) if not self.replay: self.memory += "D" def s1(self): """Switch randomly one of the selected switches""" self.switch(1) if not self.replay: self.memory += "1" def s2(self): """Switch both of the selected switches""" self.switch(2) if not self.replay: self.memory += "2" def clear(self): """Clear the lock's memory for operations""" self.memory="" self.settext("") def play(self): """Replay operations stored in the lock's memory""" action = {"P":self.p, "D":self.d, "1":self.s1, "2":self.s2} APPEND = 1 self.replay = 1 self.settext("") for t in self.memory: self.settext(t, APPEND) action[t]() if self.isopen(): break if not self.isopen(): self.settext("") self.replay = 0 def activate(buttons): """Helper function: activate exactly *buttons*""" for button in [pairButton, diagButton, oneButton, twoButton, clearButton, playButton]: if button in buttons: button["state"] = ACTIVE else: button["state"] = DISABLED def updateGUI(buttons): """Update GUI in direct (i.e. non-replay-) mode by acticating *buttons*""" if not lock.replay: commandSequence["text"] = lock.memory activate(buttons) def p(): """Eventhandler for pair-button""" lock.p() updateGUI([oneButton,twoButton]) def d(): """Eventhandler for diagonal-button""" lock.d() updateGUI([oneButton,twoButton]) def s1(): """Eventhandler for one-button""" lock.s1() updateGUI([pairButton,diagButton, clearButton, playButton]) def s2(): """Eventhandler for two-button""" lock.s2() updateGUI([pairButton,diagButton, clearButton, playButton]) def resetprog(): """Eventhandler for clear-button: clear the lock's memory""" lock.clear() updateGUI([pairButton, diagButton]) def play(): """Eventhandler for play-button: replay stored sequence od operations""" activate([]) lock.play() if lock.isopen(): activate([clearButton]) else: activate([pairButton,diagButton, clearButton, playButton]) def reset(): """Eventhandler for reset-button: reset lock to a closed state""" lock.reset() commandSequence["text"] = lock.memory if lock.memory: activate([pairButton,diagButton, clearButton, playButton]) else: activate([pairButton,diagButton]) # Assemble GUI: root = Tk() lock = Lock(root, width=400, height=400, background="red") lock.pack() buttonFont = ("Arial", 10, "bold") switchFrame = Frame(root) pairButton = Button(switchFrame, text= "pair", width=10, font = buttonFont, command = p) diagButton = Button(switchFrame, text= "diagonal", width=10, font = buttonFont, command = d) oneButton = Button(switchFrame, text= "1", width=10, font = buttonFont, command = s1) twoButton = Button(switchFrame, text= "2", width=10, font = buttonFont, command = s2) playFrame = Frame(root) clearButton = Button(playFrame, text = "clear -->", font = buttonFont, command = resetprog) commandSequence = Label(playFrame, text = "", bg = "white", fg = "blue", font=("Courier",10,"bold"), width = 20) playButton = Button(playFrame, text = "<-- play", font = buttonFont, command=play) controlFrame = Frame(root) resetButton = Button(controlFrame,text = "reset", width=20, font = buttonFont, command = reset) exitButton = Button(controlFrame,text = "exit", width=20, font = buttonFont, command = sys.exit) controls = [pairButton, diagButton, oneButton, twoButton, clearButton, commandSequence, playButton, resetButton, exitButton] frames = [switchFrame, playFrame, controlFrame] for control in controls: control.pack(side=LEFT, fill = X, expand=1) for frame in frames: frame.pack(side=TOP, fill = X, expand=1) reset() root.mainloop() --------------020800090302020309090203-- From dman@dman.ddts.net Sun Feb 16 17:34:02 2003 From: dman@dman.ddts.net (Derrick 'dman' Hudson) Date: Sun Feb 16 17:34:02 2003 Subject: [Tutor] Re: Run python cgi in local Windows??? In-Reply-To: <20030215023604.24881.qmail@station172.com> References: <20030215023604.24881.qmail@station172.com> Message-ID: <20030216223320.GA19976@dman.ddts.net> --RnlQjJ0d97Da+TV1 Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Sat, Feb 15, 2003 at 02:36:04AM +0000, prog wrote: | I am using PythonWin and would like to make some python cgi's. =20 | is there a possibility that a cgi can run on a local Windows which | is NOT a web server? No. CGI is the specification of the interface between the web server and the application. Without the web server, you don't have CGI. Instead you would have a regular application. | For example, when you type: |=20 | c:/python/mycounter.cgi=20 |=20 | in the address box of the IE, the IE triggers the python or whatever | machnism and executes the cgi and display the 'print ...' to back to | the browser? No, IE simply reads the file, which has a MIME type of text/plain, and renders it according to the MIME type. No execution has occurred. If you want to test out CGI scripts on your own machine, download apache and set it up. -D --=20 Failure is not an option. It is bundled with the software. =20 http://dman.ddts.net/~dman/ --RnlQjJ0d97Da+TV1 Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iEYEARECAAYFAj5QEbAACgkQO8l8XBKTpRSEoQCgjffYVAFlcdjGJYV8WArpgzEp SIkAn0eGR2AHI3Oo6id81zmb9eKZjNCK =dQSH -----END PGP SIGNATURE----- --RnlQjJ0d97Da+TV1-- From ramrom@earthling.net Sun Feb 16 19:49:19 2003 From: ramrom@earthling.net (Bob Gailer) Date: Sun Feb 16 19:49:19 2003 Subject: [Tutor] How to solve it ... In-Reply-To: <3E4FF08C.6050306@aon.at> Message-ID: <5.2.0.9.0.20030216170332.036c5008@66.28.54.253> --=======5D666865======= Content-Type: text/plain; x-avg-checked=avg-ok-21B32D4F; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit At 09:11 PM 2/16/2003 +0100, Gregor Lingl wrote: >The lock of the door is controlled by four simple switches, which are >arranged in a square. The door opens if all the switches are "on" or if all >of them are "off". When a member arrives to enter, the door always is >locked, which means that some switches are in the on position and some are >off. >No one who wants to enter can see the switches or touch them directly. Assumption 1: approach the door with no desire to enter. Then you can see and touch the switches directly, and opening the door is a matter of flipping 1 or 2 switches. >Instead, there are four buttons on the door, labelled "P", "D", "1" and "2". >If you press "P", a pair of two switches in a horizontal or vertical row is >randomly selected. If you press "D" a pair of diagonally arranged switches >is randomly selected. >After this selection has taken place, pushing button "1" randomly selects >one of the previously selected switches and changes its position. Contrary >to that, >pushing "2" switches both of them. The sequence "letter, digit" may be >repeated until the door opens (or you lose patience). D2 P2 D2 P1 D2 P2 D2 (the door might open after any step other than P1, and will open, if not sooner, after the final D2.) Detailed analysis available on request. Note that D1 is equivalent to P1, so D2 P2 D2 D1 D2 P2 D2 is an equivalent solution. Bob Gailer mailto:ramrom@earthling.net 303 442 2625 --=======5D666865======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-21B32D4F Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.454 / Virus Database: 253 - Release Date: 2/10/2003 --=======5D666865=======-- From ramrom@earthling.net Sun Feb 16 19:57:03 2003 From: ramrom@earthling.net (Bob Gailer) Date: Sun Feb 16 19:57:03 2003 Subject: [Tutor] How to solve it ... In-Reply-To: <3E4FF08C.6050306@aon.at> Message-ID: <5.2.0.9.0.20030216175543.036dae70@66.28.54.253> --=======4C8C7899======= Content-Type: text/plain; x-avg-checked=avg-ok-21B32D4F; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit By the way if there's any cash reward or recognition for solving the problem, I'll give you my address. Bob Gailer mailto:ramrom@earthling.net 303 442 2625 --=======4C8C7899======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-21B32D4F Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.454 / Virus Database: 253 - Release Date: 2/10/2003 --=======4C8C7899=======-- From turmunkh@mail.com Sun Feb 16 22:32:02 2003 From: turmunkh@mail.com (turmunkh@mail.com) Date: Sun Feb 16 22:32:02 2003 Subject: [Tutor] unsubscribe me Message-ID: <20030217032450.65974.qmail@mail.com> please unsubscribe me -- __________________________________________________________ Sign-up for your own FREE Personalized E-mail at Mail.com http://www.mail.com/?sr=signup From jjhegde@konark.ncst.ernet.in Sun Feb 16 23:53:02 2003 From: jjhegde@konark.ncst.ernet.in (Jayprasad J. Hegde) Date: Sun Feb 16 23:53:02 2003 Subject: [Tutor] fibonacci In-Reply-To: <7497DCA1C240C042B28F6657ADFD8E0974DABE@i2km11-ukbr.domain1.systemhost.net> References: <7497DCA1C240C042B28F6657ADFD8E0974DABE@i2km11-ukbr.domain1.systemhost.net> Message-ID: <20030217044835.GA745@ncst.ernet.in> On Fri, Feb 14, 2003 at 03:40:16PM -0000, alan.gauld@bt.com wrote: [ snip ] > > I would not recommend creating a second order (containing two > > recursive elements e.g. "fib (n - 1)" and "fib (n - 2)" ) > I'm curious, why not? > (Aside from performance maybe which is just as true with any > recursive solution.) ^^ not really. What you are saying would be true for most calls which depend on only _one_ recursive element; this would have been perfectly acceptable. However, things are a bit different with the given "fib" definition in particular. If you analyse the "fib" calls closely you'll see that the recursion is not exactly linear i.e., every "fib" call will generate two more "fib" calls and this will grow almost exponentially. Hence, for "fib (4)" -- with the base-case being "fib (0)" and "fib (1)" -- you'll be making a total of 8 calls; for "fib (5)" it will be 14 calls; for "fib (6)" you'll get 24 calls; and so on. Compare this with the typical recursive function, say recfun (x), where "recfun (5)" would possibly result in 4 more "recfun" calls and then return. - JJH -- The good die young -- because they see it's no use living if you've got to be good. -- John Barrymore (defun JJHdetails () (format t "~&~A~&~A~&~A" "Jayprasad J Hegde, KBCS, NCST" "Gulmohar Cross Road 9, Juhu, Mumbai 400049." "tel: +91-22-26201606x373")) From jjhegde@konark.ncst.ernet.in Mon Feb 17 00:07:03 2003 From: jjhegde@konark.ncst.ernet.in (Jayprasad J. Hegde) Date: Mon Feb 17 00:07:03 2003 Subject: [Tutor] fibonacci [caching] In-Reply-To: References: <3E4D25D1.8020107@aon.at> Message-ID: <20030217050244.GB745@ncst.ernet.in> On Fri, Feb 14, 2003 at 10:31:10AM -0800, Danny Yoo wrote: > > > def fib2(n): > > if n < 2: > > return n > > else: > > return fib2(n-2) + fib2(n-1) > The above defintion of the fibonacci function is always used as the > prototypical example of abusive recursion. true. > However, there is a > programming technique called "caching" that will greatly improve the > performance of something like the recursive fibonacci function. The solution that you have given is beautiful due to the elegance being retained and all the dirty work of caching/memoing being done in the "background". Simple, efficient and _not_ convoluted like the earlier examples (sorry folks!). :) The closest so far to being a true representative python version of an efficient Fibonacci algo. Thanks Danny. - JJH > ### > """Demonstration of a simple caching technique.""" > > import weakref > > class Cache: > def __init__(self, f): > self.f = f > self.cache = {} > > def __call__(self, *args): > if not self.cache.has_key(args): > self.cache[args] = self.f(*args) > return self.cache[args] > > def fib2(n): > if n < 2: > return n > return fib2(n-2) + fib2(n-1) > > fib2 = Cache(fib2) > ### > > > > Let's see how this might work: > > ### > >>> def measureFib(n): > ... start = time.time() > ... result = fib2(n) > ... stop = time.time() > ... print "fib2(%s) == %s, taking %s" % (n, result, stop-start) > ... > >>> measureFib(100) > fib2(100) == 354224848179261915075, taking 0.00286304950714 > >>> measureFib(100) > fib2(100) == 354224848179261915075, taking 4.19616699219e-05 > ### > > > > This version of fib2() performs much better than the original; in fact, > it's almost as fast as the iterative solutions! (Although it does take up > more space.) So for this specific example, at least, there are perfectly > good ways to get excellent performance as well as clean code. > > > This technique of caching is often called "memoization", and there's a > reference to it in the Python Cookbook: > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52201 - JJH -- If you don't strike oil in twenty minutes, stop boring. -- Andrew Carnegie, on public speaking (defun JJHdetails () (format t "~&~A~&~A~&~A" "Jayprasad J Hegde, KBCS, NCST" "Gulmohar Cross Road 9, Juhu, Mumbai 400049." "tel: +91-22-26201606x373")) From scot@possum.in-berlin.de Mon Feb 17 06:15:04 2003 From: scot@possum.in-berlin.de (Scot Stevenson) Date: Mon Feb 17 06:15:04 2003 Subject: [Tutor] Tabbing with vi (vim) and Python In-Reply-To: References: Message-ID: <200302171218.27405.scot@possum.in-berlin.de> Hello Tim, Paul: > I'm sure that's so, but I'm not one of them . A quick search via > Google suggested that Python vim users do > > :set expandtab tabstop=4 shiftwidth=4 > > but it's all gibberish to me. Over the last ten years, I have found that you can do everything with vim, you just have to be willing to figure out the docs, which are somewhat daunting at times. My life with Python has been pure joy with the following options in ~/.vimrc : set textwidth=75 - Wrap after 76 Chars (could probably be 77, too) set autoindent - Automatically indent set tabstop=4 - A tab is four chars wide set expandtab - Turn Tabs into whitespace set shiftwidth=4 - Indent width for autoindent filetype indent on - Indents depending on filetype The last line is somewhat magical, as it lets you edit Python with four spaces and C with eight spaces to a tab; you might not need the other entries with this. Note I use a four-space-tab for everything, YMMV. There is also a system-wide file called "/etc/vimrc" (at least with SuSE 8.1) where things are set up for all users; one line I have there that you might want to put in ~/.vimrc if it isn't in your version is syntax on which starts syntax highlighting. These are nice commands: CTRL-D - In insert mode, go back one indent level CTRL-T - In insert mode, go forward one indent level To move a whole Python block one indent level, mark the block visually (with 'v') and then use the '<' or '>' key to move it to the left or write. Oh, and a nice command to know is: :%retab - Convert all tabs depending on "expandtab" Manditory comment on the Vi-Emacs-War: If you are a touch-typist, go with vi, nothing is better: You will only have to learn one editor your whole life, and with a bit of practice, you'll slaughter everybody else on speed. If you hunt-and-peck with two fingers, you're might just possibly be better off with Emacs - I think somebody is working on a Emacs that uses Python as a scripting language instead of Lisp. At least, somebody /should/ be working on a Python version of Emacs... Y, Scot -- Scot W. Stevenson -- scot@possum.in-berlin.de -- Zepernick, Germany From eprice@ptc.com Mon Feb 17 08:16:02 2003 From: eprice@ptc.com (Erik Price) Date: Mon Feb 17 08:16:02 2003 Subject: [Tutor] Tabbing with vi (vim) and Python In-Reply-To: <200302171218.27405.scot@possum.in-berlin.de> References: <200302171218.27405.scot@possum.in-berlin.de> Message-ID: <3E50E04D.1000909@ptc.com> Scot Stevenson wrote: > Manditory comment on the Vi-Emacs-War: If you are a touch-typist, go with vi, > nothing is better: You will only have to learn one editor your whole life, > and with a bit of practice, you'll slaughter everybody else on speed. If you > hunt-and-peck with two fingers, you're might just possibly be better off with > Emacs - I think somebody is working on a Emacs that uses Python as a > scripting language instead of Lisp. Quick comment on your comment -- I am a touch typist and prefer Emacs (simply because that is what I am most used to, not out of any perception that it is better or worse than vi). The biggest advantage I've discovered to having gotten used to Emacs' navigational keybindings (the ones that move the cursor around like an arrow key would, except they are not arrow keys, and the "kill to end of line", "jump to end of line", "jump to beginning of line" and "kill next character") is that they all work in Cocoa applications. If you are a Win/Linux/BSD-only person, then this totally doesn't apply to you, but if you are a Mac user, you can reap the benefits of these power keys. They have become so ingrained in my typing that it is significantly debilitating to come to work and use my Win32 machine and not have instant access to these handy shortcuts. Erik PS: more editors and IDEs will support emacs-style nav keybindings than vi-style nav keybindings, I've discovered (because vi's are modal). Conversely, you are more likely to find vi than emacs on unix machines that are not amped out with software, so it's good to know a little of that at least. From rob@uselesspython.com Mon Feb 17 08:29:04 2003 From: rob@uselesspython.com (Rob Andrews) Date: Mon Feb 17 08:29:04 2003 Subject: [Tutor] Re: Run python cgi in local Windows??? In-Reply-To: <20030217131602.30017.99367.Mailman@mail.python.org> Message-ID: Your version of Windows may have also come with Personal Web Server, which should do the trick. -Rob A. > On Sat, Feb 15, 2003 at 02:36:04AM +0000, prog wrote: > | I am using PythonWin and would like to make some python cgi's. =20 > | is there a possibility that a cgi can run on a local Windows which > | is NOT a web server? > > No. CGI is the specification of the interface between the web server > and the application. Without the web server, you don't have CGI. > Instead you would have a regular application. > > | For example, when you type: > |=20 > | c:/python/mycounter.cgi=20 > |=20 > | in the address box of the IE, the IE triggers the python or whatever > | machnism and executes the cgi and display the 'print ...' to back to > | the browser? > > No, IE simply reads the file, which has a MIME type of text/plain, and > renders it according to the MIME type. No execution has occurred. > > If you want to test out CGI scripts on your own machine, download > apache and set it up. > From alan.gauld@bt.com Mon Feb 17 08:32:02 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon Feb 17 08:32:02 2003 Subject: [Tutor] tabs or spaces (the endless debate!) Message-ID: <7497DCA1C240C042B28F6657ADFD8E0901F850E0@i2km11-ukbr.domain1.systemhost.net> > > tab character is a fixed, known ascii character around the world. Thats true, but how it should be rendered isn't. For example FrameMaker uses the interesting technique of setting tabs by their physical distance from the left margin. You set tabs in inches or centimeters! This results in a very different display of two tabs than I get in vim, say. > > line is to be indented once. With two, you know > definitively that line is to be indented twice, etc. In Frame one tab means the line starts 1 cm from the margin, 2 tabs means it starts 2cm in etc... How many characters that translates to depends on which font you use! Incidentally Frame does this because its a WYSIWYG environment and wants tabs to line up regardless of the fonts you use, whether italics are on etc. So physical distance is the best way to do that for Frame, but it can often look wierd when you import python code. > With spaces, they may be damaged during transport from mail Why are spaces any more prone to damage than tabs? > Because if you write your code to wrap at 79 chars (which is a good > idea for readability) then whether a tab is 4 or 8 chars matters (and > diff't environments use diff't sizes for tabs). Absolutely. Also when you open code in an editor its not obvious whether the code is indented with tabs or spaces. If you then try to add some new code, inside a loop say, and use the wrong chacter your code breaks! Better if we all stick to spaces for distributed code IMHO. Alan g. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld/ PS My web tutor server was down for a few days, its back now, sorry! From alan.gauld@bt.com Mon Feb 17 08:38:03 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon Feb 17 08:38:03 2003 Subject: [Tutor] tabs or spaces (the endless debate!) Message-ID: <7497DCA1C240C042B28F6657ADFD8E0901F850E1@i2km11-ukbr.domain1.systemhost.net> > > Because if you write your code to wrap at 79 chars (which is a good > > idea for readability) > In my opinion, this is more a legacy problem. On all the major > platforms we have editors that can display long lines using scroll > bars or methods of scrolling. This isn't vi on vt220 any more :^) Unfortunately AS/400 and MVS users are still stuck with 80 character displays... In fact when I telnet into my Unix server at work I get a VT220 terminal window. However that's only one aspect, there's also the issue of printing out the listing which on my printer at work defaults to 80 chars wide too. Finally there's the human comprehension thing. When you get very long lines it's hard to scan the whole line. While 80 is maybe shorter than necessary I'd certainly draw the line at 132 (the other setting on my VT220 :-) > So? It's purely cosmetic. The content remains true. Yes, but cosmetic is important for comprehensibility > Anyway, I don't think there's a single "right" answer to this > question. I have always used real tabs up until now, but I'm trying > spaces on my latest project just for comparison. :^) There's no definitive answer because Python is happy with either. Using spaces you will probably settle on smaller indents, but you'll get used to reading that pretty quickly IME. Alan G From alan.gauld@bt.com Mon Feb 17 08:46:01 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon Feb 17 08:46:01 2003 Subject: [Tutor] Run python cgi in local Windows??? Message-ID: <7497DCA1C240C042B28F6657ADFD8E0901F850E2@i2km11-ukbr.domain1.systemhost.net> > This is a relatively simple server, and I believe it doesn't handle > the POST request. > If you need that functionality, you might want to go to www.imatix.com > and download their xitami web server. > It's fast, easy to install, and runs Python cgi scripts quite nicely. I second Don's recommendation, in fact I use Xitami for all my local machine web programming. Alan G From R. Alan Monroe" References: <7497DCA1C240C042B28F6657ADFD8E0901F850E0@i2km11-ukbr.domain1.systemhost.net> Message-ID: <25812521604.20030217093638@columbus.rr.com> >> > tab character is a fixed, known ascii character around the world. > Thats true, but how it should be rendered isn't. > For example FrameMaker uses the interesting technique of setting tabs > by their physical distance from the left margin. You set tabs in > inches or centimeters! This results in a very different display of > two tabs than I get in vim, say. Yeah. I come from a graphic design background, so this kind of behavior feels right to me. In my mind, it's vaguely similar to the same kind of debate as using Italic tags vs. Emphasis tags in HTML. Do you mark up for looks (spaces), or do you mark up to indicate the nature of the content (tabs)? Again that's just my crazy opinion :^) >> With spaces, they may be damaged during transport from mail > Why are spaces any more prone to damage than tabs? Just anecdotal experience on my part. When you copy/paste code from a website, or have code forwarded to you with quote indicators like ">" down the margin, etc. The spacing is often messed up. > Absolutely. Also when you open code in an editor its not obvious > whether the code is indented with tabs or spaces. If you then try That depends on your editor. Try Scite from scintilla.org. :^) Alan From eprice@ptc.com Mon Feb 17 10:13:02 2003 From: eprice@ptc.com (Erik Price) Date: Mon Feb 17 10:13:02 2003 Subject: [Tutor] tabs or spaces (the endless debate!) In-Reply-To: <25812521604.20030217093638@columbus.rr.com> References: <7497DCA1C240C042B28F6657ADFD8E0901F850E0@i2km11-ukbr.domain1.systemhost.net> <25812521604.20030217093638@columbus.rr.com> Message-ID: <3E50FBB1.40109@ptc.com> R. Alan Monroe wrote: > In my mind, it's vaguely similar to the same kind of debate as using > Italic tags vs. Emphasis tags in HTML. Do you mark up for looks > (spaces), or do you mark up to indicate the nature of the content > (tabs)? Again that's just my crazy opinion :^) It's Emphasis tags for text you want emphasized (since tags describe content), and then you use a style sheet to dictate an italic appearance. If you want italics but don't mean to emphasize (say, in your copyright notice or something), just use a section with a style sheet rule to italicize them. Erik From dyoo@hkn.eecs.berkeley.edu Mon Feb 17 10:39:01 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Feb 17 10:39:01 2003 Subject: [Tutor] unsubscribe me In-Reply-To: <20030217032450.65974.qmail@mail.com> Message-ID: On Mon, 17 Feb 2003 turmunkh@mail.com wrote: > please unsubscribe me Hi turmukh@mail.com, (I feel like I'm some sort of broken record... oh well. *grin*) turmukh, you can unsubscribe yourself by visiting that page you used when you first subscribed to Tutor. If you go down to the bottom of the page: http://mail.python.org/mailman/listinfo/tutor you should see a button called "Edit Options". From there, you should be able to unsubscribe by pressing the "unsubscribe me" button. If you run into any problems while unsubscribing, please feel free to email just the administrators at 'tutor-admin@python.org'. From dyoo@hkn.eecs.berkeley.edu Mon Feb 17 10:44:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Feb 17 10:44:02 2003 Subject: [Tutor] working w/ processes? In-Reply-To: <001101c2d53d$1ff27560$58bc8018@ne1.client2.attbi.com> Message-ID: On Sat, 15 Feb 2003 Jmllr891@cs.com wrote: > I know that it is possible under *nix operating systems, but is it > possible to access and/or kill currently running processes under MS > Windows with Python? Hello! Has anyone replied to you about this yet? I'm getting the feeling your question is slightly specialized; you might want to ask on the python-win32 list for this one. I did some Googling: according to, http://mail.python.org/pipermail/python-list/2002-January/079640.html the win32api extensions should include a sample script called "killProcName.py" that demonstrates how to kill win32 processes. Accordingt to Mark Hammond, it only works on NT/2k/XP machines though: http://mail.python.org/pipermail/python-list/2000-January/020468.html but, then, that email was written a few years ago, so the situation may have changed. If you ask on the python-win32 list, I'm sure that the gurus there may be able to help you better. Here's the link to the python-win32 list: http://mail.python.org/mailman/listinfo/python-win32 Good luck to you! From tim.one@comcast.net Mon Feb 17 13:46:02 2003 From: tim.one@comcast.net (Tim Peters) Date: Mon Feb 17 13:46:02 2003 Subject: [Tutor] How to solve it ... In-Reply-To: <3E4FF08C.6050306@aon.at> Message-ID: [Gregor Lingl] > Hi Pythonistas, now for something completely different ... > > The following problem is taken from "Spektrum der Wissenschaft", Feb. > 2003 (which is the German edition of Scientific American): > > Coded entry > > To cut costs for a doorguard who asks silly mathematical riddles, > the union of mathematical logicians has devised a sophisticated locking > apparatus for their union's home. > The lock of the door is controlled by four simple switches, which are > arranged in a square. The door opens if all the switches are "on" > or if all of them are "off". When a member arrives to enter, the door > always is locked, which means that some switches are in the on position > and some are off. > No one who wants to enter can see the switches or touch them directly. > Instead, there are four buttons on the door, labelled "P", "D", > "1" and "2". > If you press "P", a pair of two switches in a horizontal or > vertical row is randomly selected. If you press "D" a pair of diagonally > arranged switches is randomly selected. > After this selection has taken place, pushing button "1" randomly > selects one of the previously selected switches and changes its > position. > Contrary to that, pushing "2" switches both of them. The sequence > "letter, digit" may be repeated until the door opens (or you lose > patience). > Find the shortest complete code which opens the door with certainty, > regardless of the original position of the four switches. > > How would you solve this with Python (- just for your amusement)? How would you solve it without Python, i.e. "by hand"? Answer that, and then you can use Python to automate the tedious parts. Trying the simplest thing that could possibly work is often a good start: generate all possible sequences composed of {D1, D2, P1, P2}, in increasing order of length, and for each one see whether it solves all initial states. The first one that does is "the answer". There's no guarantee in advance that this will finish in a reasonable amount of time, and indeed there's no guarantee in advance that a solution even exists. Luckily for this most brutish of brute-force approaches, a solution to this problem is found in reasonable time. Refinements of the brute force approach can find all possible non-isomorphic solutions (and regardless of length) in a few seconds. These require thinking about the problem, to limit the amount of brute-force work required. For example, D1 and P1 both pick one switch at random and flip it, so you can pretend that one of them doesn't exist (they have exactly the same effect). This cuts the number of sequences of length N from 4**N to 3**N, and that's a huge savings in the space that needs to be searched. Symmetry arguments can also cut the amount of work, by a constant factor. For example, a little thought should convince you that if you have a sequence S that solves the case where only the upper left switch is on at the start, then S must also solve the other 3 initial states with only one switch on at the start. Deeper thought will go on to convince you that if S solves initial states with only 1 switch on, S must also solve all initial states with only 1 switch off (because "all on" and "all off" are both winning states, and the operations (D1 etc) don't know the difference between "on" and "off"). Similarly, if S solves the initial state where just the top 2 switches are on, it must also solve all initial states where just the 2 switches in a row or column are on. The only initial states remaining then are the two where just the switches on a diagonal are on, and again by symmetry those two states are equivalent. So you don't really have to check that all 14 initial states are solved, there are just 3 initial states that aren't equivalent under rotations, reflections, and exchanging the meanings of "on" and "off". Another thing to note is that if you find a sequence T that has the same effect on all initial states as a shorter sequence S, there's no point looking at any sequence U beginning with T: U could be changed to an equivalent but shorter sequence by replacing its start with S. You can find such equivalent pairs by thinking, but it's easier to write a program to find them. For example, the sequence P2P2P2 has the same effect on all initial states as P2 by itself, so there's no point looking at any sequence starting with P2P2P2. A different approach is to start at the other end, looking at the final states (all off and all on), and working backward to deduce how you could get there. A third approach is to burn the candle at both ends, moving forward from the initial states and backward from the final states, a bit of each at a time, until they meet in the middle. This can get pretty complicated, though! One thing all approaches need is a good way to represent the possible states. For example, assign a different power of 2 to each switch location: 1 2 4 8 Then the integers in 0 through 15 represent all 16 possible switch states, where, for example, 9=1+8 represents the state where the just the switches on the main diagonal are on, and 15 represents the state where all switches are on. This is particularly convenient because "flipping a swtich" corresponds to doing an exclusive-or of the integer representing the state with the power of 2 representing the switch to be flipped. For example, the effect of D2 is to xor the state with 1+8=9 or with 2+4=6. So the possible effects of D2 on the state 3 (= 1+2 = top two switches on) are >>> 3 ^ 9 10 # = 2+8 = right column of switches on >>> 3 ^ 6 5 # = 1+4 = left column of switches on >>> Putting this all together in a program isn't an easy task -- unless you've done things "like it" a dozen times before. From BranimirP@cpas.com Mon Feb 17 14:23:19 2003 From: BranimirP@cpas.com (Branimir Petrovic) Date: Mon Feb 17 14:23:19 2003 Subject: [Tutor] working w/ processes? Message-ID: <33678E78A2DD4D418396703A750048D45E63E7@RIKER> > -----Original Message----- > From: Danny Yoo [mailto:dyoo@hkn.eecs.berkeley.edu] > Sent: February 17, 2003 10:33 AM > To: Jmllr891@cs.com > Cc: tutor@python.org > Subject: Re: [Tutor] working w/ processes? > > > > > On Sat, 15 Feb 2003 Jmllr891@cs.com wrote: > > > I know that it is possible under *nix operating systems, but is it > > possible to access and/or kill currently running processes under MS > > Windows with Python? > > Hello! Has anyone replied to you about this yet? I'm > getting the feeling > your question is slightly specialized; you might want to ask on the > python-win32 list for this one. Solution for this on Windows is to use WMI. Sorry for the example in JScript (didn't have time to fully re-tool to Python), but translating to Python should be a piece of cake for which unfortunatley I will not have time, for quite some time :-( Here it is: /*//////////////////////////////////////////////////////////////////// FileName: KillProc.js Copy this script to dir in path (C:\, C:\Winnt or C:\Windows,...) From command line: C:\>KillProc notepad.exe Sript assumes: - WMI (WinXP, Win2K or WinNT with WMI core), - User running it must have administrative privileges. *///////////////////////////////////////////////////////////////////// var oShell = new ActiveXObject("Wscript.Shell"); var oArgs = WScript.Arguments; var sArgsAry = new Array(); var sArgsLine = ""; // --- Make sure there are comand line parameters: if (oArgs.length==0) { sMsg = "Usage: \n\tC:\\>KillProc notepad.exe [winword.exe ...]" WScript.Echo(sMsg); WScript.Quit(); } // --- Collect script arguments (if any): for (var i=0; i I am trying to do a regular expression match on: 20030214-001-x86.exe r'\d{8}.*x86\.exe' does not seem to do it. Any help would...help. : ) Bob From dyoo@hkn.eecs.berkeley.edu Mon Feb 17 18:06:01 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Feb 17 18:06:01 2003 Subject: [Tutor] RE match on a file In-Reply-To: <000d01c2d6d6$235b5a10$4b8a3518@olorin> Message-ID: On Mon, 17 Feb 2003, Bob Hicks wrote: > I am trying to do a regular expression match on: > > 20030214-001-x86.exe > > r'\d{8}.*x86\.exe' does not seem to do it. Hi Bob, Can you explain why you think the above pattern doesn't work? I just want to make sure we're on the same page. *grin* The reason we need to ask this is because r'\d{8}.*x86.exe' does appear to recognise your sample string: ### >>> pattern = re.compile(r'\d{8}.*x86\.exe') >>> pattern.match('20030214-001-x86.exe') <_sre.SRE_Match object at 0x816f360> ### So that matches. In general, whenever we're debugging, we need some test case to verify the problem. Your example doesn't exhibit the problem you're looking for, so we can't do much without reading your mind, or guessing. *grin* Show us a counterexample that shows where the regular expression either is too overzealous or too lenient, and we can work from there. Talk to you later! From magnus@thinkware.se Mon Feb 17 18:55:02 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Mon Feb 17 18:55:02 2003 Subject: [Tutor] tabs or spaces (the endless debate!) In-Reply-To: <20030217170018.25554.48475.Mailman@mail.python.org> Message-ID: <5.1.0.14.0.20030217183846.02b6fdd0@www.thinkware.se> At 12:00 2003-02-17 -0500, tutor-request@python.org wrote: > > > Because if you write your code to wrap at 79 chars (which is a good > > > idea for readability) > > In my opinion, this is more a legacy problem. On all the major > > platforms we have editors that can display long lines using scroll > > bars or methods of scrolling. This isn't vi on vt220 any more :^) > >Finally there's the human comprehension thing. When you get very long >lines it's hard to scan the whole line. While 80 is maybe shorter than >necessary I'd certainly draw the line at 132 (the other setting on >my VT220 :-) I think this is the really important factor. Why not take the same concerns with code as with other written text. I'm sure you would all be very irritated if your daily news paper in tabloid format with a small font used one wide column that went across the whole page. Your reading speed would crumble. I'm also pretty sure that you don't like to read text on web pages where you have to scroll horizontally on each line, because the lines are too wide to fit on the screen... All texts on the subject I've seen suggest 60-65 characters per line on paper. Many suggest that somewhat less is better on screen. For me, one of the really, really great things with python is that it's so easy to read and understand python code. Let's not spoil that! Too short lines will slow our reading down. This is because we can really only concentrate on one line at a time, and switching lines too often will take more time, than to switch more seldom. If you feel that it's faster to read these short lines than the ones above, you can probably speed up your reading speed a lot if you practice. (Unless you read in a different way than most other people.) With code, this is a problem if we indent too much, and have a limited line width. In most Python code with 4 space indentation, this is not a problem. On the other hand, very long lines means that you have to shift focus many times on the line, and with a long, rather continous line, it's easy to get lost, and above all, it's difficult to find the right next line when the line you are reading finally ends. I imagine you've experienced this with long lines of text, that you sometimes start to read the same line over again, or accidentally skip a line. It very rarely happens with a 60 character line, but it starts to get irritatingly comman at perhaps 90 lines or so. It's not quite the same with code, since those lines that extend far to the right probably start with a fair indentation. On the other hand, in code, at least in python code, the location of the text, both indentation and what line we are in, creates an essential context for the code. I certainly feel that a need for horizontal scanning for more than a very small fraction of the lines of code, would be bad, and I feel that my code is less convenient to read when the lines get beyond 80 character or so, so I usually change it if that happens. Oh well, now I have to crawl back to bed, cure my cold and get well enough to finish that manuscript review I was supposed to do... -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From dyoo@hkn.eecs.berkeley.edu Mon Feb 17 19:41:04 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Feb 17 19:41:04 2003 Subject: [Tutor] RE match on a file (fwd) Message-ID: [Ill forward Bob's response to the python-tutor list.] ---------- Forwarded message ---------- Date: Mon, 17 Feb 2003 18:26:30 -0500 From: Bob Hicks To: 'Danny Yoo' Subject: RE: [Tutor] RE match on a file Maybe I am confusing myself as well. The match may work but I think I am confused at what I am returning. This is what I am trying to do: 1. Connect to the Symantec site 2. Get the latest NAVCE file This is my code: import ftplib, re site = 'ftp.symantec.com' dir='/public/english_us_canada/antivirus_definitions/norton_antivirus' ftp = ftplib.FTP(site) ftp.login() ftp.cwd(dir) files = ftp.nlst() for fn in re.findall(r'\d{8}.*x86\.exe', "\n".join(files)): print "Fetching", fn, f = file(fn, 'wb') ftp.retrbinary('RETR ' + fn, f.write) # In case of timeout problems, decrease block size from default 8192 # ftp.retrbinary('RETR ' + fn, f.write, 1024) f.close() print 'Done!' ftp.quit() Q1: Does the re.findall return a list of files? Q2: If Q1 is yes then I should be able to a [-1] to get the last one correct? Q3: If Q1 is no then how do I make is a list? I think my confusion is I assumed that the re.findall was a list of objects an then I could do something like: files[-1] = files I was thinking this would a) get the last file name and b) make that file name the only one so that when the download is started only that one file (and then newest one date wise) would be downloaded. No matter how I try to "slice" it though it downloads every match. Of course my assumption could have been initially wrong. Ah...upon looking as well I can see I changed the re.findall from re.match which was matching the first 8 digits of all the files and giving me back more than I was thinking it should. > -----Original Message----- > From: Danny Yoo [mailto:dyoo@hkn.eecs.berkeley.edu] > Sent: Monday, February 17, 2003 6:04 PM > To: Bob Hicks > Cc: tutor@python.org > Subject: Re: [Tutor] RE match on a file > > > > On Mon, 17 Feb 2003, Bob Hicks wrote: > > > I am trying to do a regular expression match on: > > > > 20030214-001-x86.exe > > > > r'\d{8}.*x86\.exe' does not seem to do it. > > Hi Bob, > > > Can you explain why you think the above pattern doesn't work? I just want > to make sure we're on the same page. *grin* > > The reason we need to ask this is because r'\d{8}.*x86.exe' does appear to > recognise your sample string: > > ### > >>> pattern = re.compile(r'\d{8}.*x86\.exe') > >>> pattern.match('20030214-001-x86.exe') > <_sre.SRE_Match object at 0x816f360> > ### > > So that matches. > > > In general, whenever we're debugging, we need some test case to verify the > problem. Your example doesn't exhibit the problem you're looking for, so > we can't do much without reading your mind, or guessing. *grin* > > Show us a counterexample that shows where the regular expression either is > too overzealous or too lenient, and we can work from there. Talk to you > later! From learning.python@dbmail.dk Mon Feb 17 19:44:13 2003 From: learning.python@dbmail.dk (Ole Jensen) Date: Mon Feb 17 19:44:13 2003 Subject: [Tutor] How do you define the value of ACE in black jack Message-ID: <006501c2d6e6$ba3c95b0$a44c73d5@oleioq8ex4m1zx> This is a multi-part message in MIME format. ------=_NextPart_000_0062_01C2D6EF.1BF034D0 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable (I recieved a message about not being a member so I hope that Im not = double posting now because I resent the message) In Black Jack the value of the ACE depends on the sum of your cards if = the sum is lower than 21, the value of your ACE is 11 however if the sum of your cards increase to more than 21(if ace counts = for 11) then your ACE drops to the value of one. How would you define the value of ACE in python to the rules of Black = Jack? Im sure the best way is to make some sort of a function but as a nooB, = im not really sure how to get that to work (i might be able to make the = function but Im not sure how to integrate it with the rest of the = code)... this is how I've done so far: Start of code: import random Jack =3D 10 Queen =3D 10 King =3D 10 cards =3D ["dummy", ACE, 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King] firstcard =3D cards[random.randrange(1,14)] seccard =3D cards[random.randrange(1,14)] sum =3D firstcard + seccard # ACE definition if sum + 11 <=3D 21: ACE =3D 11 elif sum + 11 > 21: ACE =3D 1 =20 print "Card one:", firstcard, "\t", "Card two:", seccard, "\t", "Sum:", = sum crd =3D ["three:", "four:", "five:"] print "do you want to:\n1 - hit \n2 - stand" hitstand =3D input(">>> ") j =3D 0 while hitstand =3D=3D 1: newcard =3D cards[random.randrange(1,14)] sum =3D sum + newcard print "card "+crd[j], newcard, "\t", "\t", "sum", sum j =3D j + 1 print "do you want to:\n1 - hit \n2 - stand" hitstand =3D input(">>> ") End of code: in my defintion of ACE it seems that ACE is always 11, which might not = be surprising as it uses the sum of the first to cards (im guessing) = that are always lower than 21(or equal to). but where else can I place the definition of ACE after all the values = used to define it needs to have been stated! any help appriciated Hilsen Ole ole_jensen@dbmail.dk ------=_NextPart_000_0062_01C2D6EF.1BF034D0 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
(I recieved a message about not being a = member so I=20 hope that Im not double posting now because I resent the = message)
 
 
In Black Jack the value of the ACE = depends on the=20 sum of your cards if the sum is lower than 21, the value of your = ACE is=20 11
however if the sum of your cards = increase to more=20 than 21(if ace counts for 11) then your ACE drops to the value of=20 one.
 
How would you define the value of = ACE in=20 python to the rules of Black Jack?
 
Im sure the best way is to make some = sort of a=20 function but as a nooB, im not really sure how to get that to work (i = might be=20 able to make the function but Im not sure how to integrate it with the = rest of=20 the code)...
 
this is how I've done so = far:
 
Start of code:
 
import random
 
Jack =3D 10
Queen =3D 10
King =3D = 10
 
cards =3D ["dummy", ACE, 2, 3, 4, 5, 6, = 7, 8, 9, 10,=20 Jack, Queen, King]
firstcard =3D=20 cards[random.randrange(1,14)]
seccard =3D = cards[random.randrange(1,14)]
sum=20 =3D firstcard + seccard
 
# ACE definition
if sum + 11 <=3D = 21:
    ACE =3D=20 11
elif sum + 11 > 21:
    ACE =3D=20 1
           &n= bsp;   =20
print "Card one:", firstcard, "\t", "Card two:", seccard, "\t", = "Sum:",=20 sum
crd =3D ["three:", "four:", "five:"]
 
print "do you want to:\n1 - hit \n2 -=20 stand"
hitstand =3D input(">>> ")
 
j =3D 0
while hitstand =3D=3D = 1:
    newcard=20 =3D cards[random.randrange(1,14)]
    sum =3D sum +=20 newcard
    print "card "+crd[j], newcard, "\t", "\t", = "sum",=20 sum
    j =3D j + 1
    print "do = you want=20 to:\n1 - hit \n2 - stand"
    hitstand =3D = input(">>>=20 ")
 
End of code:
 
in my defintion of ACE it seems that = ACE is always=20 11, which might not be surprising as it uses the sum of the first to = cards (im=20 guessing) that are always lower than 21(or equal to).
but where else can I place the = definition of ACE=20 after all the values used to define it needs to have been = stated!
 
 
any help appriciated
 
Hilsen Ole
ole_jensen@dbmail.dk
------=_NextPart_000_0062_01C2D6EF.1BF034D0-- From dman@dman.ddts.net Mon Feb 17 20:09:02 2003 From: dman@dman.ddts.net (Derrick 'dman' Hudson) Date: Mon Feb 17 20:09:02 2003 Subject: [Tutor] Re: How do you define the value of ACE in black jack In-Reply-To: <006501c2d6e6$ba3c95b0$a44c73d5@oleioq8ex4m1zx> References: <006501c2d6e6$ba3c95b0$a44c73d5@oleioq8ex4m1zx> Message-ID: <20030218010850.GA5858@dman.ddts.net> --SLDf9lqlvOQaIe6s Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Tue, Feb 18, 2003 at 01:43:17AM +0100, Ole Jensen wrote: |=20 | In Black Jack the value of the ACE depends on the sum of your cards | if the sum is lower than 21, the value of your ACE is 11 however if | the sum of your cards increase to more than 21(if ace counts for 11) | then your ACE drops to the value of one. This is part of the "business logic" of your program. | How would you define the value of ACE in python to the rules of Black Jac= k? As an instance of a class. I would make a "Card" class. Each Card has a face-value associated with it. "Ace" is one of those face-values. Simply create a constant (integer or string, it doesn't matter since it will never be seen outside your program) to differentiate them. =20 In the business logic, as you compute the player's total, you will assign a numeric "score" for use in computation. The score is not the same as the identification, so don't intermix the two. HTH, -D --=20 A perverse man stirs up dissension, and a gossip separates close friends. Proverbs 16:28 =20 http://dman.ddts.net/~dman/ --SLDf9lqlvOQaIe6s Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iEYEARECAAYFAj5Rh6IACgkQO8l8XBKTpRQZLwCfdrBdedEGKJ1FdoxX2tYgaCJl wg8AoI+jDTqVfETe9D5lqeRIcch6wlJJ =5Lez -----END PGP SIGNATURE----- --SLDf9lqlvOQaIe6s-- From dman@dman.ddts.net Mon Feb 17 20:16:01 2003 From: dman@dman.ddts.net (Derrick 'dman' Hudson) Date: Mon Feb 17 20:16:01 2003 Subject: [Tutor] Re: tabs or spaces (the endless debate!) In-Reply-To: <7497DCA1C240C042B28F6657ADFD8E0901F850E0@i2km11-ukbr.domain1.systemhost.net> References: <7497DCA1C240C042B28F6657ADFD8E0901F850E0@i2km11-ukbr.domain1.systemhost.net> Message-ID: <20030218011536.GB5858@dman.ddts.net> --IrhDeMKUP4DT/M7F Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable On Mon, Feb 17, 2003 at 01:30:30PM -0000, alan.gauld@bt.com wrote: | > Because if you write your code to wrap at 79 chars (which is a good=20 | > idea for readability) then whether a tab is 4 or 8 chars matters (and= =20 | > diff't environments use diff't sizes for tabs). |=20 | Absolutely. Also when you open code in an editor its not obvious=20 | whether the code is indented with tabs or spaces. Sometimes it is too painfully obvious. :-). In vim : set lcs=3Dtab:>- set list Then tabs will appear as a blue '>' for the first character it occupies followed by a blue '-' for each additional character the tab occupies. The "painful" part comes when trying to read some documentation where tabs are scattered throughout. Then I temporarily ":set nolist" to hide the tabs. As with certain other aspects of python, the limitations are only in your tool(s), not python itself. -D --=20 Commit to the Lord whatever you do, and your plans will succeed. Proverbs 16:3 =20 http://dman.ddts.net/~dman/ --IrhDeMKUP4DT/M7F Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iEYEARECAAYFAj5RiTgACgkQO8l8XBKTpRTENACgsC8cOTIjZQgW5/aGg1v6+OY8 BUoAn07KwbhxVPmkGvyuAMrS7Iv9Vv1S =df3/ -----END PGP SIGNATURE----- --IrhDeMKUP4DT/M7F-- From tim.one@comcast.net Mon Feb 17 22:16:02 2003 From: tim.one@comcast.net (Tim Peters) Date: Mon Feb 17 22:16:02 2003 Subject: [Tutor] How to solve it ... In-Reply-To: Message-ID: [Tim, on Gregor Lingl puzzle] > ... > Trying the simplest thing that could possibly work is often a good > start: generate all possible sequences composed of {D1, D2, P1, P2}, in > increasing order of length, and for each one see whether it solves all > initial states. The first one that does is "the answer". For fun, I'll include code for that here. Of all the refinements I discussed later, it only incorporates the observation that D1 and P1 are really the same operation: """ # 1 2 # 4 8 # D1 and P1 have the same effect, so ignore (arbitrarily) P1. code2masks = {"D1": (1, 2, 4, 8), "D2": (1+8, 2+4), "P2": (1+2, 4+8, 1+4, 2+8)} winners = 0, 15 # all off or all on class Finished(Exception): def __init__(self, prog): self.prog = prog def solves_one(prog, state): if state in winners: return True if not prog: return False code, prog = prog[:2], prog[2:] for mask in code2masks[code]: if not solves_one(prog, state ^ mask): return False return True states = range(2, 15) def solves_all(prog): for state in states: if not solves_one(prog, state): return False return True def extend(prog, depth, limit): if depth == limit: if solves_all(prog): raise Finished(prog) return for code in "D2", "P2", "D1": extend(prog + code, depth + 1, limit) limit = 0 try: while True: limit += 1 print "trying all programs of length", limit extend("", 0, limit) except Finished, f: print "shortest program solving all initial states:", f.prog """ There are two techniques here especially worth noting. First is that "generating all" of some class of structured object is very often most naturally coded via recursion. However, recursion is most naturally a depth-first process, and we're interested in finding the *shortest* "program" (sequence of D1, D2, P2 thingies) solving all initial states, and that's more naturally done with a breadth-first approach. The technique used above is a compromise called "iterative deepening": the programs are generated in a natural depth-first order, but the recursion isn't allowed to go deeper than the value of the "limit" argument. When generating all programs of length N, we do all the work we did to generate all programs of length N-1 all over again, so there's quite a bit of redundant work here. However, because the amount of work required grows exponentially in N no matter how it's programmed, this has little practical consequence. Do a Google search on iterative deepening to learn a lot more about search tradeoffs; iterative deepening is a simple idea that often works great. The other technique is simpler, raising an exception to "break out" of a chain of recursive calls. That's how the first shortest program found is communicated back to the main loop. This is a lot easier, and harder to screw up, than having recursive functions return some sort of "search status" result and then branching on that. Have fun! From alan.gauld@bt.com Tue Feb 18 03:20:01 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Tue Feb 18 03:20:01 2003 Subject: [Tutor] How do you define the value of ACE in black jack Message-ID: <7497DCA1C240C042B28F6657ADFD8E0974DAC4@i2km11-ukbr.domain1.systemhost.net> > How would you define the value of ACE in python to the rules of Black Jack? Keeping it simple, I'd do this: import random Jack = 10 Queen = 10 King = 10 ACE = 11 # need initial definition cards = ["dummy", ACE, 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King] firstcard = cards[random.randrange(1,14)] seccard = cards[random.randrange(1,14)] sum = firstcard + seccard # ACE definition if (firstcard == ACE or seccard == ACE) and sum > 21 : sum = sum - 10 ACE = 1 print "Card one:", firstcard, "\t", "Card two:", seccard, "\t", "Sum:", sum crd = ["three:", "four:", "five:"] print "do you want to:\n1 - hit \n2 - stand" hitstand = input(">>> ") j = 0 while hitstand == 1: newcard = cards[random.randrange(1,14)] sum = sum + newcard print "card "+crd[j], newcard, "\t", "\t", "sum", sum j = j + 1 print "do you want to:\n1 - hit \n2 - stand" hitstand = input(">>> ") End of code: > but where else can I place the definition of ACE after all the values used to define it > needs to have been stated! Hopefully my (untested!) modification helps. There are some other tricks we can play to make this easier, including using functions as you suggested, but try this approach first... Alan G. From shalehperry@attbi.com Tue Feb 18 03:42:05 2003 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Tue Feb 18 03:42:05 2003 Subject: randrange v. choice was Re: [Tutor] How do you define the value of ACE in black jack In-Reply-To: <7497DCA1C240C042B28F6657ADFD8E0974DAC4@i2km11-ukbr.domain1.systemhost.net> References: <7497DCA1C240C042B28F6657ADFD8E0974DAC4@i2km11-ukbr.domain1.systemhost.net> Message-ID: <200302180041.26544.shalehperry@attbi.com> On Tuesday 18 February 2003 00:18, alan.gauld@bt.com wrote: > > =09firstcard =3D cards[random.randrange(1,14)] > =09seccard =3D cards[random.randrange(1,14)] > =09sum =3D firstcard + seccard > out of curiosity why not use 'random.choice(cards)'? Just wondering if t= here=20 is some reason randrange() works better here. From magnus@thinkware.se Tue Feb 18 06:14:24 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Tue Feb 18 06:14:24 2003 Subject: [Tutor] How do you define the value of ACE in black jack In-Reply-To: <20030218010902.30392.26431.Mailman@mail.python.org> Message-ID: <5.1.0.14.0.20030218094440.02b5fea8@www.thinkware.se> Someone suggested a Card class, but whether the ace is 1 or 11 in black jack depends on the context, on the whole hand. So it's the hand of cards that needs to know the calculation rules, not the individual cards. It's a long time since I played BJ, but if I remember correctly, the rules are more advanced than ace having two possible values. For instance an ace and a 10 (K, Q, J or 10) is a black jack, which gives a bigger win than three sevens which is just 21. See for instance http://www.thefinerlife.com/games_library/blackjack_rules.htm To perform the calculations, it's enough to get a list of numerical values, say [11, 11] (for two aces). We might well have a hand class that contains the hand and performs the calculation, but it will also work well to keep the values in a simple list, and use a simple function to do the calculation. It could look a bit like this: def calcHandValue(hand): value = sum(hand) if value >= FAT and ACE_HIGH in hand: hand[hand.index(ACE_HIGH)] = ACE_LOW return sum(hand) With the lacking sum function and constants defined, this will enable something like: >>> h = [11, 11] >>> print h [11, 11] >>> print calcHandValue(h) 12 >>> print h [1, 11] We could also use list looking like this: [('Ace of Clubs', 1), ('Ace of Spades', 11)] or if you wish a Card class that can contain both the numeric value and the description, but as I said, the heart of the matter is in the hand of cards, not in a card itself. Back to the review... -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From Deirdre Hackett" This is a multi-part message in MIME format. ------=_NextPart_000_004C_01C2D760.FA3E14C0 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable ----- Original Message -----=20 From: Deirdre Hackett=20 To: jtodora@fast.net=20 Sent: Tuesday, February 18, 2003 3:17 PM Subject: BCD Ascii to a binary hex value Table BCD ASCII Binary value(Hex) value High byte Low Byte 30,000 75 30 22,500 57 E4 15,000 3A 98 7,500 1D 4C 00 00 00 - 7,500 E2 B4=20 - 15,000 C3 74 - 22,500 A8 1C - 30,000 8A D0 I can convert from the BCD ascii for the positive normally using binary = and for the negative numbers using twos complement but I do not know how = to convert from the binary value to the BCD ASCII just using just a pen = and paper as I want to write a program to convert them. Just thought you might give me some guidance if you can. Thanks, Deirdre Hackett ------=_NextPart_000_004C_01C2D760.FA3E14C0 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
 
----- Original Message -----=20
From: Deirdre=20 Hackett
Sent: Tuesday, February 18, 2003 3:17 PM
Subject: BCD Ascii to a binary hex value

Table
 
BCD ASCII    =    =20             =    =20     Binary value(Hex)
value    =    =20             =    =20     High byte       =20     Low Byte
30,000    =    =20             =    =20         75    =    =20             30
22,500    =    =20             =    =20         57    =    =20             E4
15,000    =    =20             =    =20         3A    =    =20             98
7,500          = ;            =             1= D          &nbs= p;        =20 4C
00          &n= bsp;           &nb= sp;           &nbs= p;    00   =20             =    =20 00
-=20 7,500           &n= bsp;           &nb= sp;        E2   &n= bsp;           &nb= sp;   =20 B4=20
-=20 15,000           &= nbsp;           &n= bsp;      C3     &= nbsp;           &n= bsp; =20 74
- = 22,500      =20             &= nbsp;          A8 =   =20             =    =20 1C
-=20 30,000           &= nbsp;           &n= bsp;      8A   =20             =    =20 D0
 
I can convert from the BCD ascii for = the positive=20 normally using binary and for the negative numbers using twos complement = but I=20 do not know how to convert from the binary value to the BCD ASCII just = using=20 just a pen and paper as I want to write a program to convert = them.
Just thought you might give me some = guidance if you=20 can.
Thanks,
Deirdre = Hackett
------=_NextPart_000_004C_01C2D760.FA3E14C0-- From glingl@aon.at Tue Feb 18 10:19:01 2003 From: glingl@aon.at (Gregor Lingl) Date: Tue Feb 18 10:19:01 2003 Subject: [Tutor] How to solve it ... References: Message-ID: <3E524F0A.4010104@aon.at> Tim Peters schrieb: >[Tim, on Gregor Lingl puzzle] > >>... >>Trying the simplest thing that could possibly work is often a good >>start: generate all possible sequences composed of {D1, D2, P1, P2}, in >>increasing order of length, and for each one see whether it solves all >>initial states. The first one that does is "the answer". >> Hello Tim! Many thanks for your replies to my "lock-puzzle"-question. The explanations of the first one was just what I hoped to get back from the list - but I must confess I was not sure if the problem was interesting enough, before I posted it. Now I'm glad, that I gave it a try! I had tried to find a solution, and what I arrived at worked, but was rather clumsy. When I read your solution, I was really enthusiastic about it. I consider it to be a real *Python jewel*. So what you gave to me, was not only an extrordinary lecture in programming in general but also specifically a perfect example of Python programming, exemplary in every respect: clear, concise, perfect style, elegant use of recursion, most efficient use of Python specific features ... Maybe these words are superfluous, as most of us won't expect anything else from you ;-) Nevertheless I wish to express, that it was most rewarding for me .... I reworked my solution a little in the light of your remarks - and I also took one or two ideas from your program - especially the use of a code-dictionary. I put this version below, just for comparison - although I know very well, that it will mainly serve to demonstrate, that I'm not playing in the same league ... Would you agree that I put your code along with some of your remarks on my Python-website, of course with the due credits? Regards, Gregor P.S: As far as I see, the line > > >states = range(2, 15) > > in your code should read: states = range(1, 15) =========================================== # Here my solution - IMO it suffers mainly from the # ditiction between "opsequences" and "codesequences" # Aufgabe aus Spektrum der Wissenschaft # vom Februar 2003 start = range(1,15) operations = ["D","P","S"] codes = { "S" : (1,2,4,8), "P" : (3,5,10,12), "D" : (6,9) } def cantor(sets, result = [[]]): """Cantorian set-product""" if sets == []: return result else: return cantor(sets[:-1],[[el]+tupl for el in sets[-1] for tupl in result]) def check(state,codeseq): "checks, if codeseq opens state" for code in codeseq: state = state ^ code if state in [0,15]: return 1 return 0 def checkfirst(opseq): # if this fails, it's not necessary to do the time-consuming construction # of the cantor-product of all the codeseqs belonging to this opseq, codeseq = [codes[op][0] for op in opseq] for state in start: if not check(state, codeseq): return 0 return 1 def checkall(opseq): codeseqs = cantor([codes[op] for op in opseq]) for state in start: for codeseq in codeseqs: if not check(state,codeseq): return 0 return 1 depth = 0 done = False while not done: depth += 1 print "Test sequences with %d elements ..." % depth opseqs = cantor([operations]*depth) for opseq in opseqs: if checkfirst(opseq): if checkall(opseq): print "Loesung:", "".join(opseq) done = True break From ramrom@earthling.net Tue Feb 18 11:33:01 2003 From: ramrom@earthling.net (Bob Gailer) Date: Tue Feb 18 11:33:01 2003 Subject: [Tutor] How to solve it ... In-Reply-To: <3E524F0A.4010104@aon.at> References: Message-ID: <5.2.0.9.0.20030218092937.01a59d68@66.28.54.253> --=======2B71A8C======= Content-Type: text/plain; x-avg-checked=avg-ok-2CCF425C; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit Your original request was "Find the shortest complete code which opens the door with certainty, regardless of the original position of the four switches." I submitted such a solution, but have had no comment back. Was I on the right track? What did you think of my solution? Bob Gailer mailto:ramrom@earthling.net 303 442 2625 --=======2B71A8C======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-2CCF425C Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.454 / Virus Database: 253 - Release Date: 2/10/2003 --=======2B71A8C=======-- From ramrom@earthling.net Tue Feb 18 11:35:01 2003 From: ramrom@earthling.net (Bob Gailer) Date: Tue Feb 18 11:35:01 2003 Subject: [Tutor] How to solve it ... Message-ID: <5.2.0.9.0.20030218093408.02f18008@66.28.54.253> --=======49167293======= Content-Type: text/plain; x-avg-checked=avg-ok-2CCF425C; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit BTW I arrived at my solution by analysis on paper, not by computation. Bob Gailer mailto:ramrom@earthling.net 303 442 2625 --=======49167293======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-2CCF425C Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.454 / Virus Database: 253 - Release Date: 2/10/2003 --=======49167293=======-- From tim@johnsons-web.com Tue Feb 18 11:54:02 2003 From: tim@johnsons-web.com (Tim Johnson) Date: Tue Feb 18 11:54:02 2003 Subject: [Tutor] List comprehension (Map) Example Message-ID: <20030218170004.GM1478@johnsons-web.com> Hello All: I could use some examples of using List Comprehensions. This is for casual research, so pointing me to example documentation would be sufficient. Thanks -- Tim Johnson http://www.alaska-internet-solutions.com http://www.johnsons-web.com From magnus@thinkware.se Tue Feb 18 13:37:05 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Tue Feb 18 13:37:05 2003 Subject: [Tutor] Re: BCD Ascii to a binary hex value In-Reply-To: <20030218170005.24317.49370.Mailman@mail.python.org> Message-ID: <5.1.0.14.0.20030218191050.02dcdd70@www.thinkware.se> At 12:00 2003-02-18 -0500, tutor-request@python.org wrote: >I can convert from the BCD ascii for the positive normally using binary = >and for the negative numbers using twos complement but I do not know how = >to convert from the binary value to the BCD ASCII just using just a pen = >and paper as I want to write a program to convert them. >Just thought you might give me some guidance if you can. If this is supposed to have anything to do with python I'd suggest using numeric types as the path. There are standard python ways of converting both to and from hexadecimal notation. As I say so often: look in the python library reference chapter 2. http://www.python.org/doc/current/lib/built-in-funcs.html http://www.python.org/doc/current/lib/typesseq-strings.html -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From tim.one@comcast.net Tue Feb 18 14:13:02 2003 From: tim.one@comcast.net (Tim Peters) Date: Tue Feb 18 14:13:02 2003 Subject: [Tutor] How to solve it ... In-Reply-To: <5.2.0.9.0.20030218092937.01a59d68@66.28.54.253> Message-ID: [Bob Gailer, to Gregor Lindl] > Your original request was "Find the shortest complete code which > opens the door with certainty, regardless of the original position of > the four switches." That appeared to be part of the translated problem statement. Gregor's question was How would you solve this with Python (- just for your amusement)? > I submitted such a solution, but have had no comment back. Was I on the > right track? What did you think of my solution? You got the same result as the Python program I posted, so I can testify that, right or wrong, they're on the same track . Up to D1=P1 equivalence (which you noted), there were no other codes of length <= 7 that solved the problem. The interest isn't really in solving the problem, though, it's in *how* the problem gets solved. From bobsmith327@hotmail.com Tue Feb 18 15:43:02 2003 From: bobsmith327@hotmail.com (bob smith) Date: Tue Feb 18 15:43:02 2003 Subject: [Tutor] Questions about Functions Message-ID: Hi. I’m learning Python and like it very much so far, but I have some questions when it comes to functions. Question #1 -------------- What’s wrong with passing a variable to a function that receives it with the same name? def func(value): print value # main value = 10 func(value) If “value” is a good, clear name for my variable, why do I have to pick a new name when I use it in a function? And if I do use a different variable name for the parameter, like: def func(val): print val Then, if func() calls another function and passes “val”, does this second, receiving function have to have yet another name for the parameter (like “v” or something)? Question #2 -------------- Is it considered bad programming to access (and only access) global variables in functions, thus treating them as global constants? def func(): print CONSTANT #main CONSTANT = 10 func() Since I can’t assign a new value to CONSTANT in func(), does this mean that Python encourages the use of global constants used like this? It seems like a good idea to me, (especially if CONSTANT is needed in other functions in the program) but you hear the mantra “don’t use global variables” so much that I’m not sure if this is considered poor programming. Question #3 -------------- If you know your program is not going to be imported (only run as a stand-alone program) do you ever need to consider having this kind of thing: if __name__ == “__main__”: main() _________________________________________________________________ Protect your PC - get McAfee.com VirusScan Online http://clinic.mcafee.com/clinic/ibuy/campaign.asp?cid=3963 From jeff@ccvcorp.com Tue Feb 18 16:20:07 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Tue Feb 18 16:20:07 2003 Subject: [Tutor] Questions about Functions References: Message-ID: <3E52A356.1030202@ccvcorp.com> bob smith wrote: > Hi. Im learning Python and like it very much so far, but I have some > questions when it comes to functions. > > Question #1 > -------------- > Whats wrong with passing a variable to a function that receives it > with the same name? The only problem here is that it's possible that you'll lose track of the fact that they are, in fact, two separate variables. You might, for instance, change 'value' in your function, and then be surprised by the fact that the global 'value' is not updated. But if it's clear in your mind that when you're inside a function, you're in a whole different world (well, different namespace), then there's no problem. (At least, no problem until someone *else* goes to modify your code and gets surprised by this...) But this is strictly a programmer-psychology issue, and not a technical issue. > Question #2 > -------------- > Is it considered bad programming to access (and only access) global > variables in functions, thus treating them as global constants? The problem here is that functions (ideally) should be able to operate identically in a variety of contexts, and thus functions should be as self-contained as possible. If your function relies on global constants, and then you have another module that needs the same function, you have to ensure that all the same global constants are set up in that other module. > Since I cant assign a new value to CONSTANT in func(), does this mean > that Python encourages the use of global constants used like this? You *can* actually assign a new value to CONSTANT -- except that it creates a new local variable that shadows your global constant, with potentially confusing results. > It seems like a good idea to me, (especially if CONSTANT is needed in > other functions in the program) but you hear the mantra dont use > global variables so much that Im not sure if this is considered poor > programming. Here's the rub -- using constants like this *is* a very useful thing, and sometimes it really is the best option. Certainly using global constants is a lot less hazardous than using global "normal" variables, and as you say, if the constant is needed in a wide variety of places, a global constant is probably better than a dozen local constants (which would be a nightmare to keep in sync if the value needs tweaked). In programs that are large enough to have this issue, I'll usually create a separate constants.py that does nothing but define these constants. Then, every other module that needs to use the constants can 'import constants; print constants.CONSTANT' or equivalent. This gives me the practical value of having global constants available, but still keeps them (relatively) isolated in their own playground. > Question #3 > -------------- > If you know your program is not going to be imported (only run as a > stand-alone program) do you ever need to consider having this kind of > thing: > > if __name__ == __main__: main() If you're absolutely positive that your script will never be used as a module somewhere else, then this isn't necessary. The catch is that it often happens that a function that you once thought would never be needed elsewhere will suddenly become a quick solution to a new problem elsewhere, and you'll find yourself wanting to import that "only ever stand-alone" program. The other point here is that this convention supports a design practice. When I'm writing a program, I mentally break the problem down into little pieces, and then I start writing a series of functions (or a set of classes) that'll solve each of those pieces. Once I have the low-level problems solved, I start tying those bits together with higher-level functions, until I have something like a main() function that solves the whole problem. So the 'if __name__ == __main__:' convention fits well with the way that I work. If I were to approach a problem with the thought of *not* using this convention, then I'd be tempted to write a much more linear program (as opposed to a small heirarchy of classes and functions). This is fine for very small scripts, usually, but becomes increasingly difficult to follow as the size of the program grows. And, of course, even very small programs have a tendency to grow in size and complexity... so it seems best to start off in the right direction to begin with. Hope this makes a few things more clear. Jeff Shannon Technician/Programmer Credit International From hall@ouhep1.nhn.ou.edu Tue Feb 18 16:31:01 2003 From: hall@ouhep1.nhn.ou.edu (Isaac Hall) Date: Tue Feb 18 16:31:01 2003 Subject: [Tutor] Questions about Functions In-Reply-To: Message-ID: Hi Bob, I *think* I know what you are trying to ask here, but stop me if I am off= =20 track with what you are thinking.... On Tue, 18 Feb 2003, bob smith wrote: > Hi. I=92m learning Python and like it very much so far, but I have som= e=20 > questions when it comes to functions. >=20 > Question #1 > -------------- > What=92s wrong with passing a variable to a function that receives it w= ith the=20 > same name? >=20 > def func(value): > print value >=20 > # main > value =3D 10 > func(value) There should be no problem with this...I tried it in the interpreter, and= =20 it turns out that there is no problem...here is what I did, just to=20 illustrate.=20 >>>def func(value): ... print value+1 >>>value=3D10 >>>func(value) 11 >>>print value 10 further we can do this too: >>>def func(value): ... value=3Dvalue+1 ... print value >>>func(value) 11 print value 10 >=20 > If =93value=94 is a good, clear name for my variable, why do I have to = pick a=20 > new name when I use it in a function? And if I do use a different vari= able=20 > name for the parameter, like: >=20 > def func(val): > print val >=20 > Then, if func() calls another function and passes =93val=94, does this = second,=20 > receiving function have to have yet another name for the parameter (lik= e =93v=94=20 > or something)? > So it appears to me that the answer to this question is that you can reus= e=20 the same name over and over and over in different functions. >=20 > Question #2 > -------------- > Is it considered bad programming to access (and only access) global=20 > variables in functions, thus treating them as global constants? Im really not sure, as I have never considered myself knowledgeable of=20 good programming practices. For what I do, physics, just making it work=20 is considered good programming. >=20 > def func(): > print CONSTANT >=20 > #main > CONSTANT =3D 10 > func() >=20 > Since I can=92t assign a new value to CONSTANT in func(), does this mea= n that=20 > Python encourages the use of global constants used like this? It seems= like=20 > a good idea to me, (especially if CONSTANT is needed in other functions= in=20 > the program) but you hear the mantra =93don=92t use global variables=94= so much=20 > that I=92m not sure if this is considered poor programming. > Like I said, in my line of work, if this works, and doesnt cause any funk= y=20 bugs to appear, then it is considered good programming...however others=20 probably differ with that opinion, but again, I only write code because I= =20 want to get the correct answer to whatever problem I am facing....most=20 other programmers have higher aspirations/motivations when they code.... as far as re-assigning a global variable in a function, that is possible=20 too...sort of... >>>def func(value): ... return value+1 >>>value=3D10 >>>value=3Dfunc(value) >>>print value 11=20 =20 >=20 > Question #3 > -------------- > If you know your program is not going to be imported (only run as a=20 > stand-alone program) do you ever need to consider having this kind of t= hing: >=20 > if __name__ =3D=3D =93__main__=94: main() Only if you ever want to test the program as a stand-alone thing...i.e.=20 before it is ever imported into anything. Hope this helps Ike >=20 >=20 >=20 >=20 >=20 >=20 > _________________________________________________________________ > Protect your PC - get McAfee.com VirusScan Online =20 > http://clinic.mcafee.com/clinic/ibuy/campaign.asp?cid=3D3963 >=20 >=20 > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor >=20 --=20 From dyoo@hkn.eecs.berkeley.edu Tue Feb 18 16:45:01 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Feb 18 16:45:01 2003 Subject: [Tutor] Questions about Functions In-Reply-To: Message-ID: > do you ever need to consider having this kind of thing: > > > > > if __name__ =3D=3D =93__main__=94: main() > > Only if you ever want to test the program as a stand-alone thing...i.e. > before it is ever imported into anything. Hi everyone, Another reason we might want to put that line, if __name__ =3D=3D "__main__": main() at the bottom of the file is because it gives us freedom to move around the actual "main" function definition anywhere we want, even to the top. That is, it allows us doing something like: ### import time def main(): print "What is today?" print getTime() def getTime(): print time.strftime("%Y-%M-%d") if __name__ =3D=3D '__main__': main() ### If we didn't have that "if __name__ =3D=3D '__main__'..." part, then we'll = be forced by timing / variable binding issues to delay writing out our main() until the end, until all the dependent functions are defined and known: ### import time def getTime(): print time.strftime("%Y-%M-%d") print "What is today?" print getTime() ### This second version is slightly shorter, but is less versatile: now that we've exposed our main program outside of a function, we now don't have much freedom to move the main function to the top of our file. That is, if we tried doing: ### ## buggy code import time print "What is today?" print getTime() def getTime(): print time.strftime("%Y-%M-%d") ### Python will give an error, because by the time we get to the fourth line or so, it still doesn't know about getTime() yet--- it has no idea that the getTime() definition is coming up, because it hasn't read that far yet. So using "'if __name__ =3D=3D '__main__'" isn't just for making it easier t= o run tests (although it's a major reason.) But another reason is because it lets us organize our main code, so that we're more free to move things around. Hope that helps! From roland.casselbrant@bonetmail.com Tue Feb 18 16:49:01 2003 From: roland.casselbrant@bonetmail.com (Roland Casselbrant) Date: Tue Feb 18 16:49:01 2003 Subject: [Tutor] Syntax error Message-ID: <3E52AA10.3090100@bonetmail.com> I=B4m trying to learn some basic programming with Python (started today)=20 but I allready getting problems thats seems strange to me. The following lines is getting Syntax errors and I can=B4t understand why= ? Someone please help me understand this: print stringD, efbh where stringD is a text string and efbh is: efbh =3D ((uppvarm/graddar*24) * (20-(dut)) print stringZ where stringZ is a text string mdff =3D (vvu/8760) where mdff is a variable and (vvu/8760) is the value Why are this lines syntax errors? I just don=B4t get it?! --=20 Roland Casselbrant =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D Seen it all, done it all, can't remember most of it =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D WWW: www.casselbrant.net E-mail: roland.casselbrant@bonetmail.com Mobile phone: +0046-(0)70-4785052 From glingl@aon.at Tue Feb 18 16:56:00 2003 From: glingl@aon.at (Gregor Lingl) Date: Tue Feb 18 16:56:00 2003 Subject: [Tutor] How to solve it ... References: Message-ID: <3E52ABC7.30609@aon.at> Tim Peters schrieb: >[Bob Gailer, to Gregor Lingl] > > >>Your original request was "Find the shortest complete code which >>opens the door with certainty, regardless of the original position of >>the four switches." >> >> > >That appeared to be part of the translated problem statement. Gregor's >question was > > How would you solve this with Python (- just for your amusement)? > > > >>I submitted such a solution, but have had no comment back. Was I on the >>right track? What did you think of my solution? >> >> > >You got the same result as the Python program I posted, so I can testify >that, right or wrong, they're on the same track . Up to D1=P1 >equivalence (which you noted), there were no other codes of length <= 7 that >solved the problem. The interest isn't really in solving the problem, >though, it's in *how* the problem gets solved. > > That's it! BTW, I also had found a solution on paper, before I started to program it. Maybe, I wasn't really sure, if I definitely had found the *shortest* solution.;-) So I would also be interested in Bob's paper-solution. You may find interesting remarks on this in the edu-sig - list, where I also posted the problem (with a different question) : http://mail.python.org/pipermail/edu-sig/2003-February/002720.html My interest in the problem comes from thinking about how to treat it with my students, 10th or 11th graders. Should I treat it as a mathematical or as a programming problem? Hence I did this lock-simulation, which may serve as a simple programming task as well as a tool for investigating the structure of the problem. However, up to now the thing already showed a lot of interesting facets. Thanks to all Gregor > > From csm120@comcast.net Tue Feb 18 17:21:02 2003 From: csm120@comcast.net (Casey) Date: Tue Feb 18 17:21:02 2003 Subject: [Tutor] python newbie Message-ID: <000f01c2d79b$df48ad20$0201a8c0@CSM120> This is a multi-part message in MIME format. --Boundary_(ID_D9QoHoMX2MPW3MIPu/95cg) Content-type: text/plain; charset=iso-8859-1 Content-transfer-encoding: 7BIT I'm very new to python, and programming in general. Are there any online documentation especially for beginners? > I've looked at python.org. Thanks > Casey --Boundary_(ID_D9QoHoMX2MPW3MIPu/95cg) Content-type: text/html; charset=iso-8859-1 Content-transfer-encoding: 7BIT
I'm very new to python, and programming in general.  Are there any online
 documentation especially for beginners?
> I've looked at python.org.
 Thanks

> Casey
--Boundary_(ID_D9QoHoMX2MPW3MIPu/95cg)-- From tim_one@email.msn.com Tue Feb 18 17:48:28 2003 From: tim_one@email.msn.com (Tim Peters) Date: Tue Feb 18 17:48:28 2003 Subject: [Tutor] tabs or spaces (the endless debate!) In-Reply-To: <83663899366.20030215161936@columbus.rr.com> Message-ID: [attribution lost] >> diff't environments use diff't sizes for tabs). [R. Alan Monroe] > So? It's purely cosmetic. The content remains true. Not so. If you set an editor to use hard tabs, it probably uses them everywhere, and then structured comments and string contents that are *intended* to "line up" across lines no longer do so unless viewed under a tool that uses exactly the same interpretation of hard tabs as was used by the author's tool at the time of creation. A tab can "mean" anything, and, for example, *usually* means "8 spaces" to Unix people but "4 spaces" to Windows people. It's common for printing and terminal display programs to have their own ideas for what "a tab means" too, independent of what you've talked your editor into believing. Some oddball programs even interpret tab characters as they were originally intended to be viewed: like the physical tab stops on a mechanical typewriter, representing fixed distances from the left margin. > Anyway, I don't think there's a single "right" answer to this > question. The Python library defines the standard for distributed Python code (4-space indents, no hard tabs anywhere in the file). > I have always used real tabs up until now, but I'm trying > spaces on my latest project just for comparison. :^) If it's a project for your own use, suit yourself. If you intend other people to edit it, or even look at the code, do them a favor by not forcing them them to guess what you think a tab means. From ramrom@earthling.net Tue Feb 18 18:09:25 2003 From: ramrom@earthling.net (Bob Gailer) Date: Tue Feb 18 18:09:25 2003 Subject: [Tutor] Syntax error In-Reply-To: <3E52AA10.3090100@bonetmail.com> Message-ID: <5.2.0.9.0.20030218160531.02f2f7b8@66.28.54.253> --=======33506613======= Content-Type: text/plain; x-avg-checked=avg-ok-2CCF425C; charset=iso-8859-1; format=flowed Content-Transfer-Encoding: quoted-printable At 10:48 PM 2/18/2003 +0100, Roland Casselbrant wrote: >The following lines is getting Syntax errors and I can=B4t understand why? Please copy the session and any associated program to the body of an e-mail= =20 so we can see exactly the sequence of operations and the error messages. Bob Gailer mailto:ramrom@earthling.net 303 442 2625 --=======33506613======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-2CCF425C Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.454 / Virus Database: 253 - Release Date: 2/10/2003 --=======33506613=======-- From alan.gauld@bt.com Tue Feb 18 18:39:01 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Tue Feb 18 18:39:01 2003 Subject: [Tutor] List comprehension (Map) Example Message-ID: <7497DCA1C240C042B28F6657ADFD8E0974DAC6@i2km11-ukbr.domain1.systemhost.net> > I could use some examples of using List Comprehensions. Have you checked the functional programming page of my web site? It includes comprehensions now as well as map, filter etc. There are several basic examples there. Alan G http://www.freenetpages.co.uk/hp/alan.gauld/tutfctnl.htm From ramrom@earthling.net Tue Feb 18 18:51:01 2003 From: ramrom@earthling.net (Bob Gailer) Date: Tue Feb 18 18:51:01 2003 Subject: [Tutor] How to solve it ... In-Reply-To: <3E52ABC7.30609@aon.at> References: Message-ID: <5.2.0.9.0.20030218161127.02f1f3f0@66.28.54.253> --=======24A4601======= Content-Type: text/plain; x-avg-checked=avg-ok-2CCF425C; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit At 10:55 PM 2/18/2003 +0100, Gregor Lingl wrote: So I would also be interested in Bob's paper-solution. 1 - I subdivided the 16 start states into 4 categories O - all 4 the same - lock is open T - 3 the same D - 2 the same along a diagonal P - 2 the same horizontal or vertical 2 - I observed that the effect of a particular code was the same on all members of a category, and listed the effects. Since this is a non-deterministic process, codes P1 and D1 had different effects on certain categories depending on which of the 2 was chosen. Effect here means that a code transforms a member of a category to a member of some category. 3 - I drew a state-transition graph showing each category and the transitions between categories triggered by the various codes. That's hard to reproduce in a text e-mail, and I don't have a scanner set up. Sorry. 4 - I then experimented with various codes on each successive starting configuration. I discarded codes that might make no useful change. In each case one code promotes the configuration to a new useful state. With P, D and T as the starting categories: P1 in all cases toggles to another category and P2 in many cases toggles to another category, so starting with these codes might leave you with no useful change. D2, applied to category D opens, and applied to P or T makes no change. With P and T as the new starting categories: P1 and D2 in all cases just toggle to another category. P2 applied to P either opens or goes to D. That is a useful change. P2 applied to T goes to T. With D and T as the new starting categories: P1 in all cases just toggles to other categories. D2 applied to D opens, applied to T goes to T. With T as the new starting category: D2 and P2 go to T. Not useful. P1 toggles to D or P. Useful. With P and D as the new starting categories: P1 just toggles to another category. D2 applied to D opens, and applied to P goes to P. With P as the new starting category: P1 just toggles to another category. P2 applied to P either opens or goes to D. With D as the new starting category: P1 just toggles to another category. D2 applied to D opens. Bob Gailer mailto:ramrom@earthling.net 303 442 2625 --=======24A4601======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-2CCF425C Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.454 / Virus Database: 253 - Release Date: 2/10/2003 --=======24A4601=======-- From roland.casselbrant@bonetmail.com Tue Feb 18 19:01:01 2003 From: roland.casselbrant@bonetmail.com (Roland Casselbrant) Date: Tue Feb 18 19:01:01 2003 Subject: [Fwd: Re: [Tutor] Syntax error] Message-ID: <3E52C91C.3050102@bonetmail.com> This is a multi-part message in MIME format. --------------080502040908000806090902 Content-Type: text/plain; charset=iso-8859-1; format=flowed Content-Transfer-Encoding: quoted-printable X-MIME-Autoconverted: from 8bit to quoted-printable by mail.bostream.com id h1J00WQw023150 HEre is the complete code: hhe =3D 5000.0 vvu =3D 5000.0 stringA =3D 'Nettoenergibehovet: ' stringB =3D 'Nettoenergibehov minus vattenuppvarmning: ' stringC =3D 'Kompenserat for elpannans verkningsgrad: ' stringD =3D 'Effektbehovet vid dimensionerande temperatur: ' stringE =3D 'Till detta tillkommer arsmedeleffekt f=F6r varmvattenuppvarm= ning: ' stringF =3D 'Dimensionerande effektbehov for flerbostadshuset i exemplet=20 blir da: ' stringZ =3D ' ' stringG =3D ' Effektbehov for eluppvarmt hus ' stringH =3D 'Program skrivet av Roland Casselbrant' stringI =3D '*************************************' stringJ =3D 'Efter gradkorrigering av varmebehovet har vi: ' stringK =3D 'Ett normalar blir elanvandningen f=F6r smahuset i exemplet=20 alltsa: ' print stringZ print stringZ print stringG print stringH print stringI print stringZ totel =3D input("Total elaanvandning per ar: [kWh] ") pannverk =3D input("Elpannans armedelverkningsgrad: [%] ") totyta =3D input("Total uppvarmd bostadsyta: [m2] ") byggar =3D input("Byggar: ") graddar =3D input("Graddagar aktuellt ar: ") gradnorm =3D input("Graddagar normalar: ") dut =3D input ("Dimensionerande utetemperatur: [grader Celsius] ") # F=F6rst m=E5ste man r=E4kna bort den del av f=F6rbrukningen # som inte =E4r klimatberoende # d.v.s. hush=E5llsel och varmvattenuppv=E4rmning. # Vi r=E4knar h=E4r med 5000 kWh hush=E5llsel och 5000 kWh # f=F6r varmvattenuppv=E4rmning. # Uppv=E4rmningsbehovet blir d=E5: print stringA, totel print stringZ nettoel =3D totel-vvu-hhe print stringB, nettoel print stringZ # Nu =E4r inte hela denna energim=E4ngd "nyttig" utan vi m=E5ste kompense= ra # f=F6r elpannans verkningsgrad. S=E5ledes =E4r nettoenergibehovet # f=F6r uppv=E4rmning: panna =3D pannverk/100.0 uppvarm =3D nettoel*panna print stringC, uppvarm print stringZ # Effektbehovet vid dimensionerande temperatur l=F6ser vi ut # fr=E5n ekvationen: efbh =3D ((uppvarm/graddar*24) * (20-(dut)) print stringD, efbh print stringZ # Till detta tillkommer =E5rsmedeleffekt f=F6r varmvattenuppv=E4rmning. mdff =3D (vvu/8760) print stringE, mdff print stringZ # Dimensionerande effektbehov f=F6r flerbostadshuset i exemplet blir d=E5= : deff =3D efbh+mdff print stringF, deff print stringZ # Graddagskorrigering av v=E4rmebehovet g=E5r till s=E5 att man tar # kvoten av graddagarna # f=F6r normal=E5r och graddagarna f=F6r aktuell period och multiplicerar # med det # klimatberoende nettoenergibehovet f=F6r uppv=E4rmning enligt f=F6ljande= : gradkorr =3D ((gradnorm/graddar)*uppvarm print stringJ, gradkorr print stringZ # Ett normal=E5r blir elanv=E4ndningen f=F6r sm=E5huset i exemplet allts=E5= : totalel =3D ((gradkorr/panna)+(vvu+hhe)) print stringK, totalel print stringZ EOF/roland.casselbrant@bonetmail.com -------- Original Message -------- Subject: Re: [Tutor] Syntax error Date: Tue, 18 Feb 2003 16:06:45 -0700 From: Bob Gailer To: roland.casselbrant@bonetmail.com, tutor@python.org At 10:48 PM 2/18/2003 +0100, Roland Casselbrant wrote: >The following lines is getting Syntax errors and I can=B4t understand w= hy? Please copy the session and any associated program to the body of an e-ma= il so we can see exactly the sequence of operations and the error messages. Bob Gailer mailto:ramrom@earthling.net 303 442 2625 --=20 Roland Casselbrant =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D Seen it all, done it all, can't remember most of it =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D WWW: www.casselbrant.net E-mail: roland.casselbrant@bonetmail.com Mobile phone: +0046-(0)70-4785052 -----BEGIN GEEK CODE BLOCK----- version: 3.12 GCM/CC/IT/O d-(++) s+:+ a C++++ UL+ P+ L+ E- W+++ N++ o K? w++++ O++ M- V+ PS+ PE++ Y+ PGP t--- 5-- X- R* tv++(+) b++ DI+ D G e* h---- r+++ y++++(+++++)>$ ------END GEEK CODE BLOCK------ E-mail: roland.casselbrant@bonetmail.com ? WWW: www.casselbrant.net ,=3D. (o o) ------------------------------------------------ooO--(_)--Ooo-------- I only eat food delivered by www.kummingarden.com .oooO ( ) Oooo. --------------------------------------------------\ (----( )------- This signature file may not be reproduced, \_) ) / in whole or in part, by any means, (_/ including but not limited to: Mechanical reprints, electronic storage or scanning, theatrical release, musical ballads, word of mouth, sign language, braille, pantomime, hetero- or asexual reproduction, genetic engineering, or inclusion in digital media. In the process of producing this e-mail=20 signature file, no apes, ratts, chaffinch, ''' bullys, snouts, CEOs, CIOs or cute pets (0 0) came to any harm or danger. +-----oOO----(_)----------+ | Casselbrant Web Factory | | "The Power-Tool | The only thing regarded worse | of Internet" | than spam mail is excessive +------------------oOO----+ signature files like this one. |__|__| || || Made with love and a editor. ooO Ooo =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D Gravity isn't MY fault--I voted for velcro! =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D --------------080502040908000806090902 Content-Type: text/plain; name="file:///C|/DOCUME%7E1/ROLAND%7E1/LOKALA%7E1/TEMP/nsmail-1.txt" Content-Disposition: inline; filename="file:///C|/DOCUME%7E1/ROLAND%7E1/LOKALA%7E1/TEMP/nsmail-1.txt" Content-Transfer-Encoding: 7bit --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.454 / Virus Database: 253 - Release Date: 2/10/2003 --------------080502040908000806090902-- From carroll@tjc.com Tue Feb 18 20:34:02 2003 From: carroll@tjc.com (Terry Carroll) Date: Tue Feb 18 20:34:02 2003 Subject: [Tutor] Learning Tkinter Message-ID: I'm just starting to play with Tkinter, and it's (as expected), a bit alien to me. Any tips on how to learn it? It strikes me that Tkinter is probably pretty easy and intuitive to someone who already knows Tcl/Tk, but I don't. I don't really want to learn Tcl. I've found what appears to be the only book dedicated to Tk under Python (John Grayson's "Python & Tkinter Programming"), and that looks like overkill for me. I just want to add some straightforward GUI stuff[1] to an existing program to make it more usable. Ideas? Fred Lundh's "An Introduction To Tkinter"[2] looks good, and I'd buy it in a heartbeat if it were a published book. Anyone have any opinions on Wesley Chun's "Core Python Programming"? It has a chapter on "GUI Programing with Tkinter," but only about 20 pages. [1] Well, not too straightfoward; it will involve output of Chinese characters in Unicode and input in Unicode, GB and Big5 encodings. Currently I'm doing the "I/O" by altering the Python source and hard-coding hex strings. [2] http://www.pythonware.com/library/index.htm -- Terry Carroll | "To have this rare opportunity Santa Clara, CA | is a rare opportunity." carroll@tjc.com | - Houston Rockets' Yao Ming, on being named Modell delendus est | starting center for the 2003 NBA All-Star Game From nicholas_wieland@yahoo.it Tue Feb 18 20:52:01 2003 From: nicholas_wieland@yahoo.it (Nicholas Wieland) Date: Tue Feb 18 20:52:01 2003 Subject: [Tutor] ASP parsing Message-ID: <20030218193112.GA1300@localhost> Hello everyone, does someone know of a simple way of parsing a scripting languaguage like ASP in Python ? I'm having a lot of troubles because it's embedded in HTML text, so I need to parse a text file line by line switching from HTML to ASP if I encounter a '<%'. Here is the code: while(1): line = source.readline() if(string.find(line, "\<%")): while(1): asp = source.readline() start = string.find(asp, "\"") end = string.rfind(asp, "\"") quote = asp[start+1 : end] if (len(quote) > 1): dest.write(asp[:start+1]) self.TxtSource.WriteText(quote) t_dlg = wxTextEntryDialog(self, 'Question', 'Caption', '') try: if t_dlg.ShowModal() == wxID_OK: answer = t_dlg.GetValue() dest.write(answer) finally: t_dlg.Destroy() self.TxtSource.Clear() dest.write(asp[end:]) else: dest.write(asp) if(string.rfind(asp, "\%>")): break if (line == ""): break As you can see I have two files open, a source file and a dest file: I read a line and if there's quoted text I rewrite the interesting part (the quoted one), otherwise the entire line. This doesn't work, it doesn't rewrite the lines correctly and the code is buggy and unreadble. I'd like to use a module like htmllib but how ? The code I must parse is *inside* the tags, so I can't use start_tag, end_tag etc. Help please :) From nicholas_wieland@yahoo.it Tue Feb 18 20:54:02 2003 From: nicholas_wieland@yahoo.it (Nicholas Wieland) Date: Tue Feb 18 20:54:02 2003 Subject: [Tutor] ASP processing Message-ID: <20030219015934.GA1782@localhost> Hello everyone, I'm trying to parse ASP embedded in HTML files in Python, for a little translator I'm going to use to speed the translation of a web site. My problem with ASP is that I must parse the text between <% and %>, so at the moment I can't understand how to use htmllib and derivates, because they handle start and end tags, not the multiline text *inside* a tag. Here is the code. It's quite unreadable and doesn't process the text correctly... while(1): line = source.readline() if(string.find(line, "\<%")): while(1): asp = source.readline() start = string.find(asp, "\"") end = string.rfind(asp, "\"") quote = asp[start+1 : end] if (len(quote) > 1): dest.write(asp[:start+1]) self.TxtSource.WriteText(quote) t_dlg = wxTextEntryDialog(self, 'Question', 'Caption', '') try: if t_dlg.ShowModal() == wxID_OK: answer = t_dlg.GetValue() dest.write(answer) finally: t_dlg.Destroy() self.TxtSource.Clear() dest.write(asp[end:]) else: dest.write(asp) if(string.rfind(asp, "\%>")): break if (line == ""): break As you can see it's far away from being perfect, so I need suggestion. I'd like to use a module instead of writing all the parser... do I have to use something like sgmllib ? TIA, Nicholas From nicholas_wieland@yahoo.it Tue Feb 18 20:57:02 2003 From: nicholas_wieland@yahoo.it (Nicholas Wieland) Date: Tue Feb 18 20:57:02 2003 Subject: [Tutor] ASP parsing In-Reply-To: <20030218193112.GA1300@localhost>; from nicholas_wieland@yahoo.it on mar, feb 18, 2003 at 20:31:12 +0100 References: <20030218193112.GA1300@localhost> Message-ID: <20030219020326.GA1838@localhost> On 2003.02.18 20:31 Nicholas Wieland wrote: > snip > Err... sorry for the double message... :) Nicholas From tbrauch@mindless.com Tue Feb 18 21:12:05 2003 From: tbrauch@mindless.com (Timothy M. Brauch) Date: Tue Feb 18 21:12:05 2003 Subject: [Tutor] python and cron Message-ID: <001801c2d7bc$1ad0a4e0$6600a8c0@tbrauch> I am having a problem, and I'm not sure if it is with Python or cron. I have a dynamic IP address for my home computer. Every time I connect, I get a new IP. My connection is not the best, and sometimes I am only connected for an hour, sometimes a day. My machine automatically reconnects, so it's not a big deal. However, I would like to know my IP so I can ssh or ftp. I wrote a small Python script to check my IP. I would like for this script to run every hour. I thought a cron job would be perfect, but it does not seem to work. I checked my log and there are no errors and I don't get any errors emailed to me. The script works fine from command line. Here is part of my code: -------------------------------------------------------------- #! /usr/bin/python import urllib, ftplib, re, time ##Get the IP address from the router: source = urllib.urlopen('http://192.168.xxx.xxx/st_devic.html') info = source.read() source.close ##Clean up any HTML coding data = re.sub('<.*>| ','',info).split() ##The IP address is in field 29 address = data[29] ##here is the html formatting stuff for the published webpage. ##Write the formatted stuff to a file formatted = open('ip.html', 'w') formatted.write(html) formatted.close() ##Open the file and ftp it so I someone can get my IP new_file = open('ip.html', 'r') ftp = ftplib.FTP('ftp.domain.com','login','password') ftp.cwd('private') ftp.storbinary('STOR index.html', new_file) ftp.quit() new_file.close() ----------------------------------------------------------------- Here is the entry from crontab: ----------------------------------------------------------------- 0 * * * * /var/ftp/getipaddress.py ----------------------------------------------------------------- All of this is owned and run by root, so it shouldn't be permissions. Can someone offer some help? - Tim From john@hazen.net Tue Feb 18 21:30:02 2003 From: john@hazen.net (John Hazen) Date: Tue Feb 18 21:30:02 2003 Subject: [Tutor] python and cron In-Reply-To: <001801c2d7bc$1ad0a4e0$6600a8c0@tbrauch> Message-ID: On Tue, 18 Feb 2003, Timothy M. Brauch wrote: > I checked my log and there are no errors and I don't get any > errors emailed to me. The script works fine from command line. > > Here is part of my code: > -------------------------------------------------------------- > #! /usr/bin/python ----^ Hmmm. I don't think that space should be there. When you invoke from the command line, are you typing "python getipaddress.py" or "./getipaddress.py"? If the latter works, then it's probably a cron issue. > Here is the entry from crontab: > ----------------------------------------------------------------- > 0 * * * * /var/ftp/getipaddress.py > ----------------------------------------------------------------- That looks fine. If you edited the crontab directly (using vi instead of "crontab -e"), you'll need to HUP crond. HTH- John -- John Hazen john@hazen.net eFax: 801.697.4349 ---------------------------------------------------------------------- "Something is about to happen. Something peculiar is about to happen any moment." -- "James and the Giant Peach" From bobsmith327@hotmail.com Tue Feb 18 22:20:02 2003 From: bobsmith327@hotmail.com (bob smith) Date: Tue Feb 18 22:20:02 2003 Subject: [Tutor] Questions about Functions Message-ID: Thank you Jeff, Ike and Danny. I appreciate all of your quick responses and great help. I'm sure I'll be back with more questions soon. Bob >From: "Jeff Shannon" >To: tutor@python.org >CC: bob smith >Subject: Re: [Tutor] Questions about Functions >Date: Tue, 18 Feb 2003 13:19:18 -0800 > > >bob smith wrote: > >>Hi. Im learning Python and like it very much so far, but I have some >>questions when it comes to functions. >> >>Question #1 >>-------------- >>Whats wrong with passing a variable to a function that receives it with >>the same name? > > >The only problem here is that it's possible that you'll lose track of the >fact that they are, in fact, two separate variables. You might, for >instance, change 'value' in your function, and then be surprised by the >fact that the global 'value' is not updated. But if it's clear in your mind >that when you're inside a function, you're in a whole different world >(well, different namespace), then there's no problem. (At least, no problem >until someone *else* goes to modify your code and gets surprised by >this...) But this is strictly a programmer-psychology issue, and not a >technical issue. > >>Question #2 >>-------------- >>Is it considered bad programming to access (and only access) global >>variables in functions, thus treating them as global constants? > > >The problem here is that functions (ideally) should be able to operate >identically in a variety of contexts, and thus functions should be as >self-contained as possible. If your function relies on global constants, >and then you have another module that needs the same function, you have to >ensure that all the same global constants are set up in that other module. > >>Since I cant assign a new value to CONSTANT in func(), does this mean >>that Python encourages the use of global constants used like this? > > >You *can* actually assign a new value to CONSTANT -- except that it creates >a new local variable that shadows your global constant, with potentially >confusing results. > >>It seems like a good idea to me, (especially if CONSTANT is needed in >>other functions in the program) but you hear the mantra dont use global >>variables so much that Im not sure if this is considered poor >>programming. > > >Here's the rub -- using constants like this *is* a very useful thing, and >sometimes it really is the best option. Certainly using global constants is >a lot less hazardous than using global "normal" variables, and as you say, >if the constant is needed in a wide variety of places, a global constant is >probably better than a dozen local constants (which would be a nightmare to >keep in sync if the value needs tweaked). In programs that are large enough >to have this issue, I'll usually create a separate constants.py that does >nothing but define these constants. Then, every other module that needs to >use the constants can 'import constants; print constants.CONSTANT' or >equivalent. This gives me the practical value of having global constants >available, but still keeps them (relatively) isolated in their own >playground. > >>Question #3 >>-------------- >>If you know your program is not going to be imported (only run as a >>stand-alone program) do you ever need to consider having this kind of >>thing: >> >>if __name__ == __main__: main() > > >If you're absolutely positive that your script will never be used as a >module somewhere else, then this isn't necessary. The catch is that it >often happens that a function that you once thought would never be needed >elsewhere will suddenly become a quick solution to a new problem elsewhere, >and you'll find yourself wanting to import that "only ever stand-alone" >program. > >The other point here is that this convention supports a design practice. >When I'm writing a program, I mentally break the problem down into little >pieces, and then I start writing a series of functions (or a set of >classes) that'll solve each of those pieces. Once I have the low-level >problems solved, I start tying those bits together with higher-level >functions, until I have something like a main() function that solves the >whole problem. So the 'if __name__ == __main__:' convention fits well >with the way that I work. If I were to approach a problem with the thought >of *not* using this convention, then I'd be tempted to write a much more >linear program (as opposed to a small heirarchy of classes and functions). >This is fine for very small scripts, usually, but becomes increasingly >difficult to follow as the size of the program grows. And, of course, even >very small programs have a tendency to grow in size and complexity... so it >seems best to start off in the right direction to begin with. > >Hope this makes a few things more clear. > >Jeff Shannon >Technician/Programmer >Credit International > > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor _________________________________________________________________ MSN 8 helps eliminate e-mail viruses. Get 2 months FREE*. http://join.msn.com/?page=features/virus From ramrom@earthling.net Tue Feb 18 22:23:03 2003 From: ramrom@earthling.net (Bob Gailer) Date: Tue Feb 18 22:23:03 2003 Subject: [Fwd: Re: [Tutor] Syntax error] In-Reply-To: <3E52C91C.3050102@bonetmail.com> Message-ID: <5.2.0.9.0.20030218201120.02f716e8@66.28.54.253> --=======68457673======= Content-Type: text/plain; x-avg-checked=avg-ok-2CCF425C; charset=iso-8859-1; format=flowed Content-Transfer-Encoding: quoted-printable These 2 lines have unbalanced parentheses: efbh =3D ((uppvarm/graddar*24) * (20-(dut)) gradkorr =3D ((gradnorm/graddar)*uppvarm Fix them and things should be OK. For future reference, its important to distinguish between compile errors=20 and execution errors. These are compile errors; they appeared before any=20 input was requested or output generated. The thing that makes it hard to find this kind of problem is that there's=20 an extra left parentheses which causes Python to expect more lines that=20 will eventually provide the closing parenthesis. When the following line=20 fails to do that, and the combination of the 2 lines is in error, it=20 reports the problem as having to do with the 2nd line. Notice what happens= =20 when you enter the 2 lines interactively: >>> gradkorr =3D ((gradnorm/graddar)*uppvarm ## extra left ( ... print stringJ, gradkorr ## ... tells=20 you its waiting for more File "", line 2 print stringJ, gradkorr ## print=20 following uppvarm is incorrect. ^ SyntaxError: invalid syntax So if the line reported looks OK, go back in the file and look at the=20 previous line(s). An IDE such as PythonWin is helpful here because it=20 highlights pairs of () [] {} "" '' etc. and makes it easy to spot extra=20 delimiters. At 01:00 AM 2/19/2003 +0100, Roland Casselbrant wrote: >HEre is the complete code: > >hhe =3D 5000.0 >vvu =3D 5000.0 >stringA =3D 'Nettoenergibehovet: ' >stringB =3D 'Nettoenergibehov minus vattenuppvarmning: ' >stringC =3D 'Kompenserat for elpannans verkningsgrad: ' >stringD =3D 'Effektbehovet vid dimensionerande temperatur: ' >stringE =3D 'Till detta tillkommer arsmedeleffekt f=F6r= varmvattenuppvarmning: ' >stringF =3D 'Dimensionerande effektbehov for flerbostadshuset i exemplet=20 >blir da: ' >stringZ =3D ' ' >stringG =3D ' Effektbehov for eluppvarmt hus ' >stringH =3D 'Program skrivet av Roland Casselbrant' >stringI =3D '*************************************' >stringJ =3D 'Efter gradkorrigering av varmebehovet har vi: ' >stringK =3D 'Ett normalar blir elanvandningen f=F6r smahuset i exemplet= alltsa: ' > > >print stringZ >print stringZ >print stringG >print stringH >print stringI >print stringZ > >totel =3D input("Total elaanvandning per ar: [kWh] ") >pannverk =3D input("Elpannans armedelverkningsgrad: [%] ") >totyta =3D input("Total uppvarmd bostadsyta: [m2] ") >byggar =3D input("Byggar: ") >graddar =3D input("Graddagar aktuellt ar: ") >gradnorm =3D input("Graddagar normalar: ") >dut =3D input ("Dimensionerande utetemperatur: [grader Celsius] ") > ># F=F6rst m=E5ste man r=E4kna bort den del av f=F6rbrukningen ># som inte =E4r klimatberoende ># d.v.s. hush=E5llsel och varmvattenuppv=E4rmning. ># Vi r=E4knar h=E4r med 5000 kWh hush=E5llsel och 5000 kWh ># f=F6r varmvattenuppv=E4rmning. ># Uppv=E4rmningsbehovet blir d=E5: > >print stringA, totel >print stringZ > >nettoel =3D totel-vvu-hhe > >print stringB, nettoel >print stringZ > ># Nu =E4r inte hela denna energim=E4ngd "nyttig" utan vi m=E5ste kompensera ># f=F6r elpannans verkningsgrad. S=E5ledes =E4r nettoenergibehovet ># f=F6r uppv=E4rmning: > >panna =3D pannverk/100.0 >uppvarm =3D nettoel*panna > >print stringC, uppvarm >print stringZ > ># Effektbehovet vid dimensionerande temperatur l=F6ser vi ut ># fr=E5n ekvationen: > >efbh =3D ((uppvarm/graddar*24) * (20-(dut)) > >print stringD, efbh >print stringZ > ># Till detta tillkommer =E5rsmedeleffekt f=F6r varmvattenuppv=E4rmning. > >mdff =3D (vvu/8760) > >print stringE, mdff >print stringZ > ># Dimensionerande effektbehov f=F6r flerbostadshuset i exemplet blir d=E5: > >deff =3D efbh+mdff > >print stringF, deff >print stringZ > ># Graddagskorrigering av v=E4rmebehovet g=E5r till s=E5 att man tar ># kvoten av graddagarna ># f=F6r normal=E5r och graddagarna f=F6r aktuell period och multiplicerar ># med det ># klimatberoende nettoenergibehovet f=F6r uppv=E4rmning enligt f=F6ljande: > >gradkorr =3D ((gradnorm/graddar)*uppvarm > >print stringJ, gradkorr >print stringZ > ># Ett normal=E5r blir elanv=E4ndningen f=F6r sm=E5huset i exemplet allts=E5= : > >totalel =3D ((gradkorr/panna)+(vvu+hhe)) > >print stringK, totalel >print stringZ > > >EOF/roland.casselbrant@bonetmail.com > > > >-------- Original Message -------- >Subject: Re: [Tutor] Syntax error >Date: Tue, 18 Feb 2003 16:06:45 -0700 >From: Bob Gailer >To: roland.casselbrant@bonetmail.com, tutor@python.org > >At 10:48 PM 2/18/2003 +0100, Roland Casselbrant wrote: > >The following lines is getting Syntax errors and I can=B4t understand= why? > >Please copy the session and any associated program to the body of an e-mail >so we can see exactly the sequence of operations and the error messages. > >Bob Gailer >mailto:ramrom@earthling.net >303 442 2625 > > >-- >Roland Casselbrant > > >=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D > Seen it all, done it all, can't remember most of it >=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D > >WWW: www.casselbrant.net >E-mail: roland.casselbrant@bonetmail.com >Mobile phone: +0046-(0)70-4785052 > > >-----BEGIN GEEK CODE BLOCK----- >version: 3.12 >GCM/CC/IT/O d-(++) s+:+ a C++++ UL+ P+ L+ E- W+++ N++ o K? w++++ >O++ M- V+ PS+ PE++ Y+ PGP t--- 5-- X- R* tv++(+) b++ DI+ D G e* >h---- r+++ y++++(+++++)>$ >------END GEEK CODE BLOCK------ > > > >E-mail: roland.casselbrant@bonetmail.com ? >WWW: www.casselbrant.net ,=3D. > (o o) >------------------------------------------------ooO--(_)--Ooo-------- > > > I only eat food delivered by www.kummingarden.com > > .oooO > ( ) Oooo. >--------------------------------------------------\ (----( )------- >This signature file may not be reproduced, \_) ) / >in whole or in part, by any means, (_/ >including but not limited to: >Mechanical reprints, electronic storage or scanning, theatrical release, >musical ballads, word of mouth, sign language, braille, pantomime, >hetero- or asexual reproduction, genetic engineering, or inclusion in >digital media. > In the process of producing this e-mail > signature file, no apes, ratts, chaffinch, > ''' bullys, snouts, CEOs, CIOs or cute pets > (0 0) came to any harm or danger. > +-----oOO----(_)----------+ > | Casselbrant Web Factory | > | "The Power-Tool | The only thing regarded worse > | of Internet" | than spam mail is excessive > +------------------oOO----+ signature files like this one. > |__|__| > || || Made with love and a editor. > ooO Ooo > >=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D > Gravity isn't MY fault--I voted for velcro! >=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D > > > > >--- >Outgoing mail is certified Virus Free. >Checked by AVG anti-virus system (http://www.grisoft.com). >Version: 6.0.454 / Virus Database: 253 - Release Date: 2/10/2003 > > > >--- >Incoming mail is certified Virus Free. >Checked by AVG anti-virus system (http://www.grisoft.com). >Version: 6.0.454 / Virus Database: 253 - Release Date: 2/10/2003 Bob Gailer mailto:ramrom@earthling.net 303 442 2625 --=======68457673======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-2CCF425C Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.454 / Virus Database: 253 - Release Date: 2/10/2003 --=======68457673=======-- From R. Alan Monroe" Is there a special backslash code I can use in a print statement to move the cursor back to beginning of the line, to keep printing on the same line over and over? I tried "\r" but that didn't work. It seems like this has come up before but I searched my mail archives for "carriage" "beginning" "return" etc. and couldn't find it. Alan From carroll@tjc.com Tue Feb 18 23:41:04 2003 From: carroll@tjc.com (Terry Carroll) Date: Tue Feb 18 23:41:04 2003 Subject: [Tutor] weakref module (was: fibonacci [caching] In-Reply-To: Message-ID: On Fri, 14 Feb 2003, Danny Yoo wrote: > import weakref What does this do, in this program? I've read the docs on weakref and, while I admit I don't completely get it, I don't see what it does in this fibonacci code. The program (seems to) work without it, too. -- Terry Carroll | "To have this rare opportunity Santa Clara, CA | is a rare opportunity." carroll@tjc.com | - Houston Rockets' Yao Ming, on being named Modell delendus est | starting center for the 2003 NBA All-Star Game From erikprice@mac.com Tue Feb 18 23:55:17 2003 From: erikprice@mac.com (Erik Price) Date: Tue Feb 18 23:55:17 2003 Subject: [Tutor] Questions about Functions In-Reply-To: <3E52A356.1030202@ccvcorp.com> Message-ID: <48DDE3CB-43C8-11D7-8D0E-00039351FE6A@mac.com> On Tuesday, February 18, 2003, at 04:19 PM, Jeff Shannon wrote: > The other point here is that this convention supports a design=20 > practice. When I'm writing a program, I mentally break the problem=20 > down into little pieces, and then I start writing a series of=20 > functions (or a set of classes) that'll solve each of those pieces.=20 > Once I have the low-level problems solved, I start tying those bits=20 > together with higher-level functions, until I have something like a=20 > main() function that solves the whole problem. So the 'if __name__ =3D=3D= =20 > =1C__main__=1D:' convention fits well with the way that I work. If I = were=20 > to approach a problem with the thought of *not* using this convention,=20= > then I'd be tempted to write a much more linear program (as opposed to=20= > a small heirarchy of classes and functions). This is fine for very=20 > small scripts, usually, but becomes increasingly difficult to follow=20= > as the size of the program grows. And, of course, even very small=20 > programs have a tendency to grow in size and complexity... so it seems=20= > best to start off in the right direction to begin with. Yes, this here is very good advice. Force yourself to write your=20 program as chunkily as possible without going to an extreme, and you=20 will find that you are able to reuse your chunks throughout the=20 program. Also this is a good habit to get into if you ever decide to=20 pursue object oriented programming, since dividing everything up into=20 logical chunks (objects) is the main idea. Erik --=20 Erik Price email: erikprice@mac.com jabber: erikprice@jabber.org From erikprice@mac.com Wed Feb 19 00:00:04 2003 From: erikprice@mac.com (Erik Price) Date: Wed Feb 19 00:00:04 2003 Subject: [Tutor] List comprehension (Map) Example In-Reply-To: <7497DCA1C240C042B28F6657ADFD8E0974DAC6@i2km11-ukbr.domain1.systemhost.net> Message-ID: <9FDAA534-43C8-11D7-8D0E-00039351FE6A@mac.com> On Tuesday, February 18, 2003, at 06:37 PM, alan.gauld@bt.com wrote: >> I could use some examples of using List Comprehensions. > > Have you checked the functional programming page of my web site? > It includes comprehensions now as well as map, filter etc. > There are several basic examples there. > > Alan G > http://www.freenetpages.co.uk/hp/alan.gauld/tutfctnl.htm I went to check it out but the connection was refused. Erik -- Erik Price email: erikprice@mac.com jabber: erikprice@jabber.org From dyoo@hkn.eecs.berkeley.edu Wed Feb 19 00:15:02 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Feb 19 00:15:02 2003 Subject: [Tutor] weakref module (was: fibonacci [caching] In-Reply-To: Message-ID: On Tue, 18 Feb 2003, Terry Carroll wrote: > On Fri, 14 Feb 2003, Danny Yoo wrote: > > > import weakref > > What does this do, in this program? I've read the docs on weakref and, > while I admit I don't completely get it, I don't see what it does in > this fibonacci code. The program (seems to) work without it, too. Absolutely nothing. *grin* I goofed and was about to do some experiments with the "weak references" module (weakref), and when I cut and paste, I accidently pasted that module import in too. (I was planning to use it with the fibonacci cache, but then thought that it might just complicate matters... for me. *grin*) Talk to you later! From dyoo@hkn.eecs.berkeley.edu Wed Feb 19 00:19:01 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Feb 19 00:19:01 2003 Subject: [Tutor] List comprehension (Map) Example In-Reply-To: <9FDAA534-43C8-11D7-8D0E-00039351FE6A@mac.com> Message-ID: On Wed, 19 Feb 2003, Erik Price wrote: > > On Tuesday, February 18, 2003, at 06:37 PM, alan.gauld@bt.com wrote: > > >> I could use some examples of using List Comprehensions. > > > > Have you checked the functional programming page of my web site? It > > includes comprehensions now as well as map, filter etc. There are > > several basic examples there. > > > > Alan G > > http://www.freenetpages.co.uk/hp/alan.gauld/tutfctnl.htm > > I went to check it out but the connection was refused. Hi Alan, I'm seeing the same connection refused behavior on my end. Odd... Erik, there's a mirror of "Learning to Program" on Alan's other site here: http://www.crosswinds.net/~agauld/ I'm not quite sure how recent its been updated, but it should be usable till his main page comes back up. Good luck! From dyoo@hkn.eecs.berkeley.edu Wed Feb 19 00:37:01 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Feb 19 00:37:01 2003 Subject: [Tutor] ASP parsing In-Reply-To: <20030218193112.GA1300@localhost> Message-ID: On Tue, 18 Feb 2003, Nicholas Wieland wrote: > does someone know of a simple way of parsing a scripting > languaguage like ASP in Python ? I'm having a lot of troubles because > it's embedded in HTML text, so I need to parse a text file line by line > switching from HTML to ASP if I encounter a '<%'. Hi Nicholas, I took a look at the code; I see that there's a bit of wxPython graphical inteface code intermingled with the ASP parsing. You might want to separate the two from each other, so that it's easier to test the parsing code without having to invoke the GUI interface. I see that the 'source' file is full of lines that may or may not contain the '<% [asp code here...] %>' ASP chunks. For simplicity, you may want to try the 're' regular expression module; it's especially useful for breaking text into chunks for code. For example: ### >>> pattern = re.compile(r"""(<% ### The leading ASP tag start ... .*? ### followed by a bunch of ... ### character, matching minimally, ... %> ### with the ASP terminator. ... )""", re.DOTALL | re.VERBOSE) >>> pattern.split(""" ... This is a test <% yes it is %> ... <% oh ... this is ... another test %> ... ok, I'm done""") ['\nThis is a test ', '<% yes it is %>', '\n', '<% oh\n this is\n another test %>', "\nok, I'm done"] ### And now it should be much easier to process each list element, because all our parsing is done: each list element is either normal, or an ASP chunk. If you're curious to learn more about regular expressions, you may find A.M. Kuchling's tutorial on regular expressions useful: http://www.amk.ca/python/howto/regex/ This process of "chunking" our data is also known as "lexing". For lexing a piece of text, regular expressions can be powerful and versatile tools. Hope this helps! From glingl@aon.at Wed Feb 19 02:53:01 2003 From: glingl@aon.at (Gregor Lingl) Date: Wed Feb 19 02:53:01 2003 Subject: [Tutor] python newbie References: <000f01c2d79b$df48ad20$0201a8c0@CSM120> Message-ID: <3E5337ED.8080607@aon.at> Casey schrieb: > I'm very new to python, and programming in general. Are there any online > documentation especially for beginners? > > I've looked at python.org. Have you also looked at the link to Python for Beginners - *start here if you're new to programming* on the starting page, which links you to http://www.python.org/doc/Newbies.html There are more than 10 links to oline-tutorials, and others to books etc. Regards, Gregor > > Thanks > > > Casey From nicholas_wieland@yahoo.it Wed Feb 19 02:54:23 2003 From: nicholas_wieland@yahoo.it (Nicholas Wieland) Date: Wed Feb 19 02:54:23 2003 Subject: [Tutor] ASP parsing In-Reply-To: ; from dyoo@hkn.eecs.berkeley.edu on mer, feb 19, 2003 at 06:36:50 +0100 References: Message-ID: <20030219075935.GA1146@localhost> On 2003.02.19 06:36 Danny Yoo wrote: > ... > > I see that the 'source' file is full of lines that may or may not > contain the '<% [asp code here...] %>' ASP chunks. For simplicity, > you may > want to try the 're' regular expression module; it's especially > useful for > breaking text into chunks for code. > > For example: > > ### > >>> pattern = re.compile(r"""(<% ### The leading ASP tag > start > ... .*? ### followed by a bunch of > ... ### character, matching > minimally, > ... %> ### with the ASP terminator. > ... )""", re.DOTALL | re.VERBOSE) > >>> pattern.split(""" > ... This is a test <% yes it is %> > ... <% oh > ... this is > ... another test %> > ... ok, I'm done""") > ['\nThis is a test ', > '<% yes it is %>', > '\n', > '<% oh\n this is\n another test %>', > "\nok, I'm done"] > ### > > And now it should be much easier to process each list element, because > all our parsing is done: each list element is either normal, or an ASP > chunk. The re module was my first approach to the problem, but I've chosen the other one because, as you can see, I rewrite the content of the file in a temporary one with all the modifications I've done: it seems to me that parsing just a line is much more simple than parsing all the text and then doing it another time for the quoted one, becaus I've got *a lot* of ASP lines, often with a really unclear structure (i.e. <%ASP%>html<%ASP%>html<%ASP%>). Am I missing something ? Do you think that using file.readlines(), separating ASP to HTML, then parsing the ASP part and the HTML part is better then implementing a parser line by line ? I'll follow you're suggestion for GUI code of course, thank you very much. Nicholas From glingl@aon.at Wed Feb 19 02:57:02 2003 From: glingl@aon.at (Gregor Lingl) Date: Wed Feb 19 02:57:02 2003 Subject: [Tutor] Learning Tkinter References: Message-ID: <3E5338EC.30307@aon.at> Terry Carroll schrieb: >I'm just starting to play with Tkinter, and it's (as expected), a bit >alien to me. Any tips on how to learn it? > >It strikes me that Tkinter is probably pretty easy and intuitive to >someone who already knows Tcl/Tk, but I don't. I don't really want to >learn Tcl. > >I've found what appears to be the only book dedicated to Tk under Python >(John Grayson's "Python & Tkinter Programming"), and that looks like >overkill for me. I just want to add some straightforward GUI stuff[1] to >an existing program to make it more usable. > >Ideas? > Try "Thinking in Tkinter", which you can find here: http://home.att.net/~stephen_ferg/thinking_in_tkinter/index.html Bryce Embry has also six nice introduvtory lessons on Tkinter: http://bembry.org/tech/python/index.php Both ressources can be downloaded as a single file HTH, Gregor > >Fred Lundh's "An Introduction To Tkinter"[2] looks good, and I'd buy it in >a heartbeat if it were a published book. > >Anyone have any opinions on Wesley Chun's "Core Python Programming"? It >has a chapter on "GUI Programing with Tkinter," but only about 20 pages. > > > >[1] Well, not too straightfoward; it will involve output of Chinese >characters in Unicode and input in Unicode, GB and Big5 encodings. >Currently I'm doing the "I/O" by altering the Python source and >hard-coding hex strings. > >[2] http://www.pythonware.com/library/index.htm > > > From Ike Hall Wed Feb 19 04:22:02 2003 From: Ike Hall (Ike Hall) Date: Wed Feb 19 04:22:02 2003 Subject: [Tutor] Learning Tkinter References: Message-ID: <002501c2d7f8$4a2f99d0$bf27e183@chief> Hi Terry, There was an online doc called something like "Programming in Tkinter" that is on the website of the University of New Mexico Tech. I dont remember the URL to it, and Im a little too busy to go searching for it, but doing a google search on Tkinter and New Mexico Tech might bring it up....I found this one to be one of the best docs for simply explaining what does what for quick refrence when coding. Ike ----- Original Message ----- From: "Terry Carroll" To: Sent: Tuesday, February 18, 2003 7:33 PM Subject: [Tutor] Learning Tkinter > I'm just starting to play with Tkinter, and it's (as expected), a bit > alien to me. Any tips on how to learn it? > > It strikes me that Tkinter is probably pretty easy and intuitive to > someone who already knows Tcl/Tk, but I don't. I don't really want to > learn Tcl. > > I've found what appears to be the only book dedicated to Tk under Python > (John Grayson's "Python & Tkinter Programming"), and that looks like > overkill for me. I just want to add some straightforward GUI stuff[1] to > an existing program to make it more usable. > > Ideas? > > Fred Lundh's "An Introduction To Tkinter"[2] looks good, and I'd buy it in > a heartbeat if it were a published book. > > Anyone have any opinions on Wesley Chun's "Core Python Programming"? It > has a chapter on "GUI Programing with Tkinter," but only about 20 pages. > > > > [1] Well, not too straightfoward; it will involve output of Chinese > characters in Unicode and input in Unicode, GB and Big5 encodings. > Currently I'm doing the "I/O" by altering the Python source and > hard-coding hex strings. > > [2] http://www.pythonware.com/library/index.htm > > -- > Terry Carroll | "To have this rare opportunity > Santa Clara, CA | is a rare opportunity." > carroll@tjc.com | - Houston Rockets' Yao Ming, on being named > Modell delendus est | starting center for the 2003 NBA All-Star Game > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld@bt.com Wed Feb 19 05:17:02 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Wed Feb 19 05:17:02 2003 Subject: [Tutor] List comprehension (Map) Example Message-ID: <7497DCA1C240C042B28F6657ADFD8E0974DAC7@i2km11-ukbr.domain1.systemhost.net> On Wed, 19 Feb 2003, Erik Price wrote: > > http://www.freenetpages.co.uk/hp/alan.gauld/tutfctnl.htm > > I went to check it out but the connection was refused. It seems to be OK just now. I know freenet went down at the weekend but it seems OK now. > Erik, there's a mirror of "Learning to Program" on Alan's other site here: > http://www.crosswinds.net/~agauld/ Unfortunately that site doesn't have the comprehensions update... Alan g From glingl@aon.at Wed Feb 19 06:52:01 2003 From: glingl@aon.at (Gregor Lingl) Date: Wed Feb 19 06:52:01 2003 Subject: [Tutor] Learning Tkinter References: <002501c2d7f8$4a2f99d0$bf27e183@chief> Message-ID: <3E536FFE.1080506@aon.at> Ike Hall schrieb: >Hi Terry, > >There was an online doc called something like "Programming in Tkinter" that >is on the website of the University of New Mexico Tech. > It's here: http://www.nmt.edu/tcc/help/lang/python/tkinter.html (A link to it can alos be found at the former mentioned "Thinking in Tkinter") Gregor > I dont remember the >URL to it, and Im a little too busy to go searching for it, but doing a >google search on Tkinter and New Mexico Tech might bring it up....I found >this one to be one of the best docs for simply explaining what does what for >quick refrence when coding. > >Ike > From roland.casselbrant@bonetmail.com Wed Feb 19 08:20:02 2003 From: roland.casselbrant@bonetmail.com (Roland Casselbrant) Date: Wed Feb 19 08:20:02 2003 Subject: [Fwd: Re: [Tutor] Syntax error]] Message-ID: <3E53845A.7030404@bonetmail.com> -------- Original Message -------- Subject: Re: [Fwd: Re: [Tutor] Syntax error] Date: Wed, 19 Feb 2003 12:13:04 +0100 From: Roland Casselbrant Reply-To: roland.casselbrant@bonetmail.com To: Bob Gailer References: <5.2.0.9.0.20030218201120.02f716e8@66.28.54.253> Thanks a lot. That really helped me out. I guess being new to programming makes error like this easier to appear without discovering. Thanks for the tip about PythonWin. I=B4ll give it a try and se if it=B4s good enough to abandon Crimson Editor as my multi purpose tool. Thanks again. Roland Casselbrant Bob Gailer wrote: > These 2 lines have unbalanced parentheses: > efbh =3D ((uppvarm/graddar*24) * (20-(dut)) > gradkorr =3D ((gradnorm/graddar)*uppvarm > Fix them and things should be OK. > > For future reference, its important to distinguish between compile > errors and execution errors. These are compile errors; they appeared > before any input was requested or output generated. > > The thing that makes it hard to find this kind of problem is that > there's an extra left parentheses which causes Python to expect more > lines that will eventually provide the closing parenthesis. When the > following line fails to do that, and the combination of the 2 lines is > in error, it reports the problem as having to do with the 2nd line. > Notice what happens when you enter the 2 lines interactively: > >>> gradkorr =3D ((gradnorm/graddar)*uppvarm ## extra left ( > ... print stringJ, gradkorr ## ... tel= ls > you its waiting for more > File "", line 2 > print stringJ, gradkorr ## print > following uppvarm is incorrect. > ^ > SyntaxError: invalid syntax > > So if the line reported looks OK, go back in the file and look at the > previous line(s). An IDE such as PythonWin is helpful here because it > highlights pairs of () [] {} "" '' etc. and makes it easy to spot extr= a > delimiters. > > At 01:00 AM 2/19/2003 +0100, Roland Casselbrant wrote: > >> HEre is the complete code: >> >> hhe =3D 5000.0 >> vvu =3D 5000.0 >> stringA =3D 'Nettoenergibehovet: ' >> stringB =3D 'Nettoenergibehov minus vattenuppvarmning: ' >> stringC =3D 'Kompenserat for elpannans verkningsgrad: ' >> stringD =3D 'Effektbehovet vid dimensionerande temperatur: ' >> stringE =3D 'Till detta tillkommer arsmedeleffekt f=F6r >> varmvattenuppvarmning: ' >> stringF =3D 'Dimensionerande effektbehov for flerbostadshuset i exemp= let >> blir da: ' >> stringZ =3D ' ' >> stringG =3D ' Effektbehov for eluppvarmt hus ' >> stringH =3D 'Program skrivet av Roland Casselbrant' >> stringI =3D '*************************************' >> stringJ =3D 'Efter gradkorrigering av varmebehovet har vi: ' >> stringK =3D 'Ett normalar blir elanvandningen f=F6r smahuset i exempl= et >> alltsa: ' >> >> >> print stringZ >> print stringZ >> print stringG >> print stringH >> print stringI >> print stringZ >> >> totel =3D input("Total elaanvandning per ar: [kWh] ") >> pannverk =3D input("Elpannans armedelverkningsgrad: [%] ") >> totyta =3D input("Total uppvarmd bostadsyta: [m2] ") >> byggar =3D input("Byggar: ") >> graddar =3D input("Graddagar aktuellt ar: ") >> gradnorm =3D input("Graddagar normalar: ") >> dut =3D input ("Dimensionerande utetemperatur: [grader Celsius] ") >> >> # F=F6rst m=E5ste man r=E4kna bort den del av f=F6rbrukningen >> # som inte =E4r klimatberoende >> # d.v.s. hush=E5llsel och varmvattenuppv=E4rmning. >> # Vi r=E4knar h=E4r med 5000 kWh hush=E5llsel och 5000 kWh >> # f=F6r varmvattenuppv=E4rmning. >> # Uppv=E4rmningsbehovet blir d=E5: >> >> print stringA, totel >> print stringZ >> >> nettoel =3D totel-vvu-hhe >> >> print stringB, nettoel >> print stringZ >> >> # Nu =E4r inte hela denna energim=E4ngd "nyttig" utan vi m=E5ste komp= ensera >> # f=F6r elpannans verkningsgrad. S=E5ledes =E4r nettoenergibehovet >> # f=F6r uppv=E4rmning: >> >> panna =3D pannverk/100.0 >> uppvarm =3D nettoel*panna >> >> print stringC, uppvarm >> print stringZ >> >> # Effektbehovet vid dimensionerande temperatur l=F6ser vi ut >> # fr=E5n ekvationen: >> >> efbh =3D ((uppvarm/graddar*24) * (20-(dut)) >> >> print stringD, efbh >> print stringZ >> >> # Till detta tillkommer =E5rsmedeleffekt f=F6r varmvattenuppv=E4rmnin= g. >> >> mdff =3D (vvu/8760) >> >> print stringE, mdff >> print stringZ >> >> # Dimensionerande effektbehov f=F6r flerbostadshuset i exemplet blir = d=E5: >> >> deff =3D efbh+mdff >> >> print stringF, deff >> print stringZ >> >> # Graddagskorrigering av v=E4rmebehovet g=E5r till s=E5 att man tar >> # kvoten av graddagarna >> # f=F6r normal=E5r och graddagarna f=F6r aktuell period och multiplic= erar >> # med det >> # klimatberoende nettoenergibehovet f=F6r uppv=E4rmning enligt f=F6lj= ande: >> >> gradkorr =3D ((gradnorm/graddar)*uppvarm >> >> print stringJ, gradkorr >> print stringZ >> >> # Ett normal=E5r blir elanv=E4ndningen f=F6r sm=E5huset i exemplet al= lts=E5: >> >> totalel =3D ((gradkorr/panna)+(vvu+hhe)) >> >> print stringK, totalel >> print stringZ >> >> >> EOF/roland.casselbrant@bonetmail.com >> >> >> >> -------- Original Message -------- >> Subject: Re: [Tutor] Syntax error >> Date: Tue, 18 Feb 2003 16:06:45 -0700 >> From: Bob Gailer >> To: roland.casselbrant@bonetmail.com, tutor@python.org >> >> At 10:48 PM 2/18/2003 +0100, Roland Casselbrant wrote: >> >The following lines is getting Syntax errors and I can=B4t understan= d=20 why? >> >> Please copy the session and any associated program to the body of an >> e-mail >> so we can see exactly the sequence of operations and the error messag= es. >> >> Bob Gailer >> mailto:ramrom@earthling.net >> 303 442 2625 >> >> >> -- >> Roland Casselbrant >> >> >> =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D >> Seen it all, done it all, can't remember most of it >> =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D >> >> WWW: www.casselbrant.net >> E-mail: roland.casselbrant@bonetmail.com >> Mobile phone: +0046-(0)70-4785052 >> >> >> -----BEGIN GEEK CODE BLOCK----- >> version: 3.12 >> GCM/CC/IT/O d-(++) s+:+ a C++++ UL+ P+ L+ E- W+++ N++ o K? w++++ >> O++ M- V+ PS+ PE++ Y+ PGP t--- 5-- X- R* tv++(+) b++ DI+ D G e* >> h---- r+++ y++++(+++++)>$ >> ------END GEEK CODE BLOCK------ >> >> >> >> E-mail: roland.casselbrant@bonetmail.com ? >> WWW: www.casselbrant.net ,=3D. >> (o o) >> ------------------------------------------------ooO--(_)--Ooo-------- >> >> >> I only eat food delivered by www.kummingarden.com >> >> .oooO >> ( ) Oooo. >> --------------------------------------------------\ (----( )------- >> This signature file may not be reproduced, \_) ) / >> in whole or in part, by any means, (_/ >> including but not limited to: >> Mechanical reprints, electronic storage or scanning, theatrical relea= se, >> musical ballads, word of mouth, sign language, braille, pantomime, >> hetero- or asexual reproduction, genetic engineering, or inclusion in >> digital media. >> In the process of producing this e-mail >> signature file, no apes, ratts, chaffin= ch, >> ''' bullys, snouts, CEOs, CIOs or cute pets >> (0 0) came to any harm or danger. >> +-----oOO----(_)----------+ >> | Casselbrant Web Factory | >> | "The Power-Tool | The only thing regarded wor= se >> | of Internet" | than spam mail is excessive >> +------------------oOO----+ signature files like this o= ne. >> |__|__| >> || || Made with love and a editor. >> ooO Ooo >> >> =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D >> Gravity isn't MY fault--I voted for velcro! >> =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D >> >> >> >> >> --- >> Outgoing mail is certified Virus Free. >> Checked by AVG anti-virus system (http://www.grisoft.com). >> Version: 6.0.454 / Virus Database: 253 - Release Date: 2/10/2003 >> >> >> >> --- >> Incoming mail is certified Virus Free. >> Checked by AVG anti-virus system (http://www.grisoft.com). >> Version: 6.0.454 / Virus Database: 253 - Release Date: 2/10/2003 > > > Bob Gailer > mailto:ramrom@earthling.net > 303 442 2625 > > > ----------------------------------------------------------------------= -- > > > --- > Outgoing mail is certified Virus Free. > Checked by AVG anti-virus system (http://www.grisoft.com). > Version: 6.0.454 / Virus Database: 253 - Release Date: 2/10/2003 --=20 Roland Casselbrant =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D Seen it all, done it all, can't remember most of it =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D WWW: www.casselbrant.net E-mail: roland.casselbrant@bonetmail.com Mobile phone: +0046-(0)70-4785052 -----BEGIN GEEK CODE BLOCK----- version: 3.12 GCM/CC/IT/O d-(++) s+:+ a C++++ UL+ P+ L+ E- W+++ N++ o K? w++++ O++ M- V+ PS+ PE++ Y+ PGP t--- 5-- X- R* tv++(+) b++ DI+ D G e* h---- r+++ y++++(+++++)>$ ------END GEEK CODE BLOCK------ E-mail: roland.casselbrant@bonetmail.com ? WWW: www.casselbrant.net ,=3D. (o o) ------------------------------------------------ooO--(_)--Ooo-------- I only eat food delivered by www.kummingarden.com .oooO ( ) Oooo. --------------------------------------------------\ (----( )------- This signature file may not be reproduced, \_) ) / in whole or in part, by any means, (_/ including but not limited to: Mechanical reprints, electronic storage or scanning, theatrical release, musical ballads, word of mouth, sign language, braille, pantomime, hetero- or asexual reproduction, genetic engineering, or inclusion in digital media. In the process of producing this e-mail signature file, no apes, ratts, chaffinch= , ''' bullys, snouts, CEOs, CIOs or cute pets (0 0) came to any harm or danger. +-----oOO----(_)----------+ | Casselbrant Web Factory | | "The Power-Tool | The only thing regarded worse | of Internet" | than spam mail is excessive +------------------oOO----+ signature files like this one. |__|__| || || Made with love and a editor. ooO Ooo =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D Gravity isn't MY fault--I voted for velcro! =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D --=20 Roland Casselbrant =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D Seen it all, done it all, can't remember most of it =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D WWW: www.casselbrant.net E-mail: roland.casselbrant@bonetmail.com Mobile phone: +0046-(0)70-4785052 -----BEGIN GEEK CODE BLOCK----- version: 3.12 GCM/CC/IT/O d-(++) s+:+ a C++++ UL+ P+ L+ E- W+++ N++ o K? w++++ O++ M- V+ PS+ PE++ Y+ PGP t--- 5-- X- R* tv++(+) b++ DI+ D G e* h---- r+++ y++++(+++++)>$ ------END GEEK CODE BLOCK------ E-mail: roland.casselbrant@bonetmail.com ? WWW: www.casselbrant.net ,=3D. (o o) ------------------------------------------------ooO--(_)--Ooo-------- I only eat food delivered by www.kummingarden.com .oooO ( ) Oooo. --------------------------------------------------\ (----( )------- This signature file may not be reproduced, \_) ) / in whole or in part, by any means, (_/ including but not limited to: Mechanical reprints, electronic storage or scanning, theatrical release, musical ballads, word of mouth, sign language, braille, pantomime, hetero- or asexual reproduction, genetic engineering, or inclusion in digital media. In the process of producing this e-mail=20 signature file, no apes, ratts, chaffinch, ''' bullys, snouts, CEOs, CIOs or cute pets (0 0) came to any harm or danger. +-----oOO----(_)----------+ | Casselbrant Web Factory | | "The Power-Tool | The only thing regarded worse | of Internet" | than spam mail is excessive +------------------oOO----+ signature files like this one. |__|__| || || Made with love and a editor. ooO Ooo =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D Gravity isn't MY fault--I voted for velcro! =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D From reveranddaddy@yahoo.com Wed Feb 19 12:46:02 2003 From: reveranddaddy@yahoo.com (Andy Kim) Date: Wed Feb 19 12:46:02 2003 Subject: [Tutor] python and cron In-Reply-To: <001801c2d7bc$1ad0a4e0$6600a8c0@tbrauch> Message-ID: <20030219174515.32711.qmail@web13406.mail.yahoo.com> Timothy, I know you are trying to use Python for this problem, but a better solution might be to use dhs.org. What you need to sign up for is dynamic dns. You choose a server name and everytime you get a new ip address you tell dhs the new ip address and they update their dns entry. So the effect is you can ssh and ftp into myserver.dhs.org. They used to do this for free, but I think they will charge you a minimal fee now. Go check it out at: http://www.dhs.org/support/dynamic.shtml - Andy --- "Timothy M. Brauch" wrote: > I am having a problem, and I'm not sure if it is > with Python or cron. > > I have a dynamic IP address for my home computer. > Every time I connect, I > get a new IP. My connection is not the best, and > sometimes I am only > connected for an hour, sometimes a day. My machine > automatically > reconnects, so it's not a big deal. However, I > would like to know my IP so > I can ssh or ftp. > > I wrote a small Python script to check my IP. I > would like for this script > to run every hour. I thought a cron job would be > perfect, but it does not > seem to work. I checked my log and there are no > errors and I don't get any > errors emailed to me. The script works fine from > command line. > > Here is part of my code: > -------------------------------------------------------------- > #! /usr/bin/python > import urllib, ftplib, re, time > > ##Get the IP address from the router: > source = > urllib.urlopen('http://192.168.xxx.xxx/st_devic.html') > info = source.read() > source.close > > ##Clean up any HTML coding > data = re.sub('<.*>| ','',info).split() > > ##The IP address is in field 29 > address = data[29] > > ##here is the html formatting stuff for the > published webpage. > > ##Write the formatted stuff to a file > formatted = open('ip.html', 'w') > formatted.write(html) > formatted.close() > > ##Open the file and ftp it so I someone can get my > IP > new_file = open('ip.html', 'r') > > ftp = > ftplib.FTP('ftp.domain.com','login','password') > ftp.cwd('private') > ftp.storbinary('STOR index.html', new_file) > ftp.quit() > new_file.close() > ----------------------------------------------------------------- > > Here is the entry from crontab: > ----------------------------------------------------------------- > 0 * * * * /var/ftp/getipaddress.py > ----------------------------------------------------------------- > > All of this is owned and run by root, so it > shouldn't be permissions. > > Can someone offer some help? > > - Tim > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor __________________________________________________ Do you Yahoo!? Yahoo! Shopping - Send Flowers for Valentine's Day http://shopping.yahoo.com From gerrit@nl.linux.org Wed Feb 19 15:34:01 2003 From: gerrit@nl.linux.org (Gerrit Holl) Date: Wed Feb 19 15:34:01 2003 Subject: [Tutor] Return cursor to beginning of line, to overprint, in DOS/windows In-Reply-To: <22948058065.20030218231435@columbus.rr.com> References: <22948058065.20030218231435@columbus.rr.com> Message-ID: <20030219203446.GA6722@nl.linux.org> R. Alan Monroe schreef op woensdag 19 februari om 05:09:28 +0000: > Is there a special backslash code I can use in a print statement to > move the cursor back to beginning of the line, to keep printing on the > same line over and over? I tried "\r" but that didn't work. > > It seems like this has come up before but I searched my mail archives > for "carriage" "beginning" "return" etc. and couldn't find it. Works here: > Python 2.3a1 (#1, Jan 5 2003, 16:06:30) [GCC 2.96 20000731 (Red Hat Linux 7.3 2.96-110)] on linux2 Type "help", "copyright", "credits" or "license" for more information. 0 >>> print "aaa\rb" baa What did you try exactly? Remember that 'print' prints a newline after the expression. yours, Gerrit. -- Asperger Syndroom - een persoonlijke benadering: http://people.nl.linux.org/~gerrit/ Het zijn tijden om je zelf met politiek te bemoeien: http://www.sp.nl/ From learning.python@dbmail.dk Wed Feb 19 16:43:01 2003 From: learning.python@dbmail.dk (Ole Jensen) Date: Wed Feb 19 16:43:01 2003 Subject: [Tutor] in-built square root function Message-ID: <000e01c2d85f$a9dc1220$8a4c73d5@oleioq8ex4m1zx> This is a multi-part message in MIME format. ------=_NextPart_000_000B_01C2D868.0B7D61C0 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable when experimenting alittle with pythons math functions I was puzzled = concerning the results I get when trying to use the squareroot function = (sqrt(x) according to the documentation found @ = http://www.python.org/doc/current/lib/module-math.html) my problem: >>> import math >>> sqrt(9) Traceback (most recent call last): File "", line 1, in ? sqrt(9) NameError: name 'sqrt' is not defined >>>=20 If I have made a very stupid speeling mistake etc, Im sorry, but I can't = really see what Im doing wrong! I succesfully used the power function: >>> pow(3,2) 9 >>>=20 So Im just wondering what Im doing wrong... for now though I'll just stick with the power of 0.5 when finding the = sqrt thx for any info youve got Ol=E9 ole_jensen@dbmail.dk ------=_NextPart_000_000B_01C2D868.0B7D61C0 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
when experimenting alittle with pythons = math=20 functions I was puzzled concerning the results I get when trying to use = the=20 squareroot function (sqrt(x) according to the documentation found @ http://ww= w.python.org/doc/current/lib/module-math.html)
 
my problem:
 
>>> import = math
>>>=20 sqrt(9)
Traceback (most recent call last):
  File=20 "<pyshell#14>", line 1, in ?
    = sqrt(9)
NameError:=20 name 'sqrt' is not defined
>>>
 
If I have made a very stupid = speeling mistake=20 etc, Im sorry, but I can't  really see what Im doing = wrong!
 
I succesfully used the power = function:
>>> = pow(3,2)
9
>>>=20
 
So Im just wondering what Im doing=20 wrong...
 
for now though I'll just stick with the = power of=20 0.5 when finding the sqrt
thx for any info youve got
 
Ol=E9
ole_jensen@dbmail.dk
------=_NextPart_000_000B_01C2D868.0B7D61C0-- From tbrauch@mindless.com Wed Feb 19 16:52:02 2003 From: tbrauch@mindless.com (Timothy M. Brauch) Date: Wed Feb 19 16:52:02 2003 Subject: [Tutor] in-built square root function References: <000e01c2d85f$a9dc1220$8a4c73d5@oleioq8ex4m1zx> Message-ID: <005401c2d861$139bcc40$6600a8c0@tbrauch> You made a mistake, but it is a very important error to get corrected when using import. Look at this... >>> import math >>> sqrt(9) Traceback (most recent call last): File "", line 1, in ? NameError: name 'sqrt' is not defined >>> math.sqrt(9) 3.0 >>> Now look at this one... >>> from math import * >>> math.sqrt(9) Traceback (most recent call last): File "", line 1, in ? NameError: name 'math' is not defined >>> sqrt(9) 3.0 >>> See if you can figure out what is going on. - Tim From learning.python@dbmail.dk Wed Feb 19 17:03:04 2003 From: learning.python@dbmail.dk (Ole Jensen) Date: Wed Feb 19 17:03:04 2003 Subject: Fw: [Tutor] in-built square root function Message-ID: <001c01c2d862$3ceb8da0$8a4c73d5@oleioq8ex4m1zx> forwarded to tutor@python.org as I sent it directly to Tim by error: ----- Original Message ----- From: "Ole Jensen" To: "Timothy M. Brauch" Sent: Wednesday, February 19, 2003 10:58 PM Subject: Re: [Tutor] in-built square root function > > Olé > ole_jensen@dbmail.dk > ----- Original Message ----- > From: "Timothy M. Brauch" > To: "Ole Jensen" > Sent: Wednesday, February 19, 2003 10:50 PM > Subject: Re: [Tutor] in-built square root function > > > > You made a mistake, but it is a very important error to get corrected when > > using import. Look at this... > > > > >>> import math > > >>> sqrt(9) > > Traceback (most recent call last): > > File "", line 1, in ? > > NameError: name 'sqrt' is not defined > > >>> math.sqrt(9) > > 3.0 > > >>> > > > fair enough... I'll have write math.sqrt, unless of course I do the "from > math import *(which i'm guessing is all, everything) > > I didn't know that so thanks for clearing it up for me, tim. > > However I'm now alittle puzzled to why I didn't have to do the same thing > with the power operator, which worked fine without write the equevalent: > "math.pow(x,y)"??? > > From tbrauch@mindless.com Wed Feb 19 17:16:00 2003 From: tbrauch@mindless.com (Timothy M. Brauch) Date: Wed Feb 19 17:16:00 2003 Subject: [Tutor] in-built square root function References: <000e01c2d85f$a9dc1220$8a4c73d5@oleioq8ex4m1zx> <004501c2d860$f6bc70c0$6600a8c0@tbrauch> <001601c2d861$fb028970$8a4c73d5@oleioq8ex4m1zx> Message-ID: <007a01c2d864$6e984f80$6600a8c0@tbrauch> For reasons that have been argued endlessly, you have to try to remember to hit "reply-all" when replying. Don't worry, we all forget sometimes. > fair enough... I'll have write math.sqrt, unless of course I do the "from > math import *(which i'm guessing is all, everything) Yes, that is correct. I think, this is going from memory, you can also do something like: from math inport sqrt. Let me check... >>> from math import sqrt >>> sqrt(9) 3.0 >>> math.sqrt(9) Traceback (most recent call last): File "", line 1, in ? math.sqrt(9) NameError: name 'math' is not defined >>> Yes, so if you do not want to import everything, only part, you can use "from [module] import [item]" Then, if you really want to get fancy, you can try... >>> from math import sqrt as square_root >>> square_root(9) 3.0 >>> sqrt(9) Traceback (most recent call last): File "", line 1, in ? sqrt(9) NameError: name 'sqrt' is not defined >>> math.sqrt(9) Traceback (most recent call last): File "", line 1, in ? math.sqrt(9) NameError: name 'math' is not defined >>> But I have never come across a time when I thought something like this was necessary. I'm sure someone much wiser than me can explain better. > I didn't know that so thanks for clearing it up for me, tim. > > However I'm now alittle puzzled to why I didn't have to do the same thing > with the power operator, which worked fine without write the equevalent: > "math.pow(x,y)"??? As for why pow works, there is this neat little function called dir. It is my friend. You use it to find out what exists and where it exists. Like this... >>> import math >>> dir(math) ['__doc__', '__name__', 'acos', 'asin', 'atan', 'atan2', 'ceil', 'cos', 'cosh', 'e', 'exp', 'fabs', 'floor', 'fmod', 'frexp', 'hypot', 'ldexp', 'log', 'log10', 'modf', 'pi', 'pow', 'sin', 'sinh', 'sqrt', 'tan', 'tanh'] >>> That tells you all the functions that work under the module math. So, you can use math.log(). If you are not sure what a command does, you can always try "print [module].[function].__doc__" Such as... >>> print math.log.__doc__ log(x) -> the natural logarithm (base e) of x. Or even... >>> print math.__doc__ This module is always available. It provides access to the mathematical functions defined by the C standard. Not everyone uses these __doc__ strings in their code, though, so don't rely on it. Back to dir, though. Look at this... Let's see what we have so far... >>> dir() ['__builtins__', '__doc__', '__name__', 'math'] Hmm, so what functions are builtin? >>> dir(__builtins__) ['ArithmeticError', 'AssertionError', 'AttributeError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FloatingPointError', 'IOError', 'ImportError', 'IndentationError', 'IndexError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'None', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'OverflowWarning', 'ReferenceError', 'RuntimeError', 'RuntimeWarning', 'StandardError', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeError', 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', '_', '__debug__', '__doc__', '__import__', '__name__', 'abs', 'apply', 'bool', 'buffer', 'callable', 'chr', 'classmethod', 'cmp', 'coerce', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'eval', 'execfile', 'exit', 'file', 'filter', 'float', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'intern', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'long', 'map', 'max', 'min', 'object', 'oct', 'open', 'ord', 'pow', 'property', 'quit', 'range', 'raw_input', 'reduce', 'reload', 'repr', 'round', 'setattr', 'slice', 'staticmethod', 'str', 'super', 'tuple', 'type', 'unichr', 'unicode', 'vars', 'xrange', 'zip'] >>> Ah, so the pow function is always available and we do not need to import it. But, there is no sqrt function builtin. But, look at this... >>> print pow.__doc__ pow(x, y[, z]) -> number With two arguments, equivalent to x**y. With three arguments, equivalent to (x**y) % z, but may be more efficient (e.g. for longs). >>> print math.pow.__doc__ pow(x,y) Return x**y (x to the power of y). >>> So, math.pow() and pow() are two slightly different functions. Remember, dir() and __doc__ should be your friends. - Tim From R. Alan Monroe" References: <22948058065.20030218231435@columbus.rr.com> <20030219203446.GA6722@nl.linux.org> Message-ID: <131015570463.20030219175947@columbus.rr.com> > R. Alan Monroe schreef op woensdag 19 februari om 05:09:28 +0000: >> Is there a special backslash code I can use in a print statement to >> move the cursor back to beginning of the line, to keep printing on the >> same line over and over? I tried "\r" but that didn't work. > Works here: > 0 >>> print "aaa\rb" > baa > What did you try exactly? Remember that 'print' prints a newline > after the expression. I didn't know about the newline. I fooled around with it and found adding a trailing comma makes it work like I want, using \r. Is there a control code for "clear to end of line"? Where's the reference for these codes? I can't find them on Google or in the supplied docs, but I must not be searching correctly. The \r I just happened to remember from reading it somewhere. Alan From SWidney@ci.las-vegas.nv.us Wed Feb 19 22:06:02 2003 From: SWidney@ci.las-vegas.nv.us (Scott Widney) Date: Wed Feb 19 22:06:02 2003 Subject: [Tutor] working w/ processes? Message-ID: <0E5508EBA1620743B409A2B8365DE16FDC83B3@sovereign.ci.las-vegas.nv.us> > Solution for this on Windows is to use WMI. Sorry for the > example in JScript (didn't have time to fully re-tool to > Python), but translating to Python should be a piece of cake > for which unfortunatley I will not have time, for quite some > time :-( > I don't have the time to fully translate the JScript version either, but here is the core functionality: #### import sys, win32com.client wmiService = win32com.client.GetObject("winmgmts:{impersonationLevel=impersonate,(Debug)} ") for arg in sys.argv: processes = wmiService.ExecQuery("Select * from Win32_Process where name='%s'" % arg) for process in processes: try: process.terminate() except: continue #### Scott From carroll@tjc.com Wed Feb 19 22:26:02 2003 From: carroll@tjc.com (Terry Carroll) Date: Wed Feb 19 22:26:02 2003 Subject: [Tutor] in-built square root function In-Reply-To: <007a01c2d864$6e984f80$6600a8c0@tbrauch> Message-ID: On Wed, 19 Feb 2003, Timothy M. Brauch wrote: > Remember, dir() and __doc__ should be your friends. That's cool. I don't care about square roots, but I'm still saving this post. -- Terry Carroll | "To have this rare opportunity Santa Clara, CA | is a rare opportunity." carroll@tjc.com | - Houston Rockets' Yao Ming, on being named Modell delendus est | starting center for the 2003 NBA All-Star Game From carroll@tjc.com Wed Feb 19 22:29:01 2003 From: carroll@tjc.com (Terry Carroll) Date: Wed Feb 19 22:29:01 2003 Subject: [Tutor] Learning Tkinter In-Reply-To: <3E5338EC.30307@aon.at> Message-ID: On Wed, 19 Feb 2003, Gregor Lingl wrote: > Try "Thinking in Tkinter", which you can find here: > http://home.att.net/~stephen_ferg/thinking_in_tkinter/index.html > > Bryce Embry has also six nice introduvtory lessons on Tkinter: > http://bembry.org/tech/python/index.php On Wed, 19 Feb 2003, Ike Hall wrote: > There was an online doc called something like "Programming in Tkinter" > that is on the website of the University of New Mexico Tech. Thanks to both Gregor and Ike. I looked at all of these and downloaded and started using the "Thinking in Tkinter" collection today. It's pretty much just what I was looking for. -- Terry Carroll | "To have this rare opportunity Santa Clara, CA | is a rare opportunity." carroll@tjc.com | - Houston Rockets' Yao Ming, on being named Modell delendus est | starting center for the 2003 NBA All-Star Game From norvell@houseofspearman.org Thu Feb 20 00:31:02 2003 From: norvell@houseofspearman.org (Norvell Spearman) Date: Thu Feb 20 00:31:02 2003 Subject: [Tutor] in-built square root function In-Reply-To: <007a01c2d864$6e984f80$6600a8c0@tbrauch> References: <000e01c2d85f$a9dc1220$8a4c73d5@oleioq8ex4m1zx> <004501c2d860$f6bc70c0$6600a8c0@tbrauch> <001601c2d861$fb028970$8a4c73d5@oleioq8ex4m1zx> <007a01c2d864$6e984f80$6600a8c0@tbrauch> Message-ID: <20030220053017.GA13197@houseofspearman.org> On Wednesday, 2003.02.19, 17:15:37 -0500, Timothy M. Brauch wrote: > >>> print pow.__doc__ > pow(x, y[, z]) -> number > > With two arguments, equivalent to x**y. With three arguments, > equivalent to (x**y) % z, but may be more efficient (e.g. for longs). I'm still in the process of learning Python so this may seem like a silly question. I can use the built-in pow function for possibly more efficient modulo division of longs, but isn't it then limited to only dividends which can be expressed by x**y, both x and y integers? For example, for (45**89)%3 I could use the built-in pow, but not for (45**89 + 1)%3. Thanks in advance for answers and patience. -- Norvell Spearman From tbrauch@mindless.com Thu Feb 20 00:55:02 2003 From: tbrauch@mindless.com (Timothy M. Brauch) Date: Thu Feb 20 00:55:02 2003 Subject: [Tutor] in-built square root function References: <000e01c2d85f$a9dc1220$8a4c73d5@oleioq8ex4m1zx> <004501c2d860$f6bc70c0$6600a8c0@tbrauch> <001601c2d861$fb028970$8a4c73d5@oleioq8ex4m1zx> <007a01c2d864$6e984f80$6600a8c0@tbrauch> <20030220053017.GA13197@houseofspearman.org> Message-ID: <00ba01c2d8a4$8b1c0260$6600a8c0@tbrauch> > I'm still in the process of learning Python so this may seem like a > silly question. I can use the built-in pow function for possibly more > efficient modulo division of longs, but isn't it then limited to only > dividends which can be expressed by x**y, both x and y integers? For > example, for (45**89)%3 I could use the built-in pow, but not for > (45**89 + 1)%3. Thanks in advance for answers and patience. When all else fails, power up the interpreter... >>> pow(45,89+1,3) 0 >>> (45**89+1)%3 1L >>> So, yes, it seems that in the first case, it works out (45**(89+1))%3, as I expected. The second case works out as ((45**89)+1)%3, as powers take precedence over addition. But, because you are working modulo, (45**89+1)%3, meaning ((45**89)+1)%3 is actually the same thing as (45**89)%3 + 1, which works as... >>> pow(45,89,3)+1 1 >>> So, whatever floats your boat. I usually think of commas in math functions as parentheses. so pow(45,89+1,3) is interpreted as (45**(89+1))%3 Now, about the integers. I have found that when using %, sometimes funny things happen when using non-integers or negative numbers. If you work with it for a few minutes, you can see what the result is and convince yourself that the way Python does it is the way it should be done (no matter what you thought before hand). Then, if you switch languages, it might be done differently and you can convince yourself that the other way is correct also. I was working on a problem using hash tables for an assignment in a programming class. One of the most beautiful equations I came up with for the class was in this assignment. (n-1)%p+1 gives you a number in the range [1,p], which is important for hash functions, but took many students hours to come up with a solution, some of them as separate functions of quite a few lines. - Tim From norvell@houseofspearman.org Thu Feb 20 01:22:01 2003 From: norvell@houseofspearman.org (Norvell Spearman) Date: Thu Feb 20 01:22:01 2003 Subject: [Tutor] in-built square root function In-Reply-To: <00ba01c2d8a4$8b1c0260$6600a8c0@tbrauch> References: <000e01c2d85f$a9dc1220$8a4c73d5@oleioq8ex4m1zx> <004501c2d860$f6bc70c0$6600a8c0@tbrauch> <001601c2d861$fb028970$8a4c73d5@oleioq8ex4m1zx> <007a01c2d864$6e984f80$6600a8c0@tbrauch> <20030220053017.GA13197@houseofspearman.org> <00ba01c2d8a4$8b1c0260$6600a8c0@tbrauch> Message-ID: <20030220062101.GB13197@houseofspearman.org> On Thursday, 2003.02.20, 00:54:33 -0500, Timothy M. Brauch wrote: > So, yes, it seems that in the first case, it works out (45**(89+1))%3, as I > expected. The second case works out as ((45**89)+1)%3, as powers take > precedence over addition. But, because you are working modulo, > (45**89+1)%3, meaning ((45**89)+1)%3 is actually the same thing as > (45**89)%3 + 1, which works as... > > >>> pow(45,89,3)+1 > 1 > >>> So you're saying that (x + 1)%y is the same as (x%y) + 1? or just for the one instance with the example values I gave? Because in the interpreter I get >>> pow(45, 89, 3) + 1 1 >>> (45**89)%3 + 1 1L >>> ((45**89) + 1)%3 1L but I also get >>> (3%2) + 1 2 >>> (3 + 1)%2 0 which is one example showing that (x%y) + 1 is not necessarily equal to (x + 1)%y. That's why I was curious about buit-in pow's z argument: Yes, it may be more efficient for long modulo division but only for certain dividends (namely, those which can be expressed as an integer base to an integer power, per the Python Library Reference). If I'm being dense and missing something really obvious then I sincerely apologize. -- Norvell Spearman From eprice@ptc.com Thu Feb 20 08:42:00 2003 From: eprice@ptc.com (Erik Price) Date: Thu Feb 20 08:42:00 2003 Subject: [Tutor] in-built square root function In-Reply-To: References: Message-ID: <3E54DAC2.5090901@ptc.com> Terry Carroll wrote: > On Wed, 19 Feb 2003, Timothy M. Brauch wrote: > > > >>Remember, dir() and __doc__ should be your friends. > > > That's cool. I don't care about square roots, but I'm still saving this > post. Me too. Erik From gerrit@nl.linux.org Thu Feb 20 09:06:01 2003 From: gerrit@nl.linux.org (Gerrit Holl) Date: Thu Feb 20 09:06:01 2003 Subject: [Tutor] Return cursor to beginning of line, to overprint, in DOS/windows In-Reply-To: <131015570463.20030219175947@columbus.rr.com> References: <22948058065.20030218231435@columbus.rr.com> <20030219203446.GA6722@nl.linux.org> <131015570463.20030219175947@columbus.rr.com> Message-ID: <20030220140800.GA12776@nl.linux.org> R. Alan Monroe schreef op woensdag 19 februari om 23:56:25 +0000: > > R. Alan Monroe schreef op woensdag 19 februari om 05:09:28 +0000: > >> Is there a special backslash code I can use in a print statement to > >> move the cursor back to beginning of the line, to keep printing on the > >> same line over and over? I tried "\r" but that didn't work. > > > Works here: > > 0 >>> print "aaa\rb" > > baa > > What did you try exactly? Remember that 'print' prints a newline > > after the expression. > > I didn't know about the newline. I fooled around with it and found > adding a trailing comma makes it work like I want, using \r. Is there > a control code for "clear to end of line"? Where's the reference for > these codes? I can't find them on Google or in the supplied docs, but > I must not be searching correctly. The \r I just happened to remember > from reading it somewhere. Me too. I am currently unable to find it, mut the Unix man page printf has the following information: \\ backslash \a alert (BEL) \b backspace \c produce no further output \f form feed \n new line \r carriage return \t horizontal tab \v vertical tab yours, Gerrit. -- Asperger Syndroom - een persoonlijke benadering: http://people.nl.linux.org/~gerrit/ Het zijn tijden om je zelf met politiek te bemoeien: http://www.sp.nl/ From gerrit@nl.linux.org Thu Feb 20 09:08:14 2003 From: gerrit@nl.linux.org (Gerrit Holl) Date: Thu Feb 20 09:08:14 2003 Subject: [Tutor] Return cursor to beginning of line, to overprint, in DOS/windows In-Reply-To: <131015570463.20030219175947@columbus.rr.com> References: <22948058065.20030218231435@columbus.rr.com> <20030219203446.GA6722@nl.linux.org> <131015570463.20030219175947@columbus.rr.com> Message-ID: <20030220140934.GB12776@nl.linux.org> R. Alan Monroe schreef op woensdag 19 februari om 23:56:25 +0000: > I didn't know about the newline. I fooled around with it and found > adding a trailing comma makes it work like I want, using \r. Is there > a control code for "clear to end of line"? Where's the reference for > these codes? I can't find them on Google or in the supplied docs, but > I must not be searching correctly. The \r I just happened to remember > from reading it somewhere. Found it: http://www.python.org/dev/doc/devel/ref/strings.html yours, Gerrit. -- Asperger Syndroom - een persoonlijke benadering: http://people.nl.linux.org/~gerrit/ Het zijn tijden om je zelf met politiek te bemoeien: http://www.sp.nl/ From tbrauch@mindless.com Thu Feb 20 11:04:08 2003 From: tbrauch@mindless.com (Timothy M. Brauch) Date: Thu Feb 20 11:04:08 2003 Subject: [Tutor] in-built square root function References: <000e01c2d85f$a9dc1220$8a4c73d5@oleioq8ex4m1zx> <004501c2d860$f6bc70c0$6600a8c0@tbrauch> <001601c2d861$fb028970$8a4c73d5@oleioq8ex4m1zx> <007a01c2d864$6e984f80$6600a8c0@tbrauch> <20030220053017.GA13197@houseofspearman.org> <00ba01c2d8a4$8b1c0260$6600a8c0@tbrauch> <20030220062101.GB13197@houseofspearman.org> Message-ID: <001601c2d8f9$7e78d6a0$6600a8c0@tbrauch> > So you're saying that (x + 1)%y is the same as (x%y) + 1? or just for > the one instance with the example values I gave? Because in the > interpreter I get Well, yes and no, it depends on if it is a human thinking about a field, or a machine doing the calculations. > >>> pow(45, 89, 3) + 1 > 1 > >>> (45**89)%3 + 1 > 1L > >>> ((45**89) + 1)%3 > 1L > > but I also get > > >>> (3%2) + 1 > 2 > >>> (3 + 1)%2 > 0 > > which is one example showing that (x%y) + 1 is not necessarily equal to > (x + 1)%y. Yes, what you got was correct. But, if you are living in %2, then the only possible answers are (0,1), so 2=0. I was thinking about the solution in human terms of a field, not necessarily how a computer would actually do the calculation. I have that problem sometimes. Like I said, the % command doesn't always give you answers you might expect, but you can convince yourself that the anser you get is correct. I guess I was imagining ((x%y)+1)%y. Sorry, that's the algebraist in me rearing its ugly head. > That's why I was curious about buit-in pow's z argument: Yes, it may be > more efficient for long modulo division but only for certain dividends > (namely, those which can be expressed as an integer base to an integer > power, per the Python Library Reference). If I'm being dense and > missing something really obvious then I sincerely apologize. This problem really only comes up with if you look at (x%y)+n, where it adds up to some number greater than y. In the world of mathematics, though, (x%y)+1 is equal to (x+1)%y, depending on which field you live in. I guess for really large numbers you could do something like pow(pow(45,89,3)+1,1,3) or even (pow(45,89,3)+1)%3, since the after the pow function, you answer should be fairly easy to handle. - Tim From vicki@stanfield.net Thu Feb 20 12:52:03 2003 From: vicki@stanfield.net (vicki@stanfield.net) Date: Thu Feb 20 12:52:03 2003 Subject: [Tutor] Windows within windows Message-ID: <20030220095110.15178.h015.c000.wm@mail.stanfield.net.criticalpath.net> I am new to Python (have only fixed code not written it from scratch) and am having some difficulty with creating multi-window applications. I have been experimenting with some code to get used to the toplevel creation. It seems to work fine until I try to add a list widget. All I get is a quick flash of the toplevel window. Can someone tell me what I am doing wrong? --vicki --------------------------------------------------- import Tkinter def cleanup (): owSecond.destroy () owFirst.destroy () owFirst = Tkinter.Tk () Tkinter.Label (owFirst, text='This is the first window').pack () Tkinter.list = TkList(['tomato', 'orange', 'persimmons']) Tkinter.list.pack() Tkinter.list.reverse() Tkinter.Message (owFirst, text='Here is a message').pack () owSecond = Tkinter.Toplevel (owFirst) Tkinter.Label (owSecond, text='This is the second window').pack () owFirst.protocol ('WM_DELETE_WINDOW', cleanup) owSecond.protocol ('WM_DELETE_WINDOW', cleanup) owSecond.lift () owFirst.wait_window (owSecond) From dyoo@hkn.eecs.berkeley.edu Thu Feb 20 14:43:49 2003 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Feb 20 14:43:49 2003 Subject: [Tutor] Sample beta chapter of "Python in a Nutshell" is available Message-ID: Hi everyone, I just noticed that Alex Martelli's "Python in a Nutshell" page is making Chapter 4 available for beta test: http://www.oreilly.com/catalog/pythonian/chapter/ch04.pdf This looks like a very good reference to the Python language; I'm browsing through it now, and the material looks very solid. Anyway, I thought this might be interesting to folks here. Hope this helps! From eprice@ptc.com Thu Feb 20 15:16:01 2003 From: eprice@ptc.com (Erik Price) Date: Thu Feb 20 15:16:01 2003 Subject: [Tutor] Sample beta chapter of "Python in a Nutshell" is available In-Reply-To: References: Message-ID: <3E5535C1.7040102@ptc.com> Danny Yoo wrote: > Hi everyone, > > I just noticed that Alex Martelli's "Python in a Nutshell" page is making > Chapter 4 available for beta test: > > http://www.oreilly.com/catalog/pythonian/chapter/ch04.pdf > > This looks like a very good reference to the Python language; I'm browsing > through it now, and the material looks very solid. Oho! A contender steps up to "Python Essential Reference 2nd Edition". Not as portable, but that chapter looks very comprehensive in its explanations. Erik From caster17@earthlink.net Thu Feb 20 22:58:03 2003 From: caster17@earthlink.net (Chris Bailey) Date: Thu Feb 20 22:58:03 2003 Subject: [Tutor] Saving data to be retrieved later. Message-ID: <028b01c2d95d$3272b780$0e02a8c0@hatemachine> This is a multi-part message in MIME format. ------=_NextPart_000_0288_01C2D92A.E774F1D0 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Hey everyone, I'm a bit new to python, and I don't know much more than = the basics of programming in general. I'm trying to find a bit of help, but websites/tutorials haven't been = very informative in the ways I need them to be. Basically what im trying to do, is save a bunch of statistics to = seperate files, so they can be called on later. If you are familiar with muds, i'm trying to work with pfiles. I just = thought I would make a single player text based game for my friends and I to play. I have some neat ideas, and I think I = know how to implement them, But I will of course need a way to save our characters! :) ------=_NextPart_000_0288_01C2D92A.E774F1D0 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
 Hey everyone, I'm a bit new to = python, and I=20 don't know much more than the basics of programming in = general.
I'm trying to find a bit of help, but=20 websites/tutorials haven't been very informative in the ways I need them = to=20 be.
Basically what im trying to do, = is save a=20 bunch of statistics to seperate files, so they can be called = on later.=20 If
you are familiar with muds, i'm = trying to work=20 with pfiles. I just thought I would make a single player=20 text based
game for my friends and I to play. I = have some=20 neat ideas, and I think I know how to implement them, But = I
will of course need a way to = save our=20 characters! :) 
------=_NextPart_000_0288_01C2D92A.E774F1D0-- From tbrauch@mindless.com Thu Feb 20 23:20:02 2003 From: tbrauch@mindless.com (Timothy M. Brauch) Date: Thu Feb 20 23:20:02 2003 Subject: [Tutor] Saving data to be retrieved later. References: <028b01c2d95d$3272b780$0e02a8c0@hatemachine> Message-ID: <006201c2d960$612074c0$6600a8c0@tbrauch> Chris decided to let us know... >Basically what im trying to do, is save a bunch of statistics to seperate files, so >they can be called on later. If you are familiar with muds, i'm trying to work with >pfiles. I just thought I would make a single player text based game for my friends >and I to play. I have some neat ideas, and I think I know how to implement them, >But I will of course need a way to save our characters! :) Look into 'pickle'. It allows you to save data to a file and recall it later, in a special format that preserves data structures. The other option I can think of is to use simple open(file).read() and write(), but I think pickle would probably work better. I'm not too familiar with using pickle, though, perhaps once you get started if you have any problems someone else could better answer some questions. - Tim From nicholas_wieland@yahoo.it Fri Feb 21 06:04:01 2003 From: nicholas_wieland@yahoo.it (Nicholas Wieland) Date: Fri Feb 21 06:04:01 2003 Subject: [Tutor] ASP parsing In-Reply-To: ; from dyoo@hkn.eecs.berkeley.edu on mer, feb 19, 2003 at 06:36:50 +0100 References: Message-ID: <20030221092408.GA3641@localhost> On 2003.02.19 06:36 Danny Yoo wrote: > snip > Ok, here's the code I have now: import re f = open ("cdonts.asp", "r") text = " ".join(f.readlines()) p = re.compile(r'<%.*?%>', re.DOTALL) asp_part = re.match(p, str(text)) if asp_part: result = asp_part.group() q = re.compile(r'".*?"', re.DOTALL) quote = re.findall(q, result) for i in quote: print i else: print "No match" It works wonderfully... thanks to Danny for the suggestion and especially for the pointer... Two more questions: 1) I can't understand why your regex is quoted three times... Is it better than mine ? 2) My approach was to stop and write on a file the translated text every time the parser encountered a string that needs translation, inserting it in the ASP code. Now I have an array with all the text I need to translate, but how can I insert it in the context of the ASP code ? I was thinking about a for loop using the re.split() function, but I'm not sure about it... TIA, Nicholas From vicki@stanfield.net Fri Feb 21 09:40:08 2003 From: vicki@stanfield.net (vicki@stanfield.net) Date: Fri Feb 21 09:40:08 2003 Subject: [Tutor] (no subject) Message-ID: <20030221063938.26737.h014.c000.wm@mail.stanfield.net.criticalpath.net> From eprice@ptc.com Fri Feb 21 09:50:01 2003 From: eprice@ptc.com (Erik Price) Date: Fri Feb 21 09:50:01 2003 Subject: [Tutor] Saving data to be retrieved later. In-Reply-To: <028b01c2d95d$3272b780$0e02a8c0@hatemachine> References: <028b01c2d95d$3272b780$0e02a8c0@hatemachine> Message-ID: <3E563C4F.8090702@ptc.com> Chris Bailey wrote: > Hey everyone, I'm a bit new to python, and I don't know much more than > the basics of programming in general. > I'm trying to find a bit of help, but websites/tutorials haven't been > very informative in the ways I need them to be. > Basically what im trying to do, is save a bunch of statistics > to seperate files, so they can be called on later. If > you are familiar with muds, i'm trying to work with pfiles. I just > thought I would make a single player text based > game for my friends and I to play. I have some neat ideas, and I think I > know how to implement them, But I > will of course need a way to save our characters! :) If you just want to quickly serialize Python objects, the cpickle module will do the trick conveniently. However, if you wanted to store the data in a more versatile format (say if you have other programs not written in Python that needs to parse the data), you could just write some XML handlers and do it that way. Or, if your data doesn't need a hierarchical structure (say it's just a dictionary of name/value pairs), you could literally just write these to a file like so: name=Fizban class=Wizard spell=Fireball spell=Magic Missile (of course, if you really want to use multiple properties with the same name, your "read properties" code should know to put the data into a sequence or list rather than overwrite the values, etc) Just some ideas. Erik From vicki@stanfield.net Fri Feb 21 10:24:06 2003 From: vicki@stanfield.net (vicki@stanfield.net) Date: Fri Feb 21 10:24:06 2003 Subject: [Tutor] adding a listbox Message-ID: <20030221072304.6446.h014.c000.wm@mail.stanfield.net.criticalpath.net> Hi. I am trying to figure out how to use the sio module. I just need to write to the serial port and retrieve a response from the same serial port. I know to use sio, but I am having trouble figuring out just how sio works. Do I have to use a constructor to open the serial port? Does anyone have any Python example code that (very simply) initiates a connection with the serial port and then sends data to it? Thanks, --vicki From learning.python@dbmail.dk Fri Feb 21 11:18:00 2003 From: learning.python@dbmail.dk (Ole Jensen) Date: Fri Feb 21 11:18:00 2003 Subject: [Tutor] Using special characters in Python References: <20030221092408.GA3641@localhost> Message-ID: <001701c2d9c4$a33349a0$8d4c73d5@oleioq8ex4m1zx> I would like to now if it is possible to use special characters in python especially in strings. The problem is that in Danish (and Norwegian) we have some characters in the alphabet that doesn not exist in the english one, i.e. ć, ř, and ĺ (in case you can see them correctly here they are in html: æ and ø and å) I've been trying to search the subject both on google and through the python.org site, but unsuccesfully... unforunetly. currently when i try to save the program using these special charaters, i get this error message: Traceback (most recent call last): File "D:\Programmer\python\lib\lib-tk\Tkinter.py", line 1300, in __call__ return apply(self.func, args) File "D:\PROGRA~1\python\Tools\idle\IOBinding.py", line 128, in save if self.writefile(self.filename): File "D:\PROGRA~1\python\Tools\idle\IOBinding.py", line 151, in writefile chars = str(self.text.get("1.0", "end-1c")) UnicodeError: ASCII encoding error: ordinal not in range(128) So hopefully any of you know whether it is possible or not and if it is I hope you can supply a link to a list of commands for special characters. thanks in advance Ole From eprice@ptc.com Fri Feb 21 11:29:00 2003 From: eprice@ptc.com (Erik Price) Date: Fri Feb 21 11:29:00 2003 Subject: [Tutor] Using special characters in Python In-Reply-To: <001701c2d9c4$a33349a0$8d4c73d5@oleioq8ex4m1zx> References: <20030221092408.GA3641@localhost> <001701c2d9c4$a33349a0$8d4c73d5@oleioq8ex4m1zx> Message-ID: <3E565332.4060902@ptc.com> Ole Jensen wrote: > I would like to now if it is possible to use special characters in pyth= on > especially in strings. I'm not sure if this will help you, but you can designate a given string=20 as a Unicode string by using this syntax: unicode_string =3D u"=E6on flux" There is also a unicode() function, you can read the docstring: >>> print unicode.__doc__ unicode(string [, encoding[, errors]]) -> object Create a new Unicode object from the given encoded string. encoding defaults to the current default string encoding and errors, defining the error handling, to 'strict'. >>> Erik From vicki@stanfield.net Fri Feb 21 11:44:00 2003 From: vicki@stanfield.net (vicki@stanfield.net) Date: Fri Feb 21 11:44:00 2003 Subject: [Tutor] passing data to Python callback Message-ID: <20030221084313.11337.h014.c000.wm@mail.stanfield.net.criticalpath.net> First, I apologize for my errant post earlier and for the wrong subject on my follow-up message. I am not an idiot - I just play one on this list. Now my question: How do you pass data to a callback? Is it done in the bind statement? I have done this in Motif, but I am new to this Python/Tkinter thing. Here is a code snippet: --------------- CommandListbox = Listbox(Frame1) CommandListbox.insert("end","First entry") CommandListbox.insert("end","Second entry") CommandListbox.pack() index = CommandListbox.index('active') CommandListbox.bind('', CommandListboxCallback) --------------- What I would like to do is pass the index of the selected entry to the callback, so how do I pass additional information beyond the event? Thank you. --vicki From ATrautman@perryjudds.com Fri Feb 21 11:49:02 2003 From: ATrautman@perryjudds.com (Alan Trautman) Date: Fri Feb 21 11:49:02 2003 Subject: [Tutor] Saving data to be retrieved later. Message-ID: <0BA95581EDA7D611841B00A0C9AD25DD2B59E7@mail.pjinet.com> Chris Bailey wrote: > Hey everyone, I'm a bit new to python, and I don't know much more than > the basics of programming in general. > I'm trying to find a bit of help, but websites/tutorials haven't been > very informative in the ways I need them to be. > Basically what im trying to do, is save a bunch of statistics > to seperate files, so they can be called on later. If > you are familiar with muds, i'm trying to work with pfiles. I just > thought I would make a single player text based > game for my friends and I to play. I have some neat ideas, and I think I > know how to implement them, But I > will of course need a way to save our characters! :) I too am working on a similar project and the ability to save and lookup information in the file is important but so is the ability to refer to a dictionary of what that attribute means. IE .. storing fireball4 for the character is only useful if can then look up somewhere in your program what to do with the fireball spell. The documentation style I used above is an example of XML notation. which the pyXML library seems (I am early in trying this out) to do a good job of referencing. The other advantage is using files for everything is pretty slow. This is where using pickle and fast items like the python dictionary may also be useful depending on the game style and level of complexity. For my game, which is non-thumb speed dependant, I'm trying to use XML indices . HTH, Alan _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From scot@possum.in-berlin.de Fri Feb 21 11:52:12 2003 From: scot@possum.in-berlin.de (Scot Stevenson) Date: Fri Feb 21 11:52:12 2003 Subject: [Tutor] Using special characters in Python In-Reply-To: <001701c2d9c4$a33349a0$8d4c73d5@oleioq8ex4m1zx> References: <20030221092408.GA3641@localhost> <001701c2d9c4$a33349a0$8d4c73d5@oleioq8ex4m1zx> Message-ID: <200302211754.11033.scot@possum.in-berlin.de> Hello Ole,=20 > The problem is that in Danish (and Norwegian) we have some characters i= n > the alphabet that doesn not exist in the english one, i.e. =E6, =F8, an= d =E5 (in > case you can see them correctly here they are in html: æ and &osl= ash; > and å) I have had the same problem with German Umlauts since I started with Pyth= on.=20 It is not so much due to Python, which handles non-US-characters beautifu= lly,=20 but Tkinter, which doesn't, and keeps spitting out things like your=20 > UnicodeError: ASCII encoding error: ordinal not in range(128) I acutally spent the better part of an evening trying to get Tkinter to a= ccept=20 Umlauts to use with the email.Utils.unquote() method, up to the point whe= re I=20 was systematically testing just what encoding Tkinter was returning the=20 string in (UTF-8? UTF-16? ISO-8859-1? 7-bit ASCII? Klingon?) but to no av= ail.=20 I ended up doing it the hard way with the older quopri module via cString= IO,=20 which is ugly, but at least works.=20 Anyway, what has worked for me in the past (but for some reason doesn't w= ork=20 every time) is a line such as: theinputstring =3D theinputstring.encode("ISO-8859-1") I'm sure there is some perfectly logical reason why Tkinter doesn't seaml= essly=20 integrate with Python when you are trying to do something else than Engli= sh,=20 but if I wanted to do things the hard way, I'd be programming in C++.=20 Switching to Qt is on my to-do list - Tkinter was okay to get started, bu= t=20 details like this just eat up too much time.=20 Y, Scot --=20 Scot W. Stevenson -- scot@possum.in-berlin.de -- Zepernick, Germany From ramrom@earthling.net Fri Feb 21 12:14:01 2003 From: ramrom@earthling.net (Bob Gailer) Date: Fri Feb 21 12:14:01 2003 Subject: [Tutor] Troubled by Tkinter questions In-Reply-To: <20030221084313.11337.h014.c000.wm@mail.stanfield.net.criti calpath.net> Message-ID: <5.2.0.9.0.20030221101112.030b6e60@66.28.54.253> --=======3BA47046======= Content-Type: text/plain; x-avg-checked=avg-ok-3F2219CD; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit Is there a mailing list for Tkinter that we could refer folk to. I am a bit troubled by all the posts that are Tkinter-specific. As one who has no interest in Tkinter, these questions just tie up my in-box, and since some of them don't even mention Tkinter in the subject, or worse, the body, it can be time consuming to weed them out. Bob Gailer mailto:ramrom@earthling.net 303 442 2625 --=======3BA47046======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-3F2219CD Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.454 / Virus Database: 253 - Release Date: 2/10/2003 --=======3BA47046=======-- From learning.python@dbmail.dk Fri Feb 21 13:09:10 2003 From: learning.python@dbmail.dk (Ole Jensen) Date: Fri Feb 21 13:09:10 2003 Subject: [Tutor] Using special characters in Python Message-ID: <003501c2d9d4$2c6f9700$8d4c73d5@oleioq8ex4m1zx> This is a multi-part message in MIME format. ------=_NextPart_000_0032_01C2D9DC.8E1B9500 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Ive digging a little deeper with the problem... as from the unicode.org page i've found out that the =E5 is written like = this: "00E5" (without the qoutes) in unicode, BUT when trying to do = create a string to that, a la:=20 http://www.python.org/doc/2.2p1/ref/strings.html >>> s =3D "u\00E5" >>> print s u and doing this with other unicode values also returns a "u" so i guess = something is not as it should... annother thing I discovered with some result was the unichr() - = function(found at http://www.python.org/doc/2.2p1/ref/types.html#l2h-63 = under unicode), which however doesn't do exactly what i'd expect: from http://www.unicode.org/charts/PDF/U0000.pdf: letter | unicode ------------------------ e 0065 when trying to out this into the unicode function: >>> e =3D unichr(0065) >>> e u'5' >>> print e 5 as you can see I didn't quite get the result I wanted. could it be that = the unicode function used in python doesn't use the unicode exactly as = it should??? or am I just doing it wrong? again if you know of any material on this subject, don't be shy Ol=E9 ole_jensen@dbmail.dk ------=_NextPart_000_0032_01C2D9DC.8E1B9500 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
Ive digging a little deeper with the=20 problem...
 
as from the unicode.org page i've found = out that=20 the =E5 is written like this: "00E5" (without the qoutes) in unicode, = BUT when=20 trying to do create a string to that, a la:
http://www.pyth= on.org/doc/2.2p1/ref/strings.html
 
>>> s =3D = "u\00E5"
>>> print s
u
 
and doing this with other unicode = values also=20 returns a "u" so i guess something is not as it should...
 
annother thing I discovered with some = result was=20 the unichr() - function(found at http://www= .python.org/doc/2.2p1/ref/types.html#l2h-63 under=20 unicode), which however doesn't do exactly what i'd expect:
from http://www.unicode.o= rg/charts/PDF/U0000.pdf:
 
letter   | =  unicode
------------------------
  =20 e          0065<= /DIV>
 
when trying to out this into the = unicode=20 function:
 
>>> e =3D = unichr(0065)
>>> e
u'5'
>>> print e
5
 
as you can see I didn't quite get the = result I=20 wanted. could it be that the unicode function used in = python doesn't use=20 the unicode exactly as it should??? or am I just doing it = wrong?
 
again if you know of any material on = this subject,=20 don't be shy
Ol=E9
ole_jensen@dbmail.dk
------=_NextPart_000_0032_01C2D9DC.8E1B9500-- From ramrom@earthling.net Fri Feb 21 13:40:02 2003 From: ramrom@earthling.net (Bob Gailer) Date: Fri Feb 21 13:40:02 2003 Subject: [Tutor] Troubled by Tkinter questions In-Reply-To: <20030221092808.16417.h014.c000.wm@mail.stanfield.net.criti calpath.net> Message-ID: <5.2.0.9.0.20030221113504.030aca80@66.28.54.253> --=======51C47FF======= Content-Type: text/plain; x-avg-checked=avg-ok-3F2219CD; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit At 09:28 AM 2/21/2003 -0800, you wrote: >My apologies. I didn't think of Tkinter as separate >from Python since I've never heard of anyone using it >with another language. My apologies too; I did not mean to jump on you explicitly; its just that there's been a lot of Tkinter traffic. I just did a Google search and found "TKInter is a Python package that provides access to the TCL/TK environment." I did not know this. I thought it was a separate product with a Python interface. So perhaps this is the best place for such questions. I do recommend making the subject line as explicit as possible. Bob Gailer mailto:ramrom@earthling.net 303 442 2625 --=======51C47FF======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-3F2219CD Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.454 / Virus Database: 253 - Release Date: 2/10/2003 --=======51C47FF=======-- From learning.python@dbmail.dk Fri Feb 21 14:13:01 2003 From: learning.python@dbmail.dk (Ole Jensen) Date: Fri Feb 21 14:13:01 2003 Subject: [Tutor] Using special characters in Python References: <20030221092408.GA3641@localhost> <001701c2d9c4$a33349a0$8d4c73d5@oleioq8ex4m1zx> <200302211754.11033.scot@possum.in-berlin.de> Message-ID: <00c601c2d9dc$ff17fd70$8d4c73d5@oleioq8ex4m1zx> Olé ole_jensen@dbmail.dk ----- Original Message ----- From: "Scot Stevenson" To: "Ole Jensen" ; Sent: Friday, February 21, 2003 5:54 PM Subject: Re: [Tutor] Using special characters in Python > Hello Ole, > > > The problem is that in Danish (and Norwegian) we have some characters in > > the alphabet that doesn not exist in the english one, i.e. ć, ř, and ĺ (in > > case you can see them correctly here they are in html: æ and ø > > and å) > > I have had the same problem with German Umlauts since I started with Python. > It is not so much due to Python, which handles non-US-characters beautifully, > but Tkinter, which doesn't, and keeps spitting out things like your > > > UnicodeError: ASCII encoding error: ordinal not in range(128) > Ok so thats why I can't do the special characters in IDLE (IDLE being made from python and TKinter, I believe). > I acutally spent the better part of an evening trying to get Tkinter to accept > Umlauts to use with the email.Utils.unquote() method, up to the point where I > was systematically testing just what encoding Tkinter was returning the > string in (UTF-8? UTF-16? ISO-8859-1? 7-bit ASCII? Klingon?) but to no avail. > I ended up doing it the hard way with the older quopri module via cStringIO, > which is ugly, but at least works. > > Anyway, what has worked for me in the past (but for some reason doesn't work > every time) is a line such as: > > theinputstring = theinputstring.encode("ISO-8859-1") > I don't know exectly how to use that example, as when you type it in python doesn't know the 'theinputstring' function, is it a function you have made? or do you need to import something to get it to work? >>> theinputstring = theinputstring.encode("ISO-8859-1") Traceback (most recent call last): File "", line 1, in ? theinputstring = theinputstring.encode("ISO-8859-1") NameError: name 'theinputstring' is not defined > I'm sure there is some perfectly logical reason why Tkinter doesn't seamlessly > integrate with Python when you are trying to do something else than English, > but if I wanted to do things the hard way, I'd be programming in C++. > Switching to Qt is on my to-do list - Tkinter was okay to get started, but > details like this just eat up too much time. > Furthermore, when I open up python(command line) (as my guess was I coudn't use idle) I could without trouble use all the special characters on my keybord, i.e. ć, ř and ĺ. So now I was thinking I could just write the special characters in notepad and the run my program(that doesn't use TKinter) by double clicking the windows icon, which opens python.exe, but it didn't work as planned. The ĺ's became Ő and the ř became the superscipt of o. Strange... I don't even know what to comment on that > Y, Scot > > -- > Scot W. Stevenson -- scot@possum.in-berlin.de -- Zepernick, Germany > Ole From alan.gauld@bt.com Fri Feb 21 14:14:14 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Fri Feb 21 14:14:14 2003 Subject: [Tutor] passing data to Python callback Message-ID: <7497DCA1C240C042B28F6657ADFD8E0901F8510E@i2km11-ukbr.domain1.systemhost.net> > How do you pass data to a callback? Is it done in the > bind statement? I have done this in Motif, but I am new > to this Python/Tkinter thing. This is not IMHO documented well in the Tkinter books etc. If you use bind there will be an event parameter in the callback. Some of the data you need might be in the event object, but you need to dig hard to find the definitions of the ovbject. I usually find it easier to just get python to print the object to the console!!! If anyone knows the scientifoifc way of doing this - like a reference page someplace that would be appreciated. > CommandListbox.bind('', > CommandListboxCallback) > --------------- > > What I would like to do is pass the index of the As to your specific qurery I can't help other than to suggest you put some test print statements in the code of the callback function! Alan G From jeff@ccvcorp.com Fri Feb 21 14:14:28 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Fri Feb 21 14:14:28 2003 Subject: [Tutor] Troubled by Tkinter questions References: <5.2.0.9.0.20030221113504.030aca80@66.28.54.253> Message-ID: <3E567A81.9030004@ccvcorp.com> Bob Gailer wrote: > My apologies too; I did not mean to jump on you explicitly; its just > that there's been a lot of Tkinter traffic. I just did a Google search > and found "TKInter is a Python package that provides access to the > TCL/TK environment." I did not know this. I thought it was a separate > product with a Python interface. Just to be clear -- Tkinter is a Python interface to the Tk gui toolkit (TK INTERface -- get it?). Tk was originally designed for use with the Tcl language, and the two have been tightly bound for a long time -- so much so that you see references to Tcl/Tk more often than for either of them separately. However, Tk also has Python (Tkinter) and Perl (PerlTk) interfaces. I don't know about PerlTk, but in the Tkinter case, it's a matter of Python driving Tcl which drives the Tk toolkit. Since Tkinter is part of the standard Python distribution, it's not surprising that there's lots of questions about it here. But it's also a kind of specialized sub-area, and (it seems to me) it *would* be suitable to have a separate mailing list devoted to it. Whether such a list already exists or not, though, I have no idea -- there's a number of different GUI toolkits for Python, and I personally prefer wxPython to Tkinter, so I haven't kept track of what's available for Tkinter support. Jeff Shannon Technician/Programmer Credit International From am@fx.ro Fri Feb 21 15:02:15 2003 From: am@fx.ro (am@fx.ro) Date: Fri Feb 21 15:02:15 2003 Subject: [Tutor] using sockets to send a list Message-ID: <20030221235127.A293@coto> Hello all! I am working on a networked cards game called "President". The server should be able to send some information to all the clients, using sockets. After experimenting a while, i have reached a dead end. It is possible that my approach is completely wrong - maybe there are other functions/modules and i am not aware of their existance. The information i need to send over the net is a list ( whose elements are dictionaries ): print self.players [{'name': 'gogu', 'lastcards': [], 'status': 0, 'cards': [(16, 0), (4, 0), (5, 0 ), (6, 0), (7, 0), (8, 0), (9, 0), (10, 0), (11, 0), (12, 0), (13, 0), (14, 0), (15, 0), (3, 1), (4, 1), (5, 1), (6, 1), (15, 3)]}, {'name': 'gogu', 'lastcards' : [], 'status': 0, 'cards': [(7, 1), (8, 1), (9, 1), (10, 1), (11, 1), (12, 1), (13, 1), (14, 1), (15, 1), (3, 2), (4, 2), (5, 2), (6, 2), (7, 2), (8, 2), (9, 2 ), (10, 2)]}, {'name': 'gogu', 'lastcards': [], 'status': 0, 'cards': [(11, 2), (12, 2), (13, 2), (14, 2), (15, 2), (3, 3), (4, 3), (5, 3), (6, 3), (7, 3), (8, 3), (9, 3), (10, 3), (11, 3), (12, 3), (13, 3), (14, 3)]}] Here is what i've tried so far: 1. i have created the sockets, using the 'socket' module. Sending strings is working fine. 2. the list has to be converted somehow to a string before sending it, right? Is the 'pickle' module the right way to do this? or is there another solution? 3. starting from the examples found in the reference manual for pickle, i have tried to adapt them and here is the result # SERVER: def sendinfo(self,player): src=StringIO() p=pickle.Pickler(src) p.dump(self.players) self.sockets[player].send(src.getvalue(),1024) # CLIENT: def getinfo(self): dst = StringIO(self.sock.recv(1024)) up = pickle.Unpickler(dst) self.players=up.load() Errors: - server: self.sockets[player].send(src.getvalue(),1024) socket.error: (22, 'Invalid argument') ( i guess it doesn't like src.getvalue() ... ? ) - client: File "client.py", line 111, in getinfo self.players=up.load_list() File "/usr/lib/python1.5/pickle.py", line 591, in load_list k = self.marker() File "/usr/lib/python1.5/pickle.py", line 500, in marker stack = self.stack AttributeError: stack ( at least it realises that it's a list : it uses load_list ) Any ideas? Maybe i shouldn't use StringIO at all, but attach the (Un)Pickler directly to the socket? Thank you. -- Adrian Maier (am@fx.ro) From SWidney@ci.las-vegas.nv.us Fri Feb 21 15:41:06 2003 From: SWidney@ci.las-vegas.nv.us (Scott Widney) Date: Fri Feb 21 15:41:06 2003 Subject: [Tutor] Saving data to be retrieved later. Message-ID: <0E5508EBA1620743B409A2B8365DE16FDC83BD@sovereign.ci.las-vegas.nv.us> > Hey everyone, I'm a bit new to python, and I don't know much > more than the basics of programming in general. > I'm trying to find a bit of help, but websites/tutorials > haven't been very informative in the ways I need them to be. > Basically what im trying to do, is save a bunch of statistics > to seperate files, so they can be called on later. If > you are familiar with muds, i'm trying to work with pfiles. I > just thought I would make a single player text based > game for my friends and I to play. I have some neat ideas, > and I think I know how to implement them, But I > will of course need a way to save our characters! :) > A short while ago, Andrew Wilkins received help from this list for the very same thing. A quick search of the archives could provide you with some valuable information (IIRC, (c)pickle was the answer for him). He also attached the finished code to one of his messages. You might also email Andrew to see if he can send you a copy of his code. Scott From glingl@aon.at Fri Feb 21 16:05:03 2003 From: glingl@aon.at (Gregor Lingl) Date: Fri Feb 21 16:05:03 2003 Subject: [Tutor] passing data to Python callback References: <20030221084313.11337.h014.c000.wm@mail.stanfield.net.criticalpath.net> Message-ID: <3E5694AC.3050402@aon.at> vicki@stanfield.net schrieb: >First, I apologize for my errant post earlier and for >the wrong subject on my follow-up message. I am not an >idiot - I just play one on this list. > >Now my question: > >How do you pass data to a callback? Is it done in the >bind statement? I have done this in Motif, but I am new >to this Python/Tkinter thing. > I'll try to describe one way, how this can be done: # (1) Bundle your data as attributes of some object: # First you have to create a class: class Xyz: def __init__(self, data1, data2, etc): self.data1 = data1 self.data2 = data2 self.etc = self.etc # (2) Create a method as callback: def callback(self, event). #... the code # has access to all the data contained in the event-object (see Alan's statement) # but also to all the data, which are attributes of self ... # (3) Create an object (an instance of this class): # with your data as arguments: something = Xyz(value1, value2, more) # Now something.callback is exacly what bind expects: # ... a function-object with *one* parameter, to which an event is to be assigned ... # as the first parameter is already assignet to *something* ;-) CommandListbox.bind(', something.callback) Here a q&d example: ######################## from Tkinter import * message="Hello World" class Message: def __init__(self,message,label): self.message = message self.label = label def callback(self,event): self.label["text"] = self.message root = Tk() label = Label(root, width=20) label.pack() m = Message(message,label) root.bind('', m.callback) root.mainloop() ######################### More on Tkinter you can find at "hinking in Tkinter": http://home.att.net/~stephen_ferg/thinking_in_tkinter/index.html Hope that helps, Gregor > >Here is a code snippet: > >--------------- >CommandListbox = Listbox(Frame1) >CommandListbox.insert("end","First entry") >CommandListbox.insert("end","Second entry") >CommandListbox.pack() >index = CommandListbox.index('active') >CommandListbox.bind('', >CommandListboxCallback) >--------------- > >What I would like to do is pass the index of the >selected entry to the callback, so how do I pass >additional information beyond the event? > >Thank you. > >--vicki > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > > From gus.tabares@verizon.net Fri Feb 21 20:29:02 2003 From: gus.tabares@verizon.net (Gus Tabares) Date: Fri Feb 21 20:29:02 2003 Subject: [Tutor] os.path.walk Message-ID: Hey all, I'm trying to run this simple script and I'm not sure what the problem is. Any help would be appreciated. import os def visit(arg, dirname, names): for names in dirname: if (names[-4:] != '.mp3'): os.rename(names, (names[:-4] + '.mp3')) else: pass dummy = [] os.path.walk("G:\\Mp3s", visit, dummy) Here is the traceback: Traceback (most recent call last): File "mp3.py", line 19, in ? os.path.walk("G:\\Mp3s", visit, dummy) File "C:\Python22\lib\ntpath.py", line 318, in walk func(arg, top, names) File "mp3.py", line 12, in visit os.rename(names, (names[:-4] + '.mp3')) OSError: [Errno 2] No such file or directory I am 100% positive my G:\Mp3s dir does exist:) From Don Arnold" Message-ID: <0d7301c2da1b$272c44e0$8a11ba3f@defaultcomp> ----- Original Message ----- From: To: Sent: Friday, February 21, 2003 3:51 PM Subject: [Tutor] using sockets to send a list > > Hello all! > > > I am working on a networked cards game called "President". The > server should be able to send some information to all the clients, > using sockets. > > After experimenting a while, i have reached a dead end. It is > possible that my approach is completely wrong - maybe there are > other functions/modules and i am not aware of their existance. > > > The information i need to send over the net is a list ( whose > elements are dictionaries ): > > print self.players > > [{'name': 'gogu', 'lastcards': [], 'status': 0, 'cards': [(16, 0), (4, 0), (5, 0 > ), (6, 0), (7, 0), (8, 0), (9, 0), (10, 0), (11, 0), (12, 0), (13, 0), (14, 0), > (15, 0), (3, 1), (4, 1), (5, 1), (6, 1), (15, 3)]}, {'name': 'gogu', 'lastcards' > : [], 'status': 0, 'cards': [(7, 1), (8, 1), (9, 1), (10, 1), (11, 1), (12, 1), > (13, 1), (14, 1), (15, 1), (3, 2), (4, 2), (5, 2), (6, 2), (7, 2), (8, 2), (9, 2 > ), (10, 2)]}, {'name': 'gogu', 'lastcards': [], 'status': 0, 'cards': [(11, 2), > (12, 2), (13, 2), (14, 2), (15, 2), (3, 3), (4, 3), (5, 3), (6, 3), (7, 3), (8, > 3), (9, 3), (10, 3), (11, 3), (12, 3), (13, 3), (14, 3)]}] > > > Here is what i've tried so far: > > 1. i have created the sockets, using the 'socket' module. > Sending strings is working fine. > > > 2. the list has to be converted somehow to a string before > sending it, right? > > Is the 'pickle' module the right way to do this? or is there > another solution? > I don't know much (if anything) about sockets, but if you can send strings, this might work (though it is kludgy): 1. Use the str() built in function to convert your data into a string 2. Send the string to the client 3. Receive the string on the client side into a buffer 4. Use exec() with string formatting to load the buffer back into a variable. Here's the process simulated in the interpreter: >>> a = [(1,2,3),{4: 'stuff'},[5,6]] >>> aAsString = str(a) ##this gets sent via the socket.... >>> buf = aAsString ##imagine buffer is receiving its value from the socket >>> exec('b = %s' % buf) >>> print b [(1, 2, 3), {4: 'stuff'}, [5, 6]] If I haven't mangled it too badly, your code might end up looking something like this. # SERVER: def sendinfo(self,player): self.sockets[player].send(str(self.players),1024) # CLIENT: def getinfo(self): dst = self.sock.recv(1024) exec('self.players = %s' % dst) HTH, Don From carroll@tjc.com Fri Feb 21 22:12:16 2003 From: carroll@tjc.com (Terry Carroll) Date: Fri Feb 21 22:12:16 2003 Subject: [Tutor] Troubled by Tkinter questions In-Reply-To: <5.2.0.9.0.20030221101112.030b6e60@66.28.54.253> Message-ID: On Fri, 21 Feb 2003, Bob Gailer wrote: > Is there a mailing list for Tkinter that we could refer folk to. I am a bit > troubled by all the posts that are Tkinter-specific. As one who has no > interest in Tkinter, these questions just tie up my in-box.... As one who *is* highly interested, I'd agree with you. I'm fairly new to Python, and starting to use Tkinter for the first time, and am betting that my post was one you had in mind. Tkinter is, it seems to me, a specialized enough area that there ought to be a separate list (or newsgroup or some other more or less functionally equivalent forum) for it, but I've been unable to find one. I've found lists for Anygui[1] and wxPython,[2] but none for the "official" GUI, Tkinter. I guess because it *is* more or less the official GUI of Python, it's as much at home in a Tutor mailing list as anything else, but I see it as sort of a specialized area, not core language or product feature (heck, if it were more of a core feature, it'd probably be better documented and we'd have fewer questions!), much as, say, XML support or database support (each of which does have its own list[3]) are considered specialized areas. In my defense, I went looking for a Tkinter mailing list to join before posting my Tkinter question here. If there wre a Tkinter list, I'd join it. > ...and since some of them don't even mention Tkinter in the subject, or > worse, the body, it can be time consuming to weed them out. That, I think, is something we should all try to avoid. I try to use a good subject header and make sure that the subject of my post is apparent from the subject header; not so much for the benefit of people like you who don't want to read things there interested in (although that's a nice side benefit), but because I expect most people to read a moderately high-volume mailing list like this in the same way I do: I hit delete on most things *unless* I see a subject that's interesting (so messages with subjects like "Help, please!" usually go deleted unread). We should all make it a point to use good subject headings so that both delete-by-default readers like me and read-by-default readers like Bob can make better use of their time on this list. After all, it's the list membership who make it worthwhile, and every person who ends up leaving the list because it uses up too much of their time is a diminishment of the list's value. [1] http://anygui.sourceforge.net/ http://aspn.activestate.com/ASPN/Mail/About/anygui-devel/ [2] http://www.wxpython.org/maillist.php http://aspn.activestate.com/ASPN/Mail/About/wxPython-users/ [3] XML: http://aspn.activestate.com/ASPN/Mail/About/xml-sig/ DB: http://aspn.activestate.com/ASPN/Mail/About/db-sig/ -- Terry Carroll | "To have this rare opportunity Santa Clara, CA | is a rare opportunity." carroll@tjc.com | - Houston Rockets' Yao Ming, on being named Modell delendus est | starting center for the 2003 NBA All-Star Game From shalehperry@attbi.com Fri Feb 21 22:22:11 2003 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Fri Feb 21 22:22:11 2003 Subject: [Tutor] os.path.walk In-Reply-To: References: Message-ID: <200302211919.22120.shalehperry@attbi.com> On Friday 21 February 2003 20:28, Gus Tabares wrote: > Hey all, > > =09I'm trying to run this simple script and I'm not sure what the probl= em is. > Any help would be appreciated. > > > os.path.walk("G:\\Mp3s", visit, dummy) > > Here is the traceback: > > Traceback (most recent call last): > File "mp3.py", line 19, in ? > os.path.walk("G:\\Mp3s", visit, dummy) > File "C:\Python22\lib\ntpath.py", line 318, in walk > func(arg, top, names) > File "mp3.py", line 12, in visit > os.rename(names, (names[:-4] + '.mp3')) > OSError: [Errno 2] No such file or directory > > > I am 100% positive my G:\Mp3s dir does exist:) > little hint. When you get confused by something like os.path.walk, a lit= tle=20 use of 'print' goes a long way. And don't feel bad when you find the ans= wer,=20 we all forget and make the same mistake from time to time. From ramrom@earthling.net Fri Feb 21 22:28:08 2003 From: ramrom@earthling.net (Bob Gailer) Date: Fri Feb 21 22:28:08 2003 Subject: [Tutor] os.path.walk In-Reply-To: Message-ID: <5.2.0.9.0.20030221200411.0309a970@66.28.54.253> --=======3009658E======= Content-Type: text/plain; x-avg-checked=avg-ok-3F2219CD; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit At 08:28 PM 2/21/2003 -0800, Gus Tabares wrote: >1 import os >2 def visit(arg, dirname, names): >3 for names in dirname: >4 if (names[-4:] != '.mp3'): >5 os.rename(names, (names[:-4] + '.mp3')) >6 else: >7 pass >8 dummy = [] >9 os.path.walk("G:\\Mp3s", visit, dummy) 3 - the argument 'names' contains the file names, not 'dirname' 4 - this assumes that the original extension is 3 chars. Not a good idea in general. Use os.path.splitext() 5 - you must specify the complete path name, not just the filename 6,7 unnecessary 8,9 can pass None instead of creating a variable Many minor changes - Try this revision and see if you can understand why the changes. One of my assumptions is that there could be subdirectories, which would be the reason to use walk instead of glob. import os def visit(arg, dirname, names): dirname = dirname + '\\' for name in names: (root, ext) = os.path.splitext(name) if ext and (ext != '.mp3'): os.rename(dirname + name, dirname + root + '.mp3') os.path.walk("G:\\Mp3s", visit, None) Bob Gailer mailto:ramrom@earthling.net 303 442 2625 --=======3009658E======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-3F2219CD Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.454 / Virus Database: 253 - Release Date: 2/10/2003 --=======3009658E=======-- From magnus@thinkware.se Fri Feb 21 23:19:01 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Fri Feb 21 23:19:01 2003 Subject: [Tutor] Using special characters in Python In-Reply-To: <20030222023701.8794.56839.Mailman@mail.python.org> Message-ID: <5.1.0.14.0.20030222045410.02b38fc8@www.thinkware.se> At Fri, 21 Feb 2003 19:08:01 +0100, Ole Jensen wrote: >as from the unicode.org page i've found out that the =E5 is written like = >this: "00E5" (without the qoutes) in unicode, BUT when trying to do = >create a string to that, a la:=20 >http://www.python.org/doc/2.2p1/ref/strings.html > > >>> s =3D "u\00E5" > >>> print s >u I think you need to read more carefully. You want: print u"\u00E5" ... stringliteral ::= [stringprefix](shortstring | longstring) stringprefix ::= "r" | "u" | "ur" | "R" | "U" | "UR" | "Ur" | "uR" ... A prefix of 'u' or 'U' makes the string a Unicode string. ... \uxxxx Character with 16-bit hex value xxxx (Unicode only) \Uxxxxxxxx Character with 32-bit hex value xxxxxxxx (Unicode only) ... See also http://www.reportlab.com/i18n/python_unicode_tutorial.html (this is a bit old, you don't need to get Python from CVS of course.) I didn't follow this thread thorougly, but Latin1 is the default encoding in Python, so, for western European encodings, we don't usually need Unicode. Also, have a look at the locale module. You typically use it like this: import locale locale.setlocale(locale.LC_ALL, '') Then sorting etc will behave as per your locale. As far as I understand, the only European languages that behave exactly the same as English when it comes to sorting etc are Portugese and Italian, so it's not just in Scandinavia we are different... Finally, if you want to print to a DOS-box in windows, you need to know how to handle code pages: print stringWithNtnlChars.decode('latin1').encode('cp437') Sometimes you need to do vice versa: import os x = os.popen('DIR').read() print x.decode('cp437').encode('latin1') Actually, if you are printing in a Unicode aware environment, you only need: import os x = os.popen('DIR').read() print x.decode('cp437') but if you are for instance writing to a web page, Latin1 might be better. -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From Jmllr891@cs.com Fri Feb 21 23:49:08 2003 From: Jmllr891@cs.com (Jmllr891@cs.com) Date: Fri Feb 21 23:49:08 2003 Subject: [Tutor] Re: Using special characters in Python Message-ID: <000b01c2da2d$e458bf00$58bc8018@ne1.client2.attbi.com> I think I may have a solution to this problem. It seems that when you try to use characters that are not in the unicode range of 128, without first directly encoding your character or string, something like this happens: ch = unichr(256) print ch Traceback (most recent call last): File "", line 1, in ? UnicodeError: ASCII encoding error: ordinal not in range(128) I'm not 100% sure what causes this, but I think it is because Python, by default, only uses the characters normally found in the English language. I do not know what the character codes are for the particular characters you are trying to use, but you are able to use them with something like this: ch = unichr(code).encode("UTF-8") or mystring = "mystring %s%s" % (unichr(129), unichr(256)) mystring = mystring.encode("UTF-8") Of course, UTF-8 isn't the only available encoding and the above is only a basic example of what you could encode and how you could encode it. I also have a basic idea of how you could find the character codes: for n in range(256): print n, unichr(n).encode("UTF-8") The above may be a little messy, but at least it gets the job done. You may have to play with the range a bit if you can't initially find the character(s) you are looking for. I hope this helps! Joshua Miller From jeff@ccvcorp.com Sat Feb 22 01:37:16 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Sat Feb 22 01:37:16 2003 Subject: [Tutor] os.path.walk References: Message-ID: <3E56D9E1.5080907@ccvcorp.com> Gus Tabares wrote: >Traceback (most recent call last): > File "mp3.py", line 19, in ? > os.path.walk("G:\\Mp3s", visit, dummy) > File "C:\Python22\lib\ntpath.py", line 318, in walk > func(arg, top, names) > File "mp3.py", line 12, in visit > os.rename(names, (names[:-4] + '.mp3')) >OSError: [Errno 2] No such file or directory > >I am 100% positive my G:\Mp3s dir does exist:) > > Ah, but is that *really* what the error is about? :) def visit(arg, dirname, names): for names in dirname: if (names[-4:] != '.mp3'): os.rename(names, (names[:-4] + '.mp3')) else: pass Now, in this visit() function, 'dirname' will be the name of the directory (in string form), while 'names' will be a list of all the filenames within that directory. However, your first line, 'for names in dirname:', tries to iterate over the string that's bound to dirname, i.e. "G:\Mp3s". Iterating over a string yields a single character, so 'names' gets re-bound to the letter 'G'. Obviously you're going to have problems with renaming the file 'G' ... :) As a minor additional point, it's good form to use the os.path module to handle your filenames, and the 'else: pass' bit is superfluous, as is the use of a 'dummy' list (just use None instead). Try this instead: def visit(arg, dirname, names): for name in names: base, ext = os.path.splitext() if ext != '.mp3': newname = '%s.mp3' % base os.rename(name, newname) os.path.walk("G:\\Mp3s", visit, None) Feel free to ask for further clarifications about the reasoning behind this (but also be prepared to wait until Monday for an answer, since I don't check this email address on weekends :) ) Jeff Shannon Technician/Programmer Credit International From abli@freemail.hu Sat Feb 22 02:25:02 2003 From: abli@freemail.hu (Abel Daniel) Date: Sat Feb 22 02:25:02 2003 Subject: [Tutor] passing data to Python callback In-Reply-To: <20030221084313.11337.h014.c000.wm@mail.stanfield.net.criticalpath.net> References: <20030221084313.11337.h014.c000.wm@mail.stanfield.net.criticalpath.net> Message-ID: <20030222072443.GA1644@hooloovoo> vicki@stanfield.net (vicki@stanfield.net) wrote: > How do you pass data to a callback? Is it done in the > bind statement? I have done this in Motif, but I am new > to this Python/Tkinter thing. Get http://www.nmt.edu/tcc/help/lang/python/tkinter.ps, which is the best reference doc I saw about tkinter. (There is a link to a pdf version from http://www.nmt.edu/tcc/help/lang/python/tkinter.html, look for 'Tkinter reference: a GUI for Python' in the local links section.) On page 83 of that the 'extra arguments trick' is described which uses lambdas to pass in extra arguments to the callbacks. > > Here is a code snippet: > > --------------- > CommandListbox = Listbox(Frame1) > CommandListbox.insert("end","First entry") > CommandListbox.insert("end","Second entry") > CommandListbox.pack() > index = CommandListbox.index('active') > CommandListbox.bind('', > CommandListboxCallback) > --------------- > > What I would like to do is pass the index of the > selected entry to the callback, so how do I pass > additional information beyond the event? However, in this case, _you_ dont pass in the index, because you simply don't know at the time you bind the callback. The callback function will get one argument (the event object) when the event happens. This event has a widget attribute, which is the widget where the event happened, in this case the listbox. So the callback has to ask the listbox which lines are selected. So it should look like this: def callback(event): print 'selected lines:' print event.widget.curselection() .curselection will return a tuple containing the indices of the selected lines. However, this naive binding won't work, the callback will print all sorts of numbers, but not the ones which are currently selected. Further inspection will show, that it prints the indices of the previous selection. Why? You are binding to event, and that gets called when the mouse button is pressed. At that moment, the listbox itself didn't yet register the selection you made. So you should bind to , and it will work. abli From abli@freemail.hu Sat Feb 22 02:50:03 2003 From: abli@freemail.hu (Abel Daniel) Date: Sat Feb 22 02:50:03 2003 Subject: [Tutor] using sockets to send a list In-Reply-To: <0d7301c2da1b$272c44e0$8a11ba3f@defaultcomp> References: <20030221235127.A293@coto> <0d7301c2da1b$272c44e0$8a11ba3f@defaultcomp> Message-ID: <20030222074927.GB1644@hooloovoo> Don Arnold (darnold02@sprynet.com) wrote: > I don't know much (if anything) about sockets, but if you can send strings, > this might work (though it is kludgy): It's not only kludgy, but extremly dangerous, too. > > 1. Use the str() built in function to convert your data into a string > 2. Send the string to the client > 3. Receive the string on the client side into a buffer > 4. Use exec() with string formatting to load the buffer back into a > variable. Two problems: There is no garantee that exec-ing the result of str() will give back the original object. It might work for basic types (like lists, dicts), but it won't work in cases like this: >>> class foo: ... pass ... >>> f=foo() >>> f <__main__.foo instance at 0x8111be4> >>> str(f) '<__main__.foo instance at 0x8111be4>' >>> If you exec that, you will get a string and not an instace of foo. The second problem is the basic problem with using exec. Like what happens if the string you get is "42; print 'you are h4xOr3d!!'" ? >>> s="42; print 'you are h4xOr3d!!'" >>> exec('b = %s' % s) you are h4xOr3d!! >>> Replacing the print statement with something truly destructive is left as an exercise to the reader. I might trust you (and your server) enough to play a game, but I seriously doubt I would trust you enough to let you execute arbitrary commands on my computer. I would use pickle instead. abli From am@fx.ro Sat Feb 22 03:14:01 2003 From: am@fx.ro (am@fx.ro) Date: Sat Feb 22 03:14:01 2003 Subject: [Tutor] using sockets to send a list In-Reply-To: <0d7301c2da1b$272c44e0$8a11ba3f@defaultcomp>; from darnold02@sprynet.com on Fri, Feb 21, 2003 at 08:35:49PM -0600 References: <20030221235127.A293@coto> <0d7301c2da1b$272c44e0$8a11ba3f@defaultcomp> Message-ID: <20030222115718.A225@coto> On Fri, Feb 21, 2003 at 08:35:49PM -0600, Don Arnold wrote: > # SERVER: > > def sendinfo(self,player): > self.sockets[player].send(str(self.players),1024) > > # CLIENT: > > def getinfo(self): > dst = self.sock.recv(1024) > exec('self.players = %s' % dst) It worked. Thanks! The 'secret' was the str() function. A had to do a few changes to the code above: - i removed the second parameter (1024) of the send() function - it doesn't seem to be absolutely neccessary to use exec in the client: self.player=dst has the same effect. Best wishes, Adrian Maier (am@fx.ro) From am@fx.ro Sat Feb 22 03:26:21 2003 From: am@fx.ro (Adrian Maier) Date: Sat Feb 22 03:26:21 2003 Subject: [Tutor] using sockets to send a list In-Reply-To: <20030222074927.GB1644@hooloovoo>; from abli@freemail.hu on Sat, Feb 22, 2003 at 08:49:27AM +0100 References: <20030221235127.A293@coto> <0d7301c2da1b$272c44e0$8a11ba3f@defaultcomp> <20030222074927.GB1644@hooloovoo> Message-ID: <20030222121623.A342@coto> On Sat, Feb 22, 2003 at 08:49:27AM +0100, Abel Daniel wrote: > Replacing the print statement with something truly destructive is left > as an exercise to the reader. > I might trust you (and your server) enough to play a game, but I > seriously doubt I would trust you enough to let you execute arbitrary > commands on my computer. > > I would use pickle instead. I see. Now i've found an acceptable temporary solution : instead of : exec("self.player=%s"%dst) i do: self.player = dst (i guess this is less dangerous) I'll try to improve the program to use pickle later , when i'll have more time. -- Adrian Maier (am@fx.ro) From reavey@nep.net Sat Feb 22 06:53:02 2003 From: reavey@nep.net (reavey) Date: Sat Feb 22 06:53:02 2003 Subject: [Tutor] print variable in quotes Message-ID: <3E58B5A0.20409@nep.net> hi I need help printing a variable in quotes. pre = "FGRTPQMK" suf = "ack" for elem in pre: print "echo " elem+suf I'd like to get the variable elem+suf in double qoutations? The output I'd like to see: echo "Fack" echo "Gack" is to be read by a screensaver called phosphor and used in an elem school to reinforce an early reading concept using word families. thanks re-v From glingl@aon.at Sat Feb 22 07:05:01 2003 From: glingl@aon.at (Gregor Lingl) Date: Sat Feb 22 07:05:01 2003 Subject: [Tutor] print variable in quotes References: <3E58B5A0.20409@nep.net> Message-ID: <3E576772.20202@aon.at> reavey schrieb: > hi > I need help printing a variable in quotes. > pre = "FGRTPQMK" > suf = "ack" > for elem in pre: > print "echo " elem+suf > > I'd like to get the variable elem+suf in double qoutations? > The output I'd like to see: > echo "Fack" > echo "Gack" (1) print 'echo "' + elem + suf + '"' or (2) print 'echo "%s"' % (elem+suf) Regards, Gregor > > is to be read by a screensaver called phosphor and used in an elem > school to > reinforce an early reading concept using word families. > > thanks > re-v > > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From gerrit@nl.linux.org Sat Feb 22 07:22:02 2003 From: gerrit@nl.linux.org (Gerrit Holl) Date: Sat Feb 22 07:22:02 2003 Subject: [Tutor] print variable in quotes In-Reply-To: <3E58B5A0.20409@nep.net> References: <3E58B5A0.20409@nep.net> Message-ID: <20030222122339.GA3556@nl.linux.org> reavey schreef op zaterdag 22 februari om 12:54:15 +0000: > hi > I need help printing a variable in quotes. > pre = "FGRTPQMK" > suf = "ack" > for elem in pre: > print "echo " elem+suf > > I'd like to get the variable elem+suf in double qoutations? > The output I'd like to see: > echo "Fack" > echo "Gack" > is to be read by a screensaver called phosphor and used in an elem > school to > reinforce an early reading concept using word families. 36 >>> a="Monty Python's flying circus" 37 >>> print a Monty Python's flying circus 38 >>> print repr(a) "Monty Python's flying circus" 39 >>> print `a` "Monty Python's flying circus" yours, Gerrit. -- Asperger Syndroom - een persoonlijke benadering: http://people.nl.linux.org/~gerrit/ Het zijn tijden om je zelf met politiek te bemoeien: http://www.sp.nl/ From Don Arnold" <0d7301c2da1b$272c44e0$8a11ba3f@defaultcomp> <20030222074927.GB1644@hooloovoo> <20030222121623.A342@coto> Message-ID: <0e6c01c2da83$ab8a8c70$8a11ba3f@defaultcomp> ----- Original Message ----- From: "Adrian Maier" To: "Abel Daniel" Cc: "Don Arnold" ; ; Sent: Saturday, February 22, 2003 4:16 AM Subject: Re: [Tutor] using sockets to send a list > On Sat, Feb 22, 2003 at 08:49:27AM +0100, Abel Daniel wrote: > > Replacing the print statement with something truly destructive is left > > as an exercise to the reader. > > I might trust you (and your server) enough to play a game, but I > > seriously doubt I would trust you enough to let you execute arbitrary > > commands on my computer. > > > > I would use pickle instead. I would've, too, if I had known how. ; ) > > I see. > > Now i've found an acceptable temporary solution : > instead of : exec("self.player=%s"%dst) > i do: self.player = dst > (i guess this is less dangerous) Less dangerous, but non-functional: self.player is now a string representation of what was sent, not an actual object of the appropriate type. > > I'll try to improve the program to use pickle later , when i'll > have more time. > After looking through the documentation and book or two (specifically, Wesley Chun's "Core Python Programming" and Steve Holden's "Python Web Programming"), here's what I've come up with: #################################################### ## myData.py - data structure to be sent #################################################### class Data: def __init__(self,*args): self.members = [item for item in args] def showMembers(self): for item in self.members: print '\t>>', item #################################################### ## server.py - receives an object from the socket #################################################### from socket import * import cPickle import StringIO import myData if __name__ == '__main__': HOST = '127.0.0.1' PORT = 50000 BUFSIZE = 1024 ADDR = (HOST, PORT) serverSock = socket(AF_INET, SOCK_STREAM) serverSock.bind(ADDR) serverSock.listen(5) clientSock, address = serverSock.accept() print 'connection from:', address databuffer = StringIO.StringIO(clientSock.recv(BUFSIZE)) someobj = cPickle.load(databuffer) print type(someobj) someobj.showMembers() clientSock.close() serverSock.close() #################################################### ## client.py - sends an object to the server #################################################### from socket import * import cPickle import StringIO import myData if __name__ == '__main__': HOST = '127.0.0.1' PORT = 50000 BUFSIZE = 1024 ADDR = (HOST, PORT) someData = myData.Data(1,3,4,'stuff') databuffer = StringIO.StringIO() cPickle.dump(someData,databuffer) clientSock = socket(AF_INET, SOCK_STREAM) clientSock.connect(ADDR) clientSock.send(databuffer.getvalue()) clientSock.close() Run server.py in one window, then client.py in another. The client's output isn't too impressive, but the server's makes up for it (IMHO): D:\Python22\tutor>d:\python22\python server.py connection from: ('127.0.0.1', 3590) >> 1 >> 3 >> 4 >> stuff Looks like we received a full-blown object from the socket and are able to call its methods. Success! HTH, Don From gerrit@nl.linux.org Sat Feb 22 11:41:00 2003 From: gerrit@nl.linux.org (Gerrit Holl) Date: Sat Feb 22 11:41:00 2003 Subject: [Tutor] print variable in quotes In-Reply-To: <20030222122339.GA3556@nl.linux.org> References: <3E58B5A0.20409@nep.net> <20030222122339.GA3556@nl.linux.org> Message-ID: <20030222164125.GA5159@nl.linux.org> Gerrit Holl schreef op zaterdag 22 februari om 13:22:13 +0000: > reavey schreef op zaterdag 22 februari om 12:54:15 +0000: > > hi > > I need help printing a variable in quotes. > > pre = "FGRTPQMK" > > suf = "ack" > > for elem in pre: > > print "echo " elem+suf > > > > I'd like to get the variable elem+suf in double qoutations? > > The output I'd like to see: > > echo "Fack" > > echo "Gack" > > is to be read by a screensaver called phosphor and used in an elem > > school to > > reinforce an early reading concept using word families. > > 36 >>> a="Monty Python's flying circus" > 37 >>> print a > Monty Python's flying circus > 38 >>> print repr(a) > "Monty Python's flying circus" > 39 >>> print `a` > "Monty Python's flying circus" One more way: 18 >>> print "%r" % a 'This is a s t r i n g' yours, Gerrit. -- Asperger Syndroom - een persoonlijke benadering: http://people.nl.linux.org/~gerrit/ Het zijn tijden om je zelf met politiek te bemoeien: http://www.sp.nl/ From erikprice@mac.com Sat Feb 22 11:42:01 2003 From: erikprice@mac.com (Erik Price) Date: Sat Feb 22 11:42:01 2003 Subject: [Tutor] List comprehension (Map) Example In-Reply-To: <7497DCA1C240C042B28F6657ADFD8E0974DAC7@i2km11-ukbr.domain1.systemhost.net> Message-ID: <823C6A01-4686-11D7-8303-00039351FE6A@mac.com> On Wednesday, February 19, 2003, at 05:14 AM, alan.gauld@bt.com wrote: > On Wed, 19 Feb 2003, Erik Price wrote: >>> http://www.freenetpages.co.uk/hp/alan.gauld/tutfctnl.htm >> >> I went to check it out but the connection was refused. > > It seems to be OK just now. I know freenet went down at the weekend > but it seems OK now. They must be closed on weekends or something, because I just tried to go there again (first free moment I've had in days) and the connection is now timing out. Erik -- Erik Price email: erikprice@mac.com jabber: erikprice@jabber.org From Janssen@rz.uni-frankfurt.de Sat Feb 22 12:37:02 2003 From: Janssen@rz.uni-frankfurt.de (Michael Janssen) Date: Sat Feb 22 12:37:02 2003 Subject: [Tutor] using sockets to send a list In-Reply-To: <0e6c01c2da83$ab8a8c70$8a11ba3f@defaultcomp> Message-ID: On Sat, 22 Feb 2003, Don Arnold wrote: > #################################################### > ## client.py - sends an object to the server > #################################################### > from socket import * > import cPickle > import StringIO > import myData > > if __name__ == '__main__': > HOST = '127.0.0.1' > PORT = 50000 > BUFSIZE = 1024 > ADDR = (HOST, PORT) > > someData = myData.Data(1,3,4,'stuff') > > databuffer = StringIO.StringIO() > > cPickle.dump(someData,databuffer) > > clientSock = socket(AF_INET, SOCK_STREAM) > clientSock.connect(ADDR) > clientSock.send(databuffer.getvalue()) > clientSock.close() instead of this three lines: > databuffer = StringIO.StringIO() > cPickle.dump(someData,databuffer) > clientSock.send(databuffer.getvalue()) you can also use: clientSock.send(cPickle.dumps(someData))> --> cPickle's dumps (and loads) produces (and reads from) strings directly. Michael From Predrag Ivanovic Sat Feb 22 16:04:03 2003 From: Predrag Ivanovic (Predrag Ivanovic) Date: Sat Feb 22 16:04:03 2003 Subject: [Tutor] My first (er...working...) script ever Message-ID: <6610188680.20030222001709@ptt.yu> Hello... Programming and Python are pretty much new to me,but it's been fun so far... So,i would like comments on code below,especially on style(or lack of it..) It's pretty much trivial,one of the exercises from Josh Cogliati's "Non-Programmers Tutorial For Python",available thru link from PythonLabs(www.python.org),i recomend it for newcomers. It has basic functionality(it works...),but it lacks error handling and possibly a few other things. Maybe ,when i learn more about Tkinter,i'll add a GUI and send it to UselessPython :) Anyway,here comes nothing : ***** ## exercise from chapter 5 (functions)## ## choose from a menu to calculate ## ## area of circle,rectangle or square ## import math import sys ## simple menu def print_options() : print " 'o' za opcije" print " 'k' za obim kruga " print " 'p' za obim pravougaonika " print " 'c' za obim kvadrata" print " 'e' za exit" ## circle area def krug(radius) : return (math.pi*radius) ##area of rectangle def pravougaonik(visina,duzina) : return ((visina*2)+(duzina*2)) ## square area def kvadrat(stranica) : return (stranica*4) choice="o" ##initial value while choice != "e" : if choice == "k" : r=input("poluprecnik kruga : ") print "obim je : ", krug(r) elif choice == "p" : v=input ("visina : ") h=input (" duzina :") print "obim : ", pravougaonik(v,h) elif choice == "c" : d=input ("stranica :") print "obim je : ", kvadrat(d) elif choice =="e": sys.exit() elif choice != "e": print_options() choice = raw_input("opcija : ") ****** Thank you. Pedja --- "Just below my skin,I'm screaming..." Salva Mea,Faithless From gerrit@nl.linux.org Sat Feb 22 16:19:01 2003 From: gerrit@nl.linux.org (Gerrit Holl) Date: Sat Feb 22 16:19:01 2003 Subject: [Tutor] My first (er...working...) script ever In-Reply-To: <6610188680.20030222001709@ptt.yu> References: <6610188680.20030222001709@ptt.yu> Message-ID: <20030222212017.GA7098@nl.linux.org> Predrag Ivanovic schreef op zaterdag 22 februari om 22:04:30 +0000: > > Hello... > > Programming and Python are pretty much new to me,but it's been fun so far... I can guarantee that it will stay like that! > print " 'o' za opcije" > print " 'k' za obim kruga " > print " 'p' za obim pravougaonika " > print " 'c' za obim kvadrata" > print " 'e' za exit" I'm afraid I cannot comment on this one, as I do not understand a single word ;) > ## circle area > def krug(radius) : > return (math.pi*radius) Well, I think the area of a circle is math.pi*(radius**2), but that's not a Python issue. The circumference is math.pi*radius*2 (note the differenc between ** (pow) and * (mul)). > ##area of rectangle > def pravougaonik(visina,duzina) : > return ((visina*2)+(duzina*2)) This is actually the circumference, not the area. The area is width*height (visina*duzina?) > def kvadrat(stranica) : > return (stranica*4) Again, this is the circumference. > choice="o" ##initial value > > while choice != "e" : > if choice == "k" : > r=input("poluprecnik kruga : ") > print "obim je : ", krug(r) For error checking, it is recommended to use raw_input. If a user enters "100**100**100**100", it is going to take a long time to finish. You can betted to r=raw_input(...) and then try to use int(). That is more error proof. > elif choice == "p" : > v=input ("visina : ") > h=input (" duzina :") > print "obim : ", pravougaonik(v,h) Same here... > elif choice == "c" : > d=input ("stranica :") > print "obim je : ", kvadrat(d) and here. > elif choice =="e": > sys.exit() > elif choice != "e": > print_options() > choice = raw_input("opcija : ") But further, this program looks OK. You can use the cmd module if you want to extend your program: http://www.python.org/dev/doc/devel/lib/module-cmd.html "The Cmd class provides a simple framework for writing line-oriented command interpreters." But that may very well be overkill for your exercise program. yours, Gerrit. -- Asperger Syndroom - een persoonlijke benadering: http://people.nl.linux.org/~gerrit/ Het zijn tijden om je zelf met politiek te bemoeien: http://www.sp.nl/ From wilson@visi.com Sat Feb 22 17:17:11 2003 From: wilson@visi.com (Tim Wilson) Date: Sat Feb 22 17:17:11 2003 Subject: [Tutor] My first (er...working...) script ever In-Reply-To: <6610188680.20030222001709@ptt.yu> References: <6610188680.20030222001709@ptt.yu> Message-ID: <200302221619.03268.wilson@visi.com> On Friday 21 February 2003 17:17, Predrag Ivanovic wrote: > Programming and Python are pretty much new to me,but it's been fun so > far... So,i would like comments on code below,especially on style(or lack > of it..) Hi Pedja, For all matters of Python programming style, I consult Guido's style guide at http://www.python.org/doc/essays/styleguide.html One little thing you can do is use docstrings for documenting your functions. > ## circle area > def krug(radius) : > return (math.pi*radius) Would become... def krug(radius): """Return the circle's radius.""" return math.pi * radius**2 -Tim -- Tim Wilson Twin Cities, Minnesota, USA Science teacher, Linux fan, Zope developer, Grad. student, Daddy mailto:wilson@visi.com | http://qwerk.org/ | public key: 0x8C0F8813 From Predrag Ivanovic Sat Feb 22 21:59:01 2003 From: Predrag Ivanovic (Predrag Ivanovic) Date: Sat Feb 22 21:59:01 2003 Subject: Re[2]: [Tutor] My first (er...working...) script ever In-Reply-To: <20030222212017.GA7098@nl.linux.org> References: <6610188680.20030222001709@ptt.yu> <20030222212017.GA7098@nl.linux.org> Message-ID: <9943097811.20030223035705@ptt.yu> Gerrit Holl wrote: GH> Well, I think the area of a circle is math.pi*(radius**2), but that's not GH> a Python issue. The circumference is math.pi*radius*2 (note the differenc GH> between ** (pow) and * (mul)). Er...you are right,of course.My english is a bit rusty...so is my math,apparently :).Back to elementary school.Oh,well.. So,it works but produces false(in a sense)data...a bit like Windows,actually... >> choice="o" ##initial value >> >> while choice != "e" : >> if choice == "k" : >> r=input("poluprecnik kruga : ") >> print "obim je : ", krug(r) GH> For error checking, it is recommended to use raw_input. GH> If a user enters "100**100**100**100", it is going to take GH> a long time to finish. You can betted to r=raw_input(...) GH> and then try to use int(). That is more error proof. Something like this,maybe? ---------------- choice="o" while choice !="e": if choice =="k": r=int(raw_input("r:")) print "whatever ",krug(r) --------------------------------- How do i evaluate value and raise an exception if input is ,for instance,"church police" instead of "42"? GH> But further, this program looks OK. Thank you. GH> You can use the cmd module if you want to extend your program: GH> http://www.python.org/dev/doc/devel/lib/module-cmd.html GH> "The Cmd class provides a simple framework for writing line-oriented command interpreters." GH> But that may very well be overkill for your exercise program. I've looked it up,it looks interesting.Baby steps,baby steps... The more i learn Python,more i like it. GH> yours, GH> Gerrit. Again,thank you and all that responded,is on me! Pedja. --- "Just below my skin,I'm screaming..." Salva Mea,Faithless From revanna@mn.rr.com Sat Feb 22 22:33:01 2003 From: revanna@mn.rr.com (Anna Ravenscroft) Date: Sat Feb 22 22:33:01 2003 Subject: Re[2]: [Tutor] My first (er...working...) script ever In-Reply-To: <9943097811.20030223035705@ptt.yu> References: <6610188680.20030222001709@ptt.yu> <20030222212017.GA7098@nl.linux.org> <9943097811.20030223035705@ptt.yu> Message-ID: <200302222132.45647.revanna@mn.rr.com> On Saturday 22 February 2003 20:57, Predrag Ivanovic wrote: > Something like this,maybe? > ---------------- > choice="o" > while choice !="e": > if choice =="k": > r=int(raw_input("r:")) > print "whatever ",krug(r) > --------------------------------- > How do i evaluate value and raise an exception if input is > ,for instance,"church police" instead of "42"? r = raw_input("r:") try: newr = int(r) print "whatever ",krug(r)" except: print "That is not a number. " HTH Anna From revanna@mn.rr.com Sat Feb 22 22:37:01 2003 From: revanna@mn.rr.com (Anna Ravenscroft) Date: Sat Feb 22 22:37:01 2003 Subject: Re[2]: [Tutor] My first (er...working...) script ever In-Reply-To: <200302222132.45647.revanna@mn.rr.com> References: <6610188680.20030222001709@ptt.yu> <9943097811.20030223035705@ptt.yu> <200302222132.45647.revanna@mn.rr.com> Message-ID: <200302222136.19045.revanna@mn.rr.com> On Saturday 22 February 2003 21:32, Anna Ravenscroft wrote: > On Saturday 22 February 2003 20:57, Predrag Ivanovic wrote: > > Something like this,maybe? > > ---------------- > > choice="o" > > while choice !="e": > > if choice =="k": > > r=int(raw_input("r:")) > > print "whatever ",krug(r) > > --------------------------------- > > How do i evaluate value and raise an exception if input is > > ,for instance,"church police" instead of "42"? Oops! Make that: > r = raw_input("r:") > try: > newr = int(r) > print "whatever ",krug(newr)" > except: > print "That is not a number. " Just my $.03 worth... Anna From am@fx.ro Sat Feb 22 23:19:01 2003 From: am@fx.ro (Adrian Maier) Date: Sat Feb 22 23:19:01 2003 Subject: [Tutor] using sockets to send a list In-Reply-To: ; from Janssen@rz.uni-frankfurt.de on Sat, Feb 22, 2003 at 06:36:39PM +0100 References: <0e6c01c2da83$ab8a8c70$8a11ba3f@defaultcomp> Message-ID: <20030223080944.B245@coto> On Sat, Feb 22, 2003 at 06:36:39PM +0100, Michael Janssen wrote: > instead of this three lines: > > > databuffer = StringIO.StringIO() > > cPickle.dump(someData,databuffer) > > clientSock.send(databuffer.getvalue()) > > you can also use: > > clientSock.send(cPickle.dumps(someData))> > > --> cPickle's dumps (and loads) produces (and reads from) strings > directly. cool. i'll try it thanks and best wishes -- Adrian Maier (am@fx.ro) From antoneheyward@hotmail.com Sun Feb 23 00:43:03 2003 From: antoneheyward@hotmail.com (antone heyward) Date: Sun Feb 23 00:43:03 2003 Subject: [Tutor] win32 and excel Message-ID: I am trying to use data from an excel spreadsheet and create a graph in excel with the data. Does anyone have a good example? I can create a blank graph with Charts.Add() but thats it. _________________________________________________________________ The new MSN 8: smart spam protection and 2 months FREE* http://join.msn.com/?page=features/junkmail From kbond@free.fr Sun Feb 23 05:28:01 2003 From: kbond@free.fr (kbond) Date: Sun Feb 23 05:28:01 2003 Subject: [Tutor] how to get the confirmation that a cmd done using os.system is corectely done? References: <20030221235127.A293@coto> <0d7301c2da1b$272c44e0$8a11ba3f@defaultcomp> <20030222074927.GB1644@hooloovoo> <20030222121623.A342@coto> <0e6c01c2da83$ab8a8c70$8a11ba3f@defaultcomp> Message-ID: <3E58A1EE.3090103@free.fr> Hello, I have a problem in Onconnect() function (I put the code bellow). This function is called by an event in a menu. The goal of this function is to connect my linux box to the internet. The connection works fine, my problem is that during the connection the application informs the user on the status of the connection. I want to display the message ("The computer is connected to internet") in a wxStaticText when the command "pon Free_Telecom" is succesfully finish. I am attaching the complete code to this mail. Any suggestion to improve it are welcome. Regards, Yann def OnConnect(self, e): import os import time print "debut de la fonction OnConnect" self.statTxt.SetLabel("Connecting to internet") print self.statTxt.GetLabel() os.system("pon Free_Telecom") time.sleep(5) self.statTxt.SetLabel("The computer is connected to internet") self.connectedFlag = 1 print "fin de la fonction OnConnect" print self.connectedFlag From kbond@free.fr Sun Feb 23 05:33:02 2003 From: kbond@free.fr (kbond) Date: Sun Feb 23 05:33:02 2003 Subject: [Tutor] how to get the confirmation that a cmd done using os.system is corectely done? References: <20030221235127.A293@coto> <0d7301c2da1b$272c44e0$8a11ba3f@defaultcomp> <20030222074927.GB1644@hooloovoo> <20030222121623.A342@coto> <0e6c01c2da83$ab8a8c70$8a11ba3f@defaultcomp> Message-ID: <3E58A318.8030906@free.fr> This is a multi-part message in MIME format. --------------080900030406010204050505 Content-Type: text/plain; charset=us-ascii; format=flowed Content-Transfer-Encoding: 7bit Hello, I have a problem in Onconnect() function (I put the code bellow). This function is called by an event in a menu of wxPython application. The goal of this function is to connect my linux box to the internet. The connection works fine but I have the following problem: During the connection the application informs the user on the status of the connection. I want to display the message ("The computer is connected to internet") in a wxStaticText when the command "pon Free_Telecom" is succesfully finish. The actual status is the message is coming during the connection and not when the connection is done. I am attaching the complete code to this mail. Any suggestion to improve it are welcome. Regards, Yann def OnConnect(self, e): import os import time print "debut de la fonction OnConnect" self.statTxt.SetLabel("Connecting to internet") print self.statTxt.GetLabel() os.system("pon Free_Telecom") time.sleep(5) self.statTxt.SetLabel("The computer is connected to internet") self.connectedFlag = 1 print "fin de la fonction OnConnect" print self.connectedFlag --------------080900030406010204050505 Content-Type: text/plain; name="mainWindow.py" Content-Transfer-Encoding: 7bit Content-Disposition: inline; filename="mainWindow.py" #!/usr/bin/env python from wxPython.wx import * from wxPython.lib.anchors import LayoutAnchors class MyFrame(wxFrame): """This class is the main window of my application""" def __init__(self, parent, id, title): wxFrame.__init__(self,parent, -4, title, size = (550,300),style = wxDEFAULT_FRAME_STYLE) self.SetAutoLayout(true) self.panelA = wxWindow(self, -1, wxDefaultPosition, wxDefaultSize, wxSUNKEN_BORDER) self.panelA.SetBackgroundColour(wxColour(red=255, green=189, blue=255) ) txt = wxStaticText(self.panelA, -1, "Shortcut to your favorite\n" "web aplications\n", wxPoint(5,5), wxSize(-1, 50)) txt.SetForegroundColour(wxBLACK) lc = wxLayoutConstraints() lc.top.SameAs(self, wxTop, 10) lc.left.SameAs(self, wxLeft, 10) lc.bottom.SameAs(self, wxBottom, 10) lc.right.SameAs(self, wxLeft, -200) self.panelA.SetConstraints(lc) self.panelC = wxWindow(self, -1, wxDefaultPosition, wxDefaultSize) lc = wxLayoutConstraints() lc.top.SameAs(self ,wxBottom, -70) lc.right.SameAs(self, wxRight, 10) lc.bottom.SameAs(self, wxBottom, 10) lc.left.RightOf(self.panelA, 10) self.panelC.SetConstraints(lc) self.panelB = wxWindow(self, -1, wxDefaultPosition, wxDefaultSize, wxRAISED_BORDER) self.LabelPanelB = wxStaticText(self.panelB, -1, "Connection Status", wxPoint(4, 4)) self.panelB.SetBackgroundColour(wxWHITE) lc = wxLayoutConstraints() lc.top.SameAs(self, wxTop, 10) lc.right.SameAs(self, wxRight, 10) lc.bottom.Above(self.panelC) lc.left.RightOf(self.panelA, 10) self.panelB.SetConstraints(lc) b = wxButton(self.panelA, 100, ' Panel A ') lc = wxLayoutConstraints() lc.centreX.SameAs (self.panelA, wxCentreX) lc.centreY.SameAs (self.panelA, wxCentreY) lc.height.AsIs () lc.width.PercentOf (self.panelA, wxWidth, 50) b.SetConstraints(lc); self.statTxt = wxStaticText(self.panelB, -1, "", wxPoint(20, 10)) lc = wxLayoutConstraints() lc.top.Below (self.LabelPanelB, 2) lc.right.AsIs () lc.left.SameAs (self.panelB, wxLeft, 2) lc.bottom.AsIs () self.statTxt.SetConstraints(lc); self.connectedFlag = 0 self.CreateStatusBar() self.image = wxBitmap('/home/commun/scripts/python/photo/appli/V_0.03/resource/001_star_butterfly.xpm', wxBITMAP_TYPE_XPM) butterfly = wxStaticBitmap(self.panelC, -1, self.image) lc = wxLayoutConstraints() lc.bottom.SameAs(self.panelC, wxBottom,6 ) lc.right.SameAs(self.panelC, wxRight, 4) lc.height.AsIs() lc.width.AsIs() butterfly.SetConstraints(lc) b = wxButton(self.panelC, 100, ' Button ') lc = wxLayoutConstraints() lc.bottom.SameAs(self.panelC, wxTop, 20) lc.right.SameAs(self.panelC, wxRight, 40) lc.height.AsIs() lc.width.AsIs() b.SetConstraints(lc) #seting up the menus #Creating the filemenu filemenu = wxMenu() ID_ABOUT = wxNewId() filemenu.Append(ID_ABOUT, "&About", "Information about this program") filemenu.AppendSeparator() ID_EXIT = wxNewId() filemenu.Append(ID_EXIT, "&Exit", "Terminate the program") #Creating the tools menu photosmenu = wxMenu() #converting the picture to medium and small size ID_CONVERT = wxNewId() photosmenu.Append(ID_CONVERT, "&Convert Photos", "Convert the photos to medium and small size") #Generating the html page index ID_GENERATE = wxNewId() photosmenu.Append(ID_GENERATE, "&Generate Html", "Generate the html page index") #Uploading the photos from the camera ID_UPLOAD = wxNewId() photosmenu.Append(ID_UPLOAD, "&Upload Photos", "Upload the photos from the camera") #Creating the internetmenu internetmenu = wxMenu() #Connect the computer to free Telecom ID_CONNECT = wxNewId() internetmenu.Append(ID_CONNECT, "&Connect", "Connect to Free Telecom") #Disconnect the computer from free Telecom ID_DISCONNECT = wxNewId() internetmenu.Append(ID_DISCONNECT, "&Disconnect", "Disconnect from Free Telecom") #Clear the window ID_CLEAR = wxNewId() internetmenu.Append(ID_CLEAR, "&Clear", "Clear the window") #Creating the toolsmenu toolsmenu = wxMenu() #Change the panel's color ID_COLOR = wxNewId() toolsmenu.Append(ID_COLOR, "&Change Color", "Change the Color of the selected panel") #Creating the menu Bar menuBar = wxMenuBar() menuBar.Append(filemenu, "&File") menuBar.Append(photosmenu, "&Photos") menuBar.Append(internetmenu, "&Internet") menuBar.Append(toolsmenu, "&Tools") self.SetMenuBar(menuBar) #Attaching the menu events EVT_MENU(self, ID_EXIT, self.OnExit) EVT_MENU(self, ID_ABOUT, self.OnAbout) EVT_MENU(self,ID_CONVERT, self.OnConvert) EVT_MENU(self,ID_GENERATE, self.OnGenerate) EVT_MENU(self, ID_UPLOAD, self.OnUpload) EVT_MENU(self, ID_CONNECT, self.OnConnect) EVT_MENU(self, ID_DISCONNECT, self.OnDisconnect) EVT_MENU(self, ID_CLEAR, self.OnClear) EVT_MENU(self, ID_COLOR, self.OnColor) EVT_BUTTON(self, 100, self.OnButton) self.Show(true) ## ---------------------------------------------------------------------- def OnButton(self, event): wxBell() ## ---------------------------------------------------------------------- def OnColor(self, event): data = wxColourData() data.SetChooseFull(true) dlg = wxColourDialog(self, data) if dlg.ShowModal() == wxID_OK: data = dlg.GetColourData() dlg.Destroy() self.panelA.SetBackgroundColour(data.GetColour()) ## wxPaintDC(self) ## --------------------------------------------------------------------- ## def OnPaint(self): ## wxPaintDC(self) ## ------------------------------------------------------------------------ def OnExit(self, e): #close the frame self.Close(true) def OnAbout(self, e): dlg = wxMessageDialog(self, 'Sony handler was designed by Yann Malet', 'A Message Box', wxOK | wxICON_INFORMATION) ## #wxYES_NO | wxNO_DEFAULT | wxCANCEL | wxICON_INFORMATION) dlg.ShowModal() dlg.Destroy() ## ------------------------------------------------------------------------ def OnConvert(self, e): dlg = wxMessageDialog(self, 'This function is under development', 'A Message Box', wxOK | wxICON_INFORMATION) ## #wxYES_NO | wxNO_DEFAULT | wxCANCEL | wxICON_INFORMATION) dlg.ShowModal() dlg.Destroy() def OnGenerate(self, e): dlg = wxMessageDialog(self, 'This function is under development', 'A Message Box', wxOK | wxICON_INFORMATION) ## #wxYES_NO | wxNO_DEFAULT | wxCANCEL | wxICON_INFORMATION) dlg.ShowModal() dlg.Destroy() def OnUpload(self,e): from Camera import * dlg = wxDirDialog(self, "Choose a directory", "/home/commun/sony") if dlg.ShowModal() == wxID_OK: self.path = dlg.GetPath() sony = CameraClass() sony.Upload(self.path) dlg.Destroy() dlg = wxMessageDialog(self, 'The Photos have been transfered!', 'A Message Box', wxOK | wxICON_INFORMATION) ## #wxYES_NO | wxNO_DEFAULT | wxCANCEL | wxICON_INFORMATION) dlg.ShowModal() dlg.Destroy() ## ------------------------------------------------------------------------ def OnConnect(self, e): import os import time print "debut de la fonction OnConnect" self.statTxt.SetLabel("Connecting to internet") print self.statTxt.GetLabel() ## time.sleep(5) os.system("pon Free_Telecom") time.sleep(5) self.statTxt.SetLabel("The computer is connected to internet") self.connectedFlag = 1 print "fin de la fonction OnConnect" print self.connectedFlag def OnDisconnect(self, e): import os os.system("poff") self.statTxt.SetLabel("The computer is disconnected") def OnClear(self, e): self.statTxt.SetLabel("") ## ------------------------------------------------------------------------ class MyApp(wxApp): def OnInit(self): frame = MyFrame(None, -1, "Sony Handler") frame.Show(true) self.SetTopWindow(frame) return true app = MyApp(0) app.MainLoop() --------------080900030406010204050505-- From scot@possum.in-berlin.de Sun Feb 23 08:34:02 2003 From: scot@possum.in-berlin.de (Scot Stevenson) Date: Sun Feb 23 08:34:02 2003 Subject: [Tutor] Using special characters in Python In-Reply-To: <00c601c2d9dc$ff17fd70$8d4c73d5@oleioq8ex4m1zx> References: <200302211754.11033.scot@possum.in-berlin.de> <00c601c2d9dc$ff17fd70$8d4c73d5@oleioq8ex4m1zx> Message-ID: <200302221724.31367.scot@possum.in-berlin.de> Hello Ole, > I don't know exectly how to use that example, as when you type it in > python doesn't know the 'theinputstring' function, is it a function you > have made? or do you need to import something to get it to work? > >>> theinputstring = theinputstring.encode("ISO-8859-1") Sorry, I should have been clearer there. This assumes that you have some Tkinter thingy that gives you the imput string, such as self.entrythingy = Entry(rootframe) # Use the entry widget theinputstring = self.entrythingy.get() # Take the line the user has typed theinputstring = theinputstring.encode("ISO-8859-1") print theinputstring which is untested code, by the way. Y, Scot -- Verbing weirds language Scot W. Stevenson - Zepernick, Germany From ramrom@earthling.net Sun Feb 23 12:50:01 2003 From: ramrom@earthling.net (Bob Gailer) Date: Sun Feb 23 12:50:01 2003 Subject: [Tutor] win32 and excel In-Reply-To: Message-ID: <5.2.0.9.0.20030223104804.03074198@66.28.54.253> --=======2360546E======= Content-Type: text/plain; x-avg-checked=avg-ok-1157656B; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit At 05:41 AM 2/23/2003 +0000, antone heyward wrote: >I am trying to use data from an excel spreadsheet and create a graph in >excel with the data. Does anyone have a good example? I can create a blank >graph with Charts.Add() but thats it. I can probably provide you with a good example; but I need to know more. Do you want to write a python program that will automatically generate the chart from the pre-existing worksheet? Details will be helpful. Also a sample of the worksheet. Bob Gailer mailto:ramrom@earthling.net 303 442 2625 --=======2360546E======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-1157656B Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.454 / Virus Database: 253 - Release Date: 2/10/2003 --=======2360546E=======-- From phthenry@earthlink.net Sun Feb 23 12:57:02 2003 From: phthenry@earthlink.net (Paul Tremblay) Date: Sun Feb 23 12:57:02 2003 Subject: [Tutor] script too slow Message-ID: <20030223125714.B10476@localhost.localdomain> My script is running so slow that it might prove usesless, and I wondered if there was a way to speed it up. The script will convert Microsoft RTF to XML. I had originally written the script in perl, and now am converting it to python. I have completed two parts of the script. The first part uses regular expressions to break each line into tokens. perl => 20 seconds python => 45 seconds Not surprisingly, python ran slower than perl, which is designed around regular expressions. However, the next part proved very disappointing to me. This part reads each token, and determines if it is in a dictionary, and takes action if it is. perl => 4 seconds python => 40 seconds In sum, the first two steps take around 25 seconds with perl, and 1 minute and 25 seconds with python. There are at least 10 more steps, and if python proves as slow, than the python version might take 6 to 8 minutes, whereas the perl version took around 2. Here is the specific problem I am having with the dictionaries. class ProcessTokens: # put the dictionaries here instead? # first make an instance def __init__(self, file=None,copy=None,temp_dir=None): self.__file=file self.initiate_dictionaries() # there are around a dozen dictionaries, and altogether # these dictionaries have 250 entries def initiate_dictionaries(self): """Assign dictionariers to self. These dictionaries give information about the tokesn.""" self.xml_sub = { '&' : '&', '>' : '>' , '<' : '<' } # ect... # now use the dictionaries to process the tokens def process_cw(self, token, str_token, space): """Change the value of the control word by determing what dictionary it belongs to""" if token_changed == '*': pass elif self.needed_bool.has_key(token_changed): token_changed = self.needed_bool[token_changed] elif self.styles_1.has_key(token_changed): token_changed = self.styles_1[token_changed] elif self.styles_2.has_key(token_changed): token_changed = self.styles_2[token_changed] num = self.divide_num(num,2) # ect. There are around a dozen such statements It is this last function, the "def process_cw", that eats up all the clock time. If I skip over this function, then I chop around 30 seconds off the script. I am wondering if I should make the dictionaries a part of the class property rather than a property of the actual instance? That is, put then at the top of the class, and then access them with ProcessTokens.needed_bool.has_key(token_changed) ? The dictionary part of the scrpt seems so slow, that I am guessing I am doing something wroing, that Python has to read in the dictionary each time it starts the function. Thanks Paul -- ************************ *Paul Tremblay * *phthenry@earthlink.net* ************************ From shalehperry@attbi.com Sun Feb 23 13:54:02 2003 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Sun Feb 23 13:54:02 2003 Subject: [Tutor] script too slow In-Reply-To: <20030223125714.B10476@localhost.localdomain> References: <20030223125714.B10476@localhost.localdomain> Message-ID: <200302231052.53441.shalehperry@attbi.com> On Sunday 23 February 2003 09:57, Paul Tremblay wrote: > > I have completed two parts of the script. The first part uses regular > expressions to break each line into tokens. > > perl =3D> 20 seconds > python =3D> 45 seconds > > Not surprisingly, python ran slower than perl, which is designed around > regular expressions. However, the next part proved very disappointing t= o > me. This part reads each token, and determines if it is in a dictionary= , > and takes action if it is. > if you precompile the regex the two often come much closer. Especially i= f you=20 use the same ones over and over. is_entity =3D re.compile(r'&\w+;') if is_entity.search(input): handle_entity(input) > > # now use the dictionaries to process the tokens > def process_cw(self, token, str_token, space): > """Change the value of the control word by determing what > dictionary it belongs to""" > > if token_changed =3D=3D '*': > pass > elif self.needed_bool.has_key(token_changed): > token_changed =3D self.needed_bool[token_changed] > elif self.styles_1.has_key(token_changed): > token_changed =3D self.styles_1[token_changed] > elif self.styles_2.has_key(token_changed): > token_changed =3D self.styles_2[token_changed] > num =3D self.divide_num(num,2) > > =09# ect. There are around a dozen such statements > > > It is this last function, the "def process_cw", that eats up all the > clock time. If I skip over this function, then I chop around 30 seconds > off the script. > I do not see anything glaring here. > I am wondering if I should make the dictionaries a part of the class > property rather than a property of the actual instance? That is, put > then at the top of the class, and then access them with > if all instances share the same data this makes sense from a design=20 perspective. However I do not believe it will improve the performance an= y. > > The dictionary part of the scrpt seems so slow, that I am guessing I am > doing something wroing, that Python has to read in the dictionary each > time it starts the function. > Perhaps you could reorder the if statements so that the most commonly hit= =20 cases are the first ones checked. If you average 6 compares and can redu= ce=20 that to 2 you should see a decent improvement. Seeing the perl code may also help us see why the run time is so differen= t. From phthenry@earthlink.net Sun Feb 23 18:38:06 2003 From: phthenry@earthlink.net (Paul Tremblay) Date: Sun Feb 23 18:38:06 2003 Subject: [Tutor] script too slow In-Reply-To: <200302231052.53441.shalehperry@attbi.com> References: <20030223125714.B10476@localhost.localdomain> <200302231052.53441.shalehperry@attbi.com> Message-ID: <20030223183744.C10476@localhost.localdomain> On Sun, Feb 23, 2003 at 10:52:53AM -0800, Sean 'Shaleh' Perry wrote: > On Sunday 23 February 2003 09:57, Paul Tremblay wrote: > > > > I have completed two parts of the script. The first part uses regular > > expressions to break each line into tokens. > > > > perl => 20 seconds > > python => 45 seconds > > > > Not surprisingly, python ran slower than perl, which is designed around > > regular expressions. However, the next part proved very disappointing to > > me. This part reads each token, and determines if it is in a dictionary, > > and takes action if it is. > > > > if you precompile the regex the two often come much closer. Especially if you > use the same ones over and over. > > is_entity = re.compile(r'&\w+;') > > if is_entity.search(input): > handle_entity(input) Right. When I create my instance, I compile all my expressions: def __init__(self,file): self.compile_reg_exp() def compile_reg_exp(self): self.__split_exp = re.compile(r"(\\\\|\\{|\\}|...ect)) def get_tokens(self, my_string): tokens = re.split(self.__split_exp, my_string) return tokens The difference in speed between python and perl with regular expressions doesn't suprise or disappoint me. After all, perl is faster than even C++ when it comes to regular expressions. However, this difference in reading from a dictionary, versus reading from an hash in perl, is really baffling. Okay, I just checked this website out, which compares how long different computer languages take for differnet tasks: http://www.bagley.org/~doug/shootout/bench/hash/ According to this benchmark, Python is actually a bit faster than perl with associative arrays (dictionary in python, hash in perl). So there is something strange going on in my code. >Perhaps you could reorder the if statements so that the most commonly hit >cases are the first ones checked. If you average 6 compares and can reduce >that to 2 you should see a decent improvement. > >Seeing the perl code may also help us see why the run time is so different. I'll try your first suggestion. Also, I wonder if I change this line from : elif self.needed_bool.has_key(token_changed): token_changed = self.needed_bool[token_changed] to: elif self.needed_bool.get(token_changed): token_changed = self.needed_bool[token_changed] The second line only performs one lookup, whereas the first has to perform two. In addition, I wonder if I should use lists in some way. For example, I could create one giant list. allowed = ['\par', '\pard', etc] if token in allowed: # check the dictionaries That way, the dictionaries are checked only for around half of the tokens. However, that means if the token is in allowed, there has to be two lookups--one for the list, and one for the dictionary. I know that in perl, lists (called arrays in perl) are much faster than hashses. Here is the perl code: if ($token_changed eq "*"){ #do nothing } elsif ($token_changed eq ":"){ #do nothing } elsif(exists $styles_bool{$token_changed}){ $token_changed = $styles_bool{$token_changed}; if ($num eq "0"){ $num = "false"; $second_field = "sf"; #style is false } } elsif(exists $needed_bool{$token_changed}){ $token_changed = $needed_bool{$token_changed}; #could be inline, but might not be } Thanks for the help Paul -- ************************ *Paul Tremblay * *phthenry@earthlink.net* ************************ From alan.gauld@bt.com Sun Feb 23 18:57:02 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Sun Feb 23 18:57:02 2003 Subject: [Tutor] List comprehension (Map) Example Message-ID: <7497DCA1C240C042B28F6657ADFD8E0974DAD0@i2km11-ukbr.domain1.systemhost.net> > > It seems to be OK just now. I know freenet went down at the weekend > > but it seems OK now. > > They must be closed on weekends or something, Yes, I don't know what's happening. They went down last weekend, they went down briefly this week too. Service seems very sporadic just now. I sent a mail to tutor but it's held in the moderator's queue coz I'm sending from home...(as this will probably be too!) Alan G. From fredm@smartypantsco.com Sun Feb 23 19:03:02 2003 From: fredm@smartypantsco.com (Alfred Milgrom) Date: Sun Feb 23 19:03:02 2003 Subject: [Tutor] script too slow In-Reply-To: <20030223125714.B10476@localhost.localdomain> Message-ID: <5.1.0.14.0.20030224105324.02351e30@192.168.1.1> At 12:57 PM 23/02/03 -0500, Paul Tremblay wrote: >My script is running so slow that it might prove usesless, and I >wondered if there was a way to speed it up. > >The script will convert Microsoft RTF to XML. I had originally written >the script in perl, and now am converting it to python. > >I have completed two parts of the script. The first part uses regular >expressions to break each line into tokens. > >perl => 20 seconds >python => 45 seconds > >Not surprisingly, python ran slower than perl, which is designed around >regular expressions. However, the next part proved very disappointing to >me. This part reads each token, and determines if it is in a dictionary, >and takes action if it is. > # now use the dictionaries to process the tokens > def process_cw(self, token, str_token, space): > """Change the value of the control word by determing what dictionary > it belongs to""" > > if token_changed == '*': > pass > elif self.needed_bool.has_key(token_changed): > token_changed = self.needed_bool[token_changed] > elif self.styles_1.has_key(token_changed): > token_changed = self.styles_1[token_changed] > elif self.styles_2.has_key(token_changed): > token_changed = self.styles_2[token_changed] > num = self.divide_num(num,2) > > # ect. There are around a dozen such statements > > >It is this last function, the "def process_cw", that eats up all the >clock time. If I skip over this function, then I chop around 30 seconds >off the script. > >The dictionary part of the scrpt seems so slow, that I am guessing I am >doing something wroing, that Python has to read in the dictionary each >time it starts the function. I am not sure if I am on the right track or not, but as I understand it each element is only in one dictionary, but there are some different things that need to be done depending on which dictionary it is in (such as changing num). Have you thought of having a "super dictionary" which lists where each element is? The super-dictionary can be created by the program so that you don't have to worry about updating the dictionaries and the super-dictionary. Something along the lines of: dict1={'a':1, 'b':2, 'c':3} dict2={'d':4, 'e':5, 'f':6} superdict = {} dictlist=[dict1, dict2] for dictionary in dictlist: for key in dictionary: superdict[key] = dictionary items = 'adbecf' result = [] for letter in items: result.append(superdict[letter][letter]) print result >>> [1, 4, 2, 5, 3, 6] If some of the elements are present in more than one dictionary, the order of the dictionaries in creating the super-dictionary becomes important. However, I am surprised that dictionary lookups are taking the time. Is there anything else in that function that may be eating up the time? HTH, Fred Milgrom From anclo@anclo.com Sun Feb 23 20:10:03 2003 From: anclo@anclo.com (Anclo) Date: Sun Feb 23 20:10:03 2003 Subject: [Tutor] Newbie: writing same lines in 2 files In-Reply-To: <20030224003802.14839.42137.Mailman@mail.python.org> Message-ID: <5.2.0.9.0.20030223194815.0346c128@imap.telissant.com> At 07:38 PM 2/23/2003, you wrote: Hello, I'm trying to write a simple script which generates configuration files for Analog. I need 2 configuration files (so results could be displayed both with Analog and Reportmagic) which are identical except for a few lines. I would like to avoid repeating twice the lines which need to be written in both config files. However, I always seem to run into some sort of an error. Here is what I tried: #!/usr/local/bin/python2.1 import commands import string #Get username (will be used for username.analog and username.rm) username = raw_input("Username for .analog and .rm config files?\n") analog_config_file = string.join((username,'.analog'),"") analog_rm_config_file = string.join((username,'.rm'),"") print "Analog config file to create................: ",analog_config_file print "Analog for ReportMagic config file to create: ",analog_rm_config_file #Get domain name from user domain_name = raw_input("User's domain name?\n") print "User's domain name: ",domain_name #Open new Analog config file outfile_analog = open(analog_config_file,'w') outfile_analog_rm = open(analog_rm_config_file,'w') #Define config files config_files = [outfile_analog,outfile_analog_rm] #Write config files config_files[0,1].write('LOGFORMAT COMMON\n') [... write many more lines ...] The line: config_files[0,1].write('LOGFORMAT COMMON\n') is the one which doesn't work. I get the error: Traceback (most recent call last): File "./analogSetup1.py", line 26, in ? config_files[0,1].write('LOGFORMAT COMMON\n') TypeError: sequence index must be integer On the other hand, config_files[0].write('LOGFORMAT COMMON\n') config_files[1].write('LOGFORMAT COMMON\n') works fine. How would I do these 2 lines with 1 line? Thanx for your help, Anclo From Don Arnold" Message-ID: <11d601c2dba6$94ed9f10$8a11ba3f@defaultcomp> ----- Original Message ----- From: "Anclo" To: Sent: Sunday, February 23, 2003 7:07 PM Subject: [Tutor] Newbie: writing same lines in 2 files > > config_files[0].write('LOGFORMAT COMMON\n') > config_files[1].write('LOGFORMAT COMMON\n') > > works fine. > > How would I do these 2 lines with 1 line? for currentFile in config_files: currentFile.write('LOGFORMAT COMMON\n') HTH, Don From op73418@mail.telepac.pt Sun Feb 23 22:41:01 2003 From: op73418@mail.telepac.pt (=?iso-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Sun Feb 23 22:41:01 2003 Subject: Re[2]: [Tutor] My first (er...working...) script ever References: <6610188680.20030222001709@ptt.yu> <9943097811.20030223035705@ptt.yu> <200302222132.45647.revanna@mn.rr.com> <200302222136.19045.revanna@mn.rr.com> Message-ID: <001001c2daf2$fce17510$9b100dd5@violante> ----- Original Message ----- From: "Anna Ravenscroft" To: Sent: Sunday, February 23, 2003 3:36 AM Subject: Re: Re[2]: [Tutor] My first (er...working...) script ever > On Saturday 22 February 2003 21:32, Anna Ravenscroft wrote: > > On Saturday 22 February 2003 20:57, Predrag Ivanovic wrote: > > > Something like this,maybe? > > > ---------------- > > > choice="o" > > > while choice !="e": > > > if choice =="k": > > > r=int(raw_input("r:")) > > > print "whatever ",krug(r) > > > --------------------------------- > > > How do i evaluate value and raise an exception if input is > > > ,for instance,"church police" instead of "42"? > > Oops! Make that: > > > r = raw_input("r:") > > try: > > newr = int(r) > > print "whatever ",krug(newr)" > > except: > > print "That is not a number. " > A little better r = raw_input("r:") try: newr = int(r) #Catch specific exception. except ValueError: print "That is not a number" #Move print out of try block. print "whatever ", krug(newr) > Just my $.03 worth... > Anna With my best regards, G. Rodrigues From janos.juhasz@VELUX.com Mon Feb 24 02:39:01 2003 From: janos.juhasz@VELUX.com (janos.juhasz@VELUX.com) Date: Mon Feb 24 02:39:01 2003 Subject: [Tutor] Select distinct item form list Message-ID: Dear All, Can someone show me a simple list comprehension to do the same thing as= "Select distinct item form list" does in SQL So i have a list >>> l =3D (1,2,3,4,5,5,6,7,7,7,2) but i would have just l=3D(1,2,3,4,5,6,7) I know i have seen this somewhere, but i cannot find it :( Please CC me. Best regards, ----------------------- Juh=E1sz J=E1nos IT department = From Janssen@rz.uni-frankfurt.de Mon Feb 24 04:47:01 2003 From: Janssen@rz.uni-frankfurt.de (Michael Janssen) Date: Mon Feb 24 04:47:01 2003 Subject: [Tutor] Select distinct item form list In-Reply-To: Message-ID: On Mon, 24 Feb 2003 janos.juhasz@VELUX.com wrote: > Dear All, > > Can someone show me a simple list comprehension to do the same thing as > "Select distinct item form list" does in SQL > > So i have a list > >>> l =3D (1,2,3,4,5,5,6,7,7,7,2) > but i would have just > l=3D(1,2,3,4,5,6,7) Okey first try: >>> l (1, 2, 3, 4, 5, 5, 6, 7, 7, 7, 2) >>> def uniqs(inp, was_there=3D[]): =2E.. if not inp in was_there: =2E.. was_there.append(inp) =2E.. return 1 # sending "True" to filter =2E.. >>> filter(si, l) (1, 2, 3, 4, 5, 6, 7) for filter best look at Python Tutorial Section 5.1.3 > > I know i have seen this somewhere, but i cannot find it :( > > Please CC me. > Best regards, > ----------------------- > Juh=E1sz J=E1nos > IT department > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From Janssen@rz.uni-frankfurt.de Mon Feb 24 05:08:01 2003 From: Janssen@rz.uni-frankfurt.de (Michael Janssen) Date: Mon Feb 24 05:08:01 2003 Subject: [Tutor] script too slow In-Reply-To: <20030223183744.C10476@localhost.localdomain> Message-ID: On Sun, 23 Feb 2003, Paul Tremblay wrote: > In addition, I wonder if I should use lists in some way. For example, I > could create one giant list. > > allowed = ['\par', '\pard', etc] dictionary lookups are faster in python: use dictionaries for lookups and lists for sorting. These ways both the datastructures are optimized. Therefore it's realy amazing, what you are experiencing with your code :-( Fred suggestion about a super dictionary seems valueable. Have you already "profiled" your code? # in script: import profile profile.run('', '') # then in interpreter: import pstats p = pstats.Stats('') p.print_stats() # nicer output p.strip_dirs().sort_stats('time').print_stats() This possibly gives you a hint what kind of operations takes the time. Michael From Janssen@rz.uni-frankfurt.de Mon Feb 24 05:18:34 2003 From: Janssen@rz.uni-frankfurt.de (Michael Janssen) Date: Mon Feb 24 05:18:34 2003 Subject: [Tutor] how to get the confirmation that a cmd done using os.system is corectely done? In-Reply-To: <3E58A318.8030906@free.fr> Message-ID: On Sun, 23 Feb 2003, kbond wrote: > the connection. I want to display the message ("The computer is > connected to internet") in a wxStaticText when the command "pon > Free_Telecom" is succesfully finish. check for popen2 modul: lib/module-popen2.html lib/popen3-objects.html poll() and wait() seems appropiate for your task. (but also simple os.system should wait until execution of the connecting command. Does this command possibly return it's exit status before it's job is done (because it is working in the background)? In this case popen2 isn't better. You need actively check if the connection is done.) Michael > The actual status is the message is coming during the connection and not > when the connection is done. > I am attaching the complete code to this mail. > Any suggestion to improve it are welcome. > > Regards, > > Yann > From gerrit@nl.linux.org Mon Feb 24 05:19:02 2003 From: gerrit@nl.linux.org (Gerrit Holl) Date: Mon Feb 24 05:19:02 2003 Subject: [Tutor] Select distinct item form list In-Reply-To: References: Message-ID: <20030224102032.GA2846@nl.linux.org> janos.juhasz@VELUX.com schreef op maandag 24 februari om 08:39:31 +0000: > Dear All, > > Can someone show me a simple list comprehension to do the same thing as > "Select distinct item form list" does in SQL > > So i have a list > >>> l = (1,2,3,4,5,5,6,7,7,7,2) > but i would have just > l=(1,2,3,4,5,6,7) > > I know i have seen this somewhere, but i cannot find it :( The best solution, and explanation, can be found in the Python Cookbook. It is by Tim Peters: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52560 yours, Gerrit. -- Asperger Syndroom - een persoonlijke benadering: http://people.nl.linux.org/~gerrit/ Het zijn tijden om je zelf met politiek te bemoeien: http://www.sp.nl/ From glingl@aon.at Mon Feb 24 05:32:02 2003 From: glingl@aon.at (Gregor Lingl) Date: Mon Feb 24 05:32:02 2003 Subject: [Tutor] Select distinct item form list References: Message-ID: <3E59F49A.7070809@aon.at> janos.juhasz@VELUX.com schrieb: >Dear All, > >Can someone show me a simple list comprehension to do the same thing as >"Select distinct item form list" does in SQL > >So i have a list > > >>>>l = (1,2,3,4,5,5,6,7,7,7,2) >>>> >>>> >but i would have just >l=(1,2,3,4,5,6,7) > >I know i have seen this somewhere, but i cannot find it :( > > Me neither! And I also can't figure out a clear and fast example. But here are two functions, which do what you need, the second one beeing *much* faster than the first one, although it uses a kind of detour: >>> def uniques(list): ... u=[] ... for l in list: ... if l not in u: ... u.append(l) ... return u ... >>> def distincts(list): ... d = {} ... for l in list: ... d[l]=None ... return d.keys() ... >>> from time import clock >>> from random import randrange >>> example = [randrange(100) for i in range(1000)] >>> if 1: ... a=clock() ... result1 = uniques(example) ... b=clock() ... result2 = distincts(example) ... c=clock() ... print b-a, c-b ... 0.0271014815845 0.00253942818447 >>> example = [randrange(1000) for i in range(1000)] >>> if 1: ... a=clock() ... result1 = uniques(example) ... b=clock() ... result2 = distincts(example) ... c=clock() ... print b-a, c-b ... 0.15894725197 0.00390971368995 >>> len(result1) 637 >>> len(result2) 637 >>> result1 [798, 106, 230, 694, 163, 709, 666, 29, 481, 115, 682, 467, 872, 195, 311, 800, 420, 423, 881, ... Regards, Gregor P.S.: The following is also possible, but certainly not what you had in mind: >>> def weird(list): ... e = [] ... u = [e.append(l) for l in list if l not in e] ... return e ... >>> result3 = weird(example) >>> result3[:20] [798, 106, 230, 694, 163, 709, 666, 29, 481, 115, 682, 467, 872, 195, 311, 800, 420, 423, 881, 8] >>> len(result3) 637 OOPS! Michael's idea just arrived (including a typo): >>> def uniqs(inp, was_there=[]): ... if not inp in was_there: ... was_there.append(inp) ... return 1 # sending "True" to filter ... >>> if 1: ... a = clock() ... result4 = filter(uniqs, example) ... b = clock() ... print b - a, len(result4) ... 0.167666793498 637 It uses a similar idea to my first example. !!! But ti has a severe disadvantage as you can see, if you use it twice: !!! >>> if 1: ... a = clock() ... result4 = filter(uniqs, example) ... b = clock() ... print b - a, len(result4) ... 0.168840126653 0 >>> result4 [] >>> Now the resulting list is empty! This comes from using a mutable object, namely a list, as default value for a parameter. After the first run was_there contains all the numbers in example, so nothing will be added to result. So, I think, it's better to discard that idea. Sorry. >Please CC me. >Best regards, >----------------------- >Juhász János >IT department > > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > > From tim_one@email.msn.com Mon Feb 24 06:20:01 2003 From: tim_one@email.msn.com (Tim Peters) Date: Mon Feb 24 06:20:01 2003 Subject: [Tutor] How to solve it ... In-Reply-To: <3E524F0A.4010104@aon.at> Message-ID: [Gregor Lingl] > Many thanks for your replies to my "lock-puzzle"-question. The > explanations of the first one was just what I hoped to get back from the > list - but I must confess I was not sure if the problem was interesting > enough, before I posted it. Now I'm glad, that I gave it a try! Me too -- it was fun. I think it may be too hard for a beginner, though -- hard to visualize and hard to motivate. Puzzles about how to get a fox and some chickens across a river in a small boat are more like it. > I had tried to find a solution, and what I arrived at worked, but was > rather clumsy. It takes years of practice to make easy things look easy <0.9 wink>. > When I read your solution, I was really enthusiastic about it. I > consider it to be a real *Python jewel*. Thank you, but it was just the elegance of unembellished brute force <0.5 wink>. > ... > I reworked my solution a little in the light of your remarks - and I > also took one or two ideas from your program - especially the use of a > code-dictionary. I put this version below, just for comparison - although > I know very well, that it will mainly serve to demonstrate, that I'm not > playing in the same league ... You did at least one smart thing I didn't do: you represented the basic codes by single characters, where I used pairs. The instances of "-2" and "2" in my program were inelegant. > Would you agree that I put your code along with some of your remarks on > my Python-website, of course with the due credits? Sure. > ... > P.S: As far as I see, the line > >> states = range(2, 15) > > in your code should read: > > states = range(1, 15) Ack, yes. I was playing with it and forgot to revert that change. Because of the symmetry arguments I mentioned in the first reply, it's actually enough to leave this line at states = 1, 3, 9 but not enough to use (just) any two of those. It runs so fast, though, that I don't notice the difference in runtime between (1, 3, 9) and range(1, 15). Easy exercise (if you've done it before ): change any of these programs to generate all solutions, in increasing order of length. Doing it with Python's generators (the "yield" statement) is very easy. Hard: any sequence of codes takes a state to a set of states. Do that 14 times (once for each initial state), and the effect of a sequence of codes can be completely described by a tuple with 14 elements, where the first element is a tuple giving the states that state #1 maps to, and so on. Now you can use strings of codes, and tuples, as dict keys, so you can maintain dictionaries mapping code strings to their effects, and vice versa. Then you can write a driver that generates all possible sequences of codes in increasing order of length, but able to recognize (by using the dicts above) when a sequence has exactly the same effect as some sequence you've already seen. There's no point looking further at such redundant sequences (or at any sequences starting with a redundant sequence). When adding a new code at the end of a sequence, you can also look up the effect of the first N-1 codes, and just do the work needed to figure out what the single new code does beyond that. This leads to an extremely efficient program that not only finds "the answer", but also finds all distinct solutions regardless of length. If you don't screw it up , you'll find that there are surprisingly few distinct sequences of codes (where "distinct" means they have a different effect on at least one initial state). Another harder problem: the original asked for the shortest sequence of codes guaranteed to solve every initial state. Assuming that each initial state is equally likely, what's the shortest sequence of codes that minimizes the *average* number of codes executed before the lock opens? A mathematical logician in a hurry may well prefer that answer . From alan.gauld@blueyonder.co.uk Mon Feb 24 06:20:15 2003 From: alan.gauld@blueyonder.co.uk (Alan Gauld) Date: Mon Feb 24 06:20:15 2003 Subject: [Tutor] My tutor is not well again Message-ID: <01f501c2daa5$614e0fc0$6401a8c0@xp> My online tutor is up and down just now. The problem lies with the ISPs web servers hopefully nor,mal service will resume soon. Unfortunately crosswinds also appear to be having problems and, although functioning, is running very slowly. Aplologies to all. Alan G. http://www.freenetpages.co.uk/hp/alan.gauld http://www.crosswinds.net/~agauld From antonmuhin at rambler.ru" References: <5.2.0.9.0.20030223104804.03074198@66.28.54.253> Message-ID: <1614418843.20030224152019@rambler.ru> Hello, the simplest approach might be to create a template with a chart and when feed it with your data and, for example, copy it. -- Best regards, anton mailto:antonmuhin@rambler.ru From antonmuhin at rambler.ru" References: <5.2.0.9.0.20030223194815.0346c128@imap.telissant.com> Message-ID: <1404519458.20030224152159@rambler.ru> And another note: use of open is somewhat depricated now, you'd might be better with file. Anton. From antonmuhin at rambler.ru" References: Message-ID: <294864945.20030224152745@rambler.ru> Hello Michael, Monday, February 24, 2003, 12:46:06 PM, you wrote: MJ> On Mon, 24 Feb 2003 janos.juhasz@VELUX.com wrote: >>>> l MJ> (1, 2, 3, 4, 5, 5, 6, 7, 7, 7, 2) >>>> def uniqs(inp, was_there=[]): MJ> ... if not inp in was_there: MJ> ... was_there.append(inp) MJ> ... return 1 # sending "True" to filter MJ> ... It should be a little bit quickier with dictionaries or sets (in Python2.3). I seems to remebemer a long thread about uniq elements in tutor list or python list. Somewhat more trcikier solution: def unisq(seq): return dict(zip(seq, [None,]*len(seq))).keys() But it doesn't preserve order. -- Best regards, anton mailto:antonmuhin@rambler.ru From antonmuhin at rambler.ru" My first (er...working...) script ever In-Reply-To: <6610188680.20030222001709@ptt.yu> References: <6610188680.20030222001709@ptt.yu> Message-ID: <1465374958.20030224153615@rambler.ru> Hello Predrag, Saturday, February 22, 2003, 2:17:09 AM, you wrote: it was debated here and where, but I would rewrite it the following way: def processCircle(): r = float(raw_input("circle radius: ")) # try/except are good here print "result is %.3f" % krug(r) def process... # in the same fashion commands = { 'k': processCircle, .... 'e': None } def main(): while 1: print " 'o' za opcije" print " 'k' za obim kruga " print " 'p' za obim pravougaonika " print " 'c' za obim kvadrata" print " 'e' za exit" choice = raw_input("opcija : ") command = commands[choice] if command: commmand() else: break Defintely, it's just a sketch and might be improved in zillions ways Anton. PI> import math PI> import sys PI> ## simple menu PI> def print_options() : PI> print " 'o' za opcije" PI> print " 'k' za obim kruga " PI> print " 'p' za obim pravougaonika " PI> print " 'c' za obim kvadrata" PI> print " 'e' za exit" PI> ## circle area PI> def krug(radius) : PI> return (math.pi*radius) PI> ##area of rectangle PI> def pravougaonik(visina,duzina) : PI> return ((visina*2)+(duzina*2)) PI> ## square area PI> def kvadrat(stranica) : PI> return (stranica*4) PI> choice="o" ##initial value PI> while choice != "e" : PI> if choice == "k" : PI> r=input("poluprecnik kruga : ") PI> print "obim je : ", krug(r) PI> elif choice == "p" : PI> v=input ("visina : ") PI> h=input (" duzina :") PI> print "obim : ", pravougaonik(v,h) PI> elif choice == "c" : PI> d=input ("stranica :") PI> print "obim je : ", kvadrat(d) PI> elif choice =="e": PI> sys.exit() PI> elif choice != "e": PI> print_options() PI> choice = raw_input("opcija : ") PI> ****** PI> PI> Thank you. PI> Pedja PI> --- PI> "Just below my skin,I'm screaming..." PI> Salva Mea,Faithless -- Best regards, anton mailto:antonmuhin@rambler.ru From op73418@mail.telepac.pt Mon Feb 24 09:34:06 2003 From: op73418@mail.telepac.pt (=?iso-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Mon Feb 24 09:34:06 2003 Subject: [Tutor] Select distinct item form list References: Message-ID: <003f01c2dc12$be5f16a0$fc120dd5@violante> ----- Original Message ----- From: To: Sent: Monday, February 24, 2003 7:38 AM Subject: [Tutor] Select distinct item form list >Dear All, > >Can someone show me a simple list comprehension to do the same thing as >"Select distinct item form list" does in SQL > >So i have a list >>>> l = (1,2,3,4,5,5,6,7,7,7,2) >but i would have just >l=(1,2,3,4,5,6,7) > >I know i have seen this somewhere, but i cannot find it :( > >Please CC me. >Best regards, >----------------------- >Juhász János >IT department Short answer: stick the elements in a dictionary, call it dct, as in, for elem in : dct[elem] = None then take them out as unique_elem_list = dct.keys() and if you want them sorted unique_elem_list.sort(). HTH, G. Rodrigues From ramrom@earthling.net Mon Feb 24 09:35:02 2003 From: ramrom@earthling.net (Bob Gailer) Date: Mon Feb 24 09:35:02 2003 Subject: [Tutor] Select distinct item form list In-Reply-To: Message-ID: <5.2.0.9.0.20030224072634.01a03498@66.28.54.253> --=======549E270A======= Content-Type: text/plain; x-avg-checked=avg-ok-267B1AE6; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit At 08:38 AM 2/24/2003 +0100, janos.juhasz@VELUX.com wrote: >Can someone show me a simple list comprehension to do the same thing as >"Select distinct item form list" does in SQL > >So i have a list > >>> l = (1,2,3,4,5,5,6,7,7,7,2) >but i would have just >l=(1,2,3,4,5,6,7) Consider, also: >>> def r(a,b): ... if a != b:l2.append(b) ... return b ... >>> l = [1,2,3,4,5,5,6,7,7,7,2] >>> l.sort() >>> l2=[l[0]] >>> reduce(r,l) 5 >>> l2 [1, 2, 3, 4, 5, 6, 7] Bob Gailer mailto:ramrom@earthling.net 303 442 2625 --=======549E270A======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-267B1AE6 Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.454 / Virus Database: 253 - Release Date: 2/10/2003 --=======549E270A=======-- From Deirdre Hackett" Message-ID: <00a201c2dc14$841aca00$0400a8c0@egbert> You could use the serial module, which can be found at http://pyserial.sourceforge.net/ import serial ser = serial.Serial(0, timeout=1) ser.write("Something") input = ser.read() #reads one byte input = ser.readline() #reads a line input = ser.read(7) # reads 7 bytes ser.close() From Deirdre Hackett" > I want to apologise if my question was unclear. I was pretty hazy as to what > i wanted to find out myself. > > However, I did find the answer to my question. > > You use the struct module to pack and unpack binary data. > > struct.unpack('>hhhc', input_string) > > input string contains 6 hex values and a carriage return. The hex values > represented 3 signed values between -32,767 and +32,767. > > > From vicki@stanfield.net Mon Feb 24 10:56:00 2003 From: vicki@stanfield.net (vicki@stanfield.net) Date: Mon Feb 24 10:56:00 2003 Subject: [Tutor] serial connection was: adding a listbox Message-ID: <20030224075511.15870.h010.c000.wm@mail.stanfield.net.criticalpath.net> Strange, but I can't get it to work with your code, but if I change the "import serial" to "import Serial", the code will at least bring up the listbox with buttons. When I use the menu to actually execute the serial code (in callback), however, I get this: TypeError: 'module' is not callable So, I'd guess that I don't understand how modules are named and exactly what is being called within the module. I know that there are class definitions and function definitions within the module. The folder that got installed when I installed the serial stuff is "Serial" and the python script within that folder is also called "Serial". Can you tell me what I am missing? > > import serial > > ser = serial.Serial(0, timeout=1) > > ser.write("Something") > > input = ser.read() #reads one byte > input = ser.readline() #reads a line > input = ser.read(7) # reads 7 bytes > > ser.close() From Deirdre Hackett" Message-ID: <00f001c2dc20$23bdca20$0400a8c0@egbert> This is a multi-part message in MIME format. ------=_NextPart_000_00ED_01C2DC20.20F53440 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: 7bit Are you a windows user? I suppose I shouldn't have presumed you were. I used this module myself for my own project. I downloaded python 2.2. I also downloaded Mark Hammond's win32 extension from http://starship.python.net/crew/mhammond/ and then download the pyserial module which can be found at: http://sourceforge.net/project/showfiles.php?group_id=46487 Then follow the instructions on: http://pyserial.sourceforge.net/ Install them in the order they are above and the code I gave earlier should work. I have attached a program that although should not do anything for you should at least give you an idea. Hope I have been clear and that it works out for you. Deirdre ------=_NextPart_000_00ED_01C2DC20.20F53440 Content-Type: text/plain; name="tkinter4.txt" Content-Transfer-Encoding: 7bit Content-Disposition: attachment; filename="tkinter4.txt" from Tkinter import * from threading import * import timer import time import array from Numeric import * import serial root = Tk() ser = serial.Serial(0, timeout=1) data = [] def send(): ser.write("*99p\r") def take_in_data(): xinput = "" yinput = "" zinput = "" input = ser.readline() xinput = input[:9] yinput = input[9:18] zinput = input[18:27] xsplit = xinput.split() ysplit = yinput.split() zsplit = zinput.split() x2string = "" for n in range(len(xsplit)): x2string += xsplit[n] y2string = "" for n in range(len(ysplit)): y2string += ysplit[n] z2string = "" for n in range(len(zsplit)): z2string += zsplit[n] if x2string > 3: xcommasplit = x2string.split(',') if y2string > 3: ycommasplit = y2string.split(',') if z2string > 3: zcommasplit = z2string.split(',') x3string = "" for n in range(len(xcommasplit)): x3string += xcommasplit[n] y3string = "" for n in range(len(ycommasplit)): y3string += ycommasplit[n] z2string = "" for n in range(len(zcommasplit)): z3string += zcommasplit[n] data.append(int(x2string)) data.append(int(y2string)) data.append(int(z2string)) #data.append(input) for n in range(10): t = Timer(0.05, send) t.start() #print n a = Timer(0.05, take_in_data) a.start() #print input #for b in range(10): #print data[b] ser.close() root.mainloop() ------=_NextPart_000_00ED_01C2DC20.20F53440-- From Deirdre Hackett" class Application(Frame): def move(self,x,y,z): ................ def graph(self,x,y,z): .................. .................. if (count==20): count = 0 self.move() def start_input(self): .................. .................. self.take_reading() def take_reading(self): .................. .................. self.reading(reading[0], reading[1], reading[2]) t = Timer(0, self.take_reading) t.start() This is basically the skeleton of the program. I want to initialise a count and count how many times take reading is called and then when graph is called the count value is also passed to it and then when count is equal to 20 then move is called. I know this is probably a very basic "programming" problem. I don't think i have defined it very clearly but would greatly appreciate any help as I am so close to wrapping this whole thing up. Thanks Deirdre From vicki@stanfield.net Mon Feb 24 11:32:26 2003 From: vicki@stanfield.net (vicki@stanfield.net) Date: Mon Feb 24 11:32:26 2003 Subject: [Tutor] serial connection was: adding a listbox Message-ID: <20030224083130.7749.h004.c000.wm@mail.stanfield.net.criticalpath.net> Yes, I'm on Windows 2000 now. (I usually use Linux however) For some reason, it only works with "import Serial" and "Serial.Serial(0, timeout=1)". For whatever reason, when I execute the serial part of the code by calling the callback, I get this: module has no attribute Serial When I use "Serial.serial(0, timeout=1)", I get the same thing: module has no attribute serial So what exactly is an attribute? Isn't it a function within that module? --vicki From glingl@aon.at Mon Feb 24 11:43:01 2003 From: glingl@aon.at (Gregor Lingl) Date: Mon Feb 24 11:43:01 2003 Subject: [Tutor] Passing count from one function to another References: <00fd01c2dc22$63472180$0400a8c0@egbert> Message-ID: <3E5A4BB0.7010507@aon.at> Deirdre Hackett schrieb: >class Application(Frame): > def __init__(self): self.count = 0 > > def move(self,x,y,z): > ................ > > def graph(self,x,y,z): > .................. > .................. > if (self.count==20): # count --> self.count > self.count = 0 # detto > self.move() > > > def start_input(self): > .................. > .................. > > self.take_reading() > > def take_reading(self): > > .................. > .................. > self.count += 1 > self.reading(reading[0], reading[1], reading[2]) > t = Timer(0, self.take_reading) > t.start() > > >This is basically the skeleton of the program. I want to initialise a count >and count how many times take reading is called and then when graph is >called the count value is also passed to it and then when count is equal to >20 then move is called. >I know this is probably a very basic "programming" problem. >I don't think i have defined it very clearly but would greatly appreciate >any help as I am so close to wrapping this whole thing up. >Thanks >Deirdre > > > HTH, Gregor >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > > From Deirdre Hackett" Message-ID: <011f01c2dc25$fa663c60$0400a8c0@egbert> > Yes, I'm on Windows 2000 now. (I usually use Linux > however) For some reason, it only works with "import > Serial" and "Serial.Serial(0, timeout=1)". For whatever > reason, when I execute the serial part of the code by > calling the callback, I get this: > > module has no attribute Serial I think that this means that yes you have imported the module Serial but that it does not have a method called Serial. > When I use "Serial.serial(0, timeout=1)", I get the > same thing: > > module has no attribute serial > > So what exactly is an attribute? Isn't it a function > within that module? I think that is exactly what it is but I am no guru and have no inspired answer to give you. Maybe it has something to do with your operating system and the fact that you cannot call: import serial I have never had any problems with it unlike everything else. Sorry I am not any help. Deirdre From alan.gauld@bt.com Mon Feb 24 12:10:03 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon Feb 24 12:10:03 2003 Subject: [Tutor] serial connection was: adding a listbox Message-ID: <7497DCA1C240C042B28F6657ADFD8E0901F8511E@i2km11-ukbr.domain1.systemhost.net> > however) For some reason, it only works with "import > Serial" and "Serial.Serial(0, timeout=1)". For whatever > reason, when I execute the serial part of the code by > calling the callback, I get this: > > module has no attribute Serial > ... > So what exactly is an attribute? Isn't it a function > within that module? Nope, it's a name. The name could be a function or a piece of data. Attributes can exist within a module or a class. I'm not quite clear whats happening but I think you arte saying that: serial.Serial(...) serial.serial(...) and Serial.serial(....) all give errors and Serial.Serial(...) works OK? That would suggest you should use Serial.Serial(...) :-) Python is case sensitive so only the right capitalisation will work. When in doubt use the dir() function to find out what names(attributes) exist within a module: >>> import Serial >>> print dir(Serial) ....names galore here..... Once you find the nam4e you can find how to use it by examining the doc string: print Serial.Serial.__doc__ Or using the inbuilt help() function. Python is very friendly to code exploration... Alan g. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld/ From vicki@stanfield.net Mon Feb 24 13:19:02 2003 From: vicki@stanfield.net (vicki@stanfield.net) Date: Mon Feb 24 13:19:02 2003 Subject: [Tutor] serial connection was: adding a listbox Message-ID: <20030224101841.5858.h012.c000.wm@mail.stanfield.net.criticalpath.net> Okay, I found the problem. I had two different serial modules installed: Serial and serial. Only Serial was in my path. Now I have fixed it so that only serial is in the path. I'll see how that goes. Thanks for your help. --vicki From jeff@ccvcorp.com Mon Feb 24 14:31:01 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Mon Feb 24 14:31:01 2003 Subject: [Tutor] os.path.walk References: <5.2.0.9.0.20030221200411.0309a970@66.28.54.253> Message-ID: <3E5A6317.5050704@ccvcorp.com> Bob Gailer wrote: > import os > def visit(arg, dirname, names): > dirname = dirname + '\\' > for name in names: > (root, ext) = os.path.splitext(name) > if ext and (ext != '.mp3'): > os.rename(dirname + name, dirname + root + '.mp3') > os.path.walk("G:\\Mp3s", visit, None) Ah, yes, I hadn't thought about how os.path.walk and os.rename would need directory names handled. However, after commenting that os.path.splitext() was preferable, you should know better than to hard-code directory separators. ;) That's what os.path.join() is for. Also, the 'if ext' part is unneeded, as an empty string in ext will always not equal '.mp3' -- you could use this sort of structure to short-circuit a lengthy evaluation of a second clause, but a simple comparison of strings is not lengthy. def visit(arg, dirname, names): for name in names: root, ext = os.path.splitext(name) if ext != '.mp3': os.rename(os.path.join(dirname, name), os.path.join(dirname, root+'.mp3')) Jeff Shannon Technician/Programmer Credit International From jeff@ccvcorp.com Mon Feb 24 14:34:01 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Mon Feb 24 14:34:01 2003 Subject: [Tutor] script too slow References: <20030223125714.B10476@localhost.localdomain> Message-ID: <3E5A738E.5030103@ccvcorp.com> Paul Tremblay wrote: >My script is running so slow that it might prove usesless, and I >wondered if there was a way to speed it up. >[....] > > # now use the dictionaries to process the tokens > def process_cw(self, token, str_token, space): > """Change the value of the control word by determing what dictionary > it belongs to""" > > if token_changed == '*': > pass > elif self.needed_bool.has_key(token_changed): > token_changed = self.needed_bool[token_changed] > elif self.styles_1.has_key(token_changed): > token_changed = self.styles_1[token_changed] > elif self.styles_2.has_key(token_changed): > token_changed = self.styles_2[token_changed] > num = self.divide_num(num,2) > > # ect. There are around a dozen such statements > > >It is this last function, the "def process_cw", that eats up all the >clock time. If I skip over this function, then I chop around 30 seconds >off the script. > There are *much* better ways to use dictionaries. First, instead of using 'if self.[some dict].has_key(token):' you should probably be using 'if token in self.[some dict]:' -- this is easier to read, and should be slightly faster. However, I suspect that there's a better algorithm for what you're trying to do -- though it's not terribly clear what it is that you *are* trying to do. The bit of dict that you showed being initialized in your sample code looks like it should be used as straight substitution. In that case you should just say 'token = self.xml_sub.get(token, token)'. If token is in self.xml_sub, this will return the value associated with it. If it's *not* there, then it'll return token itself as a default. If you can isolate needed actions into a set of functions, then you could put those functions into the dictionary along with your text values. self.sub_dict = { '&' : ('&', func1), [...] } ################ token, action = self.sub_dict.get(token, (token, None)) if action: action() Now, every value in the dictionary is a (string, function) pair. If token is found in the dictionary, then the string is substituted for token and the function (if it exists) is called. If a particular token doesn't require an action, then None can be used in place of the function and you have a straight substitution case like the previous example I gave. If token is *not* in the dictionary, then it's left alone, and action becomes None so no function is called either. Depending on just what you're doing with your dictionaries, you may be able to consolidate them into fewer (or possibly even only one) dictionary and simply rely on the associated function to differentiate items. If the only difference between, say, your style_1 and style_2 dictionaries is the action that you want to take if a token is found, then you can simply have a single style dictionary and use different functions. (This can apply even if the action for one of the dictionaries is 'do nothing special' -- just use None as the function.) The fewer dictionaries you need to search through, the faster your program will be. Of course, you may not be able to do this if you need the segregation of dictionaries for other purposes, but even there, you could set up all of your dictionaries to work this way and then simply perform the same on each in turn: for current_dict in [self.xml_sub, self.styles_1, self.styles_2, ...]: token, action = current_dict.get(token, (token, None)) if action: action() This would replace your forest of elifs, and while it might not save much time, it'll be a lot easier to read. (You could possibly extend this to shortcircuit out of the loop if a match is found...) >I am wondering if I should make the dictionaries a part of the class >property rather than a property of the actual instance? > Yes, if the dictionaries are static (that is, you don't change them during the program), then it would be sensible to make them a class attribute rather than an instance attribute. This won't save you much time or memory, unless you're creating a lot of instances of the class, but it's a more appropriate place for it -- data that's the same for all instances of a class should be part of the class, not the instance. >The dictionary part of the scrpt seems so slow, that I am guessing I am >doing something wroing, that Python has to read in the dictionary each >time it starts the function. > Python is rebuilding the dictionaries each time that you call initiate_dictionaries(), which may take some time, but if you're only using a single instance of ProcessTokens then it's a one-time cost. I suspect that the problem is simply that you're not making full use of the strengths of dictionaries, though. If you write your Python in Perl style (or C style, or Lisp style), then you're going to end up with slow and ugly code because you're not going to be using the real strengths of Python. I'm also not entirely convinced that regular expressions are the best choice for lexing (breaking the file up into tokens). They're almost a default solution in Perl, but that doesn't mean they're the most efficient method in Python. I'm not completely certain what the requirements for that process are, though, so I can't speak any more specifically other than to suggest considering other options. Hope that this helps give you a few ideas... Jeff Shannon Technician/Programmer Credit International From ahimsa@onetel.net.uk Mon Feb 24 16:13:01 2003 From: ahimsa@onetel.net.uk (ahimsa) Date: Mon Feb 24 16:13:01 2003 Subject: [Tutor] prime numbers Message-ID: <200302242114.52374.ahimsa@onetel.net.uk> Hello folks I am wanting to do an exercise that calls for a function to calculate pri= me=20 numbers. I know that primes can *only* be divided by themself or by 1, an= d=20 nothing else. My difficulty is translating this into parsimonious code=20 without labouriously working out all the possible prime numbers as condit= ions=20 for the if control. So far I have attempted % and /, and various combinations, but after a wh= ile I=20 am almost including all the primes anyway. Can someone give me a nudge in= the=20 right direction please. Much appreciated AmF From john_keck@hotmail.com Mon Feb 24 16:39:01 2003 From: john_keck@hotmail.com (John Keck) Date: Mon Feb 24 16:39:01 2003 Subject: [Tutor] lists, tuples, arrays Message-ID: I'm a somewhat experienced programmer (though not necessarily with object-oriented code), but I'm having trouble understanding the differences between using lists, tuples, and arrays, and maybe vectors. Unforuntately the online documents I've seen have not been helpful. Perhaps part of my frustration is that so much of how Python operates on these sorts of things is so unlike what I'm used to, and I have a perhaps unrealistic hope to do with Python what I can do so easily in, say, IDL or C. First of all, what are the basic differences between these different types? For example, I'm trying to set all the values of a slice of a list (or array) to a particular value. How do I do that? Another example: I'm have a list (or array) of vectors. How do I multiply all of them by a scalar? Another question: what is the difference between range() and arange()? Thanks in advance for any direction you can provide. John Keck _________________________________________________________________ Tired of spam? Get advanced junk mail protection with MSN 8. http://join.msn.com/?page=features/junkmail From bobsmith327@hotmail.com Mon Feb 24 16:50:11 2003 From: bobsmith327@hotmail.com (bob smith) Date: Mon Feb 24 16:50:11 2003 Subject: [Tutor] Functions and Variable Names Message-ID: I'm back with another question about functions and variable names. Okay, if I have separate functions, I know I can pass a value between them with the same variable name. But is that considered poor programming? Will it make things unclear? Here’s an trivial example of what I mean: def f1(score): print "Your score of %d has been recorded." %score def f2(score): if score > 80: print "Great job!" else: print "Keep trying." f1(score) def main(): score = 90 f2(score) main() "score" is the prefect name for what I'm representing, but should I have different names for this value in each function? This would seem odd to me, but I'm trying to learn the best way to program in Python. Thanks. Bob _________________________________________________________________ Help STOP SPAM with the new MSN 8 and get 2 months FREE* http://join.msn.com/?page=features/junkmail From tbrauch@mindless.com Mon Feb 24 17:00:29 2003 From: tbrauch@mindless.com (Timothy M. Brauch) Date: Mon Feb 24 17:00:29 2003 Subject: [Tutor] prime numbers References: <200302242114.52374.ahimsa@onetel.net.uk> Message-ID: <001e01c2dc4f$d7739ac0$6600a8c0@tbrauch> >Hello folks >I am wanting to do an exercise that calls for a function to calculate prime >numbers. I know that primes can *only* be divided by themself or by 1, and >nothing else. My difficulty is translating this into parsimonious code >without labouriously working out all the possible prime numbers as conditions >for the if control. >So far I have attempted % and /, and various combinations, but after a while I >am almost including all the primes anyway. Can someone give me a nudge in the >right direction please. >Much appreciated >AmF I can think of one way to write short code to check if a number is prime. The smallest factor of a pair of factors must be less than or equal to the square root of the number. I can't think of a clear way to say that. Maybe a few examples... 4 --> (1,4) (2,2). 2 <= sqrt(4) 6 --> (1,6) (2,3). 2 <= sqrt(6) 8 --> (1,8) (2,4). 2 <= sqrt(8) 16 --> (1,16) (2,8) (4,4). 4 <= sqrt(16) 24 --> (1,24) (2,12) (3,8) (4,6) 4<= sqrt(24) A few more examples should be pretty convincing it is true. If requested, I could write up some sort of rigorous proof this is the case, but I am tired after doing proofs all day long. So, the short coding way to find if a number was prime or not would be to simply check it against all integers that are less than the square root of the number. However, just a little warning, this would only take a few lines of code, but it will be painfully slow as your numbers get bigger. If you are just sticking with numbers say less than 100**2, then it probably won't take too long to check 100 divisions. Just remember, though, this code is far from efficient. I guess you could write it so once it found one factor, to stop; that should increase the efficiency, but it would also add a few lines to the code. - Tim From phthenry@earthlink.net Mon Feb 24 18:07:18 2003 From: phthenry@earthlink.net (Paul Tremblay) Date: Mon Feb 24 18:07:18 2003 Subject: [Tutor] script too slow In-Reply-To: References: <20030223183744.C10476@localhost.localdomain> Message-ID: <20030224180157.E10476@localhost.localdomain> On Mon, Feb 24, 2003 at 11:07:34AM +0100, Michael Janssen wrote: > > Have you already "profiled" your code? > # in script: > import profile > profile.run('', '') > > > # then in interpreter: > import pstats > p = pstats.Stats('') > > p.print_stats() > > # nicer output > p.strip_dirs().sort_stats('time').print_stats() > > This possibly gives you a hint what kind of operations takes the time. > I've been struggling to profile my code for the last 1 1/2 hours with no luck. If I have a simple function called 'print_hello', then this code works: import profile profile.run('test_hello()', '/home/paul/paultemp/profile_args.data') import pstats p = pstats.Stats('/home/paul/paultemp/profile_args.data') p.strip_dirs().sort_stats('time').print_stats() However, if my code is part of a class, which is also part of a module, then I don't know how to proceed: class ProcessTokens: def __init__(self): profile.run('self.process_cw()', '/home/paul/paultemp/profile_args.data') ... File "", line 1, in ? NameError: name 'self' is not defined Where to I put the 'profile.run statment? Do I include it as part of the regular script, or do I write a completely different script to profile things? I have looked at the library documentation with no luck. Thanks Paul -- ************************ *Paul Tremblay * *phthenry@earthlink.net* ************************ From gerrit@nl.linux.org Mon Feb 24 18:12:06 2003 From: gerrit@nl.linux.org (Gerrit Holl) Date: Mon Feb 24 18:12:06 2003 Subject: [Tutor] prime numbers In-Reply-To: <200302242114.52374.ahimsa@onetel.net.uk> References: <200302242114.52374.ahimsa@onetel.net.uk> Message-ID: <20030224231304.GA7448@nl.linux.org> ahimsa schreef op maandag 24 februari om 22:14:07 +0000: > Hello folks > I am wanting to do an exercise that calls for a function to calculate prime > numbers. I know that primes can *only* be divided by themself or by 1, and > nothing else. My difficulty is translating this into parsimonious code > without labouriously working out all the possible prime numbers as conditions > for the if control. > So far I have attempted % and /, and various combinations, but after a while I > am almost including all the primes anyway. Can someone give me a nudge in the > right direction please. > > Much appreciated The demo/scripts directory contains exactly this; maybe it can help you. #! /usr/bin/env python # Print prime numbers in a given range def main(): import sys min, max = 2, 0x7fffffff if sys.argv[1:]: min = int(eval(sys.argv[1])) if sys.argv[2:]: max = int(eval(sys.argv[2])) primes(min, max) def primes(min, max): if 2 >= min: print 2 primes = [2] i = 3 while i <= max: for p in primes: if i%p == 0 or p*p > i: break if i%p <> 0: primes.append(i) if i >= min: print i i = i+2 main() yours, Gerrit. -- Asperger Syndroom - een persoonlijke benadering: http://people.nl.linux.org/~gerrit/ Het zijn tijden om je zelf met politiek te bemoeien: http://www.sp.nl/ From jeff@ccvcorp.com Mon Feb 24 18:48:01 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Mon Feb 24 18:48:01 2003 Subject: [Tutor] Functions and Variable Names References: Message-ID: <3E5AAF02.9080706@ccvcorp.com> bob smith wrote: > I'm back with another question about functions and variable names. > > Okay, if I have separate functions, I know I can pass a value between > them with the same variable name. But is that considered poor > programming? Will it make things unclear? [...] > > "score" is the prefect name for what I'm representing, but should I > have different names for this value in each function? This would seem > odd to me, but I'm trying to learn the best way to program in Python. This is perfectly reasonable. A variable should be given a name which makes the most sense *in that context* -- that is, within the function, class, or module that it's part of. If several different functions end up using a variable with the same name, well, that's okay. The trick is that it's important to keep in mind that, even though the name is the same, they are *different variables* -- the 'score' in f2() is different from the 'score' in main(), even though they have the same name and the same value. You can make a change to 'score' within f2() and that won't affect the 'score' that's in main(). (This can be complicated by the fact that sometimes, different variables can refer to the same object, but that's a different question. ;) ) Jeff Shannon Technician/Programmer Credit International From hillcino368@hotmail.com Mon Feb 24 19:05:02 2003 From: hillcino368@hotmail.com (cino hilliard) Date: Mon Feb 24 19:05:02 2003 Subject: [Tutor] Numeric Package Message-ID:

The following uses the arbitrary integer long of python to compute Pi. Can some one help getting this to use the Numeric package in float arbitrary precision.? 


def piasn(n):
     n1=n*7/2+5
     n2=n/2 + 5
     import time
     t1=time.time()
     m=n+5
     p,x,d = 3*10**m,3*10**m,1
     t1=time.time()
     while d <= n1:
          x=x*d/(d+1) >> 2
#          x=x*d/(d+1)/4
          p=p+x/(d+2)
          d += 2
     t2=time.time()
     print "Pi = ",p
     print "sec to calc",t2-t1

Cino Hilliard



Add photos to your e-mail with MSN 8. Get 2 months FREE*. From phthenry@earthlink.net Mon Feb 24 19:05:16 2003 From: phthenry@earthlink.net (Paul Tremblay) Date: Mon Feb 24 19:05:16 2003 Subject: [Tutor] best way to tokenize [was script too slow] Message-ID: <20030224190412.F10476@localhost.localdomain> Jeff Shannon wrote: >I'm also not entirely convinced that regular expressions are the best >choice for lexing (breaking the file up into tokens). They're almost a >default solution in Perl, but that doesn't mean they're the most >efficient method in Python. I'm not completely certain what the >requirements for that process are, though, so I can't speak any more >specifically other than to suggest considering other options. You actually guessed my next question. I avoided regular expressions in the original perl script in all but this one place precisely because I knew I might convert the perl script to python, and I knew that regular expressions could be inefficient. However, I don't know if there is a better way to split a line of RTF. Here is a line of RTF that exhibits each of the main type of tokens: text \par \\ \{ \} {} Broken into tokens: ['text', '\par', '\\', '\{', '\}', '{', '}'] There are 7 type of tokens: 1. text 2. control word, or a backslash followed by any number of characters. A space, backslash, or open or closed bracket ends this group. 3. escaped backslash 4. escaped open bracket 5. escaped closed bracket 6. open bracket 7. closed bracket Here is my line to tokenize: self.splitexp = re.compile(r"(\\[\\{}]|{|}|\\[^\s\\{}&]+(?:\s)?)") tokens = re.split(self.splitexp, line) Is there any way to split this line *without* using regular expressions? I know how to use string.split("exp"), but I don't know how to preserve the "exp" as a token. Once I know how split and save the tokens, I imagine I can split the line into lists, then split the lists into lists, and so on--even though I'm vague on how to do this. But I'm not sure if this would be faster. Also, I don't know how to get around using a regular expression for the control words. A control word can be any length, and can take multiple forms: '\pard ' => '\pard ' '\par\pard' => '\par', '\pard' '\par\pard ' => '\par', '\pard ' '\par}' => '\par', '}' Thanks for your help on using dictionaries. I believe your method may save time, but I am waiting to learn how to use the profile module before I can determine what is what regarding the problem I am having with dictionaries. Paul -- ************************ *Paul Tremblay * *phthenry@earthlink.net* ************************ From magnus@thinkware.se Mon Feb 24 20:23:01 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Mon Feb 24 20:23:01 2003 Subject: [Tutor] script too slow In-Reply-To: <20030225000516.30006.36516.Mailman@mail.python.org> Message-ID: <5.1.0.14.0.20030225020359.02d525d0@www.thinkware.se> At Mon, 24 Feb 2003 18:01:58 -0500, Paul Tremblay wrote: >Where to I put the 'profile.run statment? Do I include it as part of the >regular script, or do I write a completely different script to profile >things? I have looked at the library documentation with no luck. I've just successfully used the profiler to reduce runtime for a use case from 426 to 55 seconds, so I guess I can afford to provide a hint. I've done like this: if __name__=='__main__': import sys if len(sys.argv) > 2: import profile profile.run('MainFrame.main("%s")' % sys.argv[1], sys.argv[2]) elif len(sys.argv) == 2: MainFrame.main(sys.argv[1]) else: MainFrame.main() MainFrame.main() is a function in a module--whatever you would use to start your code. In this case, I use more command line parameters. sys.argv[0] is the name of the script you just launched, so I don't use that. sys.argv[1] is another optional parameter which is not related to profiling. But if I supply one more argument, sys.argv[2], I will use this as the name for a profiling file, and run profiling. (Of course you can do this in different ways, with a flag that you read with the getopt module, with another script or whatever. Or you can start python interactively, import your module (if it uses the 'if __name__ == "__main__":' guard so that it won't run at once if it is imported.) Anyway, the block after "if len(sys.argv) > 2:" is for profiling in my code. After the program finishes, I'll open an interactive python session and do something like import pstats p = pstats.Stats('filename.dat') p.strip_dirs() p.sort_stats('cumulative').print_stats(20) But now I've changed it to using the new hotshot profiler, which is much faster. The problem is that for me it takes ages to read the stats file. Then it looks like this: ... if len(sys.argv) > 2: import hotshot profiler = hotshot.Profile(sys.argv[2]) profiler.run('MainFrame.main("%s")' % sys.argv[1]) profiler.close() ... import hotshot.stats p = hotshot.stats.load('filename.dat') p.strip_dirs() p.sort_stats('cumulative').print_stats(20) Good luck! -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From ramrom@earthling.net Mon Feb 24 21:19:01 2003 From: ramrom@earthling.net (Bob Gailer) Date: Mon Feb 24 21:19:01 2003 Subject: [Tutor] lists, tuples, arrays In-Reply-To: Message-ID: <5.2.0.9.0.20030224172003.03075c68@66.28.54.253> --=======77DE4F87======= Content-Type: text/plain; x-avg-checked=avg-ok-267B1AE6; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit At 04:37 PM 2/24/2003 -0500, John Keck wrote: >I'm a somewhat experienced programmer (though not necessarily with >object-oriented code), but I'm having trouble understanding the >differences between using lists, tuples, and arrays, and maybe vectors. > >First of all, what are the basic differences between these different types? Lists and tuples are sequences native to Python. Each element of these can be any Python object. Arrays are provided by certain modules. All elements of an array are the same type. Lists and arrays are "mutable" meaning that elements can be changed, deleted, inserted. Tuples are immutable. There are a few cases where tuples are required. >For example, I'm trying to set all the values of a slice of a list (or >array) to a particular value. list = [1,2,4,3,5,8,7,9] list[2:5] = [6]*3 # yields [1, 2, 6, 6, 6, 8, 7, 9] >Another example: I'm have a list (or array) of vectors. How do I multiply >all of them by a scalar? In general you write a loop or use list comprehension. list = [i * scalarvalue for i in list] will give you a new list with each element multiplied by the scalar. If you have a nested list [[1,2,3],[4,5,6]] then you must nest the loop. >Another question: what is the difference between range() and arange()? What is arange? Where did you see it? Are you thinking of xrange? range creates a list. xrange acts as a iterator; giving one value after another rather than returning the entire list. for i in range(5): is the same as x = range(5) for i in x: whereas in for i in xrange(5): each time the loop cycles xrange delivers 0, then 1, up to 4, then raises an error which terminates the loop. For a large range, range creates a large intermediate list, whereas xrange takes a little more work and avoids the memory impact of a large list. Bob Gailer mailto:ramrom@earthling.net 303 442 2625 --=======77DE4F87======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-267B1AE6 Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.454 / Virus Database: 253 - Release Date: 2/10/2003 --=======77DE4F87=======-- From magnus@thinkware.se Mon Feb 24 21:29:02 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Mon Feb 24 21:29:02 2003 Subject: [Tutor] lists, tuples, arrays In-Reply-To: <20030225000516.30006.36516.Mailman@mail.python.org> Message-ID: <5.1.0.14.0.20030225022146.0437ae80@www.thinkware.se> At Mon, 24 Feb 2003 16:37:03 -0500, John Keck wrote: >I'm a somewhat experienced programmer (though not necessarily with >object-oriented code), but I'm having trouble understanding the differences >between using lists, tuples, and arrays, and maybe vectors. Ok. Lets forget half of these then... ;) >Unforuntately the online documents I've seen have not been helpful. Where have you looked? It's probably also helful if you say something about your background and what you are looking for. You seem to be interested in mathematical manipulations of arrays. > Perhaps >part of my frustration is that so much of how Python operates on these sorts >of things is so unlike what I'm used to, and I have a perhaps unrealistic >hope to do with Python what I can do so easily in, say, IDL or C. You should expect that the things you do in C will be easier to do in Python. Much more power, much less typing. When you learn how to use Python effectively, which is not entirely like C programming, you will be conciderably more productive in Python than in C, but of course it takes some time to get used to the different concepts. At least that's my experience, and that of many others as well. See http://www.ipd.uka.de/~prechelt/Biblio/jccpprt_computer2000.pdf for an empirical study on the subject, or http://www.thinkware.se/cgi-bin/thinki.cgi/PythonQuotes for more subjective opinions. If you are making up C-style solutions, they are probably different than the optimal pythonic solution, but you will see that in time. It might be that you just don't see how easy it is, since you are used to the convoluted ways of C... :) >First of all, what are the basic differences between these different types? Typically, you use a python list object in the cases where you would use a list, vector or array in other languages. There is not builtin vector or array type in Python. I don't know why you mention these. There is an array module and an array function in the Numeric package, but this is not part of the core Python language. Numeric is not even a standard module, although it's widely used in the scientific community. A tuple is an immutable list, you might say. Once a tuple is defined, it can't be changed. (Although if it contains mutable objects, these might change.) Tuples are more light weight than lists, and tuples containing only immutable objects are hashable, so they can be used as keys in associative arrays (called dictionaries in Python). For instance, if we fetch data from a normal database table, where each row always have the same number of elements, but where we have a varying number of rows and might append or remove rows at will, it would be natural to represent this as a list of tuples. [(1, 'Magnus', 38), (2, 'Marius', 4), (3, 'Auste', 34)] You will probably notice that python programmers often use tuples where C programmers would use structs, but tuple elements are only accessed by index, not by name. Tuples are sometimes used without parenthesis as in: >>> a, b = 5, 1 >>> print a, b 5 1 >>> a, b = b, a + b >>> print a, b 1 6 >>> a, b = b, a >>> print a, b 6 1 Lists and tuples can contain anything: >>> a = [] >>> a.append(1) # integer >>> a.append(1+1j) # complex >>> a.append(3.14159) # float >>> a.append('Hello') # string >>> a.append(a) # itself >>> a.append(Numeric) # module >>> a.append(int) # type >>> print a [1, (1+1j), 3.1415899999999999, 'Hello', [...], , ] >>> t = tuple(a) >>> for e in t: ... print e ... 1 (1+1j) 3.14159 Hello [1, (1+1j), 3.1415899999999999, 'Hello', [...], , ] Numeric arrays can only contain numeric stuff. >For example, I'm trying to set all the values of a slice of a list (or >array) to a particular value. How do I do that? Like this? >>> a = [7] * 10 >>> a [7, 7, 7, 7, 7, 7, 7, 7, 7, 7] >>> a[3:7] = [5]*4 >>> a [7, 7, 7, 5, 5, 5, 5, 7, 7, 7] >Another example: I'm have a list (or array) of vectors. How do I multiply >all of them by a scalar? If you really want to do matrix mathematics you might want Numeric python after all, but I still think it's better to get aquainted with the core language before you mess with large third party modules. In core python there are a few solutions. The simplest is to make a loop more or less as in C: >>> l = range(5) >>> l [0, 1, 2, 3, 4] >>> s = 5 >>> r = [] >>> for e in l: ... r.append(s * e) ... >>> r [0, 5, 10, 15, 20] or inline >>> l [0, 1, 2, 3, 4] >>> for i in range(len(l)): ... l[i] *= s ... >>> l [0, 5, 10, 15, 20] There is also a more lisp style solution: >>> map(lambda x: x*s, l) [0, 25, 50, 75, 100] And list comprehension which is borrowed from Haskell: >>> [x * s for x in l] [0, 25, 50, 75, 100] Of course, Numeric handles array multiplication out of the box: >>> import Numeric >>> l = Numeric.arange(5) >>> l array([0, 1, 2, 3, 4]) >>> l * s array([ 0, 5, 10, 15, 20]) >Another question: what is the difference between range() and arange()? range is a built in function, which returns a range of integers in the form of a normal list object. >>> help(range) Help on built-in function range: range(...) range([start,] stop[, step]) -> list of integers Return a list containing an arithmetic progression of integers. range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0. When step is given, it specifies the increment (or decrement). For example, range(4) returns [0, 1, 2, 3]. The end point is omitted! These are exactly the valid indices for a list of 4 elements. >>> range(5) [0, 1, 2, 3, 4] >>> range(5, 10) [5, 6, 7, 8, 9] >>> range(5, 10, 3) [5, 8] arange is a function in the Numeric package, which returns a Numeric array (not a list) with a range of integers. >>> import Numeric >>> help(Numeric.arange) Help on built-in function arange: arange(...) arange(start, stop=None, step=1, typecode=None) Just like range() except it returns an array whose type can be specified by the keyword argument typecode. In numeric, the typical python flexibility is removed to assure that we have homogenous data types and faster calculations. >>> arange = Numeric.arange >>> arange(5) array([0, 1, 2, 3, 4]) Specify integers >>> arange(5, typecode='i') array([0, 1, 2, 3, 4],'i') Specify floats >>> arange(5, typecode='f') array([ 0., 1., 2., 3., 4.],'f') Perhaps you can describe a little more what you want to achieve. It's ok to show C code, but don't expect the Python solution to look like the C solution. -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From micforster@yahoo.com Mon Feb 24 22:17:14 2003 From: micforster@yahoo.com (Mic Forster) Date: Mon Feb 24 22:17:14 2003 Subject: [Tutor] script comparing two values Message-ID: <20030225031457.99507.qmail@web13404.mail.yahoo.com> Hi Guys, I am attempting to fit an expected geometric series of relative species abundance with an observed set of relative species abundance. In doing so one has to determine a constant, k. This is done by iterating the following equation: Nmin / N = (k / (1 - k)) * (pow((1 - k),s)) / (1 - (pow((1 - k),s)) = j where Nmin is the number of individuals in the least abundant species, N is the total number of individuals and s is the number of species. In my example: Nmin = 1 N = 862 s = 11 Nmin / N = 0.00116 in this example and therefore the equation: j = (k / (1 - k)) * (pow((1 - k),s)) / (1 - (pow((1 -k),s)) must also equal 0.00116 Obviously this involves iterating through a list of values between 0 and 1 so that the program returns a value, k, when Nmin / N = j (where 0 < k < 1). This is what I have and I know that it is completely wrong: def constant(j): result = [] i = 0.0 while i is not j: result.append(k) i, k = (k / (1 - k)((1 - k)^s) / (1 - (1 - k)^s), i + 0.0001 return result SyntaxError: invalid syntax Any help? Cheers, Mic __________________________________________________ Do you Yahoo!? Yahoo! Tax Center - forms, calculators, tips, more http://taxes.yahoo.com/ From brettlea@earthlink.net Mon Feb 24 22:34:28 2003 From: brettlea@earthlink.net (Brett Leach) Date: Mon Feb 24 22:34:28 2003 Subject: [Tutor] Re: Prime numbers In-Reply-To: <20030225000516.30006.36516.Mailman@mail.python.org> Message-ID: This problem needs to be a little more closely defined. Are you trying to find out if a particular number is prime, generate a list of the first n primes, find all the primes less than n? Each of these problems lends itself to optimization in different ways. My favorite of these is to make a list of the first n primes. I like this because the list itself is used as a tool while you make it. Start with a short list of known primes: from math import sqrt primesList = [ 2, 3 ] listLimit = 10000 #arbitrary limit candidate = 5 while len( primesList ) < listLimit : factorLimit = sqrt( candidate ) for factor in primesList: if factor > factorLimit: #then the number is prime primesList.append( candidate ) break elif candidate % factor == 0: #then it is not prime break else: continue #iterate up the list of primes candidate += 2 for prime in primesList: print prime > Message: 5 > From: ahimsa > Reply-To: ahimsa@onetel.net.uk > To: > Date: Mon, 24 Feb 2003 21:14:52 +0000 > Subject: [Tutor] prime numbers > > Hello folks > I am wanting to do an exercise that calls for a function to calculate pri= > me=20 > numbers. I know that primes can *only* be divided by themself or by 1, an= > d=20 > nothing else. My difficulty is translating this into parsimonious code=20 > without labouriously working out all the possible prime numbers as condit= > ions=20 > for the if control. > So far I have attempted % and /, and various combinations, but after a wh= > ile I=20 > am almost including all the primes anyway. Can someone give me a nudge in= > the=20 > right direction please. > > Much appreciated > AmF From phthenry@earthlink.net Mon Feb 24 23:12:01 2003 From: phthenry@earthlink.net (Paul Tremblay) Date: Mon Feb 24 23:12:01 2003 Subject: [Tutor] script too slow In-Reply-To: <20030224180157.E10476@localhost.localdomain> References: <20030223183744.C10476@localhost.localdomain> <20030224180157.E10476@localhost.localdomain> Message-ID: <20030224231032.A13858@localhost.localdomain> On Mon, Feb 24, 2003 at 06:01:58PM -0500, Paul Tremblay wrote: Okay, answering my own email. Duh! It only requires that I do this to my code: if __name__=='__main__': import profile profile.run('Handle_Main(),', '/home/paul/paultemp/profile_args.data') import pstats p = pstats.Stats('/home/paul/paultemp/profile_args.data') p.strip_dirs().sort_stats('time').print_stats() I could even make this prettier, by doing something like: if __name__=='__main__': if debug: #run the profilier else: Handle_Main() But I get the idea. I won't have time to explain everything I found out by that very, very nifty profile module until tomorrow or maybe even the next day. But let me say that it is *not* the dictionaries that were eating up the time. There was a small function to split the token into the main part and the number part, and apparently this little function, which uses a regular expession, is a huge time hog. It is taking around 30 percent of the total time! Thanks for all the help so far. The profile module is really going to help me optimize my script. Paul > From: Paul Tremblay > On Mon, Feb 24, 2003 at 11:07:34AM +0100, Michael Janssen wrote: > > > > Have you already "profiled" your code? > > # in script: > > import profile > > profile.run('', '') > > > > > > # then in interpreter: > > import pstats > > p = pstats.Stats('') > > > > p.print_stats() > > > > # nicer output > > p.strip_dirs().sort_stats('time').print_stats() > > > > This possibly gives you a hint what kind of operations takes the time. > > > > I've been struggling to profile my code for the last 1 1/2 hours with > no luck. If I have a simple function called 'print_hello', then this > code works: > > > import profile > profile.run('test_hello()', '/home/paul/paultemp/profile_args.data') > import pstats > p = pstats.Stats('/home/paul/paultemp/profile_args.data') > p.strip_dirs().sort_stats('time').print_stats() > > However, if my code is part of a class, which is also part of a module, > then I don't know how to proceed: > > class ProcessTokens: > > def __init__(self): > profile.run('self.process_cw()', '/home/paul/paultemp/profile_args.data') > ... > > File "", line 1, in ? > NameError: name 'self' is not defined > > > Where to I put the 'profile.run statment? Do I include it as part of the > regular script, or do I write a completely different script to profile > things? I have looked at the library documentation with no luck. > > Thanks > > Paul > > -- > > ************************ > *Paul Tremblay * > *phthenry@earthlink.net* > ************************ > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- ************************ *Paul Tremblay * *phthenry@earthlink.net* ************************ From jeff@ccvcorp.com Mon Feb 24 23:41:04 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Mon Feb 24 23:41:04 2003 Subject: [Tutor] script comparing two values References: <20030225031457.99507.qmail@web13404.mail.yahoo.com> Message-ID: <3E5AF3B0.6050308@ccvcorp.com> Mic Forster wrote: >def constant(j): > result = [] > i = 0.0 > while i is not j: > result.append(k) > i, k = (k / (1 - k)((1 - k)^s) / (1 - (1 - k)^s), i >+ 0.0001 > return result > >SyntaxError: invalid syntax > The syntax error is because you didn't balance your parentheses properly -- you've got one more ( than you have ). However, there's a few other problems with this code: 1. The ^ operator is *not* pow() -- it's a bitwise XOR. You can use ** instead -- (1-k)**s rather than (1-k)^s. 2. You need to explicitly use a multiplication operator -- your "(1-k)((1-k)**s)" should be "(1-k) * ((1-k)**s)" instead. 3. You are appending k to result before you first assign k. This will get you an UnboundLocalError once you fix your mismatched parens. 4. You may not get the result you expect from 'i is not j', for two different reasons. 4a. The first of those reasons is that the 'is' operator tests for *identity* -- you're asking whether i and j are the same object in memory, not whether they have the same value. For some objects, this might work by accident (for instance, Python creates static internal objects for all integers under 100, IIRC, so the integer 5 will have the same identity no matter how it's refered to), but that's not a good thing to rely on. For most data, this condition will never be true. You should be using equality, not identity, to end your loop. 4b. The other reason has to do with floating point imprecision. Floats are stored internally in a binary format which is based on (possibly negative) powers of two. This internal format cannot always be perfectly converted to a decimal number. Python will convert floating point numbers to the nearest possible internal value, but there is a necessary loss of precision. This means that, when you repeatedly add 0.0001 to i, you're not going to get what you expect. >>> i = 0.0 >>> for n in range(10): ... i += 0.0001 ... print repr(i) ... 0.0001 0.00020000000000000001 0.00030000000000000003 0.00040000000000000002 0.00050000000000000001 0.00060000000000000006 0.0007000000000000001 0.00080000000000000015 0.00090000000000000019 0.0010000000000000002 >>> The conversion from decimal to binary and back to decimal cannot be done perfectly, so imprecision creeps in. This means that if you pass in, say, 0.0009 as your value for j, expecting this to run for five iterations, you may instead have an endless loop because i will never equal 0.0009 -- it'll be 0.00090000000000000019 instead, and j will actually be 0.00089999999999999998. >>> j = 0.0009 >>> i = 0.0 >>> for i in range(20): ... i += 0.0001 ... if i == j: print "Match!", repr(i) ... >>> # No match? >>> j 0.00089999999999999998 >>> Direct comparisons for equality of floats are always hazardous for this reason, and you should instead check if one value is within a certain small range of another. >>> for n in range(10): ... i += 0.0001 ... if (j-delta) < i < (j+delta): ... print "Match!", repr(i) ... else: ... print " ", repr(i) ... 0.0001 0.00020000000000000001 0.00030000000000000003 0.00040000000000000002 0.00050000000000000001 0.00060000000000000006 0.0007000000000000001 0.00080000000000000015 Match! 0.00090000000000000019 0.0010000000000000002 >>> Hope that this helps. Jeff Shannon Technician/Programmer Credit International From fredm@smartypantsco.com Mon Feb 24 23:45:01 2003 From: fredm@smartypantsco.com (Alfred Milgrom) Date: Mon Feb 24 23:45:01 2003 Subject: [Tutor] best way to tokenize [was script too slow] In-Reply-To: <20030224190412.F10476@localhost.localdomain> Message-ID: <5.1.0.14.0.20030225152446.023fb800@192.168.1.1> At 07:04 PM 24/02/03 -0500, Paul Tremblay wrote: >However, I don't know if there is a better way to split a line of RTF. >Here is a line of RTF that exhibits each of the main type of tokens: >text \par \\ \{ \} {} > >Broken into tokens: >['text', '\par', '\\', '\{', '\}', '{', '}'] > >There are 7 type of tokens: > >1. text >2. control word, or a backslash followed by any number of characters. A >space, backslash, or open or closed bracket ends this group. >3. escaped backslash >4. escaped open bracket >5. escaped closed bracket >6. open bracket >7. closed bracket > >Is there any way to split this line *without* using regular expressions? > >Once I know how split and save the tokens, I >imagine I can split the line into lists, then split the lists into >lists, and so on--even though I'm vague on how to do this. > >But I'm not sure if this would be faster. Also, I don't know how to get >around using a regular expression for the control words. A control word >can be any length, and can take multiple forms: > >'\pard ' => '\pard ' >'\par\pard' => '\par', '\pard' >'\par\pard ' => '\par', '\pard ' >'\par}' => '\par', '}' Hi Paul: I can't say whether regular expressions are the best way to tokenise your RTF input, but here is an alternative recursive approach. Each line is split into words (using spaces as the separator), and then recursively split into sub-tokens if appropriate. def splitWords(inputline): outputList = [] for word in inputline.split(' '): if word.startswith('{') and word != '{': expandedWord = '{' + ' ' + word[1:] elif word.endswith('}')and word != '}' and word != '\\}': expandedWord = word[:-1] + ' ' + '}' elif '\\' in word and word != '\\': expandedWord = ' '.join(['\\'+item for item in word.split('\\') if item]) else: expandedWord = word if expandedWord != word: expandedWord = splitWords(expandedWord) outputList.append(expandedWord) return ' '.join(outputList) example1 = 'text \par \\ \{ \} {}' print splitWords(example1) >>> text \par \ \{ \} { } print splitWords(example1).split(' ') >>> ['text', '\\par', '\\', '\\{', '\\}', '{', '}'] Seven different tokens seem to be identified correctly. example2 = 'text \par\pard \par} \\ \{ \} {differenttext}' print splitWords(example2) >>> text \par \ \{ \} { } print splitWords(example2).split(' ') >>> ['text', '\\par', '\\pard', '\\par', '}', '\\', '\\{', '\\}', '{', 'differenttext', '}'] Haven't tested exhaustively, but this seems to do what you wanted it to do. As I said, I don't know if this will end up being better than using re or not, but it is an alternative approach. Best regards, Fred From Ike Hall Mon Feb 24 23:50:37 2003 From: Ike Hall (Ike Hall) Date: Mon Feb 24 23:50:37 2003 Subject: [Tutor] prime numbers References: <200302242114.52374.ahimsa@onetel.net.uk> <001e01c2dc4f$d7739ac0$6600a8c0@tbrauch> Message-ID: <002c01c2dc89$0ac6b4a0$bf27e183@chief> This actually would be a useful tool in this case. and for the math-minded out there, the proof of it is VERY simple. all this simply states is that of 2 numbers that multiply to give a value, one must be less than or equal to (in the case that they are the same number) that values square root, which is basically saying of any 2 numbers that add to give a value, the smaller of the two must be less than half of the output value. This is the same thing, with a different operation. Thanks for pointing this out. Very useful, especially in useless code :) Ike ----- Original Message ----- From: "Timothy M. Brauch" To: ; Sent: Monday, February 24, 2003 3:58 PM Subject: Re: [Tutor] prime numbers > >Hello folks > >I am wanting to do an exercise that calls for a function to calculate prime > >numbers. I know that primes can *only* be divided by themself or by 1, and > >nothing else. My difficulty is translating this into parsimonious code > >without labouriously working out all the possible prime numbers as > conditions > >for the if control. > >So far I have attempted % and /, and various combinations, but after a > while I > >am almost including all the primes anyway. Can someone give me a nudge in > the > >right direction please. > >Much appreciated > >AmF > > I can think of one way to write short code to check if a number is prime. > The smallest factor of a pair of factors must be less than or equal to the > square root of the number. I can't think of a clear way to say that. Maybe > a few examples... > > 4 --> (1,4) (2,2). 2 <= sqrt(4) > 6 --> (1,6) (2,3). 2 <= sqrt(6) > 8 --> (1,8) (2,4). 2 <= sqrt(8) > 16 --> (1,16) (2,8) (4,4). 4 <= sqrt(16) > 24 --> (1,24) (2,12) (3,8) (4,6) 4<= sqrt(24) > > A few more examples should be pretty convincing it is true. If requested, I > could write up some sort of rigorous proof this is the case, but I am tired > after doing proofs all day long. So, the short coding way to find if a > number was prime or not would be to simply check it against all integers > that are less than the square root of the number. > > However, just a little warning, this would only take a few lines of code, > but it will be painfully slow as your numbers get bigger. If you are just > sticking with numbers say less than 100**2, then it probably won't take too > long to check 100 divisions. Just remember, though, this code is far from > efficient. I guess you could write it so once it found one factor, to stop; > that should increase the efficiency, but it would also add a few lines to > the code. > > - Tim > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From magnus@thinkware.se Tue Feb 25 05:11:00 2003 From: magnus@thinkware.se (Magnus Lycka) Date: Tue Feb 25 05:11:00 2003 Subject: [Tutor] script comparing two values In-Reply-To: <20030225044501.4255.34230.Mailman@mail.python.org> Message-ID: <5.1.0.14.0.20030225094241.04396d58@www.thinkware.se> At Mon, 24 Feb 2003 19:14:57 -0800 (PST), Mic Forster wrote: >I am attempting to fit an expected geometric series of >relative species abundance with an observed set of >relative species abundance. In doing so one has to >determine a constant, k. This is done by iterating the >following equation: > >Nmin / N = (k / (1 - k)) * (pow((1 - k),s)) / (1 - >(pow((1 - k),s)) = j > >where Nmin is the number of individuals in the least >abundant species, N is the total number of individuals >and s is the number of species. In my example: > >Nmin = 1 >N = 862 >s = 11 If this was a one time calculation, I might just make it an interactive python session. First, we need to define things. Remember as Jeff said to carefully balance parenthesis, that multiplication never happens implicitly and that ** is the power operator. Also remember that Python still thinks that 1 / 2 is 0, but that 1 / 2.0 is 0.5. In other words, dividing two integers will give an integer result. (This will change in the future.) >>> def f(k, s): ... return k / (1-k) * (1-k)**s / (1-(1-k)**s) ... >>> j = 1. / 862 >>> s = 11 Lets just get a rough picture to begin with: >>> for i in range(1,10): ... k = i / 10. ... print k, f(k,s) - j ... 0.1 0.04965363852 0.2 0.0223327647725 0.3 0.00748510854082 0.4 0.00126736096339 0.5 -0.000671573022373 0.6 -0.00109717560849 0.7 -0.0011559593701 0.8 -0.00116001088742 0.9 -0.00116009271742 Obviously, the correct value for k is somewhere between 0.4 and 0.5. I don't know what precision you need. If you throw these values into excel of some other plotting capable program, you can see that it's a smooth curve, where the derivate is constantly negative. This means that you could use the bisection method, but let's do the manual iteration two more times. >>> for i in range(10): ... k = 0.4 + i / 100. ... print k, f(k,s) - j ... 0.4 0.00126736096339 0.41 0.000941824399188 0.42 0.000653817213948 0.43 0.000399869640732 0.44 0.000176721938801 0.45 -1.86744412629e-005 0.46 -0.000189157813584 0.47 -0.000337359101879 0.48 -0.000465706337899 0.49 -0.000576430579781 >>> for i in range(10): ... k = 0.44 + i / 1000. ... print k, f(k,s) - j ... 0.44 0.000176721938801 0.441 0.000155981964688 0.442 0.000135516397721 0.443 0.000115322326515 0.444 9.53968606932e-005 0.445 7.57371308685e-005 0.446 5.6340288613e-005 0.447 3.72035064319e-005 0.448 1.8323977733e-005 0.449 -3.01083204318e-007 I just do arrow-up in PythonWin to the for loop, press enter to get a copy, changes the k = ... row and press enter again. You can continue until you reach your required accuracy, 0.4489837 or whatever. If you want to make this into a normal program, you would need to make the code determine what interval to look closer at. In this case, you can use the bisection method. Note that the bisection method only works well if the functin curve is nice enough, that is, the derivate doesn't change sign in the tested inteval. Analysis of the function of a simple plot will often determine this. With bisection, you first try a minimum point and a maximum point, and make sure that the solutions for these points have different signs. Then your solution is in between. Then you try a value in the middle, between min and max. The solution for this point will have the same sign as min or max. Look at values from our first run above. 0.1 0.04965363852 0.5 -0.000671573022373 0.9 -0.00116009271742 This solution for 0.5 has the same sign as for max, 0.9. This means that the next test should be in the interval 0.1 to 0.5. So, we should make a bisection function now, right? >>> def bisect(min, max, delta, function): ... fMax = function(max) ... fMin = function(min) ... assert fMax * fMin < 0 ... while max - min > delta: ... newX = 0.5 * (min + max) ... fNew = function(newX) ... if fNew * fMax > 0: ... # fNew has same sign as fMax, so newX should replace max ... max, fMax = newX, fNew ... else: ... min, fMin = newX, fNew ... return newX, fNew ... >>> def fun(x): ... return f(x, s) - j ... First, let's test the error handling: >>> bisect(0.1, 0.2, delta, fun) Traceback (most recent call last): File "", line 1, in ? File "", line 4, in bisect AssertionError Ok, it won't let us enter an interval where both ends lead to a solution of the same sign. Lets make a very low resolution test. >>> bisect(0.01, 0.99, 0.01, fun) (0.3775, 0.0021564007982048661) Ok, it's the right region... Let's use a higher resolution. >>> delta = 1e-9 >>> bisect(delta, 1-delta, delta, fun) (0.44898369918536085, 4.9493988790207111e-010) How far can we go? >>> delta = 1e-17 >>> bisect(delta, 1-delta, delta, fun) Traceback (most recent call last): File "", line 1, in ? File "", line 2, in bisect File "", line 2, in fun File "", line 2, in f ZeroDivisionError: float division Too far! >>> delta = 1e-16 >>> bisect(delta, 1-delta, delta, fun) (0.44898372593474889, -3.6212352561015848e-017) Is this accurate enough? ;) To determine how accurate you are, I guess you should return both min and max. Then you can say that k must be in that interval. >>> def bisect(min, max, delta, function): ... fMax = function(max) ... fMin = function(min) ... assert fMax * fMin < 0 ... while abs(fMax - fMin) > delta: ... newX = 0.5 * (min + max) ... fNew = function(newX) ... if fNew * fMax > 0: ... # fNew has same sign as fMax, so newX should replace max ... max, fMax = newX, fNew ... else: ... min, fMin = newX, fNew ... return "%.17f +/- %.17f" % (0.5*(min+max), 0.5*(max-min)) ... >>> bisect(delta, 1-delta, delta, fun) '0.44898372593474711 +/- 0.00000000000000178' -- Magnus Lycka, Thinkware AB Alvans vag 99, SE-907 50 UMEA, SWEDEN phone: int+46 70 582 80 65, fax: int+46 70 612 80 65 http://www.thinkware.se/ mailto:magnus@thinkware.se From alan.gauld@bt.com Tue Feb 25 05:39:10 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Tue Feb 25 05:39:10 2003 Subject: [Tutor] Functions and Variable Names Message-ID: <7497DCA1C240C042B28F6657ADFD8E0901F85122@i2km11-ukbr.domain1.systemhost.net> > Okay, if I have separate functions, I know I can pass a value > between them with the same variable name. But is that considered > poor programming? No its perfectly cvommon and acceptable practice. However.... > def f1(score): print "Your score of %d has been recorded." %score > > def f2(score): ... > f1(score) > > def main(): > score = 90 > f2(score) > "score" is the prefect name for what I'm representing, but > should I have different names for this value in each function? To distinguish between the global variable and the parameters you might like to adopt a naming technique. My personal one is like so: def f1(aScore): .... def f2(aScore):.... def main(): theScore = 90 f2(theScore) Thus the top level one (which gets the initial value) I call theXXX and the parameters - which could be any value - I call aXXX. FWIW I also use this technique in class definitions for languages like Java/C++ where explicit 'self' is not used. In Python that specific problem doesn't exist. HTH, Alan G. From micforster@yahoo.com Tue Feb 25 05:41:53 2003 From: micforster@yahoo.com (Mic Forster) Date: Tue Feb 25 05:41:53 2003 Subject: [Tutor] script comparing two values In-Reply-To: <5.1.0.14.0.20030225094241.04396d58@www.thinkware.se> Message-ID: <20030225104010.53132.qmail@web13404.mail.yahoo.com> Thanks Magnus and Jeff, Magnus, the result I obtained by hand was 0.449. So you were spot on! --- Magnus Lycka wrote: > At Mon, 24 Feb 2003 19:14:57 -0800 (PST), Mic > Forster wrote: > >I am attempting to fit an expected geometric series > of > >relative species abundance with an observed set of > >relative species abundance. In doing so one has to > >determine a constant, k. This is done by iterating > the > >following equation: > > > >Nmin / N = (k / (1 - k)) * (pow((1 - k),s)) / (1 - > >(pow((1 - k),s)) = j > > > >where Nmin is the number of individuals in the > least > >abundant species, N is the total number of > individuals > >and s is the number of species. In my example: > > > >Nmin = 1 > >N = 862 > >s = 11 > > If this was a one time calculation, I might just > make it > an interactive python session. First, we need to > define things. > Remember as Jeff said to carefully balance > parenthesis, that > multiplication never happens implicitly and that ** > is the > power operator. > > Also remember that Python still thinks that 1 / 2 is > 0, but > that 1 / 2.0 is 0.5. In other words, dividing two > integers will > give an integer result. (This will change in the > future.) > > >>> def f(k, s): > ... return k / (1-k) * (1-k)**s / (1-(1-k)**s) > ... > >>> j = 1. / 862 > >>> s = 11 > > Lets just get a rough picture to begin with: > > >>> for i in range(1,10): > ... k = i / 10. > ... print k, f(k,s) - j > ... > 0.1 0.04965363852 > 0.2 0.0223327647725 > 0.3 0.00748510854082 > 0.4 0.00126736096339 > 0.5 -0.000671573022373 > 0.6 -0.00109717560849 > 0.7 -0.0011559593701 > 0.8 -0.00116001088742 > 0.9 -0.00116009271742 > > Obviously, the correct value for k is somewhere > between 0.4 > and 0.5. I don't know what precision you need. If > you throw > these values into excel of some other plotting > capable program, > you can see that it's a smooth curve, where the > derivate is > constantly negative. This means that you could use > the bisection > method, but let's do the manual iteration two more > times. > > >>> for i in range(10): > ... k = 0.4 + i / 100. > ... print k, f(k,s) - j > ... > 0.4 0.00126736096339 > 0.41 0.000941824399188 > 0.42 0.000653817213948 > 0.43 0.000399869640732 > 0.44 0.000176721938801 > 0.45 -1.86744412629e-005 > 0.46 -0.000189157813584 > 0.47 -0.000337359101879 > 0.48 -0.000465706337899 > 0.49 -0.000576430579781 > >>> for i in range(10): > ... k = 0.44 + i / 1000. > ... print k, f(k,s) - j > ... > 0.44 0.000176721938801 > 0.441 0.000155981964688 > 0.442 0.000135516397721 > 0.443 0.000115322326515 > 0.444 9.53968606932e-005 > 0.445 7.57371308685e-005 > 0.446 5.6340288613e-005 > 0.447 3.72035064319e-005 > 0.448 1.8323977733e-005 > 0.449 -3.01083204318e-007 > > I just do arrow-up in PythonWin to the for loop, > press > enter to get a copy, changes the k = ... row and > press > enter again. > > You can continue until you reach your required > accuracy, > 0.4489837 or whatever. > > If you want to make this into a normal program, you > would > need to make the code determine what interval to > look closer > at. In this case, you can use the bisection method. > Note that > the bisection method only works well if the functin > curve is > nice enough, that is, the derivate doesn't change > sign in > the tested inteval. Analysis of the function of a > simple > plot will often determine this. > > With bisection, you first try a minimum point and a > maximum > point, and make sure that the solutions for these > points have > different signs. Then your solution is in between. > Then you > try a value in the middle, between min and max. The > solution > for this point will have the same sign as min or > max. Look at > values from our first run above. > > 0.1 0.04965363852 > 0.5 -0.000671573022373 > 0.9 -0.00116009271742 > > This solution for 0.5 has the same sign as for max, > 0.9. This > means that the next test should be in the interval > 0.1 to 0.5. > So, we should make a bisection function now, right? > > >>> def bisect(min, max, delta, function): > ... fMax = function(max) > ... fMin = function(min) > ... assert fMax * fMin < 0 > ... while max - min > delta: > ... newX = 0.5 * (min + max) > ... fNew = function(newX) > ... if fNew * fMax > 0: > ... # fNew has same sign as > fMax, so newX should > replace max > ... max, fMax = newX, fNew > ... else: > ... min, fMin = newX, fNew > ... return newX, fNew > ... > >>> def fun(x): > ... return f(x, s) - j > ... > > First, let's test the error handling: > > >>> bisect(0.1, 0.2, delta, fun) > Traceback (most recent call last): > File "", line 1, in ? > File "", line 4, in bisect > AssertionError > > Ok, it won't let us enter an interval where both > ends > lead to a solution of the same sign. > > Lets make a very low resolution test. > > >>> bisect(0.01, 0.99, 0.01, fun) > (0.3775, 0.0021564007982048661) > > Ok, it's the right region... Let's use a higher > resolution. > > >>> delta = 1e-9 > >>> bisect(delta, 1-delta, delta, fun) > (0.44898369918536085, 4.9493988790207111e-010) > > How far can we go? > > >>> delta = 1e-17 > >>> bisect(delta, 1-delta, delta, fun) > Traceback (most recent call last): > File "", line 1, in ? > File "", line 2, in bisect > === message truncated === __________________________________________________ Do you Yahoo!? Yahoo! Tax Center - forms, calculators, tips, more http://taxes.yahoo.com/ From alan.gauld@bt.com Tue Feb 25 06:34:02 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Tue Feb 25 06:34:02 2003 Subject: [Tutor] script comparing two values Message-ID: <7497DCA1C240C042B28F6657ADFD8E0974DAD4@i2km11-ukbr.domain1.systemhost.net> > This is what I have and I know that it is completely wrong: > > def constant(j): > result = [] > i = 0.0 > while i is not j: > result.append(k) > i, k = (k / (1 - k)((1 - k)^s) / (1 - (1 - k)^s), i > + 0.0001 Try swapping these lines round. k doesn't exist till after the assignment... Also: i = (k / (1 - k)((1 - k)^s) / (1 - (1 - k)^s) ^^ Should these be multiplied together? If so you need to use the * operator, Python doesn't know about implicit multiplication ala math. So taking the first term, should it be: (k/(1-k)) * ((1-k)**s)/(1-(1-k)**s) OR (k/((1-k)*((1-k)**s)))/(1-(1-k)**s) OR something else again.... HTH, Alan G. From ramrom@earthling.net Tue Feb 25 09:44:30 2003 From: ramrom@earthling.net (Bob Gailer) Date: Tue Feb 25 09:44:30 2003 Subject: [Tutor] win32 and excel In-Reply-To: Message-ID: <5.2.0.9.0.20030225070637.01a03ac0@66.28.54.253> --=======24237E6F======= Content-Type: text/plain; x-avg-checked=avg-ok-56086167; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit In my experience with Excel chart data needs to be arranged thus: Date: 2/3/2003 2/4/2003 2/5/2003 etc Apples Sold 3 5 9 etc Assuming this data is in A1:I2: import win32com.client ex = win32com.client.Dispatch("excel.application") ex.visible = 1 wb = ex.workbooks.open('c:\\xxx\\book1.xls') wk = ex.Worksheets(1) # worksheet chartobject1 = wk.chartobjects(1) chart1 = chartobject1.chart # chart range = ex.Range("A1:I2") chart1.seriescollection.add(range) If the initial worksheet has the data in the format you showed: Date: Apples Sold: 2/3/2003 3 2/4/2003 5 2/5/2003 9 Then (I think) you'll need to transpose it. If you are filling those cells from the Python program, just fill them in the order I gave above. Bob Gailer mailto:ramrom@earthling.net 303 442 2625 --=======24237E6F======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-56086167 Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.454 / Virus Database: 253 - Release Date: 2/10/2003 --=======24237E6F=======-- From vicki@stanfield.net Tue Feb 25 10:08:17 2003 From: vicki@stanfield.net (vicki@stanfield.net) Date: Tue Feb 25 10:08:17 2003 Subject: [Tutor] Scrolled Listbox Message-ID: <20030225070756.6615.h010.c000.wm@mail.stanfield.net.criticalpath.net> I need a Scrolled Listbox for an application that I am writing. The only one I see is in PMW which appears to still be in beta as far as I can tell. Is this the way it is done, or is there another one that I haven't stumbled across yet? I just need some way to select from a (hidden) long list. Thanks, --vicki From kenneth_boehme@hotmail.com Tue Feb 25 13:09:02 2003 From: kenneth_boehme@hotmail.com (Kenneth Boehme) Date: Tue Feb 25 13:09:02 2003 Subject: [Tutor] Classes Message-ID: This is a multi-part message in MIME format. ------=_NextPart_000_0044_01C2DCBE.0260F200 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable I'm just starting with Python and I'm having problems with getting = classes to work. I've written this basic class: class Circle: def _init_(self, rad=3D5): self.radius=3Drad def area(self): return self.radius * self.radius * 3.14 I get the following error message when I try to use it: >>> x=3Dcirc.Circle(10) Traceback (most recent call last): File "", line 1, in ? TypeError: this constructor takes no arguments >>> from circ import Circle >>> y=3DCircle(10) Traceback (most recent call last): File "", line 1, in ? TypeError: this constructor takes no arguments >>>=20 What I'm doing wrong? Thanks, Kenneth ------=_NextPart_000_0044_01C2DCBE.0260F200 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
I'm just starting with Python and I'm = having=20 problems with getting classes to work.
 
I've written this basic = class:
 
 class Circle:
        def=20 _init_(self, rad=3D5):
          &nbs= p;     self.radius=3Drad

        
def area(self):
          &nbs= p;     return=20 self.radius * self.radius * 3.14
 
I get the following error message when = I try to use=20 it:
 
>>> = x=3Dcirc.Circle(10)
Traceback (most=20 recent call last):
  File "<interactive input>", line 1, = in=20 ?
TypeError: this constructor takes no arguments
>>> from = circ=20 import Circle
>>> y=3DCircle(10)
Traceback (most recent = call=20 last):
  File "<interactive input>", line 1, in = ?
TypeError:=20 this constructor takes no arguments
>>>
 
What I'm doing wrong?
 
Thanks,
 
Kenneth
------=_NextPart_000_0044_01C2DCBE.0260F200-- From riex@ligbr.com.br Tue Feb 25 13:32:04 2003 From: riex@ligbr.com.br (riex@ligbr.com.br) Date: Tue Feb 25 13:32:04 2003 Subject: [Tutor] Practice sets for newbies Message-ID: <20030225152516.3472.qmail@ligbr.com.br> Hello, tutor, I wonder if there are any practice tutorial sets for things like loops,lists, the use of modules, and etc. I'm new to python, and programing in general. So far I have used Josh Cogliati's "non-prog. tutorial for python", and also Guido Van Rossun's nice "python tutorial" to get me started. However, I think that having some basic practice problems could take me a step further. Does anyone have a tip for me on how to improve my python skils ? All the best to all, Diego. riex@ligbr.com.br From tbrauch@mindless.com Tue Feb 25 13:39:08 2003 From: tbrauch@mindless.com (Timothy M. Brauch) Date: Tue Feb 25 13:39:08 2003 Subject: [Tutor] Classes References: Message-ID: <005201c2dcfc$b5dca200$6600a8c0@tbrauch> From: Kenneth Boehme >I'm just starting with Python and I'm having problems with getting classes to work. > >I've written this basic class: > > class Circle: > def _init_(self, rad=5): ^^^^^ It looks like the problem is here. You need 2 underscores before and after the 'special' functions. It should be _ _ i n i t _ _, not _ i n i t _. > self.radius=rad > > def area(self): > return self.radius * self.radius * 3.14 > >I get the following error message when I try to use it: > >>>> x=circ.Circle(10) >Traceback (most recent call last): > File "", line 1, in ? >TypeError: this constructor takes no arguments >>>> from circ import Circle >>>> y=Circle(10) >Traceback (most recent call last): > File "", line 1, in ? >TypeError: this constructor takes no arguments > >What I'm doing wrong? > >Thanks, > > >Kenneth I think that might fix the problem. I'm not sure the documentation makes the distinction clear. It is hard, especially if you are using a variable width font when reading, to distinguish between _ and __. I'm not sure how to notice this, other than doing what you did. I can't think of any other examples, other than the 'special' functions like these, and as far as I know, all of them use 2 underscores. - Tim Let's see if I can send this one to everyone, and when I am actually finished with what I am trying to type. From ahimsa@onetel.net.uk Tue Feb 25 14:03:01 2003 From: ahimsa@onetel.net.uk (ahimsa) Date: Tue Feb 25 14:03:01 2003 Subject: [Tutor] RE: Prime Numbers Message-ID: <200302251906.40859.ahimsa@onetel.net.uk> Brett, Ike, Gerrit, Timothy (sorry, if I have left anyone out): Thank you all for replying to my query - in truth, I have to confess it w= as=20 far more info than I needed, but was useful in a number of ways: 1. It helped me realise that the algorithm that I was trying to draft som= e=20 working code to figure out primes was *hopelessly* inadequate to the task= =20 required 2. It helped me realise that actually a simple sounding problem (find the= =20 prime numbers between 1 and 28, for e.g. ) is actually a seemingly very=20 complex problem 3. I don't feel too bad about not being able to work it out myself given = the=20 fairly sophisticated (from my perspective) code that you folk fed back to= me 4. There is - as always - still so much to learn, and that I will revisit= this=20 problem when I have a clearer understanding of what is required and how t= o=20 think through the terms of the problem. 5. And, thank you for the code snippets: I file these away for later revi= ew=20 and I am happy to be able to report that I am obviously learning more tha= n I=20 realise since the code no longer looks entirely like a strange Martian=20 dialect. Once again - thanks, and so, till next time ... all the best Andrew From glingl@aon.at Tue Feb 25 15:44:02 2003 From: glingl@aon.at (Gregor Lingl) Date: Tue Feb 25 15:44:02 2003 Subject: [Tutor] Practice sets for newbies References: <20030225152516.3472.qmail@ligbr.com.br> Message-ID: <3E5BD577.2050002@aon.at> riex@ligbr.com.br schrieb: > > Hello, tutor, > I wonder if there are any practice tutorial sets for things like > loops,lists, the use of modules, and etc. > I'm new to python, and programing in general. So far I have used Josh > Cogliati's "non-prog. tutorial for python", and also Guido Van > Rossun's nice "python tutorial" to get me started. > However, I think that having some basic practice problems could take > me a step further. > Does anyone have a tip for me on how to improve my python skils ? Try this: http://www.freenetpages.co.uk/hp/alan.gauld/port/index.htm Regards, Gregor > > All the best to all, Diego. > riex@ligbr.com.br > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From Janssen@rz.uni-frankfurt.de Tue Feb 25 16:18:03 2003 From: Janssen@rz.uni-frankfurt.de (Michael Janssen) Date: Tue Feb 25 16:18:03 2003 Subject: [Tutor] Classes In-Reply-To: Message-ID: On Tue, 25 Feb 2003, Kenneth Boehme wrote: > class Circle: > def _init_(self, rad=5): > self.radius=rad > [...] > >>> y=Circle(10) > Traceback (most recent call last): > File "", line 1, in ? > TypeError: this constructor takes no arguments > >>> > > What I'm doing wrong? two underscores: __init__(self, rad=5) . Now Python knows what to do with this __init__() (and take it as the constructor). In your case _init_() is a normal method and y hasn't a __init__() operator. Michael > > Thanks, > > Kenneth From Janssen@rz.uni-frankfurt.de Tue Feb 25 16:18:16 2003 From: Janssen@rz.uni-frankfurt.de (Michael Janssen) Date: Tue Feb 25 16:18:16 2003 Subject: [Tutor] Practice sets for newbies In-Reply-To: <20030225152516.3472.qmail@ligbr.com.br> Message-ID: On Tue, 25 Feb 2003 riex@ligbr.com.br wrote: > > Hello, tutor, > I wonder if there are any practice tutorial sets for things like > loops,lists, the use of modules, and etc. nice idea :-) You did have access to a computer? Take it as your set of practice problems ;-) I have no problems in constantly finding problems that are worth to solve (more or less ;-) and worth to do it in python (but I suppose the gurus from comp.unix.shell could replace any of my scripts with very small shell scripts ;-). It feels odd to me to suggest single tasks but nonetheless: 1. general tips: * Simple practice tasks are properly easier to find under linux, because access to the commandline-interface is easier (and you can help yourself with cmdl-tools): you needn't do your first steps mangled with GUI-programming. * When I'm in neeed of a simple task, I ask myself which common tasks with my computer are really annoying amd could better be done by a script or with the kind help by a script. * Don't believe there is something like a simple task! You need to thought thorough and look for solution, which are modular and as clear as possible. * Explain other people your plans. This helps to get a better idea what to plan. The tutor could possibly play a role in this process. * Try to see the difference between your beginners style and the style of a expierenced programmer. Learn to use better programm structures. * delete code. I have got this subtle advise from Mr Laningham. 2. special tasks I do *very* often lookups in the Python Library Reference. This means to point and click (search target - aim - shuffle with the mouse, cause it's dirty and forget, what I originally wanted...) through my webbrowser. To hard. A script come to mind that reads lib/genindex.html and found every function of a giving name. My version is pretty helpful but ugly. The same point and click, when I want to listen music. My player is xmms and fortunatelly it can be launched from commandline. A script search every file from my music-directory and choose a random track. Or it chooses from tracks matching a given string. Or the else. Reduces my afforts to get a music playback to merely a single keystroke. Best. I want to observe my usage of programm XXX (in my case the TV-viewer :-): A minutely cronjob (taskmanager on windows) checks if the programm runs and writes line for line to file. A small python script count the TV-sessions. And more of this (much more examples would come from a computer related job but a personal computer is just fine). All these scripts doesn't need special technics (like sockets, GUI or else) but the wellknown five modules string, re, time, sys, os (random for random-xmms). And you will learn a lot of lists and loops. Michael > > I'm new to python, and programing in general. So far I have used Josh > Cogliati's "non-prog. tutorial for python", and also Guido Van Rossun's nice > "python tutorial" to get me started. > > However, I think that having some basic practice problems could take me a > step further. > Does anyone have a tip for me on how to improve my python skils ? > > All the best to all, Diego. > riex@ligbr.com.br > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From abli@freemail.hu Tue Feb 25 17:03:27 2003 From: abli@freemail.hu (Abel Daniel) Date: Tue Feb 25 17:03:27 2003 Subject: [Tutor] Scrolled Listbox In-Reply-To: <20030225070756.6615.h010.c000.wm@mail.stanfield.net.criticalpath.net> References: <20030225070756.6615.h010.c000.wm@mail.stanfield.net.criticalpath.net> Message-ID: <20030225220222.GA2651@hooloovoo> vicki@stanfield.net (vicki@stanfield.net) wrote: > I need a Scrolled Listbox for an application that I am > writing. The only one I see is in PMW which appears to > still be in beta as far as I can tell. Well, I use it for my toy project, and it doesn't seem beta to me. (I guess they simply forgot to switch the 'development status' at sf :) ) But I think you don't need to switch to pmw. (At least not yet.) I think switching to pmw isn't just dropping a couple of widgets into your existing code. (Well, I guess you can do that, but once you use pmw, you'll want to rewrite the whole app to be pmwish :) ) After all, the name is Python _Mega_ _Widgets_, and not 'contributed widgets to tkinter' or something like that. Pmw uses a framework which (imho) makes you app (or at least the gui part) a bit more modular, but you have to get used to this framework (with things like having a suitable __init__ method when inheriting, with the proper incantations which make the thing work). Its easy, but you have to read docs first, and I nobody likes to do that :) > Is this the way > it is done, or is there another one that I haven't > stumbled across yet? > I just need some way to select > from a (hidden) long list. http://effbot.org/books/tkinterbook/scrollbar.htm describes the method of connecting a scrollbar so that is scrolls the listbox vertically. Adding another scrollbar is a pretty trivial extension of that pattern. http://effbot.org/zone/tkinter-listbox.htm might be interesting, too. Of course with this method, the scrollbars will be static, i.e. they are visible even if they aren't needed because the list is too sort. If you want dynamic scrollbars which only appear when they are needed, then I think using the corresponding pmw widget is the easiest solution. :) abli From glingl@aon.at Tue Feb 25 18:57:02 2003 From: glingl@aon.at (Gregor Lingl) Date: Tue Feb 25 18:57:02 2003 Subject: [Tutor] Python4Kids References: <20030225070756.6615.h010.c000.wm@mail.stanfield.net.criticalpath.net> <20030225220222.GA2651@hooloovoo> Message-ID: <3E5C029C.40607@aon.at> Hi Pythonistas! I'd like to inform you, that my new book "Python für Kids" is out now. Needless to say that, while writing the book, communicating with the members of this list for me was an indispensable support. Thank you all!!! You may have a look at the accompanying website http://python4kids.net It's a German book for Teens. I announce it here, on an English mailing-list, because I know that there are German speaking readers participating. And I know, that in the German speaking countries the use of Python among Kids and in schools is not *very* wide-spread ;-) On the other hand not seldom we here calls for material appropriate for young students, who want to learn programming. (Sometimes by programming fathers, who are in need of introductory material for their daughters (and/or sons) ). Here I'd like to point out only a few main features of my book: - it's written in a very informal (hopefully readable) style - it intentionally only uses the standard Python-distribution - concentrates on interactively using IDLE and encourages the reader to do her own interactive experiments using the interactive Python interpeter (called IPI in the book) - it uses turtle-graphics as a tool to visualize many of the fundamental concepts op programming - chapters 1 to 7 give a very gentle introduction to the fundamentals of programming, although using the ideas of "everything is an object in Python" and "variable = name + reference to an object" right from the beginning. - chapters 8 to 14 have a somewhat steeper learning curve finally leading from programming with objects to programming classes and objects themselves. (You may have a look at four "Bonus-Chapters" from the book-CD here: http://ada.rg16.asn-wien.ac.at/~python/buch.html) What more? *If* (you think that Python is a great learning - language *and* you want to propagate its use as a learning tool *and* you know (German speaking) kids or even teachers): talk to them about it encourage them to use it. Regards, Gregor From shalehperry@attbi.com Tue Feb 25 21:19:02 2003 From: shalehperry@attbi.com (Sean 'Shaleh' Perry) Date: Tue Feb 25 21:19:02 2003 Subject: [Tutor] Classes In-Reply-To: <005201c2dcfc$b5dca200$6600a8c0@tbrauch> References: <005201c2dcfc$b5dca200$6600a8c0@tbrauch> Message-ID: <200302251818.20656.shalehperry@attbi.com> On Tuesday 25 February 2003 10:35, Timothy M. Brauch wrote: > I think that might fix the problem. I'm not sure the documentation mak= es > the distinction clear. It is hard, especially if you are using a varia= ble > width font when reading, to distinguish between _ and __. I'm not sure= how > to notice this, other than doing what you did. I can't think of any ot= her > examples, other than the 'special' functions like these, and as far as = I > know, all of them use 2 underscores. > 2 underscores is the sign of "interpreter magic". These all represent sp= ecial=20 things Python does behind the scenes. They are "hidden" in the sense tha= t=20 you have to go out of the way to see them. single underscores are reserved for the programmer. If you have somethin= g you=20 want kept back from public use this is the Python idiom. Generally these= =20 names are used for behind the scenes implementations. class Random: def __init__(self, hardware): # do init stuff self.has_hardware =3D hardware def next(self): # returns the next random number from somewhere if self.has_hardware: =20 return self._real_random() return self._psuedo_random() def _real_random(self): # this will get a random number from hardware pass def _psuedo_random(self): # this will use some algorithm instead pass r =3D Random(0) # use a psuedo random number generator print "Chose this number just for you: %d" % r.next() The two functions with leading underscores are not meant to be used by th= e=20 user of the class they are just part of the implementation. From phthenry@earthlink.net Tue Feb 25 21:32:02 2003 From: phthenry@earthlink.net (Paul Tremblay) Date: Tue Feb 25 21:32:02 2003 Subject: [Tutor] best way to tokenize [was script too slow] In-Reply-To: <5.1.0.14.0.20030225152446.023fb800@192.168.1.1> References: <20030224190412.F10476@localhost.localdomain> <5.1.0.14.0.20030225152446.023fb800@192.168.1.1> Message-ID: <20030225213123.B13858@localhost.localdomain> Thanks. Your method is very instructive on how to use recursion. It is not quite perfect, since a line of tokens can look like: \par}}{\par{\ect => '\par}}' (should be '\par', '}', '}' However, it ends up that your method takes just a bit longer than using regular expressions, so there is probably no use in trying to perfect it. I did have one question about this line: > expandedWord = ' '.join(['\\'+item for item in > word.split('\\') if item]) I get this much from it: 1. first python splits the word by the "\\". 2. Then ??? It joins them somehow. I'm not sure what the .join is. Thanks Paul On Tue, Feb 25, 2003 at 03:43:25PM +1000, Alfred Milgrom wrote: > > At 07:04 PM 24/02/03 -0500, Paul Tremblay wrote: > >However, I don't know if there is a better way to split a line of RTF. > >Here is a line of RTF that exhibits each of the main type of tokens: [snip] > Hi Paul: > > I can't say whether regular expressions are the best way to tokenise your > RTF input, but here is an alternative recursive approach. > > Each line is split into words (using spaces as the separator), and then > recursively split into sub-tokens if appropriate. > > def splitWords(inputline): > outputList = [] > for word in inputline.split(' '): > if word.startswith('{') and word != '{': > expandedWord = '{' + ' ' + word[1:] > elif word.endswith('}')and word != '}' and word != '\\}': > expandedWord = word[:-1] + ' ' + '}' > elif '\\' in word and word != '\\': > expandedWord = ' '.join(['\\'+item for item in > word.split('\\') if item]) > else: > expandedWord = word > if expandedWord != word: > expandedWord = splitWords(expandedWord) > outputList.append(expandedWord) > return ' '.join(outputList) > > example1 = 'text \par \\ \{ \} {}' > > print splitWords(example1) > >>> text \par \ \{ \} { } > print splitWords(example1).split(' ') > >>> ['text', '\\par', '\\', '\\{', '\\}', '{', '}'] > > Seven different tokens seem to be identified correctly. > > example2 = 'text \par\pard \par} \\ \{ \} {differenttext}' > print splitWords(example2) > >>> text \par \ \{ \} { } > print splitWords(example2).split(' ') > >>> ['text', '\\par', '\\pard', '\\par', '}', '\\', '\\{', '\\}', '{', > 'differenttext', '}'] > > Haven't tested exhaustively, but this seems to do what you wanted it to do. > As I said, I don't know if this will end up being better than using re or > not, but it is an alternative approach. > > Best regards, > Fred > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- ************************ *Paul Tremblay * *phthenry@earthlink.net* ************************ From phthenry@earthlink.net Tue Feb 25 21:50:03 2003 From: phthenry@earthlink.net (Paul Tremblay) Date: Tue Feb 25 21:50:03 2003 Subject: [Tutor] best way to tokenize [was script too slow] In-Reply-To: <20030225213123.B13858@localhost.localdomain> References: <20030224190412.F10476@localhost.localdomain> <5.1.0.14.0.20030225152446.023fb800@192.168.1.1> <20030225213123.B13858@localhost.localdomain> Message-ID: <20030225214931.C13858@localhost.localdomain> Answering my own email. I'm still not totatlly sure of the line in question, but I do realize that the '.join' is really: create a string called "' '", and then use the method '.join' on that string. Okay, now I do see the whole thing. The list to join is: first split the token by "\\", which will get rid of the "\\", and then add the "\\" to each item. That's kind of a nice one liner to make tokens. Thanks Paul On Tue, Feb 25, 2003 at 09:31:24PM -0500, Paul Tremblay wrote: > > Thanks. Your method is very instructive on how to use recursion. It is > not quite perfect, since a line of tokens can look like: > > \par}}{\par{\ect => '\par}}' (should be '\par', '}', '}' > > However, it ends up that your method takes just a bit longer than using > regular expressions, so there is probably no use in trying to perfect > it. I did have one question about this line: > > > > expandedWord = ' '.join(['\\'+item for item in > > word.split('\\') if item]) > > I get this much from it: > > 1. first python splits the word by the "\\". > > 2. Then ??? It joins them somehow. I'm not sure what the .join is. > > Thanks > > Paul > > > > On Tue, Feb 25, 2003 at 03:43:25PM +1000, Alfred Milgrom wrote: > > > > At 07:04 PM 24/02/03 -0500, Paul Tremblay wrote: > > >However, I don't know if there is a better way to split a line of RTF. > > >Here is a line of RTF that exhibits each of the main type of tokens: > > [snip] > > > Hi Paul: > > > > I can't say whether regular expressions are the best way to tokenise your > > RTF input, but here is an alternative recursive approach. > > > > Each line is split into words (using spaces as the separator), and then > > recursively split into sub-tokens if appropriate. > > > > def splitWords(inputline): > > outputList = [] > > for word in inputline.split(' '): > > if word.startswith('{') and word != '{': > > expandedWord = '{' + ' ' + word[1:] > > elif word.endswith('}')and word != '}' and word != '\\}': > > expandedWord = word[:-1] + ' ' + '}' > > elif '\\' in word and word != '\\': > > expandedWord = ' '.join(['\\'+item for item in > > word.split('\\') if item]) > > else: > > expandedWord = word > > if expandedWord != word: > > expandedWord = splitWords(expandedWord) > > outputList.append(expandedWord) > > return ' '.join(outputList) > > > > example1 = 'text \par \\ \{ \} {}' > > > > print splitWords(example1) > > >>> text \par \ \{ \} { } > > print splitWords(example1).split(' ') > > >>> ['text', '\\par', '\\', '\\{', '\\}', '{', '}'] > > > > Seven different tokens seem to be identified correctly. > > > > example2 = 'text \par\pard \par} \\ \{ \} {differenttext}' > > print splitWords(example2) > > >>> text \par \ \{ \} { } > > print splitWords(example2).split(' ') > > >>> ['text', '\\par', '\\pard', '\\par', '}', '\\', '\\{', '\\}', '{', > > 'differenttext', '}'] > > > > Haven't tested exhaustively, but this seems to do what you wanted it to do. > > As I said, I don't know if this will end up being better than using re or > > not, but it is an alternative approach. > > > > Best regards, > > Fred > > > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > -- > > ************************ > *Paul Tremblay * > *phthenry@earthlink.net* > ************************ > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- ************************ *Paul Tremblay * *phthenry@earthlink.net* ************************ From steegness@hotmail.com Tue Feb 25 22:05:02 2003 From: steegness@hotmail.com (Steegness) Date: Tue Feb 25 22:05:02 2003 Subject: [Tutor] Practice Sets for newbie References: <20030226025003.2399.28013.Mailman@mail.python.org> Message-ID: > From: riex@ligbr.com.br > To: Tutor@python.org > Date: Tue, 25 Feb 2003 15:25:16 GMT > Subject: [Tutor] Practice sets for newbies > > > Hello, tutor, > I wonder if there are any practice tutorial sets for things like > loops,lists, the use of modules, and etc. > > I'm new to python, and programing in general. So far I have used Josh > Cogliati's "non-prog. tutorial for python", and also Guido Van Rossun's nice > "python tutorial" to get me started. > > However, I think that having some basic practice problems could take me a > step further. > Does anyone have a tip for me on how to improve my python skils ? > > All the best to all, Diego. > riex@ligbr.com.br For me, UselessPython has been indispensible. There's a lot of code there to look at, a lot of little tasks that you can try to mimic, and a page full of interesting challenges to test your mettle. I know it looks defunct, but it really isn't. Honest. :) Head on over to www.uselesspython.com for the goods. Sean Steeg From rob@uselesspython.com Tue Feb 25 22:17:24 2003 From: rob@uselesspython.com (Rob Andrews) Date: Tue Feb 25 22:17:24 2003 Subject: [Tutor] Practice Sets for newbie In-Reply-To: Message-ID: > For me, UselessPython has been indispensible. There's a lot of code there > to look at, a lot of little tasks that you can try to mimic, and > a page full > of interesting challenges to test your mettle. I know it looks > defunct, but > it really isn't. Honest. :) > > Head on over to www.uselesspython.com for the goods. > > Sean Steeg That's correct. I was actually actually working on the site at this very moment, when I noticed your comment. I've added a lits of a few of the many changes underway to the front page of the site today. Anyone interested in volunteering is welcome to investigate, BTW. -Rob From Ike Hall Wed Feb 26 04:28:02 2003 From: Ike Hall (Ike Hall) Date: Wed Feb 26 04:28:02 2003 Subject: [Tutor] RE: Prime Numbers References: <200302251906.40859.ahimsa@onetel.net.uk> Message-ID: <001601c2dd79$316c5600$bf27e183@chief> Hi Ahimsa, I should have told you at the beginning, that I wrote aprogram to do exactly this (find primes between x and y) afew years ago. It actually is not that complex, but merely involves thinking in math for a few minutes. (for me, this is easy, but for others, I realize this is not always the case...hence, I will try to replicate what I did, from memory, since that snippet of code lives on a computer far away, with comments to try to explain what is going on.) First, I decided that what I would do is define a function, prime(x,y) that returned a tuple containing all primes between x and y. code below: #So, we are going to need the math module, because I #wanted to speed it up using sqrt()... #and the types module, because I want to make sure #that x and y are integers, or floats, or longs. import math from types import * def prime(x,y): #first, I want to be sure that I have numbers for x and y if type(x) != IntType or FloatType or LongType: print 'I need numbers people!' return None elif type(y)!= IntType or FloatType or LongType: print 'I need numbers people!' return None else: pass #next, we want to find out which is smaller, and make #sure that is 'x' if x>y: dummy = x x=y y=dummy #now we also want to make sure that there is at least one #integer between x and y (floats cannot be primes, but # primes can lie between 2 floats if there is an integer #between them if int(y) < int(x)+1: print 'There are no integers between '+str(x)'+ and '+str(y)+', therefore, no primes' return None #now we have done all the checks we need, so we now turn our numbers into integers if they are not already #we add one to int(x) or long(x) to get the next integer, since we want primes between x and y if type(x)==FloatType: try: x=int(x)+1 except(OverflowError): x=long(x)+1 if type(y)==FloatType: try: y=int(y) except(OverflowError): y=long(y) #now for the meat of the program: #to save us some time, we can just check every odd number between x and y # since we know that 2 is the only even prime number #also, we will not check any negative numbers, since they cannot be prime...even if their positive #counterpart is (since -x =(x*-1) or (-x*1), assuming x is prime) primes=[] if 1 in range(x,y):primes.append(1) if 2 in range(x,y):primes.append(2) if y<=3: if y==3:primes.append(3) return primes if x<3:start=3 elif x%2: start=x else:start=x+1 for i in range(start,y,2): high=int(math.sqrt(i)) #we only check between 2 and sqrt(i) primeflag=1 for j in range(2, high): if not i%j: primeflag=0 else: pass if primeflag: primes.append(i) return tuple(primes) I hope this helps...Im not sure if I put a bug in there, as I havent tested this, but I did test the loop part, and I am sure that it works. as you can see, its not that complicated....but for larger and larger numbers, it could take some time.... BTW, if you want to go from 1 to anything instead of x to anything, you only need to check each number against the prime numbers that are lower than its square root...and since you add them to the list in order, you just loop over the list that already exists....anyway, I hope this helps some...and if not, I hope it doesnt make you throw your hands in the air screaming.... Ike ----- Original Message ----- From: "ahimsa" To: Sent: Tuesday, February 25, 2003 1:06 PM Subject: [Tutor] RE: Prime Numbers > Brett, Ike, Gerrit, Timothy (sorry, if I have left anyone out): > > Thank you all for replying to my query - in truth, I have to confess it was > far more info than I needed, but was useful in a number of ways: > > 1. It helped me realise that the algorithm that I was trying to draft some > working code to figure out primes was *hopelessly* inadequate to the task > required > 2. It helped me realise that actually a simple sounding problem (find the > prime numbers between 1 and 28, for e.g. ) is actually a seemingly very > complex problem > 3. I don't feel too bad about not being able to work it out myself given the > fairly sophisticated (from my perspective) code that you folk fed back to me > 4. There is - as always - still so much to learn, and that I will revisit this > problem when I have a clearer understanding of what is required and how to > think through the terms of the problem. > 5. And, thank you for the code snippets: I file these away for later review > and I am happy to be able to report that I am obviously learning more than I > realise since the code no longer looks entirely like a strange Martian > dialect. > > Once again - thanks, and so, till next time ... all the best > > Andrew > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld@bt.com Wed Feb 26 06:53:02 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Wed Feb 26 06:53:02 2003 Subject: [Tutor] Scrolled Listbox Message-ID: <7497DCA1C240C042B28F6657ADFD8E0974DADA@i2km11-ukbr.domain1.systemhost.net> > I need a Scrolled Listbox for an application that I am > writing. The only one I see is in PMW which appears to > still be in beta as far as I can tell. Assuming you are definitely using Tkinter then that seems to be the normal route. If you have the flexibility to choose wxPython has a scrolling list as a native widget I believe. > ...is there another one that I haven't stumbled across yet? Its not enormously difficult to create your own using a lust and a scrollbar widget. I think there is an example in the Tk demo that comes with Tcl/Tk. The Tcl sources are installed in Python in: ....Python22\tcl\tk8.3\demos If you have wish installed you can run widget.tcl to see them in action, otherwise you need to browse using grep and a text editor... Alan g. From alan.gauld@bt.com Wed Feb 26 07:03:02 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Wed Feb 26 07:03:02 2003 Subject: [Tutor] Practice sets for newbies Message-ID: <7497DCA1C240C042B28F6657ADFD8E0901F8512D@i2km11-ukbr.domain1.systemhost.net> > I wonder if there are any practice tutorial sets for things like > loops,lists, the use of modules, and etc. Most of the tutors have some, including mine - also available in Portuguese... :-) > However, I think that having some basic practice problems > could take me a step further. You might find the Useless Python website has what you want. It has some project type challenges to try, some of whicvh have solutions too. > Does anyone have a tip for me on how to improve my python skils ? Take an existing program and play with it. Make changes and see if you can predict what the change will do. If it doesn't do what you expect, figure out why. If you can't figure out why, ask here! HTH, Alan g. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld/ From siddharth178@hotmail.com Wed Feb 26 07:12:24 2003 From: siddharth178@hotmail.com (siddharth karandikar) Date: Wed Feb 26 07:12:24 2003 Subject: [Tutor] sorting the list Message-ID: i have list like this >>>a = ['a1', 'a2', 'a3', 'a4', 'a10', 'a11', 'a12'] >>>a ['a1', 'a2', 'a3', 'a4', 'a10', 'a11', 'a12'] when i call >>>a.sort() list becomes >>>a ['a1', 'a10', 'a11', 'a12', 'a2', 'a3', 'a4'] **# here a10 is getting ahead of a2 a3 etc >>> but i need the list to be sorted like a1 a2 a3 a4 ... a10 a11 etc. any possible solution ??? _________________________________________________________________ MSN 8 with e-mail virus protection service: 2 months FREE* http://join.msn.com/?page=features/virus From ramrom@earthling.net Wed Feb 26 07:35:01 2003 From: ramrom@earthling.net (Bob Gailer) Date: Wed Feb 26 07:35:01 2003 Subject: [Tutor] RE: Prime Numbers In-Reply-To: <001601c2dd79$316c5600$bf27e183@chief> References: <200302251906.40859.ahimsa@onetel.net.uk> Message-ID: <5.2.0.9.0.20030226053213.01a03aa8@66.28.54.253> --=======499F78A2======= Content-Type: text/plain; x-avg-checked=avg-ok-4A6E6042; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit At 03:26 AM 2/26/2003 -0600, Ike Hall wrote: >#So, we are going to need the math module, because I wanted to speed it up >using sqrt()... Just a reminder that you don't need the math module and sqrt. To get the square root of a number x just use: sx = x**.5 Bob Gailer mailto:ramrom@earthling.net 303 442 2625 --=======499F78A2======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-4A6E6042 Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.454 / Virus Database: 253 - Release Date: 2/10/2003 --=======499F78A2=======-- From Don Arnold" Message-ID: <00a501c2dd95$7045bf80$1ad1b241@defaultcomp> ----- Original Message ----- From: "siddharth karandikar" To: Sent: Wednesday, February 26, 2003 6:09 AM Subject: [Tutor] sorting the list > > > i have list like this > >>>a = ['a1', 'a2', 'a3', 'a4', 'a10', 'a11', 'a12'] > >>>a > ['a1', 'a2', 'a3', 'a4', 'a10', 'a11', 'a12'] > > when i call > >>>a.sort() > > list becomes > >>>a > ['a1', 'a10', 'a11', 'a12', 'a2', 'a3', 'a4'] > **# here a10 is getting ahead of a2 a3 etc > >>> > > but i need the list to be sorted like > > a1 a2 a3 a4 ... a10 a11 etc. > > > any possible solution ??? > This is a little simplistic, but I think this works. It requires that each string has 1 or more numeric characters after the first one. def mysort(lhs, rhs): if rhs[0] <> lhs[0]: return cmp(lhs[0],rhs[0]) else: return cmp(int(lhs[1:]),int(rhs[1:])) a = ['a11','a10','a9','a8','a7','a6','a5','a4','a3','a2','a1'] a.sort(mysort) print a >>>> ['a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'a7', 'a8', 'a9', 'a10', 'a11'] a = ['b11','a10','b9','a8','b7','a6','b5','a4','b3','a2','b1'] a.sort(mysort) print a >>>>['a2', 'a4', 'a6', 'a8', 'a10', 'b1', 'b3', 'b5', 'b7', 'b9', 'b11'] Note that this sort will consider 'a07' == 'a7'. Not sure if that's a problem for you or not. HTH, Don From ATrautman@perryjudds.com Wed Feb 26 10:08:55 2003 From: ATrautman@perryjudds.com (Alan Trautman) Date: Wed Feb 26 10:08:55 2003 Subject: [Tutor] Python4Kids Message-ID: <0BA95581EDA7D611841B00A0C9AD25DD2B59F3@mail.pjinet.com> Gregor, Nice site, my German is horribly rusty to non-existent but it looks = like a really good project and I was really able to understand most of it. I personally think that Python with its many capabilities and strong = style would have benefited me more than Pascal and Basic which I started on. = I didn't really learn to program until my first job in COBOL. Sometimes I think it would be good to go back to punch cards as you then have to = spend more time thinking than compiling. I will continue to recommend Python = as my choice for teaching young people how to program because it uses very = few (IMO) symbols and has a strong object oriented base. Tkinter is more = than adequate for basic teen and pre-teen games and you don't have to worry = about the platform they are on much. Sorry if this is too off topic for this list but this is another area = where I think Python really can excel. Alan >I'd like to inform you, that my new book "Python f=FCr Kids" >is out now. Needless to say that, while writing the >book, communicating with the members of this list >for me was an indispensable support. Thank you all!!! >You may have a look at the accompanying website >http://python4kids.net >It's a German book for Teens. I announce it here, >on an English mailing-list, because I know that >there are German speaking readers participating. From Janssen@rz.uni-frankfurt.de Wed Feb 26 11:08:02 2003 From: Janssen@rz.uni-frankfurt.de (Michael Janssen) Date: Wed Feb 26 11:08:02 2003 Subject: [Tutor] join - was best way to tokenize [was script too slow] In-Reply-To: <20030225214931.C13858@localhost.localdomain> Message-ID: On Tue, 25 Feb 2003, Paul Tremblay wrote: > Answering my own email. I'm still not totatlly sure of the line in > question, but I do realize that the '.join' is really: create a string > called "' '", and then use the method '.join' on that string. "join" is here the string-method "join". It's aequivalent to the module's function string.join(): Every (?) function from module string was also made into a string-method since a recent version of Python (2.0?). But join should better not have made this evolution :-( Because: >>> string.join('qwert', ' ') 'q w e r t' is (might be ;-) what you expected: 'qwert' is the string to work about and ' ' is the string used to manipulate 'qwert'. The string-method toggles this: >>> 'qwert'.join(' ') # wrong in most cases ' ' >>> ' '.join('qwert') 'q w e r t' ---> instead of using a method as the method of the string you are working on you make an "auxiliary" string and give your "working-string" as a parameter. There might be good reasons for this, but that's not python-like syntax as readable as natural language. Once you know that ' '.join() behaves a little different it's realy fun to use it ;-) Michael > > Okay, now I do see the whole thing. The list to join is: first split the > token by "\\", which will get rid of the "\\", and then add the "\\" to > each item. > > That's kind of a nice one liner to make tokens. > > Thanks > > Paul > > On Tue, Feb 25, 2003 at 09:31:24PM -0500, Paul Tremblay wrote: > > > > Thanks. Your method is very instructive on how to use recursion. It is > > not quite perfect, since a line of tokens can look like: > > > > \par}}{\par{\ect => '\par}}' (should be '\par', '}', '}' > > > > However, it ends up that your method takes just a bit longer than using > > regular expressions, so there is probably no use in trying to perfect > > it. I did have one question about this line: > > > > > > > expandedWord = ' '.join(['\\'+item for item in > > > word.split('\\') if item]) > > > > I get this much from it: > > > > 1. first python splits the word by the "\\". > > > > 2. Then ??? It joins them somehow. I'm not sure what the .join is. > > > > Thanks > > > > Paul > > > > > > > > On Tue, Feb 25, 2003 at 03:43:25PM +1000, Alfred Milgrom wrote: > > > > > > At 07:04 PM 24/02/03 -0500, Paul Tremblay wrote: > > > >However, I don't know if there is a better way to split a line of RTF. > > > >Here is a line of RTF that exhibits each of the main type of tokens: > > > > [snip] > > > > > Hi Paul: > > > > > > I can't say whether regular expressions are the best way to tokenise your > > > RTF input, but here is an alternative recursive approach. > > > > > > Each line is split into words (using spaces as the separator), and then > > > recursively split into sub-tokens if appropriate. > > > > > > def splitWords(inputline): > > > outputList = [] > > > for word in inputline.split(' '): > > > if word.startswith('{') and word != '{': > > > expandedWord = '{' + ' ' + word[1:] > > > elif word.endswith('}')and word != '}' and word != '\\}': > > > expandedWord = word[:-1] + ' ' + '}' > > > elif '\\' in word and word != '\\': > > > expandedWord = ' '.join(['\\'+item for item in > > > word.split('\\') if item]) > > > else: > > > expandedWord = word > > > if expandedWord != word: > > > expandedWord = splitWords(expandedWord) > > > outputList.append(expandedWord) > > > return ' '.join(outputList) > > > > > > example1 = 'text \par \\ \{ \} {}' > > > > > > print splitWords(example1) > > > >>> text \par \ \{ \} { } > > > print splitWords(example1).split(' ') > > > >>> ['text', '\\par', '\\', '\\{', '\\}', '{', '}'] > > > > > > Seven different tokens seem to be identified correctly. > > > > > > example2 = 'text \par\pard \par} \\ \{ \} {differenttext}' > > > print splitWords(example2) > > > >>> text \par \ \{ \} { } > > > print splitWords(example2).split(' ') > > > >>> ['text', '\\par', '\\pard', '\\par', '}', '\\', '\\{', '\\}', '{', > > > 'differenttext', '}'] > > > > > > Haven't tested exhaustively, but this seems to do what you wanted it to do. > > > As I said, I don't know if this will end up being better than using re or > > > not, but it is an alternative approach. > > > > > > Best regards, > > > Fred > > > > > > > > > _______________________________________________ > > > Tutor maillist - Tutor@python.org > > > http://mail.python.org/mailman/listinfo/tutor > > > > -- > > > > ************************ > > *Paul Tremblay * > > *phthenry@earthlink.net* > > ************************ > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > -- > > ************************ > *Paul Tremblay * > *phthenry@earthlink.net* > ************************ > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From vicki@stanfield.net Wed Feb 26 13:28:02 2003 From: vicki@stanfield.net (vicki@stanfield.net) Date: Wed Feb 26 13:28:02 2003 Subject: [Tutor] Adding label to listbox Message-ID: <20030226102713.4168.h004.c000.wm@mail.stanfield.net.criticalpath.net> I have successfully created a listbox with a scrollbar, but now I want to add a label to precede it and explain what is being selected. Does this have to be a separate label or can it be packed into the Listbox somehow. IIRC in Motif, there was a label attribute which could be set for a Listbox. Basically, the gui has a text box with a label to the left in one frame and a listbox in a frame below it. The text box has a label and the listbox does not. I would like them both to have labels. I have searched around on google and other sites but have not found an example. Thanks, --vicki From vicki@stanfield.net Wed Feb 26 14:13:01 2003 From: vicki@stanfield.net (vicki@stanfield.net) Date: Wed Feb 26 14:13:01 2003 Subject: [Tutor] Adding label to listbox Message-ID: <20030226111041.24539.h017.c000.wm@mail.stanfield.net.criticalpath.net> Okay, I am becoming a little more self-sufficient. I found the attributes of the PmwListbox which contains the label that I was looking for. Thanks anyway. : ) --vicki > I have successfully created a listbox with a scrollbar, > but now I want to add a label to precede it and explain > what is being selected. Does this have to be a separate > label or can it be packed into the Listbox somehow. > IIRC in Motif, there was a label attribute which could > be set for a Listbox. Basically, the gui has a text box > with a label to the left in one frame and a listbox in > a frame below it. The text box has a label and the > listbox does not. I would like them both to have > labels. I have searched around on google and other > sites but have not found an example. > > Thanks, > --vicki > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From jeff@ccvcorp.com Wed Feb 26 14:33:01 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Wed Feb 26 14:33:01 2003 Subject: [Tutor] best way to tokenize [was script too slow] References: <20030224190412.F10476@localhost.localdomain> <5.1.0.14.0.20030225152446.023fb800@192.168.1.1> <20030225213123.B13858@localhost.localdomain> <20030225214931.C13858@localhost.localdomain> Message-ID: <3E5D1623.4090808@ccvcorp.com> Paul Tremblay wrote: >Okay, now I do see the whole thing. The list to join is: first split the >token by "\\", which will get rid of the "\\", and then add the "\\" to >each item. > > > >>> expandedWord = ' '.join(['\\'+item for item in >>>word.split('\\') if item]) >>> A good approach with this sort of thing is to try to spread it out into several lines. One-liners can be convenient, but sometimes they're a little confusing, especially if you're not terribly familiar with the way that things fit together. So let's break this down into several steps. WordList = word.split('\\') TokenList = ['\\' + item for item in WordList if item] ExpandedWord = ' '.join(TokenList) This code has the exact same effect as the one-liner, but is a little bit easier to figure out (even though it may take a bit longer to read). I find myself using intermediate variables like this semi-frequently -- if it takes me more than a couple seconds to figure out what a compound expression is doing, I figure that it's too complex and would be better to split it into several parts. The decision of how much complexity is appropriate is, of course, a very personal stylistic one. For instance, my second line above is actually doing two things -- filtering out any null items from WordList, and prepending '\\' to each remaining item. I could have split that out into two separate list comprehensions, and I could argue that it would make things a little more explicitly clear... but that would also require two iterations through the list, instead of one, so it has the potential of actually affecting performance -- and if it might be a long list, that could be a significant effect. I feel that the (marginal) extra clarity is not worth that possible performance loss. On the other hand, splitting the original one-liner into these three lines adds only a few variable lookups. That's a very small cost, so it's much easier to argue that the increased clarity is worth it. Personally, if I was writing code that I thought might be read by others (especially, say, example code for this list), which would probably include most code for programs that would be in use for any length of time, then I'd use the longer multi-line version. Only if I were writing a quick script, or in a throw-away interactive session, would I use the one-liner. Jeff Shannon Technician/Programmer Credit International From jeff@ccvcorp.com Wed Feb 26 16:20:04 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Wed Feb 26 16:20:04 2003 Subject: [Tutor] RE: Prime Numbers References: <200302251906.40859.ahimsa@onetel.net.uk> <001601c2dd79$316c5600$bf27e183@chief> Message-ID: <3E5D2F73.5030402@ccvcorp.com> Ike Hall wrote: >First, I decided that what I would do is define a function, >prime(x,y) that returned a tuple containing all primes between x and y. >code below: > A few (hopefully instructive) style comments on your code, here... :) >def prime(x,y): > #first, I want to be sure that I have numbers for x and y > > if type(x) != IntType or FloatType or LongType: > print 'I need numbers people!' > return None > elif type(y)!= IntType or FloatType or LongType: > print 'I need numbers people!' > return None > else: > pass > Typechecking like this really isn't good practice. What if someone else introduces a new numeric type? They might still reasonably want to pass that in, and it may well support all the operations you need, but your typechecking will exclude it needlessly. One of the Python maxims is "It's easier to ask forgiveness than permission" -- which usually translates to trying what you need to do, and catching any exceptions if it doesn't work. All we need to do is determine whether our input can handle division, really. So we can simply test it like this: try: temp = x / 2 temp = y / 2 except: print "Arguments must be numeric values!" return (Note that 'return None' does exactly the same thing as 'return' by itself.) This means we don't need to import types at all, and results in clearer and more generic code. (Any time I see 'elif' I start wondering if there might not be a better way to organize things...) > #next, we want to find out which is smaller, and make #sure that is 'x' > if x>y: > dummy = x > x=y > y=dummy > Python can actually do this without using a dummy intermediate variable: if x > y: x, y = y, x > #now we also want to make sure that there is at least one > #integer between x and y (floats cannot be primes, but > # primes can lie between 2 floats if there is an integer > #between them > Is it really necessary to special-case this? Two floats that are that close together have no primes between them, true, but is that significantly different from having inputs of, say, 7.9 and 10.1 where there are no primes between them? I'd say skip this check, and simply return an empty list in this case (as with any other case where no primes are found). > #now we have done all the checks we need, so we now turn our numbers into >integers if they are not already > #we add one to int(x) or long(x) to get the next integer, since we want >primes between x and y > if type(x)==FloatType: > try: > x=int(x)+1 > except(OverflowError): > x=long(x)+1 > > if type(y)==FloatType: > try: > y=int(y) > except(OverflowError): > y=long(y) > Of course, your previous code already tried to do int(x) without catching any exceptions, so if you were going to get an OverflowError you'd already have done so. ;) (Note, though, that my suggested code doesn't care so far whether something is an int or a long, and wouldn't have this problem.) But really, is there a significant advantage to using ints instead of longs? Why not just automatically use longs for everything? Once again, this gets you away from specific typechecking. Or, since fractions are really all we have to worry about (whether they're floats or third-party arbitrary-precision decimals or third-party rational numbers or...) if x != long(x): x = long(x) + 1 if y != long(y): y = long(y) + 1 This takes advantage of the fact that Python is smart about comparing different numeric types, and keeps everything generic. You're passing up a bit of efficiency in the case of x and y being fractions within the range of MAXINT, since longs are slower than ints, but this seems like a rare enough case to not worry overmuch about. (Premature optimization is the root of all evil!) > primes=[] > if 1 in range(x,y):primes.append(1) > if 2 in range(x,y):primes.append(2) > Instead of generating two lists, and checking for membership in them, why not do straight numeric comparisons? if x <= 1 <= y: primes.append(1) if y <= 2 <= y: primes.append (2) > if y<=3: > if y==3:primes.append(3) > return primes > if x<3:start=3 > elif x%2: start=x > else:start=x+1 > for i in range(start,y,2): > high=int(math.sqrt(i)) #we only check between 2 and sqrt(i) > primeflag=1 > for j in range(2, high): > if not i%j: > primeflag=0 > else: > pass > if primeflag: > primes.append(i) > Boy, that's complicated, and it's going to be doing a lot of extra work, with the inner loop testing numbers that we already know aren't prime. I'd do this a bit differently. I'd generate all prime numbers between 1 and y (because you can use the earlier primes to simplify searches for later primes -- remember that once you check if all prime numbers are factors, you've checked non-prime numbers by implication, as a non-prime factor must have smaller prime factors) and then throw away all the numbers below x. This method also means that we don't need to specifically check that 1 and 2 are greater than x, as well. In fact, if we also throw away any primes that are greater than y, we can just start with 1 and 2. So let's completely rewrite this segment of the function. primes = [1, 2] for candidate in range(3, y, 2): limit = sqrt(candidate) for factor in primes: if factor > limit: # then number is prime primes.append(candidate) break elif candidate % factor == 0: # then it's *not* prime break primes = [item for item in primes if x <= item < y] return tuple(primes) Note that, in both the range() statement and the list comp that makes the final trim, if y is a prime number it will *not* be in the returned tuple. This is intentional, to match with the behavior of range() itself, and with slices, etc. Python is pretty consistent about using half-open intervals (where the lower bound is included but the upper bound is excluded), so I'm remaining consistent with the Python standard to maintain the principle of least surprise. Jeff Shannon Technician/Programmer Credit International From jeff@ccvcorp.com Wed Feb 26 16:42:03 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Wed Feb 26 16:42:03 2003 Subject: [Tutor] join - was best way to tokenize [was script too slow] References: Message-ID: <3E5D3488.8030109@ccvcorp.com> Michael Janssen wrote: >---> instead of using a method as the method of the string you are working >on you make an "auxiliary" string and give your "working-string" as a >parameter. There might be good reasons for this, but that's not >python-like syntax as readable as natural language. > Except that most often when using join(), you're not using a string as the "other" argument -- any sequence can be used and it's *much* more common to use a list. This "working string" you talk about usually doesn't exist, as such. At the time that string methods were being introduced, there was a camp who argued that (sequence).join(string) was a more "intuitive" way to spell this, but the problem is that then you need to have a join() method on *every* possible type of sequence... which may well include user-defined types, where it's impossible to enforce a join() method. It was decided that having the current spelling was much more sensible, since it's easy for a string to join *any* sort of sequence, and nothing depends on the type of sequence being used. If you read it as "use this string to join together the elements of this sequence", it's not at all bad readability-wise, either. Jeff Shannon Technician/Programmer Credit International From Predrag Ivanovic Wed Feb 26 16:49:02 2003 From: Predrag Ivanovic (Predrag Ivanovic) Date: Wed Feb 26 16:49:02 2003 Subject: Fwd: Re[4]: [Tutor] My first (er...working...) script ever In-Reply-To: <2424372215.20030223222351@ptt.yu> References: <6610188680.20030222001709@ptt.yu> <9943097811.20030223035705@ptt.yu> <200302222132.45647.revanna@mn.rr.com> <200302222136.19045.revanna@mn.rr.com> <2424372215.20030223222351@ptt.yu> Message-ID: <16511305206.20030226225129@ptt.yu> This is a forwarded message From: Predrag Ivanovic To: Anna Ravenscroft Date: Sunday, February 23, 2003, 10:23:51 PM Subject: [Tutor] My first (er...working...) script ever ===8<==============Original message text=============== Anna Ravenscroft wrote: AR> Oops! Make that: >> r = raw_input("r:") >> try: >> newr = int(r) >> print "whatever ",krug(newr)" >> except: >> print "That is not a number. " AR> Just my $.03 worth... AR> Anna Thanks,Anna. Pedja. --- "Just below my skin,I'm screaming..." Salva Mea,Faithless ===8<===========End of original message text=========== -- Best regards, Predrag mailto:predivan@ptt.yu From Janssen@rz.uni-frankfurt.de Wed Feb 26 17:25:16 2003 From: Janssen@rz.uni-frankfurt.de (Michael Janssen) Date: Wed Feb 26 17:25:16 2003 Subject: [Tutor] join - was best way to tokenize [was script too slow] In-Reply-To: <3E5D3488.8030109@ccvcorp.com> Message-ID: On Wed, 26 Feb 2003, Jeff Shannon wrote: > ' '.join(seq) > ... read it as "use this string to join together the > elements of this sequence" ... Hey, that helps me. Until now, i have read it as "this works the other way round as you believe and has to look odd to work proper" ;-) Thanks for your explanation of the reasons for the implementation. Michael From ahimsa@onetel.net.uk Wed Feb 26 17:45:05 2003 From: ahimsa@onetel.net.uk (ahimsa) Date: Wed Feb 26 17:45:05 2003 Subject: [Tutor] RE: Prime Numbers In-Reply-To: <001601c2dd79$316c5600$bf27e183@chief> References: <200302251906.40859.ahimsa@onetel.net.uk> <001601c2dd79$316c5600$bf27e183@chief> Message-ID: <200302262201.25720.ahimsa@onetel.net.uk> Hello Ike Thank you for the more detailed explanation - I could follow the majority= of=20 the code (I enjoyed the user interactions!!) although what is the=20 'OverFlowError' parameter of the exception? Does that refer to unwieldy f= loat=20 to integer conversions? Is that a module or a builtin? Sorry, but am show= ing=20 my crass ignorance here. I appreciate the algorithm about differentiating= =20 between the evens and odds that 2 is the only prime that is even. That's = a=20 neat way of figuring out the initial stages of the problem. Not coming fr= om a=20 math background, this wouldn't have occurred to me to do. Good tip. I was able to mostly follow what you did but must confess to finding it a= bit=20 hard going about the middle of the "if y <=3D 3:" suite not being sure wh= ere=20 the "primeflag" and "high" variables fit in, and what purpose they serve.= My=20 confusion may have also been compounded by the way that your code structu= re=20 was messed up by the email client. Nevertheless, if you wouldn't mind, co= uld=20 you kindly go over that step a little slower. Thank you Ike - this list is a great source of learning!!! All the best Andrew > for i in range(start,y,2): > high=3Dint(math.sqrt(i)) #we only check between 2 and sqrt(i) > primeflag=3D1 > for j in range(2, high): > if not i%j: > primeflag=3D0 > else: > pass > if primeflag: > primes.append(i) > > return tuple(primes) From ahimsa@onetel.net.uk Wed Feb 26 17:45:19 2003 From: ahimsa@onetel.net.uk (ahimsa) Date: Wed Feb 26 17:45:19 2003 Subject: [Tutor] RE: Prime Numbers In-Reply-To: <5.2.0.9.0.20030226053213.01a03aa8@66.28.54.253> References: <200302251906.40859.ahimsa@onetel.net.uk> <5.2.0.9.0.20030226053213.01a03aa8@66.28.54.253> Message-ID: <200302262203.48536.ahimsa@onetel.net.uk> Hello Bob What does the "s" reference in the piece "sx =3D x **.5" mean and why ".5= "?=20 Sorry if this is elementary. Andrew From ramrom@earthling.net Wed Feb 26 18:29:02 2003 From: ramrom@earthling.net (Bob Gailer) Date: Wed Feb 26 18:29:02 2003 Subject: [Tutor] RE: Prime Numbers In-Reply-To: <200302262203.48536.ahimsa@onetel.net.uk> References: <5.2.0.9.0.20030226053213.01a03aa8@66.28.54.253> <200302251906.40859.ahimsa@onetel.net.uk> <5.2.0.9.0.20030226053213.01a03aa8@66.28.54.253> Message-ID: <5.2.0.9.0.20030226162703.030aedc0@66.28.54.253> --=======5DF96F6D======= Content-Type: text/plain; x-avg-checked=avg-ok-4A6E6042; charset=us-ascii; format=flowed Content-Transfer-Encoding: 8bit At 10:03 PM 2/26/2003 +0000, ahimsa wrote: >What does the "s" reference in the piece "sx = x **.5" mean and why ".5"? sx is my arbitrary choice of a variable to assign the result to. Mathematical identity: the nth root of a number is the same as raising the number to the reciprocal of n. Bob Gailer mailto:ramrom@earthling.net 303 442 2625 --=======5DF96F6D======= Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-4A6E6042 Content-Disposition: inline --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.454 / Virus Database: 253 - Release Date: 2/10/2003 --=======5DF96F6D=======-- From micforster@yahoo.com Wed Feb 26 18:30:04 2003 From: micforster@yahoo.com (Mic Forster) Date: Wed Feb 26 18:30:04 2003 Subject: [Tutor] Practice Sets for newbie In-Reply-To: Message-ID: <20030226232946.59084.qmail@web13402.mail.yahoo.com> Hi Sean, I tried that website to no avail. Is the address correct? Cheers, Mic --- Steegness wrote: > > From: riex@ligbr.com.br > > To: Tutor@python.org > > Date: Tue, 25 Feb 2003 15:25:16 GMT > > Subject: [Tutor] Practice sets for newbies > > > > > > Hello, tutor, > > I wonder if there are any practice tutorial sets > for things like > > loops,lists, the use of modules, and etc. > > > > I'm new to python, and programing in general. So > far I have used Josh > > Cogliati's "non-prog. tutorial for python", and > also Guido Van Rossun's > nice > > "python tutorial" to get me started. > > > > However, I think that having some basic practice > problems could take me a > > step further. > > Does anyone have a tip for me on how to improve my > python skils ? > > > > All the best to all, Diego. > > riex@ligbr.com.br > > For me, UselessPython has been indispensible. > There's a lot of code there > to look at, a lot of little tasks that you can try > to mimic, and a page full > of interesting challenges to test your mettle. I > know it looks defunct, but > it really isn't. Honest. :) > > Head on over to www.uselesspython.com for the goods. > > Sean Steeg > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor __________________________________________________ Do you Yahoo!? Yahoo! Tax Center - forms, calculators, tips, more http://taxes.yahoo.com/ From rob@uselesspython.com Wed Feb 26 18:40:33 2003 From: rob@uselesspython.com (Rob Andrews) Date: Wed Feb 26 18:40:33 2003 Subject: [Tutor] Practice Sets for newbie In-Reply-To: <20030226232946.59084.qmail@web13402.mail.yahoo.com> Message-ID: The site has moved from one server to another this week, and so you might have caught it in a vulnerable moment. For instance, where you're at uselesspython.com may be pointing to the old server for a day or two. Please pardon any inconvenience, and if you keep having problems with it after another day or two, please email website@uselesspython.com with a problem report. We're cute, and we're cuddly, and we're eager to please. -Rob Andrews uselesspython.com staffer > Hi Sean, > > I tried that website to no avail. Is the address > correct? > > Cheers, > Mic > > > For me, UselessPython has been indispensible. > > There's a lot of code there > > to look at, a lot of little tasks that you can try > > to mimic, and a page full > > of interesting challenges to test your mettle. I > > know it looks defunct, but > > it really isn't. Honest. :) > > > > Head on over to www.uselesspython.com for the goods. > > > > Sean Steeg From micforster@yahoo.com Wed Feb 26 21:00:02 2003 From: micforster@yahoo.com (Mic Forster) Date: Wed Feb 26 21:00:02 2003 Subject: [Tutor] script comparing two values - ASCII encoding error In-Reply-To: <5.1.0.14.0.20030225094241.04396d58@www.thinkware.se> Message-ID: <20030227015603.48983.qmail@web13403.mail.yahoo.com> Hi Guys, I repeated the code you recommended and had no problem. All of the sudden this started happening: >>> def f(k, s): return k / (1-k) * (1-k)**s / (1-(1-k)**s) >>> j = 1. / 862 >>> s = 11 >>> def bisect(min, max, delta, function): fMax = function(max) fMin = function(min) assert fMax * fMin < 0 while max - min > delta: newX = 0.5 * (min + max) fNew = function(newX) if fNew * fMax > 0: # fNew has same sign as fMax, so newX should max, fMax = newX, fNew else: min, fMin = newX, fNew return newX, fNew >>> def fun(x): return f(x, s) – j UnicodeError: ASCII encoding error: ordinal not in range(128) Help??? __________________________________________________ Do you Yahoo!? Yahoo! Tax Center - forms, calculators, tips, more http://taxes.yahoo.com/ From jeff@ccvcorp.com Wed Feb 26 21:36:00 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Wed Feb 26 21:36:00 2003 Subject: [Tutor] script comparing two values - ASCII encoding error References: <20030227015603.48983.qmail@web13403.mail.yahoo.com> Message-ID: <3E5D7999.3090002@ccvcorp.com> Mic Forster wrote: >I repeated the code you recommended and had no >problem. All of the sudden this started happening: > I don't see offhand anything that should be causing a UnicodeError. Can you give us the complete traceback that you're getting? Those few lines that precede the "UnicodeError: ..." bit can tell us a lot about where your problem is... However, I'd like to point out one thing... >>>>def f(k, s): >>>> >>>> > return k / (1-k) * (1-k)**s / (1-(1-k)**s) > You should probably add some parens to this -- as it is, it could be read two different ways (depending on which has higher priority, multiplication or division -- I can't remember offhand which is higher priority, which says to me that relying on priority is a bad idea). Those two ways are: ( k / (1-k) ) * ( (1-k)**s / (1-(1-k)**s) ) or k / ( (1-k) * (1-k)**s) / (1-(1-k)**s) I think the first is what you meant, but since I'm not certain which way Python will read it, I'd recommend being explicit about it. For that matter, your last subexpression, 1-(1-k)**s, is slightly vague too -- should that be (1-(1-k))**s, or 1-((1-k)**s)?? I'm pretty sure that Python will presume the latter, and I believe that that's what you want, but it never hurts to add parens to make it explicit. I'm a big fan of using lots of parens in complicated mathematical expressions -- extra parens don't hurt, and may make the intended order more clear. I'm also a big fan of using intermediate variables to split complicated expressions into two or more lines, and I'd probably write the above function like this: def f(k, s): subterm = (1-k)**s return ( k / (1-k) ) * (subterm / (1-subterm) ) This makes the function a little easier to read, and also emphasises the symmetry involved (and, as a side bonus, saves you time by calculating the exponent only once). Of course, this is really just a matter of taste... Jeff Shannon Technician/Programmer Credit International From micforster@yahoo.com Wed Feb 26 21:49:02 2003 From: micforster@yahoo.com (Mic Forster) Date: Wed Feb 26 21:49:02 2003 Subject: [Tutor] script comparing two values - ASCII encoding error In-Reply-To: <3E5D7999.3090002@ccvcorp.com> Message-ID: <20030227024759.28482.qmail@web13408.mail.yahoo.com> Hi Jeff, What I sent you originally was all Python gave to me. There was no traceback given. I also tried all your suggestions below, including your personalised function, but still to no avail. Confused, Mic --- Jeff Shannon wrote: > Mic Forster wrote: > > >I repeated the code you recommended and had no > >problem. All of the sudden this started happening: > > > > I don't see offhand anything that should be causing > a UnicodeError. Can > you give us the complete traceback that you're > getting? Those few lines > that precede the "UnicodeError: ..." bit can tell us > a lot about where > your problem is... > > However, I'd like to point out one thing... > > >>>>def f(k, s): > >>>> > >>>> > > return k / (1-k) * (1-k)**s / (1-(1-k)**s) > > > > You should probably add some parens to this -- as it > is, it could be > read two different ways (depending on which has > higher priority, > multiplication or division -- I can't remember > offhand which is higher > priority, which says to me that relying on priority > is a bad idea). > Those two ways are: > > ( k / (1-k) ) * ( (1-k)**s / (1-(1-k)**s) ) > or > k / ( (1-k) * (1-k)**s) / (1-(1-k)**s) > > I think the first is what you meant, but since I'm > not certain which way > Python will read it, I'd recommend being explicit > about it. > > For that matter, your last subexpression, > 1-(1-k)**s, is slightly vague > too -- should that be (1-(1-k))**s, or > 1-((1-k)**s)?? I'm pretty sure > that Python will presume the latter, and I believe > that that's what you > want, but it never hurts to add parens to make it > explicit. I'm a big > fan of using lots of parens in complicated > mathematical expressions -- > extra parens don't hurt, and may make the intended > order more clear. > > I'm also a big fan of using intermediate variables > to split complicated > expressions into two or more lines, and I'd probably > write the above > function like this: > > def f(k, s): > subterm = (1-k)**s > return ( k / (1-k) ) * (subterm / (1-subterm) ) > > This makes the function a little easier to read, and > also emphasises the > symmetry involved (and, as a side bonus, saves you > time by calculating > the exponent only once). Of course, this is really > just a matter of > taste... > > Jeff Shannon > Technician/Programmer > Credit International > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor __________________________________________________ Do you Yahoo!? Yahoo! Tax Center - forms, calculators, tips, more http://taxes.yahoo.com/ From jeff@ccvcorp.com Wed Feb 26 22:03:02 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Wed Feb 26 22:03:02 2003 Subject: [Tutor] script comparing two values - ASCII encoding error References: <20030227024759.28482.qmail@web13408.mail.yahoo.com> Message-ID: <3E5D7FEC.9060101@ccvcorp.com> Mic Forster wrote: >Hi Jeff, > >What I sent you originally was all Python gave to me. >There was no traceback given. I also tried all your >suggestions below, including your personalised >function, but still to no avail. > > So, you're saying that when you typed >>> def fun(x): ... return f(x, s)  j You got an immediate response of UnicodeError: ASCII encoding error: ordinal not in range(128) with no other information? Odd... I wonder if you might be getting that error due to using non-ASCII characters as part of your code? It doesn't *look* as though there's any non-ASCII characters there, though... Any chance that your default site encoding changed or something odd like that? I'm afraid that I don't know enough about Unicode and such to be able to help much beyond that. One of the hazards of being American, I guess -- not enough pressure to learn how to deal with non-ASCII characters. I know I *should* figure this stuff out, but there's always something else that seems more immediately relevant... Jeff Shannon Technician/Programmer Credit International From micforster@yahoo.com Wed Feb 26 23:21:02 2003 From: micforster@yahoo.com (Mic Forster) Date: Wed Feb 26 23:21:02 2003 Subject: [Tutor] script comparing two values - ASCII encoding error In-Reply-To: <3E5D7FEC.9060101@ccvcorp.com> Message-ID: <20030227032040.51486.qmail@web13405.mail.yahoo.com> Jeff, I've seem to have solved the problem: code with problem: >>> def f(k, s): return k / (1-k) * (1-k)**s / (1-(1-k)**s) >>> j = 1. / 1600 >>> s = 15 >>> def bisect(min, max, delta, function): fMax = function(max) fMin = function(min) assert fMax * fMin < 0 while max - min > delta: newX = 0.5 * (min + max) fNew = function(newX) if fNew * fMax > 0: max, fMax = newX, fNew else: min, fMin = newX, fNew return newX, fNew >>> def fun(x): return f(x, s) – j UnicodeError: ASCII encoding error: ordinal not in range(128) code without problem: >>> def f(k, s): return k / (1-k) * (1-k)**s / (1-(1-k)**s) >>> j = 1. / 1600 >>> s = 15 >>> def bisect(min, max, delta, function): fMax = function(max) fMin = function(min) assert fMax * fMin < 0 while max - min > delta: newX = 0.5 * (min + max) fNew = function(newX) if fNew * fMax > 0: max, fMax = newX, fNew else: min, fMin = newX, fNew return newX, fNew >>> def fun(x): return f(x, s) - j >>> For some reason the identation in that last line got mucked up. Thanks for your help, Mic __________________________________________________ Do you Yahoo!? Yahoo! Tax Center - forms, calculators, tips, more http://taxes.yahoo.com/ From fredm@smartypantsco.com Wed Feb 26 23:43:02 2003 From: fredm@smartypantsco.com (Alfred Milgrom) Date: Wed Feb 26 23:43:02 2003 Subject: [Tutor] script comparing two values - ASCII encoding error In-Reply-To: <20030227024759.28482.qmail@web13408.mail.yahoo.com> References: <3E5D7999.3090002@ccvcorp.com> Message-ID: <5.1.0.14.0.20030227143216.0235a610@192.168.1.1> Hi Mic: I tried the code that you submitted, and when I typed it in it worked fine= :) However when I copied what you emailed, I got the same error as you did :( I identified the problem as being in your string 'f(x, s) =AD j' Specifically, although the minus sign in that expression looks like a minus= =20 sign it is not a minus sign. It is not the same character as you used in=20 the line 'while max - min > delta'. (Perhaps you have two minus sign keys=20 on your keyboard or you pressed another key at the same time ? In any case= =20 I cannot duplicate the wrong minus sign.) You can check this out by copying out the function definition, and then=20 replacing the bad minus sign with the good minus sign from bisect, and you= =20 will see everything works fine. Fred At 06:47 PM 26/02/03 -0800, Mic Forster wrote: >Hi Jeff, > >What I sent you originally was all Python gave to me. >There was no traceback given. I also tried all your >suggestions below, including your personalised >function, but still to no avail. > >Confused, Mic > > >--- Jeff Shannon wrote: > > Mic Forster wrote: > > > > >I repeated the code you recommended and had no > > >problem. All of the sudden this started happening: > > > > > > > I don't see offhand anything that should be causing > > a UnicodeError. From antonmuhin at rambler.ru" References: <00a501c2dd95$7045bf80$1ad1b241@defaultcomp> Message-ID: <1964940964.20030227115540@rambler.ru> Hello Don, Wednesday, February 26, 2003, 3:48:18 PM, you wrote: DA> ----- Original Message ----- DA> From: "siddharth karandikar" DA> To: DA> Sent: Wednesday, February 26, 2003 6:09 AM DA> Subject: [Tutor] sorting the list >> >> >> i have list like this >> >>>a = ['a1', 'a2', 'a3', 'a4', 'a10', 'a11', 'a12'] >> >>>a >> ['a1', 'a2', 'a3', 'a4', 'a10', 'a11', 'a12'] >> >> when i call >> >>>a.sort() >> >> list becomes >> >>>a >> ['a1', 'a10', 'a11', 'a12', 'a2', 'a3', 'a4'] >> **# here a10 is getting ahead of a2 a3 etc >> >>> >> >> but i need the list to be sorted like >> >> a1 a2 a3 a4 ... a10 a11 etc. >> >> >> any possible solution ??? >> DA> This is a little simplistic, but I think this works. It requires that each DA> string has 1 or more numeric characters after the first one. DA> def mysort(lhs, rhs): DA> if rhs[0] <> lhs[0]: DA> return cmp(lhs[0],rhs[0]) DA> else: DA> return cmp(int(lhs[1:]),int(rhs[1:])) DA> a = ['a11','a10','a9','a8','a7','a6','a5','a4','a3','a2','a1'] DA> a.sort(mysort) DA> print a >>>>> ['a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'a7', 'a8', 'a9', 'a10', 'a11'] DA> a = ['b11','a10','b9','a8','b7','a6','b5','a4','b3','a2','b1'] DA> a.sort(mysort) DA> print a >>>>>['a2', 'a4', 'a6', 'a8', 'a10', 'b1', 'b3', 'b5', 'b7', 'b9', 'b11'] DA> Note that this sort will consider 'a07' == 'a7'. Not sure if that's a DA> problem for you or not. DA> HTH, DA> Don Another solution that can be a little bit quicker for big lists: >>> a = ['a1', 'a2', 'a3', 'a4', 'a10', 'a11', 'a12'] >>> s = [(e[0], int(e[1:])) for e in a] >>> print s [('a', 1), ('a', 2), ('a', 3), ('a', 4), ('a', 10), ('a', 11), ('a', 12)] >>> s.sort() >>> print s [('a', 1), ('a', 2), ('a', 3), ('a', 4), ('a', 10), ('a', 11), ('a', 12)] >>> new_a = ["%s%s" % e for e in s] >>> print new_a ['a1', 'a2', 'a3', 'a4', 'a10', 'a11', 'a12'] >>> Actually, you may consider another presentation for your data too. -- Best regards, anton mailto:antonmuhin@rambler.ru From alan.gauld@bt.com Thu Feb 27 06:44:01 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Thu Feb 27 06:44:01 2003 Subject: [Tutor] Adding label to listbox Message-ID: <7497DCA1C240C042B28F6657ADFD8E0974DADE@i2km11-ukbr.domain1.systemhost.net> I have successfully created a listbox with a scrollbar, but now I want to add a label to precede it and explain what is being selected. Does this have to be a separate label or can it be packed into the Listbox somehow. I'd probably put the label and listbox/scrollbar into a frame each then pack both of those into a single frame. I might even bundle all of that together as a LabelledListBox class... In fact I'd probably create a ListBox module with two classes - one unlabelled listbox with Scrollbar - ScrollingList - one labelled scrolling list - LabelScrollingList And maybe even a third: - one labelled list box without scrolling - LabelledList That gives me nice reuse options for the future. Alan g. From Don Arnold" <00a501c2dd95$7045bf80$1ad1b241@defaultcomp> <1964940964.20030227115540@rambler.ru> Message-ID: <032201c2de5e$0c7d8540$1ad1b241@defaultcomp> ----- Original Message ----- From: "antonmuhin at rambler.ru" To: "Don Arnold" ; Sent: Thursday, February 27, 2003 2:55 AM Subject: Re[2]: [Tutor] sorting the list > Hello Don, Hi! > > Another solution that can be a little bit quicker for big lists: > I'm not used to using the decorate/sort/undecorate pattern, so I thought I'd see what I had been missing: import time def mysort(lhs, rhs): if rhs[0] <> lhs[0]: return cmp(lhs[0],rhs[0]) else: return cmp(int(lhs[1:]),int(rhs[1:])) a = [ 'a' + str(i) for i in xrange (100000,-1,-1)] starttime = time.clock() a.sort(mysort) endtime = time.clock() print 'mysort() - %06f elapsed' % (endtime - starttime) a = [ 'a' + str(i) for i in xrange (100000,-1,-1)] starttime = time.clock() s = [(e[0], int(e[1:])) for e in a] s.sort() a = ["%s%s" % e for e in s] endtime = time.clock() print 'DSU - %06f elapsed' % (endtime - starttime) [---output---] >>>> mysort() - 1.982278 elapsed >>>> DSU - 3.472156 elapsed It looks like using DSU is actually slower than providing your own sort method. This agrees with my intuition that the overhead of creating the decorated list then undecorating it can be sizable, but we all know intuition can often be wrong. ; ) Is this really the case, or is there a problem with my implementation? > > Actually, you may consider another presentation for your data too. > Well, it was the OP's data. I was just working with what I was given. > -- > Best regards, > anton mailto:antonmuhin@rambler.ru > Thanks, Don From phthenry@earthlink.net Thu Feb 27 11:06:04 2003 From: phthenry@earthlink.net (Paul Tremblay) Date: Thu Feb 27 11:06:04 2003 Subject: [Tutor] script still too slow Message-ID: <20030227105905.D13858@localhost.localdomain> After re-writing parts of my script for 8 hours yesterday, it is still almost 3 times slower than its perl counterpart. The script reads in an RTF file and then breaks it into tokens. It then makes several passes through the file, reading each token and performing the appropriate action. I have profiled the script using Python's profile utility. There is no one function that slows down the script. Rather, each function seems to take as much time. Here is an example: def evaluate_token(self,token): """Evaluate tokens. Return a value if the token is not a control word. Otherwise, pass token onto another method for further evaluation.""" if token == '{': self.__bracket_count = self.__bracket_count + 1 num = '%04d' % self.__bracket_count token = 'ob I think I am missing some very basic knowledge with regard to my Python/Tkinter programming which is preventing me from understanding the examples that I find. First the __init__ part, when do I need one? I notice that most of the modules that I include contain one. Also the example that I am trying to use to make my callback (for a Pmw.Entrybox) includes one. Can someone point me to some clear definition of what it is and when I need it. I apologize for being dense, but I can't seem to get past this. Thanks, --vicki From alan.gauld@bt.com Thu Feb 27 13:32:49 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Thu Feb 27 13:32:49 2003 Subject: [Tutor] script comparing two values - ASCII encoding error Message-ID: <7497DCA1C240C042B28F6657ADFD8E0974DAE0@i2km11-ukbr.domain1.systemhost.net> > What I sent you originally was all Python gave to me. > There was no traceback given. I also tried all your > suggestions below, including your personalised > function, but still to no avail. In that case can you put all the code in a separate file rather than type it at the interpreter - it'll save you work too! Call it formula.py or something... Then import the file and send us the file and all of the output. That should generate more error output... >>> import formula.py Finally, to get unicode errors should require a string. Can you search for quorte characters - ' or " in your code. An unmatched quote might be doing something odd. Just a thought, Alan g. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld/ From alan.gauld@bt.com Thu Feb 27 13:48:01 2003 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Thu Feb 27 13:48:01 2003 Subject: [Tutor] script still too slow Message-ID: <7497DCA1C240C042B28F6657ADFD8E0974DAE1@i2km11-ukbr.domain1.systemhost.net> > def evaluate_token(self,token): > if token == '{': > self.__bracket_count = self.__bracket_count + 1 > num = '%04d' % self.__bracket_count This line can come out coz its just creating a temporary string which is promptly thrown away! > token = 'ob elif token == '}': > num = '%04d' % self.__bracket_count Same here! > token = 'cb self.__bracket_count = self.__bracket_count - 1 > elif token == r'\{': > token = 'tx elif token == r'\}': > token = 'tx elif token == r'\\': # double or escaped \ > token = 'tx elif token[0:1] != '\\': # single \ You could just use token[0] here which will be marginally faster... > token = 'tx else: > token = self.evaluate_cw(token) Can we see this function too? Since its time will be included with the outer function we need to see it. Also do we know how often this default function gets called? - Your profile output should say. Overall I would expect Python to be slightly slower at this kind of task, but only by 20-50% not 300%! Alan g. From antonmuhin at rambler.ru" References: <20030227105905.D13858@localhost.localdomain> Message-ID: <328326651.20030227214731@rambler.ru> Hello, Paul! This version is approximately 30% faster than yours (token = changed to return, otherwise it doesn't seem to make sense). Cannot suggest anything better :( def evaluate_token1(s,t): """Evaluate ts. Return a value if the t is not a control word. Otherwise, pass t onto another method for further evaluation.""" if t == '{': s.bracket_count = s.bracket_count + 1 return 'ob Message-ID: <3E5E6985.30700@ccvcorp.com> Paul Tremblay wrote: >After re-writing parts of my script for 8 hours yesterday, it is still >almost 3 times slower than its perl counterpart. >[...] > def evaluate_token(self,token): > """Evaluate tokens. Return a value if the token is not a > control word. Otherwise, pass token onto another method > for further evaluation.""" > if token == '{': > self.__bracket_count = self.__bracket_count + 1 > num = '%04d' % self.__bracket_count > token = 'ob elif token == '}': > num = '%04d' % self.__bracket_count > token = 'cb self.__bracket_count = self.__bracket_count - 1 > elif token == r'\{': > token = 'tx elif token == r'\}': > token = 'tx elif token == r'\\': # double or escaped \ > token = 'tx elif token[0:1] != '\\': # single \ > token = 'tx else: > token = self.evaluate_cw(token) > > return token > >This function takes around 17 seconds to run. The tokens have to be >further evaluated in many cases with two other functions. Each of these >functions takes 17 seconds as well. > This function, to my mind, screams out to be made into a dictionary lookup. (Any time I'm dealing with a situation of "pick one option from this list of possibilities", or what in C/C++ would be a switch/case, I immediately think dictionary.) If you put each of the given options into a small one- to three-line function and put all of those functions into a dictionary, you can then change this function into something like the following: def evaluate_token(self, token): function = self.token_dict.get(token, self.evaluate_cw) return function(self, token) # passing in self so that we can access self.__bracket_count Or, almost equivalently but sparing the helper functions from needing to know so much about the bracket count: def evaluate_token(self, token): function = self.token_dict.get(token, self.evaluate_cw) token, self.__bracket_count = function(token, self.__bracket_count) return token This will have the advantage of saving you quite a few comparisons -- just how much savings it gives will depend on the proportion of tokens that make it to the 'else' clause above, but since I'd imagine that this will be the majority of them, you're trading trading seven comparisons for a dict lookup and (in some small proportion of cases) an extra function call. Since I presume that you're calling this function (at least) once for every token in the file, those savings will add up. I also suspect that using the "formatstring % vars()" trick that you use is slower than simply making use of the actual variables in question. Try swapping, say, "token = 'txI am beginning to think that python is just much slower than perl, and >shouldn't be used for this task? > Not at all. You just aren't used to thinking about how to write efficient Python. For most tasks, pythonic Python code will be fairly equivalent in speed to perlish Perl code. I suspect that if I were to start learning Perl and tried to convert a sizeable Python program to Perl, my port would be slower than the original, too, but that's just because I'm unfamiliar with good Perl practices, not because Perl is slower. With practice, your Python will become more efficient and you'll be able to find lots of ways to optimize your code. >Sorry I am vague on asking specifics, but I can't really pin point the >exact problem with speed, and obviously I can't dump hundreds of lines >on the mailing list. > One thing that others have done in the past, is to post their code on the web and give a link to it in the mailing list. That way people who are interested in helping out can investigate and make suggestings. Jeff Shannon Technician/Programmer Credit International From nicholas_wieland@yahoo.it Thu Feb 27 15:00:02 2003 From: nicholas_wieland@yahoo.it (Nicholas Wieland) Date: Thu Feb 27 15:00:02 2003 Subject: [Tutor] __init__ In-Reply-To: <20030227081907.1452.h010.c000.wm@mail.stanfield.net.criticalpath.net>; from vicki@stanfield.net on gio, feb 27, 2003 at 17:19:07 +0100 References: <20030227081907.1452.h010.c000.wm@mail.stanfield.net.criticalpath.net> Message-ID: <20030227200356.GA2115@localhost> On 2003.02.27 17:19 vicki@stanfield.net wrote: > I think I am missing some very basic knowledge with > regard to my Python/Tkinter programming which is > preventing me from understanding the examples that I > find. First the __init__ part, when do I need one? I > notice that most of the modules that I include contain > one. Also the example that I am trying to use to make > my callback (for a Pmw.Entrybox) includes one. Can > someone point me to some clear definition of what it is > and when I need it. I apologize for being dense, but I > can't seem to get past this. The __init__ method is the constructor of your class, i.e. when you make an instance of a class __init__ runs automatically: class Foo: def __init__(self): print "Bar" >>> foo = Foo() Bar >>> Hope it helps Nicholas From ATrautman@perryjudds.com Thu Feb 27 15:08:02 2003 From: ATrautman@perryjudds.com (Alan Trautman) Date: Thu Feb 27 15:08:02 2003 Subject: [Tutor] __init__ Message-ID: <0BA95581EDA7D611841B00A0C9AD25DD2B5A02@mail.pjinet.com> Vicki, This is one of the hardest things to get in programming but also the best once you figure out how. I'll try to give an example. class Circle: def __init__(self,radius): if radius > 0 : self.radius = radius else: print "invalid radius" self.radius = 1 self.pi = 3.14 def circumference_calc (self): circ = self.pi * self.radius * self.radius print 'The circumference is ', circ if __name__ == '__main__': print 'testing' c = Circle(3) c.circumference_calc() c = Circle(-3) c.circumference_calc() You'll see that the __init__ property verifies the data and sets all values needed to ensure the class functions properly in all cases. In my example that radius is set to a positive value and that a safe default value is inserted if it is not. This is not usually necessary as unchecked values should never be used to create a class. In the other I create a value that will be used within the class and set its value. Esstentially the __init__ block ensures that with no other support this class will function properly even though it will not generate the values expected. It will also give an error is someone attempts to use a class without giving it the proper elements( arguements formally). HTH Alan -----Original Message----- From: vicki@stanfield.net [mailto:vicki@stanfield.net] Sent: Thursday, February 27, 2003 10:19 AM To: tutor@python.org Subject: [Tutor] __init__ I think I am missing some very basic knowledge with regard to my Python/Tkinter programming which is preventing me from understanding the examples that I find. First the __init__ part, when do I need one? I notice that most of the modules that I include contain one. Also the example that I am trying to use to make my callback (for a Pmw.Entrybox) includes one. Can someone point me to some clear definition of what it is and when I need it. I apologize for being dense, but I can't seem to get past this. Thanks, --vicki _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From vicki@stanfield.net Thu Feb 27 15:27:02 2003 From: vicki@stanfield.net (vicki@stanfield.net) Date: Thu Feb 27 15:27:02 2003 Subject: [Tutor] __init__ Message-ID: <20030227122553.10467.h009.c000.wm@mail.stanfield.net.criticalpath.net> Thanks. I think what was confusing me was the self that usually gets passed to __init__. I think I am getting it now though. Thanks for enduring my questions. --vicki From vicki@stanfield.net Thu Feb 27 15:51:02 2003 From: vicki@stanfield.net (vicki@stanfield.net) Date: Thu Feb 27 15:51:02 2003 Subject: [Tutor] passing widget to callback before defined Message-ID: <20030227125016.17690.h003.c000.wm@mail.stanfield.net.criticalpath.net> What do you do when you have to define the callback when the item is created (ScrolledListBox has the selectioncommand argument) and you want to pass the name of the item to the callback. As shown below, the selectioncommand needs to use the name Listbox1 before the Listbox is actually defined. ---------------------------------- callback=SimpleCallback(CommandCallback,Listbox1) Listbox1=Pmw.ScrolledListBox(Frame3, selectioncommand=callback, listbox_height=1, labelpos='w', label_text='Commands', items=("06", "09")) Listbox1.pack() --------------------------------- For the record, the callback looks something like this: ---------------------------------- def CommandCallback(Listbox1) index=Pmw.ScrolledListBox.getcurselection(self.Listbox1) --------------------------------- Regards, --vicki From jeff@ccvcorp.com Thu Feb 27 16:29:01 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Thu Feb 27 16:29:01 2003 Subject: [Tutor] sorting the list References: <00a501c2dd95$7045bf80$1ad1b241@defaultcomp> <1964940964.20030227115540@rambler.ru> <032201c2de5e$0c7d8540$1ad1b241@defaultcomp> Message-ID: <3E5E8321.9020308@ccvcorp.com> Don Arnold wrote: >>>>>mysort() - 1.982278 elapsed >>>>>DSU - 3.472156 elapsed >>>>> >>>>> > >It looks like using DSU is actually slower than providing your own sort >method. This agrees with my >intuition that the overhead of creating the decorated list then undecorating >it can be sizable, but we >all know intuition can often be wrong. ; ) Is this really the case, or is >there a problem with my >implementation? > > I think it's partially a matter of the specifics of this case. Because this data requires an extra int() call for every element, the time taken by creating all those ints starts to swamp the time taken by the extra cmp() function calls. Typically, DSU is used to sort by the nth (existing) element of a sequence, rather than having to create new objects to populate the decorated list. Also, given the fact that (for the test data used) every comparison is being resolved by the second element, the DSU requires more comparisons than your sort. I suspect that if the test data included many different values for the initial letter, the times would be much closer. More importantly, though, you're doing DSU wrong. Instead of decorating and undecorating, you're decomposing and recreating. You should tack the original item as the final element of the tuple, and then simply extract that element from each item in the list when you undecorate. Here's my tests. >>> import time >>> def timetest(func, testlist) ... starttime = time.clock() ... func(testlist) ... endtime = time.clock() ... print "%10s -- %06f elapsed" % (func.__name__, endtime - starttime) ... >>> def mysort(lhs, rhs): ... if lhs[0] != rhs[0]: ... return cmp(lhs[0], rhs[0]) ... else: ... return cmp(int(lhs[1:]), int(rhs[1:])) ... >>> def test_mysort(testlist): ... testlist.sort(mysort) ... >>> def test_DSU(testlist): ... D = [(e[0], int(e[1:]), e) for e in testlist] ... D.sort() ... testlist = [item[-1] for item in D] ... >>> a = ['a' + str(i) for i in xrange(100000,-1,-1)] >>> timetest(test_mysort, a) test_mysort -- 1.468711 elapsed >>> a = ['a' + str(i) for i in xrange(100000,-1,-1)] >>> timetest(test_DSU, a) test_DSU -- 1.708165 elapsed >>> So, simply by fixing the DSU algorithm, we've made them fairly comparable. Now, let's try it with a wider assortment of initial letters: >>> import string >>> a = [string.lowercase[i % 26] + str(i) for i in xrange(100000,-1,-1)] >>> timetest(test_mysort, a) test_mysort -- 19.758318 elapsed >>> a = [string.lowercase[i % 26] + str(i) for i in xrange(100000,-1,-1)] >>> timetest(test_DSU, a) test_DSU -- 4.045212 elapsed Now, *there's* a significant difference! So it looks like the main advantage of your sort routine was that it had some short-circuiting built in, which happened to be advantageous with the data set you were testing but isn't always going to make much difference. DSU is pretty close to equal even in that special case, but is well ahead in the more general case. Jeff Shannon Technician/Programmer Credit International From Predrag Ivanovic Thu Feb 27 17:38:03 2003 From: Predrag Ivanovic (Predrag Ivanovic) Date: Thu Feb 27 17:38:03 2003 Subject: Fwd: Re[2]: [Tutor] My first (er...working...) script ever In-Reply-To: <1812809409.20030225204403@ptt.yu> References: <6610188680.20030222001709@ptt.yu> <1465374958.20030224153615@rambler.ru> <1812809409.20030225204403@ptt.yu> Message-ID: <70535209.20030227234115@ptt.yu> This is a forwarded message From: Predrag Ivanovic To: "antonmuhin at rambler.ru" Date: Tuesday, February 25, 2003, 8:44:03 PM Subject: [Tutor] My first (er...working...) script ever ===8<==============Original message text=============== antonmuhin at rambler.ru wrote: aarr> Hello Predrag, aarr> Saturday, February 22, 2003, 2:17:09 AM, you wrote: aarr> it was debated here and where, but I would rewrite it the following aarr> way: aarr> def processCircle(): aarr> r = float(raw_input("circle radius: ")) # try/except are good here aarr> print "result is %.3f" % krug(r) aarr> def process... aarr> # in the same fashion aarr> commands = { aarr> 'k': processCircle, aarr> .... aarr> 'e': None aarr> } aarr> def main(): aarr> while 1: aarr> print " 'o' za opcije" aarr> print " 'k' za obim kruga " aarr> print " 'p' za obim pravougaonika " aarr> print " 'c' za obim kvadrata" aarr> print " 'e' za exit" aarr> choice = raw_input("opcija : ") aarr> command = commands[choice] aarr> if command: aarr> commmand() aarr> else: aarr> break aarr> Defintely, it's just a sketch and might be improved in zillions ways aarr> Anton. That looks like a more elegant solution than mine.I'll try to rewrite it,with suggestions from you and others,and maybe post it here yet again for comments? Thank you. Pedja. ---- "Just below my skin,I'm screaming..." Salva Mea,Faithless ===8<===========End of original message text=========== -- Best regards, Predrag mailto:predivan@ptt.yu From Predrag Ivanovic Thu Feb 27 17:39:01 2003 From: Predrag Ivanovic (Predrag Ivanovic) Date: Thu Feb 27 17:39:01 2003 Subject: Fwd: Re[4]: [Tutor] My first (er...working...) script ever In-Reply-To: <1914887257.20030225211841@ptt.yu> References: <6610188680.20030222001709@ptt.yu> <9943097811.20030223035705@ptt.yu> <200302222132.45647.revanna@mn.rr.com> <200302222136.19045.revanna@mn.rr.com> <001001c2daf2$fce17510$9b100dd5@violante> <1914887257.20030225211841@ptt.yu> Message-ID: <53562518.20030227234142@ptt.yu> This is a forwarded message From: Predrag Ivanovic To: Gon=E7alo Rodrigues Date: Tuesday, February 25, 2003, 9:18:41 PM Subject: [Tutor] My first (er...working...) script ever =3D=3D=3D8<=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3DOriginal message tex= t=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D Gon=E7alo Rodrigues wrote: GR> A little better GR> r =3D raw_input("r:") GR> try: GR> newr =3D int(r) GR> #Catch specific exception. GR> except ValueError: GR> print "That is not a number" GR> #Move print out of try block. GR> print "whatever ", krug(newr) Here is a code as I wrote it... ----- r=3Draw_input("r:") try: newr=3Dint(r) ##Catch specific exception except ValueError: print "That'not a number." ##if all goes well... print "result is %.3d"% krug(newr) ------ When executed... ----- Traceback (most recent call last): File "D:\Python22\tutorial\obim.py", line 40, in -toplevel- print "obim je %.3d"% krug(newr) NameError: name 'newr' is not defined ----- But like this... ---- r=3Draw_input("r:") try: newr=3Dint(r) ##Catch specific exception except ValueError: print "That'not a number." ##if all goes well... else : print "result is %.3d"% krug(newr) ----- ...works. GR> With my best regards, GR> G. Rodrigues See you, Pedja. ---- "Just below my skin,I'm screaming..." Salva Mea,Faithless =3D=3D=3D8<=3D=3D=3D=3D=3D=3D=3D=3D=3D=3D=3DEnd of original message text=3D= =3D=3D=3D=3D=3D=3D=3D=3D=3D=3D --=20 Best regards, Predrag mailto:predivan@ptt.yu From micforster@yahoo.com Thu Feb 27 23:37:01 2003 From: micforster@yahoo.com (Mic Forster) Date: Thu Feb 27 23:37:01 2003 Subject: [Tutor] raw_input and converting string to digit Message-ID: <20030228043637.93279.qmail@web13408.mail.yahoo.com> Hi Guys, The purpose of this script is to obtain an expected species-abundance curve given an observed curve. The script works fine for this purpose but it is cumbersome to implement. What I am trying to do is to open this file, enter in a number that represents the fundamental biodiversity number (theta) and another that represents the community size (jM), let the program do its stuff and then give the expected abundance output. I am unsure of the correct syntax to convert a string from raw_input into a digit. Here is what I have (any additional comments on any aspect of this code is more than welcome): >>>from random import random as rnd >>>theta = [] >>>def addTheta(): theta.append(raw_input(‘Fundamental biodiversity number is: ‘)) >>>jM = [] >>>def addJM: jM.append(raw_input(‘The metacommmunity size is: ‘)) >>>class growList(list): '''A list that does as in Perl: Grows when we assign to new indices. I.e. x[1] = 5 will work if x was previously empty.''' def __setitem__(self, i, val): while i >= len(self): self.append(None) list.__setitem__(self, i, val) def __getitem__(self, i): 'Return 0 for unused slots' if i < len(self): return list.__getitem__(self, i) else: return 0 >>>abund = growList() >>>abund[1] = 1 >>>cumul = growList() >>>def nsp(): '''Number of species must be the same as the size of the abundence list (I guess). Note that first position is unused to match the 1-based algorithm syntax.''' return len(abund) - 1 >>>for j in range(2, jM + 1): x = rnd() if x < (theta / float(theta + j - 1)): abund.append(1) else: cumul[1] = abund[1] / float(j-1) for i in range(2, nsp()+1): cumul[i] = cumul[i-1] + abund[i] / float(j-1) i = 1 while x >= cumul[i]: i += 1 abund[i] += 1 >>>for abundance in zip(abund): print '%s' % abundance __________________________________________________ Do you Yahoo!? Yahoo! Tax Center - forms, calculators, tips, more http://taxes.yahoo.com/ From charlie@begeistert.org Fri Feb 28 07:59:02 2003 From: charlie@begeistert.org (Charlie Clark) Date: Fri Feb 28 07:59:02 2003 Subject: [Tutor] re: Script too slow Message-ID: <20030228135910.1678.6@.1046426236.fake> On 2003-02-27 at 18:00:07 [+0100], tutor-request@python.org wrote: > I have profiled the script using Python's profile utility. There is no > one function that slows down the script. Rather, each function seems to > take as much time. Here is an example: > > > def evaluate_token(self,token): > """Evaluate tokens. Return a value if the token is not a control > word. Otherwise, pass token onto another method for further > evaluation.""" > if token == '{': > self.__bracket_count = self.__bracket_count + 1 > num = '%04d' % self.__bracket_count > token = 'ob elif token == '}': > num = '%04d' % self.__bracket_count > token = 'cb self.__bracket_count = self.__bracket_count - 1 > elif token == r'\{': > token = 'tx elif token == r'\}': > token = 'tx elif token == r'\\': # double or escaped \ > token = 'tx elif token[0:1] != '\\': # single \ > token = 'tx else: > token = self.evaluate_cw(token) Paul, I'm probably the last person who can really help you on this but there are a couple of things that strike me about this function. First of all you can use self_bracket += 1 to get a bit more speed!!! Not much and I can't really tell you why but it is faster, it has something to do with only one value being used... I don't know how you're getting your tokens but it looks this looks a lot like the stuff you write when using the HTML/SGML-parser. Are you hooked up to an RTF-Parser to do all the stuff? If not it might be worth looking at the SGMLParser code as to how it deals with stuff - looks quite analogue to your "{", "}" stuff. Python has a nioe way of avoiding long if, elif, ... else. You can use dictionaries. ie. d_test 0 = {"{":count+1, "}":count-1, r"\{":"tx"} try: fn(d_test[token]) # some function which knows what to or use exec except KeyError: other_fn(token) that might be a little tricky to get right but should run faster, particularly for longer comparisons it's only one look-up per token. Hope this is a little helpful. Charlie From abli@freemail.hu Fri Feb 28 08:44:03 2003 From: abli@freemail.hu (Abel Daniel) Date: Fri Feb 28 08:44:03 2003 Subject: [Tutor] passing widget to callback before defined In-Reply-To: <20030227125016.17690.h003.c000.wm@mail.stanfield.net.criticalpath.net> References: <20030227125016.17690.h003.c000.wm@mail.stanfield.net.criticalpath.net> Message-ID: <20030228134128.GA2294@hooloovoo> vicki@stanfield.net (vicki@stanfield.net) wrote: > What do you do when you have to define the callback > when the item is created (ScrolledListBox has the > selectioncommand argument) and you want to pass the > name of the item to the callback. As shown below, the > selectioncommand needs to use the name Listbox1 before > the Listbox is actually defined. 1) Create Listbox 2) make callback 3) set callback as selectioncommand of the listbox Like this: > > ---------------------------------- > Listbox1=Pmw.ScrolledListBox(Frame3, > listbox_height=1, labelpos='w', > label_text='Commands', > items=("06", "09")) callback=SimpleCallback(CommandCallback,Listbox1) # ^^ moved here Listbox1.configure(selectioncommand=callback) > Listbox1.pack() abli From antonmuhin at rambler.ru" References: <20030227105905.D13858@localhost.localdomain> <3E5E6985.30700@ccvcorp.com> Message-ID: <19614998877.20030228221412@rambler.ru> Hello Jeff, Thursday, February 27, 2003, 10:39:49 PM, you wrote: JS> This function, to my mind, screams out to be made into a dictionary JS> lookup. (Any time I'm dealing with a situation of "pick one option from JS> this list of possibilities", or what in C/C++ would be a switch/case, I JS> immediately think dictionary.) If you put each of the given options JS> into a small one- to three-line function and put all of those functions JS> into a dictionary, you can then change this function into something like JS> the following: JS> def evaluate_token(self, token): JS> function = self.token_dict.get(token, self.evaluate_cw) JS> return function(self, token) # passing in self so that we can JS> access self.__bracket_count JS> Or, almost equivalently but sparing the helper functions from needing to JS> know so much about the bracket count: JS> def evaluate_token(self, token): JS> function = self.token_dict.get(token, self.evaluate_cw) JS> token, self.__bracket_count = function(token, self.__bracket_count) JS> return token I tried similar approach, but it was *slower*. I'm really surprised and it might some subtle bug that slipped into my code. JS> I also suspect that using the "formatstring % vars()" trick that you use JS> is slower than simply making use of the actual variables in question. JS> Try swapping, say, "token = 'tx "token = 'tx increase. (You're saving at least a function call each time, and JS> possibly a dictionary construction as well, depending on how vars() JS> operates.) I wouldn't expect a large increase but it should help. It really accelerates. Especially form I used: token = 'tx Thanks for all the help with the listbox callback stuff. Now onto something else. I am trying to use the strip function on the data which is returned from a getcurselection() call on that same listbox. What is returned is in the following format (number will vary): ('06',) I want to get only the number part, so I use the following: command=string.strip([(),]) The error I get is Attribute.Error: 'list' object has no attribute strip I am including the string module. Can anyone tell me what I am missing (this time)? --vicki From vicki@stanfield.net Fri Feb 28 15:02:59 2003 From: vicki@stanfield.net (vicki@stanfield.net) Date: Fri Feb 28 15:02:59 2003 Subject: [Tutor] Attribute.Error: 'list' object has no attribute strip Message-ID: <20030228120050.21734.h018.c000.wm@mail.stanfield.net.criticalpath.net> Thanks for all the help with the listbox callback stuff. Now onto something else. I am trying to use the strip function on the data which is returned from a getcurselection() call on that same listbox. What is returned is in the following format (number will vary): ('06',) I want to get only the number part, so I use the following: command=string.strip([(),]) The error I get is Attribute.Error: 'list' object has no attribute strip I am including the string module. Can anyone tell me what I am missing (this time)? --vicki From glingl@aon.at Fri Feb 28 15:04:01 2003 From: glingl@aon.at (Gregor Lingl) Date: Fri Feb 28 15:04:01 2003 Subject: [Tutor] script still too slow References: <20030227105905.D13858@localhost.localdomain> <3E5E6985.30700@ccvcorp.com> <19614998877.20030228221412@rambler.ru> Message-ID: <3E5FC054.2020702@aon.at> antonmuhin at rambler.ru schrieb: >And even Python2.3 >might be of help as they say that every version of Python is faster. > > > AFAIK they say, that every version of Python is slower (although not really sgnificantly ;-) ) Gregor From glingl@aon.at Fri Feb 28 15:19:01 2003 From: glingl@aon.at (Gregor Lingl) Date: Fri Feb 28 15:19:01 2003 Subject: [Tutor] Attribute.Error: 'list' object has no attribute strip References: <20030228120050.21734.h018.c000.wm@mail.stanfield.net.criticalpath.net> Message-ID: <3E5FC3BB.9050804@aon.at> vicki@stanfield.net schrieb: >Thanks for all the help with the listbox callback >stuff. Now onto something else. I am trying to use the >strip function on the data which is returned from a >getcurselection() call on that same listbox. What is >returned is in the following format (number will vary): > >('06',) > >I want to get only the number part, so I use the >following: > >command=string.strip([(),]) > >The error I get is > >Attribute.Error: 'list' object has no attribute strip > >I am including the string module. Can anyone tell me >what I am missing (this time)? > > In string.py the functino string is implemented like this: def strip(s): """strip(s) -> string Return a copy of the string s with leading and trailing whitespace removed. """ return s.strip() That is, is uses the strip - *method* of type string. If cou call it with a list as argument, it will complain, that list don't have a method called strip. In fact I cannot imagine, what you expected the rsult of string.strip([(),]) to be, as the documentation about string.stript says: strip(s[, chars]) Return a copy of the string with leading and trailing characters removed. If chars is omitted or None, whitespace characters are removed. If given and not None, chars must be a string; the characters in the string will be stripped from the both ends of the string this method is called on. Regards, Gregor >--vicki > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > > From gerrit@nl.linux.org Fri Feb 28 15:41:40 2003 From: gerrit@nl.linux.org (Gerrit Holl) Date: Fri Feb 28 15:41:40 2003 Subject: [Tutor] Attribute.Error: 'list' object has no attribute strip In-Reply-To: <20030228120050.21734.h018.c000.wm@mail.stanfield.net.criticalpath.net> References: <20030228120050.21734.h018.c000.wm@mail.stanfield.net.criticalpath.net> Message-ID: <20030228204201.GA11658@nl.linux.org> vicki@stanfield.net schreef op vrijdag 28 februari om 21:03:44 +0000: > Thanks for all the help with the listbox callback > stuff. Now onto something else. I am trying to use the > strip function on the data which is returned from a > getcurselection() call on that same listbox. What is > returned is in the following format (number will vary): > > ('06',) > > I want to get only the number part, so I use the > following: > > command=string.strip([(),]) > > The error I get is > > Attribute.Error: 'list' object has no attribute strip > > I am including the string module. Can anyone tell me > what I am missing (this time)? strip is a string method. Your object is not a string. If you type the name of an object in your interpreter, you may get something like ('06',). This does *not* mean that this is a string containing those characters! In this case, it is only the *representation* of the object: for humans, so that it is readable: 52 >>> t ('06',) In this case, you probably have a _tuple_, with one _element_, which is a _string_. You want an _integer_. So you need to: * get the only element from the tuple * this element is a string * get the integer out of a string A tuple is a sequence. This time, you want the first element: 53 >>> s=t[0] 54 >>> s '06' Now, we have a string containing the characters '06'. But we want to have an object with the *number* 6, right? Well, if you are absolutely sure that the string contains only integers, you can do: 55 >>> i = int(s) 56 >>> i 6 Voila! Here we have our integer. Now we are going to write this in one line: 57 >>> i = int(t[0]) The relevant documentation can be found online: * http://www.python.org/dev/doc/devel/tut/node5.html * http://www.python.org/dev/doc/devel/lib/built-in-funcs.html * http://www.python.org/dev/doc/devel/lib/typesnumeric.html * http://www.python.org/dev/doc/devel/lib/typesseq.html * http://www.python.org/dev/doc/devel/ref/parenthesized.html#l2h-241 Hope this helps! yours, Gerrit Holl. -- Asperger Syndroom - een persoonlijke benadering: http://people.nl.linux.org/~gerrit/ Het zijn tijden om je zelf met politiek te bemoeien: http://www.sp.nl/ From jeff@ccvcorp.com Fri Feb 28 15:44:02 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Fri Feb 28 15:44:02 2003 Subject: [Tutor] raw_input and converting string to digit References: <20030228043637.93279.qmail@web13408.mail.yahoo.com> Message-ID: <3E5FCA0D.7040006@ccvcorp.com> (Apologies if this appears twice -- my mailer seems to be having problems.) Mic Forster wrote: >Hi Guys, > >The purpose of this script is to obtain an expected >species-abundance curve given an observed curve. The >script works fine for this purpose but it is >cumbersome to implement. What I am trying to do is to >open this file, enter in a number that represents the >fundamental biodiversity number (theta) and another >that represents the community size (jM), let the >program do its stuff and then give the expected >abundance output. > >I am unsure of the correct syntax to convert a string >from raw_input into a digit. Here is what I have (any >additional comments on any aspect of this code is more >than welcome): > Usually you would use the int() (or possibly long() or float(), depending on the specific case) built-in function. Each of these functions will convert a string into a number of the appropriate type. They will throw an exception if the string doesn't represent a valid number of that type. >>>>def addTheta(): >>>> >>>> > theta.append(raw_input(Fundamental biodiversity >number is: )) > This can simply be: theta.append( int(raw_input('Fundamental biodiversity number is: ')) ) >>>>class growList(list): >>>> >>>> > '''A list that does as in Perl: Grows when > we assign to new indices. I.e. x[1] = 5 will > work if x was previously empty.''' > [...] > >>>>def nsp(): >>>> >>>> > '''Number of species must be the same as the size >of the abundence list (I guess). Note that first >position is unused to match the 1-based algorithm >syntax.''' > return len(abund) - 1 > In this, and in your following code, you spend a lot of work adjusting by one in order to fit your 1-based algorithm. You'd be better off using a 0-base -- you can then forget about all of that adjusting, and you're much less likely to have errors. Your calculation can then be written like this: for j in range(1, jM): x = rnd() if x < (theta / float(theta + j): abund.append(1) else: cumul[0] = abund[0] / float(j) for i in range(1, len(abund)): cumul[i] = cumul[i - 1] + abund[i] / float(j) i = 0 while x >= cumul[i]: i += 1 abund[i] += 1 This has the exact same values for everything except the indices, there's no worrying about adding or subtracting one, etc, etc. Much simpler and clearer. Speaking of simpler and clearer, your last, innermost loop ( "while x >= cumul[i]" ) could be rewritten like this: for i in range(len(cumul)): if x < cumul[i]: abund[i] += 1 break To my mind, this is a much clearer expression of the intent -- "step through cumul until we find an item smaller than x, and then add 1 to the matching element of abund". You can also make a simple change to one of your loops in order to remove the need for your special growlist class. You're only adding elements onto the end of your cumul list (you already use append() for the abund list), so you can simply special-case the final calculation, or better yet use try/except: for i in range(1, len(abund)): value = cumul[i - 1] + abund[i] / float(j) try: cumul[i] = value except IndexError: cumul.append(value) Now you can do away with your growList class, and simply initialize abund and cumul like this: abund = [1] cumul = [0] And you don't need zip() to print out your results: for abundance in abund: print abundance Jeff Shannon Technician/Programmer Credit International From vicki@stanfield.net Fri Feb 28 15:56:01 2003 From: vicki@stanfield.net (vicki@stanfield.net) Date: Fri Feb 28 15:56:01 2003 Subject: [Tutor] Attribute.Error: 'list' object has no attribute strip Message-ID: <20030228125509.2936.h018.c000.wm@mail.stanfield.net.criticalpath.net> Thanks. I only needed to do part of what you suggested. The line: string=(Pmw.ScrolledListBox.getcurselection(self))[0] gave me the 09 that I was looking for. Thanks for your patience. --vicki From Sean Abrahams Fri Feb 28 18:40:02 2003 From: Sean Abrahams (Sean Abrahams) Date: Fri Feb 28 18:40:02 2003 Subject: [Tutor] Object Instantiation via Dictionary Values Message-ID: <115787977765.20030228154311@sfsu.edu> I want to create new objects with names and classes that are stored inside a list of dictionaries. Example: modules = [{'Name' : 'Sean', 'Type' : 'Person'}, {'Name' : 'Buddy', 'Type' : 'Dog'}, {'Name' : 'Evil', ' Type' : 'Cat'}] for module in modules: module['Name'] = module['Type'].module['Type']() # Would be: # Sean = Person.Person() # Buddy = Dog.Dog() # Evil = Cat.Cat() I'm not exactly sure how to go about this, but assume it has something to do with using special methods. Thanks, --Sean From jeff@ccvcorp.com Fri Feb 28 21:08:03 2003 From: jeff@ccvcorp.com (Jeff Shannon) Date: Fri Feb 28 21:08:03 2003 Subject: [Tutor] Object Instantiation via Dictionary Values References: <115787977765.20030228154311@sfsu.edu> Message-ID: <3E6015D8.1070609@ccvcorp.com> Sean Abrahams wrote: >I want to create new objects with names and classes that are stored >inside a list of dictionaries. > >Example: > >modules = [{'Name' : 'Sean', 'Type' : 'Person'}, >{'Name' : 'Buddy', 'Type' : 'Dog'}, >{'Name' : 'Evil', ' Type' : 'Cat'}] > >for module in modules: > module['Name'] = module['Type'].module['Type']() > # Would be: > # Sean = Person.Person() > # Buddy = Dog.Dog() > # Evil = Cat.Cat() > > >I'm not exactly sure how to go about this, but assume it has something >to do with using special methods. > Not if you're happy keeping your created objects in a dictionary. I presume that you have, say, a module Person.py that contains class Person, etc? If you've already imported your modules, they'll be in sys.modules; if not, you can investigate the imp() builtin (IIRC). Presuming you've already imported them, and also sys: objects = {} for module in modules: type = module['Type'] mod = sys.modules[type] objects[module['Name']] = getattr(mod, type)() This is completely untested, and just off the top of my head, so use with caution -- but I think it should work, or at least give you a general idea... Jeff Shannon Technician/Programmer Credit International