From linuxasking at netscape.net Mon Feb 2 01:03:56 2004 From: linuxasking at netscape.net (Xuer) Date: Sat Jan 31 01:05:14 2004 Subject: [Tutor] "=" invalid syntax ? Message-ID: <401DE84C.8030707@netscape.net> print all lines of a simple file test.py ----------------------------------------------- #!/usr/bin/python try: fi = open('test.py', 'r') except IOError: print 'Can\'t open file for reading.' sys.exit(0) while (line=fi.readline()): print line ----------------------------------------------- then run it $./test.py File "./test.py", line 8 while (line=fi.readline()): ^ SyntaxError: invalid syntax what's the problem? thanks and regards :) From dyoo at hkn.eecs.berkeley.edu Sun Feb 1 00:03:02 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun Feb 1 00:03:09 2004 Subject: [Tutor] "=" invalid syntax ? In-Reply-To: <20040131173532.GI5205@johnsons-web.com> Message-ID: On Sat, 31 Jan 2004, Tim Johnson wrote: > > File "./test.py", line 8 > > while (line=fi.readline()): > > ^ > > SyntaxError: invalid syntax > > > > what's the problem? > > while (line=fi.readline()): > > '=' is an assignment operator in python. > '==' is the comparison operator in python. > use '==' > > happens to me all the time .... Hi Tim, Changing '=' to '==' will make it syntactically correct, but it won't preserve the intended meaning. Xuer appears to be using a C-ish syntax: in the C language, it's legal to say something like: while((ch = getc(stdin)) != EOF) { ... } In the C language, assignment is treated as an "expression" that can be nested within other expressions, so the above C code mixes together an assigment with a comparison. Very succinct, but also very error prone. In Python, assignment is treated as a "statement". The thing that distinguishes a "statement" from an "expression" is that a statement isn't very nestable within another statement. This prevents certain mistakes (like using 'assignment' on accident, when we really mean 'equality test'), but at the cost of being more verbose. That should explain why we're getting a SyntaxError out of: > > File "./test.py", line 8 > > while (line=fi.readline()): > > ^ > > SyntaxError: invalid syntax because the assignment statement can't nest within the while statement. How do we fix this? To get the direct effect of ### while (line=fi.readline()): ## pseudo-C/Python ... ### with the 'while' loop, we must break it up into separate statements: ### while 1: line = fi.readline() if not line: break ... ### But this ends up being longer than the equivalent code in C! Is there a better way to say this? There's actually an alternative that's available in recent versions of Python, if we use the 'for' loop: ### for line in fi: ... ### This has almost the same effect as the original code, and it scans well too. It takes advantage of the widespread support of 'iterators' into the Python language, and here, we treat the file as an iterable object that we can loop across. Hope this helps! From dyoo at hkn.eecs.berkeley.edu Sun Feb 1 00:19:44 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun Feb 1 00:19:49 2004 Subject: [Tutor] "=" invalid syntax ? [Assignment grammar stuff] In-Reply-To: <20040131162728.2908c5fb.orbitz@ezabel.com> Message-ID: On Sat, 31 Jan 2004 orbitz@ezabel.com wrote: > I just learned this recently, but if you say = is a statement then you > would imagine: > > a = b = 2 to not work. = is actually special cased for this to work. > however > a = (b = 2) does not work. There is some 'magic' some people might say > to =, but I think a = b = .. is the only excpetion to the = is a > statement operator rule. Hi orbitz, If people are interested in how it's special cased, the Reference Manual has the gory details. *grin* The grammar definition in: http://www.python.org/doc/ref/assignment.html shows that assignment_stmt ::= (target_list "=")+ expression_list That is, an assignment statement is made up of a number of targets, followed by the expression that will be assigned to those targets. Usually, we define a single target, but nothing stops us from defining multiple targets. If we're looking at somthing like: a = b = 2 then we can see that a = b = matches (target_list "=")+ and 2 matches expression_list If we look at the grammar, we can also see that assignment allows for a limited form of pattern matching --- it's possible to say something like: ### >>> p1 = (x1, y1) = (3, 17) >>> p1 (3, 17) >>> x1 3 >>> y1 17 ### Hope this helps! From isrgish at fusemail.com Sun Feb 1 01:03:31 2004 From: isrgish at fusemail.com (Isr Gish) Date: Sun Feb 1 01:03:36 2004 Subject: [Tutor] Converting string or list to sum Message-ID: Thanks I had rebound the variable str. Isr -----Original Message----- >From: "Terry Carroll" >Sent: 1/31/04 9:47:23 PM >To: "tutor@python.org" >Subject: Re: Re: [Tutor] Converting string or list to sum > >On Sat, 31 Jan 2004, Isr Gish wrote: > >> When I try doing. >> map(str, a) >> I got a traceback >> TypeError: 'str' object is not callable >> But when I do, >> map(__builtin__.str, a) >> It works fine. > >did you rebind the variable name str elsewhere in your program, e.g., > >>>> a=['1','2','3'] >>>> a >['1', '2', '3'] >>>> d=''.join(map(str,a)) >>>> d >'123' >>>> str="xyz" >>>> d=''.join(map(str,a)) >Traceback (most recent call last): > File "", line 1, in ? >TypeError: 'str' object is not callable >>>> > > > > > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > From project5 at redrival.net Sun Feb 1 07:10:00 2004 From: project5 at redrival.net (Andrei) Date: Sun Feb 1 07:13:07 2004 Subject: [Tutor] Re: .tar.gz in Py References: <401B2AE4.5090107@netzero.net> <18j8mrbjmj000$.ireckbqsmp5u.dlg@40tude.net> <20040131222126.15808966@phatbox.local> Message-ID: Nick Lunt wrote on Sat, 31 Jan 2004 22:21:26 +0000: Thanks, Nick. That's a lot easier than I expected. The possible errors aren't a problem for me because I am pretty certain that my dirs and their contents are "safe" since the script where I'll use it creates those dirs and files itself. > I asked a tar question myself yesterday and included my problematic program. Here it is - > > # CODE > > """ > tar.py: > Usage: > tar.py filetocreate.tar list_of_files_to_tar > > imports: > tarfile - to do the tarring > sys - to manipulate command line args > """ > > # Fails in the if block on os.access when dirs are submitted as args. > # ie the dir submitted is readable but some files below it may not be, > # which the if os.access() does not pick up. > # So create a new function to walk the dir and only return the files it can > # backup successfully, but print a list of the ones it cant. > > > As you can see from the comments in my code it is not perfect yet, but it will hopefully show you how to use the tar module, and it will create a tar file for you. > > There is also a gzip module you can import to gzip the tar file, but I've not got my head round that yet as the tar part is not 100%, but that is my plans for it. Then it's going to write it to CD. Then I'd like to make a GUI for it, just to learn how to ;) Oh yeah, the final version is also gonna be OOP. > -- Yours, Andrei ===== Mail address in header catches spam. Real contact info (decode with rot13): cebwrpg5@jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From red_necks25 at yahoo.com Sun Feb 1 16:11:08 2004 From: red_necks25 at yahoo.com (moore william) Date: Sun Feb 1 16:13:26 2004 Subject: [Tutor] Activating a box Message-ID: <20040201211108.15838.qmail@web13609.mail.yahoo.com> I am adding boxes to my program and am looking for informatioin to get my box to activate diffrent parts of my program. Anyone have a toutorial on this? Example: (BOX) # File: toolbar1.py from Tkinter import * root = Tk() def Deposite(): print "Amount:" # create a toolbar toolbar = Frame(root) b = Button(toolbar, text="Deposite", width=10, command=Deposite) b.pack(side=LEFT, padx=2, pady=2) b = Button(toolbar, text="Withdraw", width=10, command=Deposite) b.pack(side=LEFT, padx=2, pady=2) toolbar.pack(side=TOP, fill=X) mainloop() (Action) # I added the exception line so that negartive numbers woudl not be added. if choice == 1: amount = raw_input ('Amount: ') elif amount < 0: raise ValueError, 'Deposites must be positive' elif self.balance - amount < 0: raise ValueError, 'The account only holds $' + str(self.balance) self._perform_transaction(-amount) date = raw_input ('Date: ') numbers[amount] = date __________________________________ Do you Yahoo!? Yahoo! SiteBuilder - Free web site building tool. Try it! http://webhosting.yahoo.com/ps/sb/ From alan.gauld at blueyonder.co.uk Sun Feb 1 18:05:37 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sun Feb 1 18:07:24 2004 Subject: [Tutor] Buttons References: <20040201023500.51351.qmail@web13608.mail.yahoo.com> Message-ID: <00f901c3e917$e7f24600$6401a8c0@xp> > I have a cash program that I am trying to create > buttons for instead of a simple number menu. I > understand that I need to import the Tkinter, create > and position the widgets, and enter the main loop Yes, but of course you aren't doing any of that here... > (Python in a nut shell). But I am still having > problems. I have attached the code It would help if you gave us a clue as to what the problems were? They obviously are not related to the Buttons since there is no Tkinter code here. I'll try to add some comments.... > class AccountTransaction(object): > def __init__(self, amount, time): > self.amount = amount > self.time = time Not sure why you are using a new style class here, especially given that you use old stuyle classes later on. But it shouldn't cause any real problems. > def __repr__(self): > description = time.ctime(self.time) + ' ' > if self.amount < 0: > description += '-' > description += '$' + str(abs(self.amount)) > return description This would be much easier with a format string, something like: description += "%s$%05.2s" % (sign, self.amount) Set the sign using the code above or the simpler(IMHO!): sign = (sign < 0 and '-') or '' > def __init__(self, initial): > self.balance = amount Not sure why we have two init methods? This will replace the first one. If you come from Java or C++ maybe you are used to multiple constructors but you can't do that in Python, sorry. > while 1: > print > print > print 'Show Me The Money' > print '1. Deposite' > print '2. Withdraw' > print '3. Getbalance' > print '9. Quit' > print > choice = int(raw_input('Enter your choice: ')) Lots of print statements are usually better done with a triple quoted string and/or a format string. In this case: print ''' Show Me The Money 1. Deposit 2. Withdraw 3. Getbalance 9. Quit ''' > # I added the exception line so that negartive > numbers woudl not be added. > > if choice == 1: > amount = raw_input ('Amount: ') > elif amount < 0: > raise ValueError, 'Deposites must be positive' This only gets called if choice is not 1. That is it will not check the value input by the user. Even if it did you would be comparing a string and a number, you need to convert the raw_input() value to an int. > elif self.balance - amount < 0: Again, this only gets called if choice is not 1 and amount is positive. I suspect you want these tests all to be plain if statements nested under the if choice === 1?. > date = raw_input ('Date: ') > numbers[amount] = date If you are storing a date why not convert it to a date and store that? Its probably easier to manipulate later. There is a third party date module (mxdate?) that you might find easier to use that the standard time module. > elif choice == 2: > amount = raw_input ('Amount: ') > if amount < 0: > raise ValueError, 'Withdrawals must be This will mostly work as you expect, but mainly by accident. If none of the tests above are true then you will do the choice test, then because the elif chain is stopped ypu will do the 'if amount' test I suspect the structure you really want is: if choice == 1: # get the amount # if amount < 0 : raise error # elif balance-amount < 0 : raise error elif choice == 2: # get amount # if amount < 0: raise error # etc elif choice == 3: # and so on. elif choice == 9: # and here else: # finally... > class Account: > def Deposit(self, amt): > self.balance = self.balance + amt > def Withdraw(self,amt): > self.balance = self.balance - amt > def getbalance(self): > return self.balance You never set balance(no init method?) so any attempt to call the methods will fail because self.balance has not been defined before use. HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From Harm_Kirchhoff at mail.digital.co.jp Sun Feb 1 19:54:07 2004 From: Harm_Kirchhoff at mail.digital.co.jp (Harm_Kirchhoff@mail.digital.co.jp) Date: Sun Feb 1 19:55:00 2004 Subject: [Tutor] How to close a file opened with csv.write Message-ID: Thanks Gerrit, that was a good tip. I had been wondering about this for some time and I know others, too. Is there a way this could be included into the python docu for the csv module ? From python at keep-trying.com Sun Feb 1 20:31:56 2004 From: python at keep-trying.com (richard) Date: Sun Feb 1 20:32:26 2004 Subject: [Tutor] Piping stdout to external Program Message-ID: <6.0.0.22.0.20040202011856.01eaf8b8@192.168.5.1> Folks, Having given up on my dialog box problem for moment. I have progressed onto other things. I am attempting to create and preview pdf reports. I have no problems creating the pdf saving it to disk then manually opening it using reportlabs.What I wish to do is pipe the pdf straight to acrobat reader. This is what I have so far: (To get the pdf output -> c.save() ) The function is to escape the spaces correctly. (taken for the newsgroups) >>> def _quote(*args): ... fmt = max(map(lambda s: len(string.split(s)), args))>1 and '"%s"' or '%s' ... return fmt % string.join(map(lambda s: len(string.split(s))>1 and '"%s"' % s or s, args),' ') os.system(_quote(r'C:\Program Files\Adobe\Acrobat 6.0\Reader\AcroRd32.exe', c.save())) This gets me the following: (1) A new command/dos box which locks python (2) After waiting a minute dismissing the dos box results in Acrobat coming up minus the document (3) The pdf document is simply outputted to the screen. Similar problems with popen. Is it possible to do this?? XP,Python 2.3 Regards Richard From littledanehren at yahoo.com Sun Feb 1 21:00:27 2004 From: littledanehren at yahoo.com (Daniel Ehrenberg) Date: Sun Feb 1 21:00:32 2004 Subject: [Tutor] "=" invalid syntax ? In-Reply-To: <401C201B.9060403@venix.com> Message-ID: <20040202020027.66211.qmail@web41813.mail.yahoo.com> > try/except and try/finally are two different forms. > There is no try/except/finally. > > (thanks to Alex Martelli) it should look more like: > > try: > try: > fi = open('test.py', 'r') > except IOError: > print "Can't open file for reading." > else: > for line in fi: > print line > finally: > fi.close() > > The else is a convenient to limit the scope of the > try statement. > > The exceptions chapter of "Python in a Nutshell" has > very lucid descriptions > of exception handling strategies. I'm probably making some big mistake again, but if you're using both except and else, why not just write: try: fi = open('test.py', 'r') except IOError: print "Can't open file for reading." else: for line in fi: print line fi.close() Daniel Ehrenberg __________________________________ Do you Yahoo!? Yahoo! SiteBuilder - Free web site building tool. Try it! http://webhosting.yahoo.com/ps/sb/ From littledanehren at yahoo.com Sun Feb 1 21:05:06 2004 From: littledanehren at yahoo.com (Daniel Ehrenberg) Date: Sun Feb 1 21:05:14 2004 Subject: [Tutor] Visitor Pattern Message-ID: <20040202020506.31323.qmail@web41803.mail.yahoo.com> What is a visitor pattern? I've heard that it shows how good a language is, and that Lisp is really good because it can be done in two (cryptic) lines. How can a visitor pattern be implimented in Python? Daniel Ehrenberg __________________________________ Do you Yahoo!? Yahoo! SiteBuilder - Free web site building tool. Try it! http://webhosting.yahoo.com/ps/sb/ From pythontutor at venix.com Sun Feb 1 21:36:31 2004 From: pythontutor at venix.com (Lloyd Kvam) Date: Sun Feb 1 21:36:29 2004 Subject: [Tutor] "=" invalid syntax ? In-Reply-To: <20040202020013.30010.qmail@web41802.mail.yahoo.com> References: <20040202020013.30010.qmail@web41802.mail.yahoo.com> Message-ID: <401DB7AF.3050202@venix.com> Daniel Ehrenberg wrote: >>try/except and try/finally are two different forms. >>There is no try/except/finally. >> >>(thanks to Alex Martelli) it should look more like: >> >>try: >> try: >> fi = open('test.py', 'r') >> except IOError: >> print "Can't open file for reading." >> else: >> for line in fi: >> print line >>finally: >> fi.close() >> >>The else is a convenient to limit the scope of the >>try statement. >> >>The exceptions chapter of "Python in a Nutshell" has >>very lucid descriptions >>of exception handling strategies. > > > I'm probably making some big mistake again, but if > you're using both except and else, why not just write: > > try: > fi = open('test.py', 'r') > except IOError: > print "Can't open file for reading." > else: > for line in fi: > print line > > fi.close() > > Daniel Ehrenberg In actual practise, that is what I'd write. I was just showing the general approach to having finally and except for the same block of code. Typically try/finally encloses a "logically" large block of cade and simply guarantees that a log entry will get written or that a file or other resource will get closed. try/except usually covers small blocks of code. It also provides general recovery control for applications that must continue after an exception is raised. -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-653-8139 fax: 801-459-9582 From littledanehren at yahoo.com Mon Feb 2 12:52:13 2004 From: littledanehren at yahoo.com (Daniel Ehrenberg) Date: Mon Feb 2 12:52:19 2004 Subject: [Tutor] "=" invalid syntax ? In-Reply-To: <20040131162728.2908c5fb.orbitz@ezabel.com> Message-ID: <20040202175213.58433.qmail@web41808.mail.yahoo.com> orbitz@ezabel.com wrote: > I just learned this recently, but if you say = is a > statement then you > would imagine: > > a = b = 2 to not work. = is actually special cased > for this to work. > however > a = (b = 2) does not work. There is some 'magic' > some people might say > to =, but I think a = b = .. is the only excpetion > to the = is a > statement operator rule. Yeah, it's just an exception to the rule. Daniel Ehrenberg __________________________________ Do you Yahoo!? Yahoo! SiteBuilder - Free web site building tool. Try it! http://webhosting.yahoo.com/ps/sb/ From darnold02 at sprynet.com Mon Feb 2 12:42:14 2004 From: darnold02 at sprynet.com (don arnold) Date: Mon Feb 2 12:56:26 2004 Subject: [Tutor] Activating a box References: <20040201211108.15838.qmail@web13609.mail.yahoo.com> Message-ID: <038f01c3e9b3$e68db410$7210ba3f@don2uvsu54fwiq> ----- Original Message ----- From: "moore william" To: "Python" Sent: Sunday, February 01, 2004 3:11 PM Subject: [Tutor] Activating a box > I am adding boxes to my program and am looking for > informatioin to get my box to activate diffrent parts > of my program. Anyone have a toutorial on this? > > Example: > Well, I was hoping someone more knowledgeable than I in Tkinter (i.e.: just about anyone) would field this, but here goes: First, we'll import the modules we need: from Tkinter import * from tkSimpleDialog import askfloat from tkMessageBox import showinfo We'll be using the askfloat and showinfo functions to create simple dialogs. The tkSimpleDialog and tkMessageBox modules are given just a passing mention in the Python Library Reference under Tkinter, but you can use the online help system to get more info on them (type 'help(modulename)' at the interactive prompt). When using Tkinter, all input and output is done through widgets. So we want to isolate the actual program logic from the user input/output routines. We'll create a simple Account class that represents an account, and an App class that provides the user interface. Here's the Account class: class Account: def __init__(self): self.balance = 0.0 def deposit(self, amount): self.balance += amount def withdraw(self, amount): self.balance -= amount def getBalance(self): return self.balance The App class contains the interface logic, and an Account instance that its widgets will interact with. It's pretty straightforward, so commenting is minimal: class App: def __init__(self, master): ''' creates an Account instance and presents the button menu ''' self.account = Account() ## menu button texts and the actions they invoke buttons = (('Deposit', self.doDeposit), ('Withdraw', self.doWithdraw), ('Get Balance', self.showBalance), ('Exit',root.destroy) ) f = Frame(master) for bText, bCommand in buttons: Button(f,text=bText,command=bCommand).pack(fill=X, side=TOP) f.pack() def doDeposit(self): ''' prompt user for amount of deposit. don't allow negative values. apply amount to the account. ''' retval = askfloat('Deposit', 'Amount of deposit:', minvalue = 0) if retval != None: self.account.deposit(retval) def doWithdraw(self): ''' prompt user for amount of withdrawal. don't allow negative values or an amount greater than the current balance. apply amount to the account. ''' retval = askfloat('Withdrawal', 'Amount of withdrawal:', minvalue = 0, maxvalue = self.account.getBalance()) if retval != None: self.account.withdraw(retval) def showBalance(self): ''' show the current balance ''' showinfo('Account Balance', 'Current account balance is $%12.2f' % self.account.getBalance()) And finally, the logic to initialise Tkinter and start the application: root = Tk() theApp = App(root) root.mainloop() Since some long lines will probably get mangled in the mail, I've also attached the source code. Hopefully, that will give you something to work with. HTH, Don -------------- next part -------------- from Tkinter import * from tkSimpleDialog import askfloat from tkMessageBox import showinfo class Account: def __init__(self): self.balance = 0.0 def deposit(self, amount): self.balance += amount def withdraw(self, amount): self.balance -= amount def getBalance(self): return self.balance class App: def __init__(self, master): ''' creates an Account instance and presents the button menu ''' self.account = Account() ## menu button texts and the actions they invoke buttons = (('Deposit', self.doDeposit), ('Withdraw', self.doWithdraw), ('Get Balance', self.showBalance), ('Exit',root.destroy) ) f = Frame(master) for bText, bCommand in buttons: Button(f,text=bText,command=bCommand).pack(fill=X, side=TOP) f.pack() def doDeposit(self): ''' prompt user for amount of deposit. don't allow negative values. apply amount to the account. ''' retval = askfloat('Deposit', 'Amount of deposit:', minvalue = 0) if retval != None: self.account.deposit(retval) def doWithdraw(self): ''' prompt user for amount of withdrawal. don't allow negative values or an amount greater than the current balance. apply amount to the account. ''' retval = askfloat('Withdrawal', 'Amount of withdrawal:', minvalue = 0, maxvalue = self.account.getBalance()) if retval != None: self.account.withdraw(retval) def showBalance(self): ''' show the current balance ''' showinfo('Account Balance', 'Current account balance is $%12.2f' % self.account.getBalance()) root = Tk() theApp = App(root) root.mainloop() From xthereal at bigfoot.com Mon Feb 2 13:12:08 2004 From: xthereal at bigfoot.com (steve) Date: Mon Feb 2 13:14:04 2004 Subject: [Tutor] Concatenating Strings into Variable Names? Message-ID: <20040202131208.F4F781C0.xthereal@bigfoot.com> Hello, I'm a day 1 complete newcomer to python and programming in general, so I apologize in advance for any stupid questions or code butchering that may follow... I'm trying to write my first program besides good old hello world. Is there a way to concatenate strings into a variable name? Here's a brief example of what i'm trying to do: choiceA_option1= 2.0 choiceA_option2= 3.0 choiceB_option1= 4.0 choiceB_option2= 5.0 choice=raw_input("Do you want choice A or B?") option=raw_input("Do you want option 1 or 2?") the_answer="choice" + choice + "_option" + option print the_answer When i run this, and type in A and 2, it sets the_answer as choiceA_ option2 and prints "choiceA_option2" as another string instead of the value 3.0. Is there a way to set the resulting concatenation of the_ answer as the variable name that i set previously, and not a literal string? Hope this question makes some sense, and sorry for any misuse of terms. Gotta start somewhere lol Thanks for any help! From darnold02 at sprynet.com Mon Feb 2 13:37:11 2004 From: darnold02 at sprynet.com (don arnold) Date: Mon Feb 2 13:37:44 2004 Subject: [Tutor] Concatenating Strings into Variable Names? References: <20040202131208.F4F781C0.xthereal@bigfoot.com> Message-ID: <040e01c3e9bb$94a36c00$7210ba3f@don2uvsu54fwiq> ----- Original Message ----- From: "steve" To: Sent: Monday, February 02, 2004 12:12 PM Subject: [Tutor] Concatenating Strings into Variable Names? > Hello, > I'm a day 1 complete newcomer to python and programming in general, > so I apologize in advance for any stupid questions or code butchering > that may follow... > I'm trying to write my first program besides good old hello world. Is > there a way to concatenate strings into a variable name? Here's a > brief example of what i'm trying to do: > > choiceA_option1= 2.0 > choiceA_option2= 3.0 > choiceB_option1= 4.0 > choiceB_option2= 5.0 > > choice=raw_input("Do you want choice A or B?") > option=raw_input("Do you want option 1 or 2?") > > the_answer="choice" + choice + "_option" + option > > print the_answer > > > When i run this, and type in A and 2, it sets the_answer as choiceA_ > option2 and prints "choiceA_option2" as another string instead of the > value 3.0. Is there a way to set the resulting concatenation of the_ > answer as the variable name that i set previously, and not a literal > string? > This seems to be a very common question. Instead of using a 'regular' variable, you create a dictionary to hold your data. Then you use a string representing the variable's name as the key to that dictionary: myvars = {} myvars['choiceA_option1'] = 2.0 myvars['choiceA_option2'] = 3.0 myvars['choiceB_option1'] = 4.0 myvars['choiceB_option2'] = 5.0 choice=raw_input("Do you want choice A or B?") option=raw_input("Do you want option 1 or 2?") the_answer = "choice" + choice + "_option" + option if the_answer in myvars: print 'answer:', myvars[the_answer] else: print 'invalid choice/option combination' > Hope this question makes some sense, and sorry for any misuse of terms. > Gotta start somewhere lol > > Thanks for any help! HTH, Don From rmkrauter at yahoo.com Mon Feb 2 14:06:34 2004 From: rmkrauter at yahoo.com (Rich Krauter) Date: Mon Feb 2 14:11:30 2004 Subject: [Tutor] Concatenating Strings into Variable Names? In-Reply-To: <20040202131208.F4F781C0.xthereal@bigfoot.com> References: <20040202131208.F4F781C0.xthereal@bigfoot.com> Message-ID: <1075748793.4059.43.camel@vaio> > > print the_answer > You can test these out: try: print eval('the_answer') except: "Invalid choice" or print globals()['the_answer'] or print locals()['the_answer'] or print globals().get('the_answer',"Not a valid choice") or print locals().get('the_answer',"Not a valid choice") I hope others comment on the right way - I'm interested in which is considered the best, if any. The dictionary method posted by Don is good too. The first and last two examples above provide a check for invalid entries, similar to Don's method. Good luck. Rich From dyoo at hkn.eecs.berkeley.edu Mon Feb 2 14:13:38 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Feb 2 14:13:56 2004 Subject: [Tutor] Concatenating Strings into Variable Names? In-Reply-To: <040e01c3e9bb$94a36c00$7210ba3f@don2uvsu54fwiq> Message-ID: > This seems to be a very common question. Instead of using a 'regular' > variable, you create a dictionary to hold your data. Then you use a > string representing the variable's name as the key to that dictionary: > > myvars = {} > myvars['choiceA_option1'] = 2.0 > myvars['choiceA_option2'] = 3.0 > myvars['choiceB_option1'] = 4.0 > myvars['choiceB_option2'] = 5.0 > > choice=raw_input("Do you want choice A or B?") > option=raw_input("Do you want option 1 or 2?") > > the_answer = "choice" + choice + "_option" + option > > if the_answer in myvars: > print 'answer:', myvars[the_answer] > else: > print 'invalid choice/option combination' Hi Steve, I agree with Don; a "dictionary" seems like a good way to represent these choices. All of these choices are related, so using a single dictionary container to hold them is probably a good idea to show that intent. Here's a variation on Don's program: ### all_choices = {} all_choices['A', '1'] = 2.0 all_choices['A', '2'] = 3.0 all_choices['B', '1'] = 4.0 all_choices['B', '2'] = 5.0 choice = raw_input("Do you want choice A or B?") option = raw_input("Do you want option 1 or 2?") if (choice, option) in all_choices: print 'answer:', all_choices[choice, option] else: print 'invalid choice/option combination' ### Python's dictionaries are versatile, because not only can we use numbers and strings as keys, but we're even allowed to use tuples! The code above does the same thing as Don's program, but instead of using strings as keys into the dictionary, we use the (choice, option) pair. Hope this helps! From tim at johnsons-web.com Mon Feb 2 15:57:55 2004 From: tim at johnsons-web.com (Tim Johnson) Date: Mon Feb 2 15:53:42 2004 Subject: [Tutor] lstrip() question In-Reply-To: References: <040e01c3e9bb$94a36c00$7210ba3f@don2uvsu54fwiq> Message-ID: <20040202205755.GB13611@johnsons-web.com> Hello All: I'd like to remove all leading occurance of a html break tag in a string such that "

test" => "test" and "
test
this" =>"test
this" It appears that lstrip() will not do this as this console session using version 2.2.2 seems to demonstrate: >>> tmp1 = 'real estate broker courtesy' >>> tmp2 = tmp1.lstrip('
') >>> tmp2 'eal estate broker courtesy' It looks like '
' is being treated as a set rather than a substring. (that's why the 'r' was removed) Is there a builtin python method to strip leading substrings? Or do I have to do something using startswidth()? Before I re-invent an existing wheel.... TIA tim -- Tim Johnson http://www.alaska-internet-solutions.com From sigurd at 12move.de Mon Feb 2 16:17:14 2004 From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=) Date: Mon Feb 2 16:19:35 2004 Subject: [Tutor] lstrip() question In-Reply-To: <20040202205755.GB13611@johnsons-web.com> (Tim Johnson's message of "Mon, 2 Feb 2004 11:57:55 -0900") References: <040e01c3e9bb$94a36c00$7210ba3f@don2uvsu54fwiq> <20040202205755.GB13611@johnsons-web.com> Message-ID: On 2 Feb 2004, Tim Johnson <- tim@johnsons-web.com wrote: > It appears that lstrip() will not do this > as this console session using version 2.2.2 > seems to demonstrate: >>>> tmp1 = 'real estate broker courtesy' >>>> tmp2 = tmp1.lstrip('
') >>>> tmp2 > 'eal estate broker courtesy' > It looks like '
' is being treated as > a set rather than a substring. > (that's why the 'r' was removed) Yes; strip works with characters. > Is there a builtin > python method to strip leading substrings? Or do > I have to do something using startswidth()? I would use a regexp. >>> tmp1 = '
real estate broker courtesy' >>> import re >>> re.sub('^
*', '', tmp1) 'real estate broker courtesy' >>> tmp1 = 'real estate broker courtesy' >>> re.sub('^
*', '', tmp1) 'real estate broker courtesy' Karl -- Please do *not* send copies of replies to me. I read the list From WRSimoni at MAPLLC.com Mon Feb 2 16:16:15 2004 From: WRSimoni at MAPLLC.com (Simoni, Bill) Date: Mon Feb 2 16:30:16 2004 Subject: [Tutor] lstrip() question Message-ID: > Hello All: > I'd like to remove all leading occurance of a html break tag > in a string such that > "

test" => "test" > and > "
test
this" =>"test
this" Hi Tim, off the top of my head, I came up with this: >>> def repstrip(s, sub): if s.startswith(sub): s = repstrip(s[len(sub):], sub) #strip the leading characters that match and try it again return s >>> print repstrip('real estate broker courtesy', '
') real estate broker courtesy >>> print repstrip('
real estate broker courtesy', '
') real estate broker courtesy >>> print repstrip('

real estate broker courtesy', '
') real estate broker courtesy >>> print repstrip('

real estate
broker courtesy', '
') real estate
broker courtesy There may be a better way to do this - if so, I'm sure someone else will post it soon. Bill From tim at johnsons-web.com Mon Feb 2 16:54:22 2004 From: tim at johnsons-web.com (Tim Johnson) Date: Mon Feb 2 16:50:13 2004 Subject: [Tutor] lstrip() question In-Reply-To: References: <040e01c3e9bb$94a36c00$7210ba3f@don2uvsu54fwiq> <20040202205755.GB13611@johnsons-web.com> Message-ID: <20040202215422.GC13611@johnsons-web.com> Things Karl. Right on the money! * Karl Pfl?sterer [040202 12:31]: > On 2 Feb 2004, Tim Johnson <- tim@johnsons-web.com wrote: > > > It appears that lstrip() will not do this > > as this console session using version 2.2.2 > > seems to demonstrate: > >>>> tmp1 = 'real estate broker courtesy' > >>>> tmp2 = tmp1.lstrip('
') > >>>> tmp2 > > 'eal estate broker courtesy' > > > It looks like '
' is being treated as > > a set rather than a substring. > > (that's why the 'r' was removed) > > Yes; strip works with characters. > > > Is there a builtin > > python method to strip leading substrings? Or do > > I have to do something using startswidth()? > > I would use a regexp. > > >>> tmp1 = '
real estate broker courtesy' > >>> import re > >>> re.sub('^
*', '', tmp1) > 'real estate broker courtesy' > >>> tmp1 = 'real estate broker courtesy' > >>> re.sub('^
*', '', tmp1) > 'real estate broker courtesy' > > > > Karl > -- > Please do *not* send copies of replies to me. > I read the list > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Tim Johnson http://www.alaska-internet-solutions.com From darnold02 at sprynet.com Mon Feb 2 17:11:22 2004 From: darnold02 at sprynet.com (don arnold) Date: Mon Feb 2 17:12:04 2004 Subject: [Tutor] lstrip() question References: <040e01c3e9bb$94a36c00$7210ba3f@don2uvsu54fwiq><20040202205755.GB13611@johnsons-web.com> Message-ID: <04fd01c3e9d9$817fd780$7210ba3f@don2uvsu54fwiq> ----- Original Message ----- From: "Karl Pfl?sterer" To: Sent: Monday, February 02, 2004 3:17 PM Subject: Re: [Tutor] lstrip() question > On 2 Feb 2004, Tim Johnson <- tim@johnsons-web.com wrote: > > > It appears that lstrip() will not do this > > as this console session using version 2.2.2 > > seems to demonstrate: > >>>> tmp1 = 'real estate broker courtesy' > >>>> tmp2 = tmp1.lstrip('
') > >>>> tmp2 > > 'eal estate broker courtesy' > > > It looks like '
' is being treated as > > a set rather than a substring. > > (that's why the 'r' was removed) > > Yes; strip works with characters. > > > Is there a builtin > > python method to strip leading substrings? Or do > > I have to do something using startswidth()? > > I would use a regexp. > > >>> tmp1 = '
real estate broker courtesy' > >>> import re > >>> re.sub('^
*', '', tmp1) > 'real estate broker courtesy' > >>> tmp1 = 'real estate broker courtesy' > >>> re.sub('^
*', '', tmp1) > 'real estate broker courtesy' > > Karl But this doesn't seem to quite work if there are multiple leading
's. >>> tmp = '

real estate
broker
' >>> import re >>> re.sub('^
*','',tmp) '
real estate
broker
' I don't know much about regexes, but is this because only the very first occurrence is considered to be at the beginning of the line? I'm sure there is a regex way to do it, but you could just use a simple loop and startswith(): >>> tmp2 = tmp >>> while tmp2.startswith('
'): tmp2 = tmp2[4:] >>> tmp2 'real estate
broker
' >>> tmp2 = '


' >>> while tmp2.startswith('
'): tmp2 = tmp2[4:] >>> tmp2 '' >>> HTH, Don From tim at johnsons-web.com Mon Feb 2 17:29:33 2004 From: tim at johnsons-web.com (Tim Johnson) Date: Mon Feb 2 17:25:22 2004 Subject: [Tutor] lstrip() question In-Reply-To: <04fd01c3e9d9$817fd780$7210ba3f@don2uvsu54fwiq> References: <040e01c3e9bb$94a36c00$7210ba3f@don2uvsu54fwiq> <20040202205755.GB13611@johnsons-web.com> <04fd01c3e9d9$817fd780$7210ba3f@don2uvsu54fwiq> Message-ID: <20040202222933.GE13611@johnsons-web.com> * don arnold [040202 13:22]: > ----- Original Message ----- > From: "Karl Pfl?sterer" > To: > Sent: Monday, February 02, 2004 3:17 PM > Subject: Re: [Tutor] lstrip() question > > > > > > I would use a regexp. > > > > >>> tmp1 = '
real estate broker courtesy' > > >>> import re > > >>> re.sub('^
*', '', tmp1) > > 'real estate broker courtesy' > > >>> tmp1 = 'real estate broker courtesy' > > >>> re.sub('^
*', '', tmp1) > > 'real estate broker courtesy' > > > > Karl > '
real estate
broker
' > > I don't know much about regexes, but is this because only the very first > occurrence is considered to be at the beginning of the line? I'm sure there > is a regex way to do it, but you could just use a simple loop and > startswith(): > > >>> tmp2 = tmp > >>> while tmp2.startswith('
'): tmp2 = tmp2[4:] > >>> tmp2 > 'real estate
broker
' > >>> tmp2 = '


' > >>> while tmp2.startswith('
'): tmp2 = tmp2[4:] > >>> tmp2 Actually what I am *really* looking for is a way to strip either specific tags (like '
' from the left *or* any number of tags. I'm a regex dunce myself, so am researching patterns as we speak, but your iteration is kind of what I have in mind. thanks! tj -- Tim Johnson http://www.alaska-internet-solutions.com From sigurd at 12move.de Mon Feb 2 18:27:37 2004 From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=) Date: Mon Feb 2 18:27:57 2004 Subject: [Tutor] lstrip() question In-Reply-To: <04fd01c3e9d9$817fd780$7210ba3f@don2uvsu54fwiq> (don arnold's message of "Mon, 2 Feb 2004 16:11:22 -0600") References: <040e01c3e9bb$94a36c00$7210ba3f@don2uvsu54fwiq> <20040202205755.GB13611@johnsons-web.com> <04fd01c3e9d9$817fd780$7210ba3f@don2uvsu54fwiq> Message-ID: On 2 Feb 2004, don arnold <- darnold02@sprynet.com wrote: > But this doesn't seem to quite work if there are multiple leading
's. >>>> tmp = '

real estate
broker
' >>>> import re >>>> re.sub('^
*','',tmp) > '
real estate
broker
' What Python version do you have; it seems to be broken. $ python Python 2.3.3 (#1, Dec 30 2003, 08:29:25) [GCC 3.3.1 (cygming special)] on cygwin Type "help", "copyright", "credits" or "license" for more information. >>> import re >>> s = '

foobar' >>> re.sub('
*', '', s) 'foobar' >>> tmp = '

real estate
broker
' >>> re.sub('
*', '', tmp) 'real estatebroker' >>> I can't reproduce your observation here. The regexp could be made better since a
tag should be written like this (HTML 4.01 and XHTML) >>> re.sub('*', '', tmp) 'real estatebroker' >>> > I don't know much about regexes, but is this because only the very first > occurrence is considered to be at the beginning of the line? I'm sure there No that can't be. There is something other wrong. Did you type it in exactly the way you posted it here? > is a regex way to do it, but you could just use a simple loop and > startswith(): That's possible but IMO extremly inefficient. Also with tags written as a mixture of
and
your loop couldn't be written so simple. Karl -- Please do *not* send copies of replies to me. I read the list From darnold02 at sprynet.com Mon Feb 2 18:48:02 2004 From: darnold02 at sprynet.com (don arnold) Date: Mon Feb 2 18:48:35 2004 Subject: [Tutor] lstrip() question References: <040e01c3e9bb$94a36c00$7210ba3f@don2uvsu54fwiq><20040202205755.GB13611@johnsons-web.com><04fd01c3e9d9$817fd780$7210ba3f@don2uvsu54fwiq> Message-ID: <058a01c3e9e6$ffc7f430$7210ba3f@don2uvsu54fwiq> ----- Original Message ----- From: "Karl Pfl?sterer" To: Sent: Monday, February 02, 2004 5:27 PM Subject: Re: [Tutor] lstrip() question > On 2 Feb 2004, don arnold <- darnold02@sprynet.com wrote: > > > But this doesn't seem to quite work if there are multiple leading
's. > > >>>> tmp = '

real estate
broker
' > >>>> import re > >>>> re.sub('^
*','',tmp) > > '
real estate
broker
' > > > What Python version do you have; it seems to be broken. > > $ python > Python 2.3.3 (#1, Dec 30 2003, 08:29:25) > [GCC 3.3.1 (cygming special)] on cygwin > Type "help", "copyright", "credits" or "license" for more information. > >>> import re > >>> s = '

foobar' > >>> re.sub('
*', '', s) > 'foobar' > >>> tmp = '

real estate
broker
' > >>> re.sub('
*', '', tmp) > 'real estatebroker' > >>> > Yes, but this regex doesn't have the initial caret ('^') that your original did. As a result, it removes all occurrences of the tag, not just the leading one(s). > I can't reproduce your observation here. > > The regexp could be made better since a
tag should be written > like this (HTML 4.01 and XHTML) > > >>> re.sub('*', '', tmp) > 'real estatebroker' > >>> > > > > I don't know much about regexes, but is this because only the very first > > occurrence is considered to be at the beginning of the line? I'm sure there > > No that can't be. There is something other wrong. Did you type it in > exactly the way you posted it here? > > > is a regex way to do it, but you could just use a simple loop and > > startswith(): > > That's possible but IMO extremly inefficient. Also with tags written as > a mixture of
and
your loop couldn't be written so simple. > > Karl No argument there. But the truth of the matter is that neither string methods nor regexes are very well-suited for parsing full-blown HTML. For that, you're probably better off using the HTMLParser module. Don From dyoo at hkn.eecs.berkeley.edu Mon Feb 2 18:58:27 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Feb 2 18:58:33 2004 Subject: [Tutor] lstrip() question In-Reply-To: Message-ID: > > But this doesn't seem to quite work if there are multiple leading
's. > > >>>> tmp = '

real estate
broker
' > >>>> import re > >>>> re.sub('^
*','',tmp) > > '
real estate
broker
' > > > What Python version do you have; it seems to be broken. > > $ python > Python 2.3.3 (#1, Dec 30 2003, 08:29:25) > [GCC 3.3.1 (cygming special)] on cygwin > Type "help", "copyright", "credits" or "license" for more information. > >>> import re > >>> s = '

foobar' > >>> re.sub('
*', '', s) > 'foobar' > >>> tmp = '

real estate
broker
' > >>> re.sub('
*', '', tmp) > 'real estatebroker' Hi Karl, No, the regular expression itself is broken. Here is one counterexample that should clearly show the problem: "
>>>hello" Try running that regular expression on this string, and see what gets replaced. The problem with the regex should be a little clearer then. To fix the problem, take a look at: http://www.amk.ca/python/howto/regex/ and look at section 4.2 on "Groups" --- using groups properly should fix the issue. Hope this helps! From sigurd at 12move.de Mon Feb 2 19:00:20 2004 From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=) Date: Mon Feb 2 19:02:46 2004 Subject: [Tutor] lstrip() question In-Reply-To: (Karl =?iso-8859-1?q?Pfl=E4sterer's?= message of "Tue, 03 Feb 2004 00:27:37 +0100") References: <040e01c3e9bb$94a36c00$7210ba3f@don2uvsu54fwiq> <20040202205755.GB13611@johnsons-web.com> <04fd01c3e9d9$817fd780$7210ba3f@don2uvsu54fwiq> Message-ID: On 3 Feb 2004, Karl Pfl?sterer <- sigurd@12move.de wrote: > On 2 Feb 2004, don arnold <- darnold02@sprynet.com wrote: >> But this doesn't seem to quite work if there are multiple leading
's. >>>>> tmp = '

real estate
broker
' >>>>> import re >>>>> re.sub('^
*','',tmp) >> '
real estate
broker
' > What Python version do you have; it seems to be broken. No what I wrote was broken; sorry. I forgot the parentheses around the regexp. I should be: re.sub('^(]*>)*','',tmp) See my other posting for a better approach. Karl -- Please do *not* send copies of replies to me. I read the list From tim at johnsons-web.com Mon Feb 2 19:14:49 2004 From: tim at johnsons-web.com (Tim Johnson) Date: Mon Feb 2 19:10:35 2004 Subject: [Tutor] lstrip() question In-Reply-To: References: <040e01c3e9bb$94a36c00$7210ba3f@don2uvsu54fwiq> <20040202205755.GB13611@johnsons-web.com> <04fd01c3e9d9$817fd780$7210ba3f@don2uvsu54fwiq> Message-ID: <20040203001449.GH13611@johnsons-web.com> This is what I have come up with thus far: Note: I need to reconstruct the 'stripped' breaks tags, thus the returned tuple, and I'm also stripping leading spaces from the original string. # ==================================================================================== # seperate leading break tags from rest of string. Ignore case def lparse_br(self,st): pattern = '\<[br|BR|Br|bR]+\>' #for br tag tmp = st.lstrip() # remove leading spaces found = re.match(pattern,st) if found: brks = 1 tmp1 = tmp[4:] while 1: found = re.match(pattern,tmp1) if found: brks = brks + 1 tmp1 = tmp1[4:] else: break return brks * '
',''.join(tmp1) else: return '',tmp I've run a couple of tests that appear to succeed, but observations are welcome. All help so far has been greatly appreciated. Regards tim -- Tim Johnson http://www.alaska-internet-solutions.com From tim at johnsons-web.com Mon Feb 2 20:08:08 2004 From: tim at johnsons-web.com (Tim Johnson) Date: Mon Feb 2 20:03:55 2004 Subject: [Tutor] lstrip() question In-Reply-To: References: Message-ID: <20040203010808.GI13611@johnsons-web.com> * Simoni, Bill [040202 13:22]: > > Hello All: > > I'd like to remove all leading occurance of a html break tag > > in a string such that > > "

test" => "test" > > and > > "
test
this" =>"test
this" > > > Hi Tim, > off the top of my head, I came up with this: > > >>> def repstrip(s, sub): > if s.startswith(sub): > s = repstrip(s[len(sub):], sub) #strip the leading characters that match and try it again > return s > > >>> print repstrip('real estate broker courtesy', '
') > real estate broker courtesy > > >>> print repstrip('
real estate broker courtesy', '
') > real estate broker courtesy > > >>> print repstrip('

real estate broker courtesy', '
') > real estate broker courtesy > > >>> print repstrip('

real estate
broker courtesy', '
') > real estate
broker courtesy Hi Bill: I liked that, so I modified it to the following: # ========================================================================================================== def repstrip(st, substr, reps=0): s = st.lower() sub = substr.lower() if s.startswith(sub): reps = reps + 1 # keep track of number of replacements reps,s = repstrip(s[len(sub):], sub, reps) #strip the leading characters that match and try it again return reps,st[(reps * len(sub)):] # This allows me to reconstruct the leading tags. -- Tim Johnson http://www.alaska-internet-solutions.com From sigurd at 12move.de Mon Feb 2 20:38:00 2004 From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=) Date: Mon Feb 2 20:40:24 2004 Subject: [Tutor] lstrip() question In-Reply-To: <20040202222933.GE13611@johnsons-web.com> (Tim Johnson's message of "Mon, 2 Feb 2004 13:29:33 -0900") References: <040e01c3e9bb$94a36c00$7210ba3f@don2uvsu54fwiq> <20040202205755.GB13611@johnsons-web.com> <04fd01c3e9d9$817fd780$7210ba3f@don2uvsu54fwiq> <20040202222933.GE13611@johnsons-web.com> Message-ID: On 2 Feb 2004, Tim Johnson <- tim@johnsons-web.com wrote: > Actually what I am *really* looking for is a way to > strip either specific tags (like '
' from the > left *or* any number of tags. I'm a regex dunce I think I forgot the parentheses in my first example. But as you describe your problem now a simple regexp won't suffice. To strip off all tags is simple; As a function (now also case-insensitive and includes line breaks): def strip_tags (string): return re.sub('^(?is)(<[^<>]*>)*', '', string) But to strip specific tags you need e.g.: def strip_tags (string, tag=''): L = re.split('(<[^<>]*>)', string) for token in L[:]: if re.match('<.*>', token, re.S) or token == '': if re.search(tag, token, re.I|re.S): L.remove(token) else: return ''.join(L) >>> tmp = '

real estate
broker
' >>> strip_tags(tmp, 'foo') '

real estate
broker
' >>> strip_tags(tmp, 'foo|bar') '

real estate
broker
' >>> strip_tags(tmp) 'real estate
broker
' Above will split your string with the tags as seperators. Then the code iterates over the list, looks if the next token is a tag (if not all tags from the left have been processed and the joined list is returned) or an empty string, tries to match the code against the tag names to be removed and if it finds a match removes exactly that token from the list. Above code iterates over a copy of the list since it's not good to change the list which is iterated over. If you don't give a tag name (actually a regexp) the empty string is used which matches every tag. Karl -- Please do *not* send copies of replies to me. I read the list From sigurd at 12move.de Mon Feb 2 20:39:58 2004 From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=) Date: Mon Feb 2 20:40:27 2004 Subject: [Tutor] lstrip() question In-Reply-To: (Danny Yoo's message of "Mon, 2 Feb 2004 15:58:27 -0800 (PST)") References: Message-ID: On 3 Feb 2004, Danny Yoo <- dyoo@hkn.eecs.berkeley.edu wrote: > No, the regular expression itself is broken. Here is one counterexample > that should clearly show the problem: Yea I know; I wrote it yet in another posting *blush*. I forgot the parentheses. Karl -- Please do *not* send copies of replies to me. I read the list From sigurd at 12move.de Mon Feb 2 21:00:06 2004 From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=) Date: Mon Feb 2 21:00:41 2004 Subject: [Tutor] lstrip() question In-Reply-To: <20040203001449.GH13611@johnsons-web.com> (Tim Johnson's message of "Mon, 2 Feb 2004 15:14:49 -0900") References: <040e01c3e9bb$94a36c00$7210ba3f@don2uvsu54fwiq> <20040202205755.GB13611@johnsons-web.com> <04fd01c3e9d9$817fd780$7210ba3f@don2uvsu54fwiq> <20040203001449.GH13611@johnsons-web.com> Message-ID: On 3 Feb 2004, Tim Johnson <- tim@johnsons-web.com wrote: > This is what I have come up with thus far: > Note: I need to reconstruct the 'stripped' breaks tags, > thus the returned tuple, and I'm also stripping leading spaces > from the original string. Could you explain what exactly you want to achieve and which kind of input you expect? In another posting you wrote you wanted to strip specific tags from the left. That here is completely different. > # ==================================================================================== > # seperate leading break tags from rest of string. Ignore case > def lparse_br(self,st): > pattern = '\<[br|BR|Br|bR]+\>' #for br tag That's not necessary. Regexps can be declared case-insensitive. Why the backslashes? I'm not sure that this pattern does what you want it to do. Could you explain (in words) what you want to find?. For e.g the above matches: >>> re.match(pattern, '') <_sre.SRE_Match object at 0xb08ad8> I think you meant: pattern = '(?i)<(br)>' >>> pattern = '(?i)<(br)>' >>> re.match(pattern, '') >>> re.match(pattern, '
') <_sre.SRE_Match object at 0xaf7120> But that won't find all kind of
tags (XHTML tags won't be found). See my other posting for an example. But since you need the tags you have to change that code. The best is you explain what you want to achieve. > tmp = st.lstrip() # remove leading spaces > found = re.match(pattern,st) Did you mean st here? Do you know about the difference betwenn `match' and `search'? HTH Karl -- Please do *not* send copies of replies to me. I read the list From dyoo at hkn.eecs.berkeley.edu Mon Feb 2 21:47:48 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Feb 2 21:47:54 2004 Subject: [Tutor] lstrip() question In-Reply-To: <20040202205755.GB13611@johnsons-web.com> Message-ID: On Mon, 2 Feb 2004, Tim Johnson wrote: > I'd like to remove all leading occurance of a html break tag in a > string such that "

test" => "test" and "
test
this" > =>"test
this" Hi Tim, Just out of curiosity, why are you trying to do this? Would it be possible to use something like HTMLParser? http://www.python.org/doc/lib/module-HTMLParser.html I know it sounds like using the library might be overkill, but HTMLParser is meant to deal with the ugliness that is HTML. It can handle some strange situations like ### s = """


this is a test""" ### where a regular expression for this might be more subtle than we might expect. (The example above is meant to be a nightmare case. *grin*) Using a real HTML parser normalizes this wackiness so that we don't see it. Here's a subclass of HTMLParser that shows how we might use it for the problem: ### from HTMLParser import HTMLParser class IgnoreLeadingBreaksParser(HTMLParser): def __init__(self): HTMLParser.__init__(self) self.seen_nonbreak_tag = False self.text = [] def get_text(self): return ''.join(self.text) def handle_starttag(self, tag, attrs): if tag != 'br': self.seen_nonbreak_tag = True if self.seen_nonbreak_tag: self.text.append(self.get_starttag_text()) def handle_endtag(self, tag): if tag != 'br': self.seen_nonbreak_tag = True if self.seen_nonbreak_tag: self.text.append('' % tag) def handle_data(self, data): self.seen_nonbreak_tag = True self.text.append(data) def ignore_leading_breaks(text): parser = IgnoreLeadingBreaksParser() parser.feed(text) return parser.get_text() ### Note: this is not quite production-quality yet. In particular, it doesn't handle comments or character references, so we may need to add more methods to the IgnoreLeadingBreaksParser so that it handles those cases too. Hope this helps! From dyoo at hkn.eecs.berkeley.edu Mon Feb 2 22:10:27 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Feb 2 22:10:31 2004 Subject: [Tutor] "=" invalid syntax ? [Assignment grammar stuff] (fwd) Message-ID: [Forwarding to Tutor --- slightly busy at the moment. Sorry!] ---------- Forwarded message ---------- Date: Sun, 1 Feb 2004 12:02:11 -0500 From: orbitz@ezabel.com To: Danny Yoo Subject: Re: [Tutor] "=" invalid syntax ? [Assignment grammar stuff] Hey thanks, i just learned it was special cased recently and didn't really understand it that well. Thanks for putting some work into explaining it. Do you know, off the top of your head, any other special cased things like that. Another one someone showed me was: x, y = [1,2] Also, in an lvalue, if i do (x, y) = [1,2] The () don't make it a tuple in such a situtaion do they? Thanks On Sat, 31 Jan 2004 21:19:44 -0800 (PST) Danny Yoo wrote: > > > On Sat, 31 Jan 2004 orbitz@ezabel.com wrote: > > > I just learned this recently, but if you say = is a statement then > > you would imagine: > > > > a = b = 2 to not work. = is actually special cased for this to work. > > however > > a = (b = 2) does not work. There is some 'magic' some people might > > say to =, but I think a = b = .. is the only excpetion to the = is a > > statement operator rule. > > Hi orbitz, > > > If people are interested in how it's special cased, the Reference > Manual has the gory details. *grin* > > > The grammar definition in: > > http://www.python.org/doc/ref/assignment.html > > shows that > > assignment_stmt ::= (target_list "=")+ expression_list > > > That is, an assignment statement is made up of a number of targets, > followed by the expression that will be assigned to those targets. > Usually, we define a single target, but nothing stops us from defining > multiple targets. If we're looking at somthing like: > > a = b = 2 > > then we can see that > > a = b = matches (target_list "=")+ > > and > > 2 matches expression_list > > > > If we look at the grammar, we can also see that assignment allows for > a limited form of pattern matching --- it's possible to say something > like: > > ### > >>> p1 = (x1, y1) = (3, 17) > >>> p1 > (3, 17) > >>> x1 > 3 > >>> y1 > 17 > ### > > > Hope this helps! > From matthewmhoffman at hotmail.com Mon Feb 2 23:36:50 2004 From: matthewmhoffman at hotmail.com (Matthew Hoffman) Date: Mon Feb 2 23:36:56 2004 Subject: [Tutor] Simple ROT-13 Script Message-ID: Hello all! I have been reading this list for a goodly amount of time and have never felt worthy to submit a question until now. I just wrote a quick one-off script and I would like your opinions on any Python-isms. It's just a ROT-13 script (I got a Neal Stephenson book for xmas). I would just like to entertain your thoughts about what I could have done better, etc. Cheers! ~Matt #! /usr/bin/python encrypt = lambda s: chr(ord(s) + 13) decrypt = lambda s: chr(ord(s) - 13) s = 'guido' r = map(encrypt, s) t = map(decrypt, r) >>>r ['t', '\x82', 'v', 'q', '|'] >>>t ['g', 'u', 'i', 'd', 'o'] _________________________________________________________________ Find high-speed ‘net deals — comparison-shop your local providers here. https://broadband.msn.com From alan.gauld at blueyonder.co.uk Tue Feb 3 01:31:08 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Tue Feb 3 01:32:31 2004 Subject: [Tutor] Concatenating Strings into Variable Names? References: <20040202131208.F4F781C0.xthereal@bigfoot.com> Message-ID: <016f01c3ea1f$4f53e5d0$6401a8c0@xp> > I'm trying to write my first program besides good old hello world. Is > there a way to concatenate strings into a variable name? There is, but it's nearly always the wrong thing to do. Instead use a dictionary. > Here's a > brief example of what i'm trying to do: > options = {} options['choiceA_option1']= 2.0 options['choiceA_option2']= 3.0 etc... > choice=raw_input("Do you want choice A or B?") > option=raw_input("Do you want option 1 or 2?") > > the_answer="choice" + choice + "_option" + option > > print options[the_answer] There is another example of this at the end of the OOP topic on my web site. HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at blueyonder.co.uk Tue Feb 3 01:34:06 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Tue Feb 3 01:35:29 2004 Subject: [Tutor] Concatenating Strings into Variable Names? References: <20040202131208.F4F781C0.xthereal@bigfoot.com> <1075748793.4059.43.camel@vaio> Message-ID: <017601c3ea1f$b90eb360$6401a8c0@xp> > You can test these out: > > try: > print eval('the_answer') > except: > "Invalid choice" But using eval() on user input is potentially dangerous since it could be a malicious value. In this case because we add the "Choice" string etc its probably safe, but in general eval() is a risky choice. Alan G. From alan.gauld at blueyonder.co.uk Tue Feb 3 01:35:57 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Tue Feb 3 01:37:20 2004 Subject: [Tutor] lstrip() question References: <040e01c3e9bb$94a36c00$7210ba3f@don2uvsu54fwiq> <20040202205755.GB13611@johnsons-web.com> Message-ID: <017d01c3ea1f$fb51e580$6401a8c0@xp> > Is there a builtin > python method to strip leading substrings? Or do > I have to do something using startswidth()? Try the string.replace() function? Just replace the substring with an empty string. Alan G. From alan.gauld at blueyonder.co.uk Tue Feb 3 01:37:53 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Tue Feb 3 01:39:16 2004 Subject: [Tutor] lstrip() question References: <040e01c3e9bb$94a36c00$7210ba3f@don2uvsu54fwiq><20040202205755.GB13611@johnsons-web.com> <20040202215422.GC13611@johnsons-web.com> Message-ID: <018601c3ea20$407728f0$6401a8c0@xp> Things Karl. Right on the money! > I would use a regexp. > > >>> tmp1 = '
real estate broker courtesy' > >>> import re > >>> re.sub('^
*', '', tmp1) > 'real estate broker courtesy' > >>> tmp1 = 'real estate broker courtesy' > >>> re.sub('^
*', '', tmp1) > 'real estate broker courtesy' A simple string replace is cheaper than a regex in this case - you know the string in advance. But in practice the difference isn't likely to be serious! Alan G. From dyoo at hkn.eecs.berkeley.edu Tue Feb 3 02:31:08 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Feb 3 02:31:13 2004 Subject: [Tutor] Simple ROT-13 Script In-Reply-To: Message-ID: On Mon, 2 Feb 2004, Matthew Hoffman wrote: > I just wrote a quick one-off script and I would like your opinions on > any Python-isms. It's just a ROT-13 script (I got a Neal Stephenson book > for xmas). I would just like to entertain your thoughts about what I > could have done better, etc. Cheers! ~Matt > encrypt = lambda s: chr(ord(s) + 13) > decrypt = lambda s: chr(ord(s) - 13) > > s = 'guido' > r = map(encrypt, s) > t = map(decrypt, r) > > >>>r > ['t', '\x82', 'v', 'q', '|'] > >>>t > ['g', 'u', 'i', 'd', 'o'] Hi Matt, Cool! Can you make the character rotation wrap around? At the moment, the letter 'u' is getting rotated to '\x82', but it should really wrap around to 'h'. You may find the remainder operator '%' useful to do the wrap-around: ### >>> for i in range(10): ... print i % 3 ... 0 1 2 0 1 2 0 1 2 0 ### Good luck! From dyoo at hkn.eecs.berkeley.edu Tue Feb 3 02:58:50 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Feb 3 02:58:54 2004 Subject: [Tutor] "=" invalid syntax ? [Assignment grammar stuff] (fwd) In-Reply-To: Message-ID: > Do you know, off the top of your head, any other special cased things > like that. Hi orbitz, Nope... Can't remember a thing. *grin* Thank goodness for Google. > Another one someone showed me was: > > x, y = [1,2] Yes, this works too, because [1, 2] is treated as a sequence. Here's the official word from the reference docs: """If the target is a target list enclosed in parentheses or in square brackets: The object must be a sequence with the same number of items as there are targets in the target list, and its items are assigned, from left to right, to the corresponding targets.""" (http://www.python.org/doc/ref/assignment.html) So that part of the definition covers the case when we say: x, y = [1, 2] Hmmm... I wonder, though... ### >>> def test_iterator(): ... yield 1 ... yield 2 ... >>> x, y = test_iterator() >>> x 1 >>> y 2 ### It looks like tuple unpacking works even on iterators. If we know exactly how many things are coming out of an iteration, we can use tuple assignment. Not that we'd ever do this, but still neat. *grin* > Also, in an lvalue, if i do > > (x, y) = [1,2] > > The () don't make it a tuple in such a situtaion do they? The documentation implies that it treats the left hand side as a bunch of targets, so I don't think it constructs an intermediate tuple with them. But that's just a guess. We can check this! ### >>> l = [1, 2] >>> def t1(): ... x = l[1] ... y = l[2] ... >>> def t2(): ... x, y = l[1], l[2] ... >>> def t3(): ... x, y = l ... >>> import dis ### The 'dis' module provides a very low-level "disassembly" view of what Python really thinks a function is doing. Here's some sample output: ### >>> dis.dis(t1) 2 0 LOAD_GLOBAL 0 (l) 3 LOAD_CONST 1 (1) 6 BINARY_SUBSCR 7 STORE_FAST 1 (x) 3 10 LOAD_GLOBAL 0 (l) 13 LOAD_CONST 2 (2) 16 BINARY_SUBSCR 17 STORE_FAST 0 (y) 20 LOAD_CONST 0 (None) 23 RETURN_VALUE >>> dis.dis(t2) 2 0 LOAD_GLOBAL 0 (l) 3 LOAD_CONST 1 (1) 6 BINARY_SUBSCR 7 LOAD_GLOBAL 0 (l) 10 LOAD_CONST 2 (2) 13 BINARY_SUBSCR 14 BUILD_TUPLE 2 17 UNPACK_SEQUENCE 2 20 STORE_FAST 1 (x) 23 STORE_FAST 0 (y) 26 LOAD_CONST 0 (None) 29 RETURN_VALUE >>> dis.dis(t3) 2 0 LOAD_GLOBAL 0 (l) 3 UNPACK_SEQUENCE 2 6 STORE_FAST 1 (x) 9 STORE_FAST 0 (y) 12 LOAD_CONST 0 (None) 15 RETURN_VALUE ### You don't have to understand everything here. But just from casual comparison, we can see that the disassembly of t1() and t3() shows that Python isn't constructing a tuple, so we can definitively say that tuple assignment doesn't make a tuple for the lvalue. Whew; I had felt a little uncomfortable about guessing. *grin* By the way, in t2(), Python does construct a tuple, but that's because Python's evaluating the right hand side of: x, y = l[1], l[2] and constructing the tuple (l[1], l[2]) before doing the tuple assignment. So Python has to fully evaluate the right hand side before doing assignments, and if it means it needs to create an intermediate tuple, it does so. This explains why we can do swapping like this: x, y = y, x because Python first creates an intermediate tuple with the values of 'y' and 'x', and then assigns that rvalue tuple to 'x' and 'y'. Hope this helps! From darnold02 at sprynet.com Tue Feb 3 07:24:54 2004 From: darnold02 at sprynet.com (don arnold) Date: Tue Feb 3 07:25:06 2004 Subject: [Tutor] Simple ROT-13 Script References: Message-ID: <06ff01c3ea50$bbfc6730$7210ba3f@don2uvsu54fwiq> ----- Original Message ----- From: "Danny Yoo" To: "Matthew Hoffman" Cc: Sent: Tuesday, February 03, 2004 1:31 AM Subject: Re: [Tutor] Simple ROT-13 Script > > > On Mon, 2 Feb 2004, Matthew Hoffman wrote: > > > I just wrote a quick one-off script and I would like your opinions on > > any Python-isms. It's just a ROT-13 script (I got a Neal Stephenson book > > for xmas). I would just like to entertain your thoughts about what I > > could have done better, etc. Cheers! ~Matt > > > encrypt = lambda s: chr(ord(s) + 13) > > decrypt = lambda s: chr(ord(s) - 13) > > > > s = 'guido' > > r = map(encrypt, s) > > t = map(decrypt, r) > > > > >>>r > > ['t', '\x82', 'v', 'q', '|'] > > >>>t > > ['g', 'u', 'i', 'd', 'o'] > > > Hi Matt, > > Cool! Can you make the character rotation wrap around? At the moment, > the letter 'u' is getting rotated to '\x82', but it should really wrap > around to 'h'. > And in case you didn't know, the reason you want it to wrap around is so that you only need a single rot13() function, not individual encrypt() and decrypt() functions: >>> print rot13('abc') nop >>> print rot13('nop') abc HTH, Don From sigurd at 12move.de Tue Feb 3 09:13:09 2004 From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=) Date: Tue Feb 3 09:18:21 2004 Subject: [Tutor] Simple ROT-13 Script In-Reply-To: <06ff01c3ea50$bbfc6730$7210ba3f@don2uvsu54fwiq> (don arnold's message of "Tue, 3 Feb 2004 06:24:54 -0600") References: <06ff01c3ea50$bbfc6730$7210ba3f@don2uvsu54fwiq> Message-ID: On 3 Feb 2004, don arnold <- darnold02@sprynet.com wrote: > And in case you didn't know, the reason you want it to wrap around is so > that you only need a single rot13() function, not individual encrypt() and > decrypt() functions: >>>> print rot13('abc') > nop >>>> print rot13('nop') > abc Right. And you should take care, that only characters are moved. Numbers or punctuation signs e.g. are not touched. >>> s = "Guido 123; Tim 456" >>> s.encode('rot13') 'Thvqb 123; Gvz 456' >>> _.encode('rot13') 'Guido 123; Tim 456' >>> Karl -- Please do *not* send copies of replies to me. I read the list From python.tutorial at jarava.org Tue Feb 3 11:09:22 2004 From: python.tutorial at jarava.org (Javier JJ) Date: Tue Feb 3 11:09:28 2004 Subject: [Tutor] Simple ROT-13 Script In-Reply-To: References: <06ff01c3ea50$bbfc6730$7210ba3f@don2uvsu54fwiq> Message-ID: <401FC7B2.9040008@jarava.org> And the reason that it wont' work on other than ASCII.- strings ?? I mean: >>> s = "asasas" >>> s.encode("rot13") 'nfnfnf' >>> type(s) >>> s = "aaa???aaaaaaaa" >>> s 'aaa\xf1\xf1\xf1aaaaaaaa' >>> type(s) >>> s.encode("rot13") Traceback (most recent call last): File "", line 1, in ? File "C:\Python23\lib\encodings\rot_13.py", line 18, in encode return codecs.charmap_encode(input,errors,encoding_map) UnicodeDecodeError: 'ascii' codec can't decode byte 0xf1 in position 3: ordinal not in range(128) >>> ???????? Thanks a lot... Javier Jarava On this day, 03/02/2004 15:13, Karl Pfl?sterer wrote: >On 3 Feb 2004, don arnold <- darnold02@sprynet.com wrote: > > > >>And in case you didn't know, the reason you want it to wrap around is so >>that you only need a single rot13() function, not individual encrypt() and >>decrypt() functions: >> >> > > > >>>>>print rot13('abc') >>>>> >>>>> >>nop >> >> >>>>>print rot13('nop') >>>>> >>>>> >>abc >> >> > >Right. And you should take care, that only characters are moved. >Numbers or punctuation signs e.g. are not touched. > > > >>>>s = "Guido 123; Tim 456" >>>>s.encode('rot13') >>>> >>>> >'Thvqb 123; Gvz 456' > > >>>>_.encode('rot13') >>>> >>>> >'Guido 123; Tim 456' > > > > > > Karl > > From tim at johnsons-web.com Tue Feb 3 11:42:45 2004 From: tim at johnsons-web.com (Tim Johnson) Date: Tue Feb 3 11:38:30 2004 Subject: [Tutor] lstrip() question(Thanks all!) In-Reply-To: References: <20040202205755.GB13611@johnsons-web.com> Message-ID: <20040203164245.GJ13611@johnsons-web.com> Hello All: I wish I had that time to thank every one on this topic and respond to all your comments, but I'm laboring over a hot keyboard and trying to beat a deadline. I solved my problem and got a very large amount of informative input. My thanks to all of you! Regards tim * Danny Yoo [040202 18:00]: > Just out of curiosity, why are you trying to do this? Would it be > possible to use something like HTMLParser? > > http://www.python.org/doc/lib/module-HTMLParser.html > > I know it sounds like using the library might be overkill, but HTMLParser > is meant to deal with the ugliness that is HTML. It can handle some > strange situations like > > > ### > s = """
>

this is a test""" > ### > > > where a regular expression for this might be more subtle than we might > expect. (The example above is meant to be a nightmare case. *grin*) > > > Using a real HTML parser normalizes this wackiness so that we don't see > it. Here's a subclass of HTMLParser that shows how we might use it for > the problem: > > > ### > from HTMLParser import HTMLParser > > class IgnoreLeadingBreaksParser(HTMLParser): > def __init__(self): > HTMLParser.__init__(self) > self.seen_nonbreak_tag = False > self.text = [] > > def get_text(self): > return ''.join(self.text) > > def handle_starttag(self, tag, attrs): > if tag != 'br': > self.seen_nonbreak_tag = True > if self.seen_nonbreak_tag: > self.text.append(self.get_starttag_text()) > > def handle_endtag(self, tag): > if tag != 'br': > self.seen_nonbreak_tag = True > if self.seen_nonbreak_tag: > self.text.append('' % tag) > > def handle_data(self, data): > self.seen_nonbreak_tag = True > self.text.append(data) > > > def ignore_leading_breaks(text): > parser = IgnoreLeadingBreaksParser() > parser.feed(text) > return parser.get_text() > ### > > > Note: this is not quite production-quality yet. In particular, it doesn't > handle comments or character references, so we may need to add more > methods to the IgnoreLeadingBreaksParser so that it handles those cases > too. > > > Hope this helps! -- Tim Johnson http://www.alaska-internet-solutions.com From barrys at datatree.co.uk Mon Feb 2 09:50:17 2004 From: barrys at datatree.co.uk (Barry Smithers) Date: Tue Feb 3 12:40:19 2004 Subject: [Tutor] Using Python with VI Message-ID: <00a801c3e99b$dfb52820$b364a8c0@datatree> Hello everyone. I'm having difficulty with a program call from inside of VI. What I basically need to do is get the line numbers input in the ex command. Or maybe even get the text on those lines to go into a list. For example the ex command ":20,21!xxx.py" would run xxx.py as a whole, but I need the data currently on lines 20 and 21 for modification. Can anyone help?? Cheers Barry From ganjeali at hotmail.com Mon Feb 2 03:16:10 2004 From: ganjeali at hotmail.com (Meisam Ganjeali darani) Date: Tue Feb 3 12:42:51 2004 Subject: [Tutor] (no subject) Message-ID: Hi Thanks for your help. I have some question about python. How I can run python in my system? My system platform is windows Thank you. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040202/fb2b50f6/attachment.html From dyoo at hkn.eecs.berkeley.edu Tue Feb 3 12:56:23 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Feb 3 12:56:30 2004 Subject: [Tutor] (no subject) In-Reply-To: <3119.63.225.172.24.1075552557.squirrel@mail.zoper.com> Message-ID: > Also, this is my first email to a list like this one, so I'm wondering > if I'm observing proper social conventions. This message feels kind of > long to me. What do you think? Hi Dana, Welcome aboard! Your message is fine, but make sure to add a "subject line" on your email, so that it's easier for people to find your message. (Also, if you haven't already, you may want to subscribe to Tutor --- otherwise, your messages will be held until one of the lazy admins here gets a chance to validate the message for non-spaminess. The page: http://mail.python.org/mailman/listinfo/tutor explains how to subscribe to Python-Tutor.) Let's take a look at the InteractiveURLParser: > class InteractiveURLParser(HTMLParser.HTMLParser): > def open(self, URL): > page = getPage(URL) > page = flattenPage(page) > self.feed(page) > def newURL(self, URL): > __init__(self, URL) > def handle_starttag(self, tag, attrs): > print "tag is %s with attributes %s." %(self, tag, attrs) > def handle_data(self, data): > print data There are two issues I can see so far: the newURL method looks a little weird, and there's a bug in handle_starttag(). Let's cover the newURL() method briefly: > def newURL(self, URL): > __init__(self, URL) This looks a little weird because no __init__ method has yet been defined. Can you explain what newURL is trying to do? And do you need it? I don't see anything in the code that uses it, so maybe it can be removed? Let's take a look at handle_starttag(): > def handle_starttag(self, tag, attrs): > print "tag is %s with attributes %s." %(self, tag, attrs) ^^ ^^ ^^^^ ^^^ ^^^^^ There are two formatting positions in the string, but the code is trying to fill it up with three things. Given that, does the error message: > File "r.py", line 31, in handle_starttag > print "tag is %s with attributes %s." %(self, tag, attrs) > TypeError: not all arguments converted during string formatting make sense now? Talk to you later! From sigurd at 12move.de Tue Feb 3 12:59:32 2004 From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=) Date: Tue Feb 3 13:03:55 2004 Subject: [Tutor] Simple ROT-13 Script In-Reply-To: <401FC7B2.9040008@jarava.org> (Javier JJ's message of "Tue, 03 Feb 2004 17:09:22 +0100") References: <06ff01c3ea50$bbfc6730$7210ba3f@don2uvsu54fwiq> <401FC7B2.9040008@jarava.org> Message-ID: On 3 Feb 2004, Javier JJ <- python.tutorial@jarava.org wrote: > And the reason that it wont' work on other than ASCII.- strings ?? [...] > Traceback (most recent call last): > File "", line 1, in ? > File "C:\Python23\lib\encodings\rot_13.py", line 18, in encode > return codecs.charmap_encode(input,errors,encoding_map) > UnicodeDecodeError: 'ascii' codec can't decode byte 0xf1 in position > 3: ordinal not in range(128) > >>> ^^^^^^^^^^^ The reason is here ; the error code says that that function only works for characters in the ASCII range. If you see how you do rot13 with pen and paer it's clear why it's so: >>> alph = ''.join(map(chr, range(ord('a'), ord('z')+1))) >>> alphrot = alph[13:] + alph[:13] >>> alph 'abcdefghijklmnopqrstuvwxyz' >>> alphrot 'nopqrstuvwxyzabcdefghijklm' >>> Look at the alphabet and how it's mapped: a b c d e f g h i j k l m n o p q r s t u v w x y z | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | n o p q r s t u v w x y z a b c d e f g h i j k l m The same is true capitals. Now if you wanted to include other characters you (the sender == encrypting person) and the reader (== decrypting person) must agree where to place these additional characters. Since this is most of the time not possible normally rot13 is only applied to characters in the ASCII range. I found it interesting to write a small Python solution on how to do a caesar chiffre and came up with the following (rot13 encrypted): qrs znxr_gnoyr (*netf): gnoyr = {} sbe ghc va netf: fgp, raqp, qvf = ghc nycu = ''.wbva(znc(pue, enatr(beq(fgp), beq(raqp)+1))) nycuebg = nycu[qvf:] + nycu[:qvf] gnoyr.hcqngr(qvpg(mvc(nycu, nycuebg))) erghea gnoyr qrs znxr_gnoyr (*netf): gnoyr = {} sbe ghc va netf: fgp, raqp, qvf = ghc fga, raqa = beq(fgp), beq(raqp) jvqgu = raqa - fga + 1 sbe p va enatr(fga, raqa + 1): gnoyr[pue(p)] = pue((p - fga + qvf) % jvqgu + fga) erghea gnoyr qrs ebg_a (frd, goy): erghea ''.wbva(znc(ynzoqn p: goy.trg(p, p), frd)) qrs ebg13 (frd, goy = znxr_gnoyr(('n', 'm', 13), ('N', 'M', 13))): erghea ebg_a(frd, goy) There are two alternative functions to generate a table; that table is used to find a substitution for a character in the rot13 function. You could add in that table mappings for additional characters if you liked. Karl -- Please do *not* send copies of replies to me. I read the list From philip at pacer.co.za Tue Feb 3 13:08:59 2004 From: philip at pacer.co.za (philip gilchrist) Date: Tue Feb 3 13:09:00 2004 Subject: [Tutor] Maths (slightly OT) Message-ID: <598B5E93DCDC614C9C1FE22406A0F5BE36CD@pacer-server.pacer.local> Hi Pythoners My Son has challenged me to name a few careers that would use Maths exponents and all the calculations in them as a way of getting out of learning them. Obviously, programming and basically anything to do with Computers is foremost in the answer, but I was hoping that you studious types would be able to supply me with more than the obvious answer. Hoping to hear from all the career people that can use Mathematical Calculations on a regular basis. regards, Philip -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040203/b09d268e/attachment.html From gerrit at nl.linux.org Tue Feb 3 13:18:43 2004 From: gerrit at nl.linux.org (Gerrit Holl) Date: Tue Feb 3 13:20:46 2004 Subject: [Tutor] Maths (slightly OT) In-Reply-To: <598B5E93DCDC614C9C1FE22406A0F5BE36CD@pacer-server.pacer.local> References: <598B5E93DCDC614C9C1FE22406A0F5BE36CD@pacer-server.pacer.local> Message-ID: <20040203181843.GA5060@nl.linux.org> philip gilchrist wrote: > My Son has challenged me to name a few careers that would use Maths > exponents and all the calculations in them as a way of getting out of > learning them. Obviously, programming and basically anything to do with > Computers is foremost in the answer, but I was hoping that you studious > types would be able to supply me with more than the obvious answer. > > Hoping to hear from all the career people that can use Mathematical > Calculations on a regular basis. Physists use a lot more math than computer people. I'm only in my first year of a Physics course, but to name a popular example, you can't send a rocket into the space without a **lot** of mathematics. Gerrit. -- PrePEP: Builtin path type http://people.nl.linux.org/~gerrit/creaties/path/pep-xxxx.html Asperger's Syndrome - a personal approach: http://people.nl.linux.org/~gerrit/english/ From littledanehren at yahoo.com Tue Feb 3 13:43:48 2004 From: littledanehren at yahoo.com (Daniel Ehrenberg) Date: Tue Feb 3 13:43:53 2004 Subject: [Tutor] Simple ROT-13 Script In-Reply-To: <401FC7B2.9040008@jarava.org> Message-ID: <20040203184348.54136.qmail@web41803.mail.yahoo.com> Javier JJ wrote: > And the reason that it wont' work on other than > ASCII.- strings ?? > > I mean: > > >>> s = "asasas" > >>> s.encode("rot13") > 'nfnfnf' > >>> type(s) > > > >>> s = "aaañññaaaaaaaa" > >>> s > 'aaa\xf1\xf1\xf1aaaaaaaa' > >>> type(s) > > >>> s.encode("rot13") > Traceback (most recent call last): > File "", line 1, in ? > File "C:\Python23\lib\encodings\rot_13.py", line > 18, in encode > return > codecs.charmap_encode(input,errors,encoding_map) > UnicodeDecodeError: 'ascii' codec can't decode byte > 0xf1 in position 3: > ordinal not in range(128) > >>> > > ¿¿¿????? > > Thanks a lot... > > Javier Jarava What would you expect that to be encoded as? There's no a with a ~ over it. rot13 is only made to work with ASCII. If you wanted the accent marks to just be removed, you might want to define your own rot13 function. Daniel Ehrenberg __________________________________ Do you Yahoo!? Yahoo! SiteBuilder - Free web site building tool. Try it! http://webhosting.yahoo.com/ps/sb/ From op73418 at mail.telepac.pt Tue Feb 3 14:19:03 2004 From: op73418 at mail.telepac.pt (=?ISO-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Tue Feb 3 14:16:40 2004 Subject: [Tutor] Maths (slightly OT) In-Reply-To: <598B5E93DCDC614C9C1FE22406A0F5BE36CD@pacer-server.pacer.local> References: <598B5E93DCDC614C9C1FE22406A0F5BE36CD@pacer-server.pacer.local> Message-ID: <2ksv1090cbgemb7m8grftehtbu5c8tvcfh@4ax.com> Em Tue, 3 Feb 2004 20:08:59 +0200, "philip gilchrist" atirou este peixe aos pinguins: >Hi Pythoners > >My Son has challenged me to name a few careers that would use Maths >exponents and all the calculations in them as a way of getting out of >learning them. Obviously, programming and basically anything to do with >Computers is foremost in the answer, but I was hoping that you studious >types would be able to supply me with more than the obvious answer. > >Hoping to hear from all the career people that can use Mathematical >Calculations on a regular basis. > The obvious answer to your question is: a mathematician. Physicists also use a lot of mathematics, in fact a lot of mathematical research is motivated by problems in physics. Having said this, let me add that mathematics is being applied to various subjects. People studying DNA use knot theory, biologists model the evolution of populations using differential equations, economists use game theory, sociologists make heavy use of statistics, research in computer science makes heavy use of category theory, and the list goes on. With my best regards, G. Rodrigues From nullpointer at heartoftn.net Tue Feb 3 14:28:06 2004 From: nullpointer at heartoftn.net (Null Pointer) Date: Tue Feb 3 14:28:27 2004 Subject: [Tutor] Maths (slightly OT) In-Reply-To: <598B5E93DCDC614C9C1FE22406A0F5BE36CD@pacer-server.pacer.local> References: <598B5E93DCDC614C9C1FE22406A0F5BE36CD@pacer-server.pacer.local> Message-ID: <200402031428.06645.nullpointer@heartoftn.net> On Tuesday 03 February 2004 13:08, philip gilchrist wrote: > Hi Pythoners > > My Son has challenged me to name a few careers that would use > Maths exponents and all the calculations in them as a way of > getting out of learning them. Obviously, programming and > basically anything to do with Computers is foremost in the > answer, but I was hoping that you studious types would be able to > supply me with more than the obvious answer. Not my particular career path, but . . . . Men's Room Attendant at an international airport You have to think about it a bit. N.P. From CwiklaJ at diebold.com Tue Feb 3 15:03:20 2004 From: CwiklaJ at diebold.com (Cwikla, Joe) Date: Tue Feb 3 15:03:56 2004 Subject: [Tutor] Maths (slightly OT) Message-ID: <8711C7B083FE6F4FBD07F622FF8217EB0111C6FD@msexch14.diebold.com> Electrical Engineering. AC circuit analysis, Electromagnetics ... the list goes on. Without a solid knowledge of logs/exponents it's just impossible. And, when it comes to larger numbers, I find it easier to do everyday mental math with exponents. Let's see ... this yard is about 400 feet x 80 feet=(4x8)x(10**2)x(10**1)=32x10**3 sq feet Each bag of fertilizer covers 16,000 =16x10**3 sq feet per bag 32 10**3 -- X ----- = 'I'll take two bags please' 16 10**3 Good luck with your son, mine is 9 :-) Joe >Date: Tue, 3 Feb 2004 20:08:59 +0200 >From: "philip gilchrist" >Subject: [Tutor] Maths (slightly OT) >To: >Message-ID: > <598B5E93DCDC614C9C1FE22406A0F5BE36CD@pacer-server.pacer.local> >Content-Type: text/plain; charset="us-ascii" > >Hi Pythoners > >My Son has challenged me to name a few careers that would use Maths >exponents and all the calculations in them as a way of getting out of >learning them. Obviously, programming and basically anything to do with >Computers is foremost in the answer, but I was hoping that you studious >types would be able to supply me with more than the obvious answer. > >Hoping to hear from all the career people that can use Mathematical >Calculations on a regular basis. > > >regards, >Philip From abli at freemail.hu Tue Feb 3 15:09:15 2004 From: abli at freemail.hu (Abel Daniel) Date: Tue Feb 3 15:09:10 2004 Subject: [Tutor] Finding things in the docs, was: Re: special call for deleted objects? In-Reply-To: <200401302240.09010.thomi@thomi.imail.net.nz> (Thomas Clive Richards's message of "Fri, 30 Jan 2004 22:40:09 +1300") References: <200401301333.23303.thomi@thomi.imail.net.nz> <00f201c3e70b$63fa7240$6401a8c0@xp> <200401302240.09010.thomi@thomi.imail.net.nz> Message-ID: Thomas Clive Richards writes: > BTW, where can I find this information? Am I missing some documentation > somewhere? (I'm looking in the documentation distributed with python2.3)... __del__ is mentioned in the Language reference, section 3.3.1 Basic customization an online version is at: http://python.org/doc/2.3.3/ref/customization.html the non-official Python reference might come handy when looking for stuff ( its basically and index of the official docs ) : http://www.ferg.org/pyref/index.html -- Abel Daniel From abli at freemail.hu Tue Feb 3 15:52:27 2004 From: abli at freemail.hu (Abel Daniel) Date: Tue Feb 3 15:52:23 2004 Subject: [Tutor] Re: Using Python with VI In-Reply-To: <00a801c3e99b$dfb52820$b364a8c0@datatree> (Barry Smithers's message of "Mon, 2 Feb 2004 14:50:17 -0000") References: <00a801c3e99b$dfb52820$b364a8c0@datatree> Message-ID: "Barry Smithers" writes: > I'm having difficulty with a program call from inside of VI. What I > basically need to do is get the line numbers input in the ex command. Or > maybe even get the text on those lines to go into a list. For example the > ex command ":20,21!xxx.py" would run xxx.py as a whole, but I need the data > currently on lines 20 and 21 for modification. This ex command expects the program you run (xxx.py) to be a filter: it should read on stdin and write to stdout. Something like this: --- import sys l=sys.stdin.readlines() # this l will be the list you need print "l:", l # print writes to stdout by default. Or you can use # sys.stdout.write() # (and .flush(), and .close(), just to be safe) --- I don't know how you could pass the _line_numbers_ (instead of the contents of the lines). -- Abel Daniel From david at graniteweb.com Tue Feb 3 17:04:37 2004 From: david at graniteweb.com (David Rock) Date: Tue Feb 3 17:04:43 2004 Subject: [Tutor] (no subject) In-Reply-To: References: Message-ID: <20040203220437.GA16943@wdfs.graniteweb.com> * Meisam Ganjeali darani [2004-02-02 11:46]: > Hi > > Thanks for your help. > > I have some question about python. > > How I can run python in my system? > > My system platform is windows The simplest thing is to go to http://www.python.org/download/ There you will find downloads for all kinds of platforms. -- David Rock david at graniteweb dot com -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20040203/26010670/attachment.bin From dana at momerath.us Tue Feb 3 20:53:57 2004 From: dana at momerath.us (dana@momerath.us) Date: Tue Feb 3 20:54:03 2004 Subject: [Tutor] HTMLParser, (no subject) In-Reply-To: References: <3119.63.225.172.24.1075552557.squirrel@mail.zoper.com> Message-ID: <2359.63.225.172.24.1075859637.squirrel@mail.zoper.com> > Welcome aboard! Your message is fine, but make sure to add a "subject > line" on your email, so that it's easier for people to find your message. > Yeah, I noticed that right after I sent the message and felt dumb about it. I'll do better next time. :) > (Also, if you haven't already, you may want to subscribe to Tutor --- > otherwise, your messages will be held until one of the lazy admins here > gets a chance to validate the message for non-spaminess. The page: > > http://mail.python.org/mailman/listinfo/tutor > > explains how to subscribe to Python-Tutor.) I was subscribed, but at a different address. Fixed. > There are two issues I can see so far: the newURL method looks a little > weird, and there's a bug in handle_starttag(). Let's cover the newURL() > method briefly: > >> def newURL(self, URL): >> __init__(self, URL) > > > This looks a little weird because no __init__ method has yet been defined. > Can you explain what newURL is trying to do? And do you need it? I don't > see anything in the code that uses it, so maybe it can be removed? > > > Let's take a look at handle_starttag(): > >> def handle_starttag(self, tag, attrs): >> print "tag is %s with attributes %s." %(self, tag, attrs) > ^^ ^^ ^^^^ ^^^ ^^^^^ > > There are two formatting positions in the string, but the code is trying > to fill it up with three things. Given that, does the error message: > > >> File "r.py", line 31, in handle_starttag >> print "tag is %s with attributes %s." %(self, tag, attrs) >> TypeError: not all arguments converted during string formatting > > make sense now? I found and fixed the main problem while I was waiting for you "lazy admins" to approve my post. :) As for the newURL() method, when I wrote it I was thinking that I would need to call the same InteractiveURLParser instance again for different URLs and that it was necessary to call the __init__() method to do that. Now I see that calling the close() method and then the open() method again would be the way to do that. I think. I'll have to play with it. Thank you! Dana From missive at hotmail.com Tue Feb 3 21:28:24 2004 From: missive at hotmail.com (Lee Harr) Date: Tue Feb 3 21:28:29 2004 Subject: [Tutor] Re: Maths (slightly OT) Message-ID: >My Son has challenged me to name a few careers that would use Maths >exponents and all the calculations in them as a way of getting out of >learning them. Obviously, programming and basically anything to do with >Computers is foremost in the answer, but I was hoping that you studious >types would be able to supply me with more than the obvious answer. > >Hoping to hear from all the career people that can use Mathematical >Calculations on a regular basis. > Pretty much any business... Think about the people sitting around a boardroom table looking at a bunch of "charts". Presumably those charts were created by plotting numbers and applying different statistical methods to try to make out what the charts "mean". They say that something like 90% of all new businesses fail. My feeling is that many of them fail not because their owners are not good at what they do, but because they do not have a good handle on the numbers --- ie. "am I able to make a profit?" Exponents are particularly import to business people because of compound interest and the way you can make a serious fortune by investing your money wisely. _________________________________________________________________ STOP MORE SPAM with the new MSN 8 and get 2 months FREE* http://join.msn.com/?page=features/junkmail From isrgish at fusemail.com Tue Feb 3 22:47:47 2004 From: isrgish at fusemail.com (Isr Gish) Date: Tue Feb 3 22:48:16 2004 Subject: [Tutor] glob module Message-ID: I want to get a list of all files from a folder with a certain pattern. But I want to look in sub folders also Example: Lets say I have this dir tree Docs recipes new old help all ... I want to find all files with "a*.txt" from whole tree of Docs how would I do that. I understand that I could iterate the whole tree. But what I would like to know, if it can be done, with the glob module. Thanks for any help Isr From david at graniteweb.com Wed Feb 4 00:05:48 2004 From: david at graniteweb.com (David Rock) Date: Wed Feb 4 00:06:15 2004 Subject: [Tutor] glob module In-Reply-To: References: Message-ID: <40207DAC.70300@graniteweb.com> Isr Gish wrote: > I want to get a list of all files from a folder with a certain pattern. > But I want to look in sub folders also > > Example: > Lets say I have this dir tree > > Docs > recipes > new > old > help > all > ... You are probably looking for something like this: http://www.python.org/doc/current/lib/os-file-dir.html#l2h-1473 -- David Rock david@graniteweb.com -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 254 bytes Desc: OpenPGP digital signature Url : http://mail.python.org/pipermail/tutor/attachments/20040203/e1994d0f/signature.bin From dyoo at hkn.eecs.berkeley.edu Wed Feb 4 01:26:41 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Feb 4 01:27:02 2004 Subject: [Tutor] Maths (slightly OT) In-Reply-To: <2ksv1090cbgemb7m8grftehtbu5c8tvcfh@4ax.com> Message-ID: > >Hoping to hear from all the career people that can use Mathematical > >Calculations on a regular basis. Hi Philip, Math is not an artificial construct, but a very human endeavor: http://perso.unifr.ch/rafael.nunez/ The reason people reason with exponentials is because they're part of our common human experience. People have mentioned compound interest to appeal to the financial side of things. Maybe your son isn't that much into finance. But perhaps your son is into fairy tales. Show him the story about A Grain of Rice: http://www.lhsgems.org/MAWConx.html#grain The story goes that there's a beggar who once does a favor to a king. The king owes him, so he asks the beggar to choose his own reward. The beggar asks for a single grain of rice, and to have his amount of rice double every day, for one hundred days. The king, not knowing much about exponentials, foolishly agrees. ### >>> def count_grains_of_rice(day): ... if day == 1: return 1 ... else: return 2 * count_grains_of_rice(day - 1) ... >>> count_grains_of_rice(1) 1 >>> count_grains_of_rice(2) 2 >>> count_grains_of_rice(3) 4 >>> count_grains_of_rice(4) 8 ### Not too scary so far. 8 grains of rice? Bah, that's nothing. What do things look like on the hundredth day? ### >>> count_grains_of_rice(100) 633825300114114700748351602688L ### That's a honking large number. *grin* What does this have to do with exponentials? It turns out that the function we've written is equivalent to: ### >>> def f(x): ... return 2**(x-1) ... >>> f(1) 1 >>> f(2) 2 >>> f(100) 633825300114114700748351602688L ### That's exponential growth. We use exponentials because they're one of the standard ways we can describe such tremendous rates of change. And these things happen in real life, in both natural and unnatural situations. > The obvious answer to your question is: a mathematician. Physicists also > use a lot of mathematics, in fact a lot of mathematical research is > motivated by problems in physics. Computer science is one of those "unnatural" sciences, and computer scientists use math very heavily. The kind of mathematics that CS students use, though, might be much different than one might expect --- unlike Physics, CS depends less on calculus, and more on discrete math. Programmers eventually need to understand exponentials, because programs that take exponential time to complete are pretty useless programs. We need to know about exponentials in order to recognize (and avoid writing) programs that take exponential time to solve problems. > Having said this, let me add that mathematics is being applied to > various subjects. People studying DNA use knot theory, biologists model > the evolution of populations using differential equations, economists > use game theory, sociologists make heavy use of statistics, research in > computer science makes heavy use of category theory, and the list goes > on. Biologists also use discrete math quite a bit. As a concrete example of the kind of mathematics involved in molecular biology and computer science, you might want to browse 'Algorithms on Strings, Trees, and Sequences: Computer Science and Computational Biology': http://wwwcsif.cs.ucdavis.edu/~gusfield/paperlist.html The kind of mathematics that's used there is heavy on proof techniques and reasoning about recursive data structures. The book may not use many exponents or integral signs, but it does have sigma summation signs everywhere. But computer scientists do use calculus --- in particular, it provides very useful tools in the analysis of recurrence relations: http://www.math.upenn.edu/~wilf/DownldGF.html (The program at the very top, the count_grains_of_sand() function, is an implementation of a "recurrence relation" as code.) Anyway, that link to the 'Literature Connections to Math Around the World' from the very top of this post may be useful. http://www.lhsgems.org/MAWConx.html Your son may still doubt you after reading some of the books listed there, but at least he'll be mildly entertained for a few minutes. *grin* Talk to you later! From janwillem.maaskant at planet.nl Wed Feb 4 10:47:28 2004 From: janwillem.maaskant at planet.nl (jan willem maaskant) Date: Wed Feb 4 11:23:52 2004 Subject: [Tutor] comparing lists of strings with each other Message-ID: Hello, i have a problem, with comparison of two strings in a list using the filter function. and i really don't know the solution. Here is the problem. i have two lists filled with strings and i want to filter the strings from one list out of the other. for example: listOne = [ 'a','b','c'] listTwo = ['a','c'] i want to remove the strings in listOne which are equal to the strings in listTwo. So the list i want to have must look like this. listThree = ['b'] i tried it with the following code: >>> def removeStrings(list): for key in listTwo: if key != list: return list >>> listThree = filter(removeStrings, listOne) however this results in >>> listThree ['a', 'b', 'c'] >>> so this is wrong, but what i really don't understand, is why the opposite seems to work quite fine if I put this code in >>> def removeStrings(list): for key in listTwo: if key == list: # i changed the comparison operator return list than the function gives exactly what i expected: >>> listThree = filter(removeStrings, listOne) >>> listThree ['a', 'c'] So i'm obviously missing something here, but i'm out of solutions and i am not able to find it in any of my books. I would be very much helped if somebody could explain this to me jan willem maaskant From gerrit at nl.linux.org Wed Feb 4 11:30:08 2004 From: gerrit at nl.linux.org (Gerrit) Date: Wed Feb 4 11:30:18 2004 Subject: [Tutor] glob module In-Reply-To: References: Message-ID: <20040204163008.GA5327@nl.linux.org> Isr Gish wrote: > Docs > recipes > new > old > help > all > ... > I want to find all files with "a*.txt" from whole tree of Docs how would I do that. I understand that I could iterate the whole tree. But what I would like to know, if it can be done, with the glob module. If it's always 3 levels deep, you can use '*/*/a*.txt'. That makes using os.walk unnecesary. Gerrit. -- PrePEP: Builtin path type http://people.nl.linux.org/~gerrit/creaties/path/pep-xxxx.html Asperger's Syndrome - a personal approach: http://people.nl.linux.org/~gerrit/english/ From pythontutor at venix.com Wed Feb 4 12:37:12 2004 From: pythontutor at venix.com (Lloyd Kvam) Date: Wed Feb 4 12:37:30 2004 Subject: [Tutor] comparing lists of strings with each other In-Reply-To: References: Message-ID: <40212DC8.4000304@venix.com> > for key in listTwo: > if key != list: # this is line is not what you really want > return list You really wanted: if key not in list: In Python2.3 there is now a sets module. I've been going wild using it in my unit testing scripts. The sets module makes it VERY easy to convert lists to Sets and determine the differences between Sets. jan willem maaskant wrote: > Hello, > i have a problem, with comparison of two strings in a list using the filter > function. > and i really don't know the solution. > > Here is the problem. > > i have two lists filled with strings and i want to filter the strings from > one list out of the other. > > for example: > > listOne = [ 'a','b','c'] > listTwo = ['a','c'] > > i want to remove the strings in listOne which are equal to the strings in > listTwo. > So the list i want to have must look like this. > > listThree = ['b'] > > i tried it with the following code: > > >>>>def removeStrings(list): > > for key in listTwo: > if key != list: > return list > > > >>>>listThree = filter(removeStrings, listOne) > > however this results in > >>>>listThree > > ['a', 'b', 'c'] > > > so this is wrong, but what i really don't understand, is why the opposite > seems to work quite fine > if I put this code in > > >>>>def removeStrings(list): > > for key in listTwo: > if key == list: # i changed the comparison operator > return list > > than the function gives exactly what i expected: > > >>>>listThree = filter(removeStrings, listOne) >>>>listThree > > ['a', 'c'] > > So i'm obviously missing something here, but i'm out of solutions and i am > not able to find it in any of my books. > I would be very much helped if somebody could explain this to me > > jan willem maaskant > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-653-8139 fax: 801-459-9582 From rmkrauter at yahoo.com Wed Feb 4 12:38:46 2004 From: rmkrauter at yahoo.com (Rich Krauter) Date: Wed Feb 4 12:38:55 2004 Subject: [Tutor] comparing lists of strings with each other Message-ID: <20040204173847.54392.qmail@web40106.mail.yahoo.com> If you trace out each step of what filter is doing, you'll see why you are getting what you are getting. By using filter, you are passing each element of the first list into your comparison function. Your comparison function compares the passed-in item with each item in the second list, and returns the item (a true value) when the two are not equal: 'a' in list1 != 'c' in list2, so 'a' is returned 'b' in list1 != 'a' in list2, so 'b' is returned 'c' in list1 != 'a' in list2, so 'c' is returned Filter is documented here: http://www.python.org/doc/current/lib/built-in-funcs.html#l2h-26 You can do this without filter, using list membership tests: >>> newlist = [] >>> for x in list1: ... if x not in list2: ... newlist.append(x) or >>> f = lambda i: i not in list2 >>> filter(f,list1) >>> ['b'] One way you can do what you want in python 2.3 is with sets: >>> import sets >>> a1 = ['a','b','c'] >>> a2 = ['a','c'] >>> s1 = sets.Set(a1) >>> s2 = sets.Set(a2) #find all elements of s1 not in s2 >>> list(s1-s2) ['b'] Rich __________________________________ Do you Yahoo!? Yahoo! SiteBuilder - Free web site building tool. Try it! http://webhosting.yahoo.com/ps/sb/ From pythontutor at venix.com Wed Feb 4 12:56:20 2004 From: pythontutor at venix.com (Lloyd Kvam) Date: Wed Feb 4 12:56:27 2004 Subject: [Tutor] comparing lists of strings with each other In-Reply-To: <20040204173847.54392.qmail@web40106.mail.yahoo.com> References: <20040204173847.54392.qmail@web40106.mail.yahoo.com> Message-ID: <40213244.7030002@venix.com> Good thing you are watching Rich. I scanned right past the use of filter. The variable name "list" convinced me I was looking at a list. (Actually list is also a bad choice for variable name because it hides the builtin list.) Rich Krauter wrote: > If you trace out each step of what filter is doing, > you'll see why you are getting what you are getting. > > By using filter, you are passing each element of the > first list into your comparison function. Your > comparison function compares the passed-in item with > each item in the second list, and returns the item (a > true value) when the two are not equal: > > 'a' in list1 != 'c' in list2, so 'a' is returned > 'b' in list1 != 'a' in list2, so 'b' is returned > 'c' in list1 != 'a' in list2, so 'c' is returned > > Filter is documented here: > http://www.python.org/doc/current/lib/built-in-funcs.html#l2h-26 > > You can do this without filter, using list membership > tests: > >>>>newlist = [] >>>>for x in list1: > > ... if x not in list2: > ... newlist.append(x) > > or > > >>>>f = lambda i: i not in list2 >>>>filter(f,list1) >>>>['b'] > > > One way you can do what you want in python 2.3 is with > sets: > >>>>import sets >>>>a1 = ['a','b','c'] >>>>a2 = ['a','c'] >>>>s1 = sets.Set(a1) >>>>s2 = sets.Set(a2) > > > #find all elements of s1 not in s2 > >>>>list(s1-s2) > > ['b'] > > Rich > > __________________________________ > Do you Yahoo!? > Yahoo! SiteBuilder - Free web site building tool. Try it! > http://webhosting.yahoo.com/ps/sb/ > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-653-8139 fax: 801-459-9582 From idiot1 at netzero.net Wed Feb 4 12:55:27 2004 From: idiot1 at netzero.net (Kirk Bailey) Date: Wed Feb 4 12:56:38 2004 Subject: [Tutor] globbing and sorting and dating, oh my! Message-ID: <4021320F.8090608@netzero.net> Ok, I want to write a WHAT'S NEW function for wikinehesa the wikiwikiweb system I wrote in python. This is something to sort through available pages, organize/sort according to date, chop off that portion of the list which is older than FOO days old, and concert the date to something mere normals will comprehend, then print each item as a line in a web page- as a link of course. NATURALLY I grok the html part. converting data data to calendar is a little odd to me, and I am considering several ways to organize the data- and as arrays are not inherent to python, I am going to use several parallel lists instead. I throw open the front door to discussion, suggestions, ON TOPIC BAUDY HUMOR, and anything else that fits in through the door. If the dates are a list, and I sort the list, the corresponding list of filenames no longer corresponds. THIS is an issue which looms large in my army surplus used brain. -- end think http://www.tinylist.org/ - $FREE$ software for liberty +-------+ http://www.pinellasintergroupsociety.org/ - In Her Service | BOX | http://www.listville.net/ - $FREE$ list hosting services +-------+ http://www.howlermonkey.net/ - $FREE$ email service kniht http://www.sacredelectron.org/ - My personal SCREED pit (C)2004 Kirk D Bailey, all rights reserved- but ask! From sigurd at 12move.de Wed Feb 4 13:04:33 2004 From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=) Date: Wed Feb 4 13:06:12 2004 Subject: [Tutor] comparing lists of strings with each other In-Reply-To: (jan willem maaskant's message of "Wed, 04 Feb 2004 16:47:28 +0100") References: Message-ID: jan willem maaskant <- janwillem.maaskant@planet.nl wrote: > i have a problem, with comparison of two strings in a list using the filter > function. > and i really don't know the solution. [...] > for example: > listOne = [ 'a','b','c'] > listTwo = ['a','c'] > i want to remove the strings in listOne which are equal to the strings in > listTwo. > So the list i want to have must look like this. > listThree = ['b'] > i tried it with the following code: >>>> def removeStrings(list): > for key in listTwo: > if key != list: > return list Do not use list as parameter; it's a builtin. Did you read what the filter function does? It iterates over a sequence and returns those elemenst for which the functions returns a true value. Above function will always return True for the values you gave; e.g: a != c => True b != a => True c != a => True >>>> listThree = filter(removeStrings, listOne) > however this results in >>>> listThree > ['a', 'b', 'c'] So the result is exactly that what you asked for. > seems to work quite fine > if I put this code in >>>> def removeStrings(list): > for key in listTwo: > if key == list: # i changed the comparison operator > return list > than the function gives exactly what i expected: >>>> listThree = filter(removeStrings, listOne) >>>> listThree > ['a', 'c'] Above you wrote you wanted the difference between the two lists. Now you write the intersection is what you want? Which one is true? Anyway I assume you meant what you first wrote. First a solution nearly the same as yours. What you need is a function which returns *False* if a value from one list is not in the other list. Python has something like that builtin; `in' >>> L = [1,2,3] >>> 1 in L True >>> 4 in L False >>> So you simply have to call `in' for the elements of list1 with list2 and negate the result. >>> listOne = [ 'a','b','c'] >>> listTwo = ['a','c'] >>> filter(lambda el: not el in listTwo, listOne) ['b'] >>> If you wanted the intersection just don't negate the result. If you have longer lists it might be better to use the new set module (it works with dictionaries) otherwise the code might be to slow. Karl -- Please do *not* send copies of replies to me. I read the list From littledanehren at yahoo.com Wed Feb 4 15:13:10 2004 From: littledanehren at yahoo.com (Daniel Ehrenberg) Date: Wed Feb 4 15:13:16 2004 Subject: [Tutor] globbing and sorting and dating, oh my! In-Reply-To: <4021320F.8090608@netzero.net> Message-ID: <20040204201310.30288.qmail@web41812.mail.yahoo.com> Kirk Bailey wrote: > Ok, I want to write a WHAT'S NEW function for > wikinehesa the > wikiwikiweb system I wrote in python. This is > something to sort > through available pages, organize/sort according to > date, chop off > that portion of the list which is older than FOO > days old, and concert > the date to something mere normals will comprehend, > then print each > item as a line in a web page- as a link of course. > NATURALLY I grok > the html part. converting data data to calendar is a > little odd to me, > and I am considering several ways to organize the > data- and as arrays > are not inherent to python, I am going to use > several parallel lists > instead. I throw open the front door to discussion, > suggestions, ON > TOPIC BAUDY HUMOR, and anything else that fits in > through the door. > > If the dates are a list, and I sort the list, the > corresponding list > of filenames no longer corresponds. THIS is an issue > which looms large > in my army surplus used brain. > -- > > > end > > > think http://www.tinylist.org/ - $FREE$ > software for liberty > +-------+ http://www.pinellasintergroupsociety.org/ > - In Her Service > | BOX | http://www.listville.net/ - $FREE$ list > hosting services > +-------+ http://www.howlermonkey.net/ - $FREE$ > email service > kniht http://www.sacredelectron.org/ - My > personal SCREED pit > (C)2004 Kirk D Bailey, all rights > reserved- but ask! Try zipping the lists together and then sorting it. Be sure that the one you want to sort by is first. Daniel Ehrenberg __________________________________ Do you Yahoo!? Yahoo! SiteBuilder - Free web site building tool. Try it! http://webhosting.yahoo.com/ps/sb/ From anna at aleax.it Wed Feb 4 15:37:12 2004 From: anna at aleax.it (Anna Ravenscroft) Date: Wed Feb 4 15:37:21 2004 Subject: [Tutor] globbing and sorting and dating, oh my! In-Reply-To: <4021320F.8090608@netzero.net> References: <4021320F.8090608@netzero.net> Message-ID: <200402042137.12960.anna@aleax.it> On Wednesday 04 February 2004 06:55 pm, Kirk Bailey wrote: > If the dates are a list, and I sort the list, the corresponding list > of filenames no longer corresponds. THIS is an issue which looms large > in my army surplus used brain. I'd consider using a dict. Python dicts are fast, easy to use, and highly useful. mydict = {key1:value1, key2:value2} You can use dates as the keys (and any lists or strings or combination thereof as the values), pull a list of the keys using d.keys(), sort them, remove any that are old, then use the remaining list to pull the corresponding values into a new dict or list for display. Or, use a list comprehension directly on the dict to get a list of new items (since you don't really *have* to sort them by date, do you?). It'll give you a new list of tuples, which you can pass to a new dict if you want to: newstuph = dict( [(date, mydict[date]) for date in mydict if date > olddate] ) Hope this helps. Anna -- There is a type 3 error in which your mind goes totally blank whenever you try to remember which is which of type 1 and type 2. -Richard Dawkins -- There is a type 3 error in which your mind goes totally blank whenever you try to remember which is which of type 1 and type 2. -Richard Dawkins From anna at aleax.it Wed Feb 4 15:39:32 2004 From: anna at aleax.it (Anna Ravenscroft) Date: Wed Feb 4 15:39:42 2004 Subject: [Tutor] comparing lists of strings with each other In-Reply-To: References: Message-ID: <200402042139.32255.anna@aleax.it> On Wednesday 04 February 2004 04:47 pm, jan willem maaskant wrote: > i have two lists filled with strings and i want to filter the strings from > one list out of the other. You'd be better off with a list comprehension. threelist = [i for i in onelist if i not in twolist] But, if you really must use filter for some reason....: > for example: > > listOne = [ 'a','b','c'] > listTwo = ['a','c'] > > i want to remove the strings in listOne which are equal to the strings in > listTwo. > So the list i want to have must look like this. > > listThree = ['b'] > > i tried it with the following code: > >>> def removeStrings(list): > > for key in listTwo: > if key != list: > return list > > >>> listThree = filter(removeStrings, listOne) First, you really really don't want to use "list" as an argument or variable name. list is one of the built-in types in Python, and you *REALLY* don't want to use it as a variable name. > however this results in > > >>> listThree > > ['a', 'b', 'c'] > > > so this is wrong, but what i really don't understand, is why the opposite > seems to work quite fine > if I put this code in Okay, in order to see what's happening, I added some print statements to the function. then ran the whole thing again. alist = ['d', 'b', 'c'] blist = ['d', 'f', 'b'] def remstring(item): print 'filter passes item', item for key in blist: print "key is ", key if key != item: print "key != item. returning", item return item clist = filter(remstring, alist) print clist >>> filter passes item d key is d key is f key != item. returning d filter passes item b key is d key != item. returning b filter passes item c key is d key != item. returning c ['d', 'b', 'c'] >>> Does this help you see what's happening? HTH, Anna -- There is a type 3 error in which your mind goes totally blank whenever you try to remember which is which of type 1 and type 2. -Richard Dawkins From michel.belanger at seidel.ca Wed Feb 4 16:35:34 2004 From: michel.belanger at seidel.ca (=?ISO-8859-1?Q?Michel_B=E9langer?=) Date: Wed Feb 4 17:11:07 2004 Subject: [Tutor] Executable file version in windows Message-ID: <402165A6.90301@seidel.ca> Hi, How can I query a file executable (exe, dll, com)for its version including the revision, i.e. exemple: >>>queryVersion("someprog.exe") 5.1.2 Michel Belanger From kim.branson at csiro.au Wed Feb 4 08:34:12 2004 From: kim.branson at csiro.au (Kim Branson) Date: Wed Feb 4 17:45:02 2004 Subject: [Tutor] reg exps Message-ID: Hi all, i'm trying to get my head around regexps in python. i've now found the difference between the .match and the .search methods. (i'm used to perl :) i have a program which will spit out data like so: % ~/Desktop/Dock4_osx/bin/scorer 1rx3.pdb dock_nrg.mol2 PK= 6.08 Qual= 2.12 PMF= -159.15 PMF_rb= -144.15 SMoG= -161.27 SMoG_H= -7.68 ChemScore= -23.86 Clash= 0.85 Int= 2.58 DockNRG= -24.51 AutoDock= -20.14 so i'm working on a script which has a function (below) that checks for this data (the program called can spit out other data when inputs are bad) then grabs the matches. so now i'm making dictionaries for each field, using the line number as a key. my pattern match does not return the first match in the list in position 0. i.e [' ', ' 6.08', ' 2.12', '-159.15', '-144.15', '-161.27', '-7.68', '-23.86', ' 0.85', ' 2.58', '-24.51', '-20.14', '\n'] so i'm grabbing the data from position 1 in the list etc, and working from there. Why is this, is this a default behaviour? note the values in the output can be negative or really large, as in PK= -6.08 etc, or Qual= 12.12 so i use (.*) to grab the region. Oh one more thing, if you declare a global, can i simply add dictionary content, or should one declare and then initialise? def score_orientations(): counter = 1 global score_dict global qual_dict global pmf_dict global pmf_rb_dict global smog_dict global smog_h_dict global chemscore_dict global clash_dict global int_dict global docknrg_dict global autodock_dict score_dict = {} qual_dict = {} pmf_dict = {} pmf_rb_dict = {} smog_dict = {} smog_h_dict = {} chemscore_dict = {} clash_dict = {} int_dict = {} docknrg_dict = {} autodock_dict = {} score_lines = re.compile('PK= (.*) Qual= (.*) PMF= (.*) PMF_rb= (.*) SMoG= (.*) SMoG_H= (.*) ChemScore= (.*) Clash= (.*) Int= (.*) DockNRG= (.*) AutoDock= (.*)') results = os.popen2('/Users/kbranson/Desktop/Dock4_osx/bin/scorer %s dock_nrg.mol2' % receptor_pdb) results_data = results[1].readlines() for line in results_data: if (score_lines.search(line)): line = re.split(score_lines, line) score_dict[counter] = line[1] qual_dict[counter] = line[2] pmf_dict[counter] = line[3] pmf_rb_dict[counter] = line[4] smog_dict[counter] = line[5] smog_h_dict[counter] = line[6] chemscore_dict[counter] = line[7] clash_dict[counter] = line[8] int_dict[counter] = line[9] docknrg_dict[counter] = line[10] autdock_dict[counter] = line[11] counter = counter + 1 print score_dict score_orientations() From janwillem.maaskant at planet.nl Wed Feb 4 17:59:20 2004 From: janwillem.maaskant at planet.nl (jan willem maaskant) Date: Wed Feb 4 18:07:51 2004 Subject: [Tutor] RE: comparing list of strings with each other In-Reply-To: Message-ID: thanks every one, for your quick response. i have still some more studying to do. with all the answers that i got. greetings, jan willem. -----Original Message----- From: tutor-bounces@python.org [mailto:tutor-bounces@python.org]On Behalf Of tutor-request@python.org Sent: woensdag 4 februari 2004 23:45 To: tutor@python.org Subject: Tutor Digest, Vol 7, Issue 10 Send Tutor mailing list submissions to tutor@python.org To subscribe or unsubscribe via the World Wide Web, visit http://mail.python.org/mailman/listinfo/tutor or, via email, send a message with subject or body 'help' to tutor-request@python.org You can reach the person managing the list at tutor-owner@python.org When replying, please edit your Subject line so it is more specific than "Re: Contents of Tutor digest..." Today's Topics: 1. Re: comparing lists of strings with each other (Lloyd Kvam) 2. comparing lists of strings with each other (Rich Krauter) 3. Re: comparing lists of strings with each other (Lloyd Kvam) 4. globbing and sorting and dating, oh my! (Kirk Bailey) 5. Re: comparing lists of strings with each other (Karl Pfl?sterer ) 6. Re: globbing and sorting and dating, oh my! (Daniel Ehrenberg) 7. Re: globbing and sorting and dating, oh my! (Anna Ravenscroft) 8. Re: comparing lists of strings with each other (Anna Ravenscroft) 9. Executable file version in windows (Michel B?langer) 10. reg exps (Kim Branson) ---------------------------------------------------------------------- Message: 1 Date: Wed, 04 Feb 2004 12:37:12 -0500 From: Lloyd Kvam Subject: Re: [Tutor] comparing lists of strings with each other To: jan willem maaskant Cc: tutor@python.org Message-ID: <40212DC8.4000304@venix.com> Content-Type: text/plain; charset=us-ascii; format=flowed > for key in listTwo: > if key != list: # this is line is not what you really want > return list You really wanted: if key not in list: In Python2.3 there is now a sets module. I've been going wild using it in my unit testing scripts. The sets module makes it VERY easy to convert lists to Sets and determine the differences between Sets. jan willem maaskant wrote: > Hello, > i have a problem, with comparison of two strings in a list using the filter > function. > and i really don't know the solution. > > Here is the problem. > > i have two lists filled with strings and i want to filter the strings from > one list out of the other. > > for example: > > listOne = [ 'a','b','c'] > listTwo = ['a','c'] > > i want to remove the strings in listOne which are equal to the strings in > listTwo. > So the list i want to have must look like this. > > listThree = ['b'] > > i tried it with the following code: > > >>>>def removeStrings(list): > > for key in listTwo: > if key != list: > return list > > > >>>>listThree = filter(removeStrings, listOne) > > however this results in > >>>>listThree > > ['a', 'b', 'c'] > > > so this is wrong, but what i really don't understand, is why the opposite > seems to work quite fine > if I put this code in > > >>>>def removeStrings(list): > > for key in listTwo: > if key == list: # i changed the comparison operator > return list > > than the function gives exactly what i expected: > > >>>>listThree = filter(removeStrings, listOne) >>>>listThree > > ['a', 'c'] > > So i'm obviously missing something here, but i'm out of solutions and i am > not able to find it in any of my books. > I would be very much helped if somebody could explain this to me > > jan willem maaskant > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-653-8139 fax: 801-459-9582 ------------------------------ Message: 2 Date: Wed, 4 Feb 2004 09:38:46 -0800 (PST) From: Rich Krauter Subject: [Tutor] comparing lists of strings with each other To: tutor@python.org Message-ID: <20040204173847.54392.qmail@web40106.mail.yahoo.com> Content-Type: text/plain; charset=us-ascii If you trace out each step of what filter is doing, you'll see why you are getting what you are getting. By using filter, you are passing each element of the first list into your comparison function. Your comparison function compares the passed-in item with each item in the second list, and returns the item (a true value) when the two are not equal: 'a' in list1 != 'c' in list2, so 'a' is returned 'b' in list1 != 'a' in list2, so 'b' is returned 'c' in list1 != 'a' in list2, so 'c' is returned Filter is documented here: http://www.python.org/doc/current/lib/built-in-funcs.html#l2h-26 You can do this without filter, using list membership tests: >>> newlist = [] >>> for x in list1: ... if x not in list2: ... newlist.append(x) or >>> f = lambda i: i not in list2 >>> filter(f,list1) >>> ['b'] One way you can do what you want in python 2.3 is with sets: >>> import sets >>> a1 = ['a','b','c'] >>> a2 = ['a','c'] >>> s1 = sets.Set(a1) >>> s2 = sets.Set(a2) #find all elements of s1 not in s2 >>> list(s1-s2) ['b'] Rich __________________________________ Do you Yahoo!? Yahoo! SiteBuilder - Free web site building tool. Try it! http://webhosting.yahoo.com/ps/sb/ ------------------------------ Message: 3 Date: Wed, 04 Feb 2004 12:56:20 -0500 From: Lloyd Kvam Subject: Re: [Tutor] comparing lists of strings with each other To: tutor@python.org Message-ID: <40213244.7030002@venix.com> Content-Type: text/plain; charset=us-ascii; format=flowed Good thing you are watching Rich. I scanned right past the use of filter. The variable name "list" convinced me I was looking at a list. (Actually list is also a bad choice for variable name because it hides the builtin list.) Rich Krauter wrote: > If you trace out each step of what filter is doing, > you'll see why you are getting what you are getting. > > By using filter, you are passing each element of the > first list into your comparison function. Your > comparison function compares the passed-in item with > each item in the second list, and returns the item (a > true value) when the two are not equal: > > 'a' in list1 != 'c' in list2, so 'a' is returned > 'b' in list1 != 'a' in list2, so 'b' is returned > 'c' in list1 != 'a' in list2, so 'c' is returned > > Filter is documented here: > http://www.python.org/doc/current/lib/built-in-funcs.html#l2h-26 > > You can do this without filter, using list membership > tests: > >>>>newlist = [] >>>>for x in list1: > > ... if x not in list2: > ... newlist.append(x) > > or > > >>>>f = lambda i: i not in list2 >>>>filter(f,list1) >>>>['b'] > > > One way you can do what you want in python 2.3 is with > sets: > >>>>import sets >>>>a1 = ['a','b','c'] >>>>a2 = ['a','c'] >>>>s1 = sets.Set(a1) >>>>s2 = sets.Set(a2) > > > #find all elements of s1 not in s2 > >>>>list(s1-s2) > > ['b'] > > Rich > > __________________________________ > Do you Yahoo!? > Yahoo! SiteBuilder - Free web site building tool. Try it! > http://webhosting.yahoo.com/ps/sb/ > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-653-8139 fax: 801-459-9582 ------------------------------ Message: 4 Date: Wed, 04 Feb 2004 12:55:27 -0500 From: Kirk Bailey Subject: [Tutor] globbing and sorting and dating, oh my! To: tutor@python.org Message-ID: <4021320F.8090608@netzero.net> Content-Type: text/plain; charset=us-ascii; format=flowed Ok, I want to write a WHAT'S NEW function for wikinehesa the wikiwikiweb system I wrote in python. This is something to sort through available pages, organize/sort according to date, chop off that portion of the list which is older than FOO days old, and concert the date to something mere normals will comprehend, then print each item as a line in a web page- as a link of course. NATURALLY I grok the html part. converting data data to calendar is a little odd to me, and I am considering several ways to organize the data- and as arrays are not inherent to python, I am going to use several parallel lists instead. I throw open the front door to discussion, suggestions, ON TOPIC BAUDY HUMOR, and anything else that fits in through the door. If the dates are a list, and I sort the list, the corresponding list of filenames no longer corresponds. THIS is an issue which looms large in my army surplus used brain. -- end think http://www.tinylist.org/ - $FREE$ software for liberty +-------+ http://www.pinellasintergroupsociety.org/ - In Her Service | BOX | http://www.listville.net/ - $FREE$ list hosting services +-------+ http://www.howlermonkey.net/ - $FREE$ email service kniht http://www.sacredelectron.org/ - My personal SCREED pit (C)2004 Kirk D Bailey, all rights reserved- but ask! ------------------------------ Message: 5 Date: Wed, 04 Feb 2004 19:04:33 +0100 From: sigurd@12move.de (Karl Pfl?sterer ) Subject: Re: [Tutor] comparing lists of strings with each other To: tutor@python.org Message-ID: Content-Type: text/plain; charset=us-ascii jan willem maaskant <- janwillem.maaskant@planet.nl wrote: > i have a problem, with comparison of two strings in a list using the filter > function. > and i really don't know the solution. [...] > for example: > listOne = [ 'a','b','c'] > listTwo = ['a','c'] > i want to remove the strings in listOne which are equal to the strings in > listTwo. > So the list i want to have must look like this. > listThree = ['b'] > i tried it with the following code: >>>> def removeStrings(list): > for key in listTwo: > if key != list: > return list Do not use list as parameter; it's a builtin. Did you read what the filter function does? It iterates over a sequence and returns those elemenst for which the functions returns a true value. Above function will always return True for the values you gave; e.g: a != c => True b != a => True c != a => True >>>> listThree = filter(removeStrings, listOne) > however this results in >>>> listThree > ['a', 'b', 'c'] So the result is exactly that what you asked for. > seems to work quite fine > if I put this code in >>>> def removeStrings(list): > for key in listTwo: > if key == list: # i changed the comparison operator > return list > than the function gives exactly what i expected: >>>> listThree = filter(removeStrings, listOne) >>>> listThree > ['a', 'c'] Above you wrote you wanted the difference between the two lists. Now you write the intersection is what you want? Which one is true? Anyway I assume you meant what you first wrote. First a solution nearly the same as yours. What you need is a function which returns *False* if a value from one list is not in the other list. Python has something like that builtin; `in' >>> L = [1,2,3] >>> 1 in L True >>> 4 in L False >>> So you simply have to call `in' for the elements of list1 with list2 and negate the result. >>> listOne = [ 'a','b','c'] >>> listTwo = ['a','c'] >>> filter(lambda el: not el in listTwo, listOne) ['b'] >>> If you wanted the intersection just don't negate the result. If you have longer lists it might be better to use the new set module (it works with dictionaries) otherwise the code might be to slow. Karl -- Please do *not* send copies of replies to me. I read the list ------------------------------ Message: 6 Date: Wed, 4 Feb 2004 12:13:10 -0800 (PST) From: Daniel Ehrenberg Subject: Re: [Tutor] globbing and sorting and dating, oh my! To: pytutor Message-ID: <20040204201310.30288.qmail@web41812.mail.yahoo.com> Content-Type: text/plain; charset=us-ascii Kirk Bailey wrote: > Ok, I want to write a WHAT'S NEW function for > wikinehesa the > wikiwikiweb system I wrote in python. This is > something to sort > through available pages, organize/sort according to > date, chop off > that portion of the list which is older than FOO > days old, and concert > the date to something mere normals will comprehend, > then print each > item as a line in a web page- as a link of course. > NATURALLY I grok > the html part. converting data data to calendar is a > little odd to me, > and I am considering several ways to organize the > data- and as arrays > are not inherent to python, I am going to use > several parallel lists > instead. I throw open the front door to discussion, > suggestions, ON > TOPIC BAUDY HUMOR, and anything else that fits in > through the door. > > If the dates are a list, and I sort the list, the > corresponding list > of filenames no longer corresponds. THIS is an issue > which looms large > in my army surplus used brain. > -- > > > end > > > think http://www.tinylist.org/ - $FREE$ > software for liberty > +-------+ http://www.pinellasintergroupsociety.org/ > - In Her Service > | BOX | http://www.listville.net/ - $FREE$ list > hosting services > +-------+ http://www.howlermonkey.net/ - $FREE$ > email service > kniht http://www.sacredelectron.org/ - My > personal SCREED pit > (C)2004 Kirk D Bailey, all rights > reserved- but ask! Try zipping the lists together and then sorting it. Be sure that the one you want to sort by is first. Daniel Ehrenberg __________________________________ Do you Yahoo!? Yahoo! SiteBuilder - Free web site building tool. Try it! http://webhosting.yahoo.com/ps/sb/ ------------------------------ Message: 7 Date: Wed, 4 Feb 2004 21:37:12 +0100 From: Anna Ravenscroft Subject: Re: [Tutor] globbing and sorting and dating, oh my! To: Kirk Bailey , tutor@python.org Message-ID: <200402042137.12960.anna@aleax.it> Content-Type: text/plain; charset="iso-8859-1" On Wednesday 04 February 2004 06:55 pm, Kirk Bailey wrote: > If the dates are a list, and I sort the list, the corresponding list > of filenames no longer corresponds. THIS is an issue which looms large > in my army surplus used brain. I'd consider using a dict. Python dicts are fast, easy to use, and highly useful. mydict = {key1:value1, key2:value2} You can use dates as the keys (and any lists or strings or combination thereof as the values), pull a list of the keys using d.keys(), sort them, remove any that are old, then use the remaining list to pull the corresponding values into a new dict or list for display. Or, use a list comprehension directly on the dict to get a list of new items (since you don't really *have* to sort them by date, do you?). It'll give you a new list of tuples, which you can pass to a new dict if you want to: newstuph = dict( [(date, mydict[date]) for date in mydict if date > olddate] ) Hope this helps. Anna -- There is a type 3 error in which your mind goes totally blank whenever you try to remember which is which of type 1 and type 2. -Richard Dawkins -- There is a type 3 error in which your mind goes totally blank whenever you try to remember which is which of type 1 and type 2. -Richard Dawkins ------------------------------ Message: 8 Date: Wed, 4 Feb 2004 21:39:32 +0100 From: Anna Ravenscroft Subject: Re: [Tutor] comparing lists of strings with each other To: tutor@python.org Message-ID: <200402042139.32255.anna@aleax.it> Content-Type: text/plain; charset="iso-8859-1" On Wednesday 04 February 2004 04:47 pm, jan willem maaskant wrote: > i have two lists filled with strings and i want to filter the strings from > one list out of the other. You'd be better off with a list comprehension. threelist = [i for i in onelist if i not in twolist] But, if you really must use filter for some reason....: > for example: > > listOne = [ 'a','b','c'] > listTwo = ['a','c'] > > i want to remove the strings in listOne which are equal to the strings in > listTwo. > So the list i want to have must look like this. > > listThree = ['b'] > > i tried it with the following code: > >>> def removeStrings(list): > > for key in listTwo: > if key != list: > return list > > >>> listThree = filter(removeStrings, listOne) First, you really really don't want to use "list" as an argument or variable name. list is one of the built-in types in Python, and you *REALLY* don't want to use it as a variable name. > however this results in > > >>> listThree > > ['a', 'b', 'c'] > > > so this is wrong, but what i really don't understand, is why the opposite > seems to work quite fine > if I put this code in Okay, in order to see what's happening, I added some print statements to the function. then ran the whole thing again. alist = ['d', 'b', 'c'] blist = ['d', 'f', 'b'] def remstring(item): print 'filter passes item', item for key in blist: print "key is ", key if key != item: print "key != item. returning", item return item clist = filter(remstring, alist) print clist >>> filter passes item d key is d key is f key != item. returning d filter passes item b key is d key != item. returning b filter passes item c key is d key != item. returning c ['d', 'b', 'c'] >>> Does this help you see what's happening? HTH, Anna -- There is a type 3 error in which your mind goes totally blank whenever you try to remember which is which of type 1 and type 2. -Richard Dawkins ------------------------------ Message: 9 Date: Wed, 04 Feb 2004 16:35:34 -0500 From: Michel B?langer Subject: [Tutor] Executable file version in windows To: tutor@python.org Message-ID: <402165A6.90301@seidel.ca> Content-Type: text/plain; charset=us-ascii; format=flowed Hi, How can I query a file executable (exe, dll, com)for its version including the revision, i.e. exemple: >>>queryVersion("someprog.exe") 5.1.2 Michel Belanger ------------------------------ Message: 10 Date: Thu, 5 Feb 2004 00:34:12 +1100 From: Kim Branson Subject: [Tutor] reg exps To: tutor@python.org Message-ID: Content-Type: text/plain; charset=US-ASCII; format=flowed Hi all, i'm trying to get my head around regexps in python. i've now found the difference between the .match and the .search methods. (i'm used to perl :) i have a program which will spit out data like so: % ~/Desktop/Dock4_osx/bin/scorer 1rx3.pdb dock_nrg.mol2 PK= 6.08 Qual= 2.12 PMF= -159.15 PMF_rb= -144.15 SMoG= -161.27 SMoG_H= -7.68 ChemScore= -23.86 Clash= 0.85 Int= 2.58 DockNRG= -24.51 AutoDock= -20.14 so i'm working on a script which has a function (below) that checks for this data (the program called can spit out other data when inputs are bad) then grabs the matches. so now i'm making dictionaries for each field, using the line number as a key. my pattern match does not return the first match in the list in position 0. i.e [' ', ' 6.08', ' 2.12', '-159.15', '-144.15', '-161.27', '-7.68', '-23.86', ' 0.85', ' 2.58', '-24.51', '-20.14', '\n'] so i'm grabbing the data from position 1 in the list etc, and working from there. Why is this, is this a default behaviour? note the values in the output can be negative or really large, as in PK= -6.08 etc, or Qual= 12.12 so i use (.*) to grab the region. Oh one more thing, if you declare a global, can i simply add dictionary content, or should one declare and then initialise? def score_orientations(): counter = 1 global score_dict global qual_dict global pmf_dict global pmf_rb_dict global smog_dict global smog_h_dict global chemscore_dict global clash_dict global int_dict global docknrg_dict global autodock_dict score_dict = {} qual_dict = {} pmf_dict = {} pmf_rb_dict = {} smog_dict = {} smog_h_dict = {} chemscore_dict = {} clash_dict = {} int_dict = {} docknrg_dict = {} autodock_dict = {} score_lines = re.compile('PK= (.*) Qual= (.*) PMF= (.*) PMF_rb= (.*) SMoG= (.*) SMoG_H= (.*) ChemScore= (.*) Clash= (.*) Int= (.*) DockNRG= (.*) AutoDock= (.*)') results = os.popen2('/Users/kbranson/Desktop/Dock4_osx/bin/scorer %s dock_nrg.mol2' % receptor_pdb) results_data = results[1].readlines() for line in results_data: if (score_lines.search(line)): line = re.split(score_lines, line) score_dict[counter] = line[1] qual_dict[counter] = line[2] pmf_dict[counter] = line[3] pmf_rb_dict[counter] = line[4] smog_dict[counter] = line[5] smog_h_dict[counter] = line[6] chemscore_dict[counter] = line[7] clash_dict[counter] = line[8] int_dict[counter] = line[9] docknrg_dict[counter] = line[10] autdock_dict[counter] = line[11] counter = counter + 1 print score_dict score_orientations() ------------------------------ _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor End of Tutor Digest, Vol 7, Issue 10 ************************************ From dyoo at hkn.eecs.berkeley.edu Wed Feb 4 18:08:35 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Feb 4 18:08:44 2004 Subject: [Tutor] Executable file version in windows In-Reply-To: <402165A6.90301@seidel.ca> Message-ID: On Wed, 4 Feb 2004, [ISO-8859-1] Michel B=E9langer wrote: > How can I query a file executable (exe, dll, com)for its version > including the revision, i.e. > > exemple: > >>>queryVersion("someprog.exe") > 5.1.2 Hi Michel, Hmmm... This is a very specific question to the Win32 platform; you might have better luck asking on the Python-Win32 list for this one. From=20some initial Googling, it appears that you may need to get access to the VERSION.DLL Windows library: http://support.microsoft.com/default.aspx?scid=3Dkb;EN-US;139491 We can get access to such DLLs through the Dynwin package: http://www.nightmare.com/~rushing/dynwin/ Unfortunately, that's as far as I can go; I don't run Windows. *grin* Talk to the Win32 folks at: http://mail.python.org/mailman/listinfo/python-win32 The folks there should be better able to help you get this working. Good luck to you! From alan.gauld at blueyonder.co.uk Wed Feb 4 19:23:34 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Wed Feb 4 19:24:29 2004 Subject: [Tutor] Maths (slightly OT) References: <598B5E93DCDC614C9C1FE22406A0F5BE36CD@pacer-server.pacer.local> Message-ID: <005501c3eb7e$4af25cf0$6401a8c0@xp> > My Son has challenged me to name a few careers that would > use Maths exponents and all the calculations in them as a > way of getting out of learning them. Anything vaguely scientific. Including architects, electrical engineering, building trades, draughtsmen, chemists, meteorologists etc Also anything vaguely numeric like: statistician, accountant, businessman, stocks trader. Almost any kind of graphics type thing including animators, graphics artists etc. Navigators either on boats or planes. In fact its kind of hard for me to think of a reasonably well paid career out side of entertainment (including sports in that) that doesn't involve exponentiation somewhere. Its so fundamental to everything in our world and iniverse that you can't hope to understand any physical, chemical or natural phenomenon without it! You might as well as what careers use the ability to read... > Hoping to hear from all the career people that can use > Mathematical Calculations on a regular basis. Depends on what you mean by use them. I use my understanding of exponentiation every day, but I actually do exponential "sums" maybe 6 or 7 times a year... But every time I discuss the "law of diminishing returns", or radiation half life, or electronic timing circuits (important in my job!) I am relying on an understanding of exponentiation. In fact every time I adjust the volume onmy TV or HiFi I am using that same understanding, and when I hit the gas pedal in my car... Every time I listen to a CD or talk on my cell phone, I'm using exponentiation... its everywhere. Alan G. From michel.belanger at seidel.ca Wed Feb 4 20:05:32 2004 From: michel.belanger at seidel.ca (=?ISO-8859-1?Q?Michel_B=E9langer?=) Date: Wed Feb 4 20:05:45 2004 Subject: [Tutor] file transfered through ftplib not the right size Message-ID: <402196DC.7000106@seidel.ca> Hi all, I open an ftp channel with my web site from the following commands: ftp = ftplib.FTP("Host.com") ftp.login("User","Password") then the transfer call for a download is as follow: getbinary(ftp, row[0], row[0]) but the file received is not the right size (larger), i.e. 5150 kb received vs 5136 kb Any idea why? def getbinary(ftp, filename, outfile=None): # fetch a binary file if outfile is None: outfile = sys.stdout f = open(outfile, "w") ftp.retrbinary("RETR " + filename, f.write) f.flush() f.close() Many thanks Michel Belanger From sigurd at 12move.de Wed Feb 4 20:22:30 2004 From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=) Date: Wed Feb 4 20:26:25 2004 Subject: [Tutor] reg exps In-Reply-To: (Kim Branson's message of "Thu, 5 Feb 2004 00:34:12 +1100") References: Message-ID: On 4 Feb 2004, Kim Branson <- kim.branson@csiro.au wrote: > i have a program which will spit out data like so: > % ~/Desktop/Dock4_osx/bin/scorer 1rx3.pdb dock_nrg.mol2 > PK= 6.08 Qual= 2.12 PMF= -159.15 PMF_rb= -144.15 SMoG= -161.27 > SMoG_H= -7.68 ChemScore= -23.86 Clash= 0.85 Int= 2.58 DockNRG= > -24.51 AutoDock= -20.14 > so i'm working on a script which has a function (below) that checks > for this data (the program called can spit out other data when inputs > are bad) then grabs the matches. so now i'm making dictionaries for > each field, using the line number as a key. my pattern match does not > return the first match in the list in position 0. > i.e > [' ', ' 6.08', ' 2.12', '-159.15', '-144.15', '-161.27', '-7.68', > '-23.86', ' 0.85', ' 2.58', '-24.51', '-20.14', '\n'] > so i'm grabbing the data from position 1 in the list etc, and working > from there. Why is this, is this a default behaviour? That's the default behaviour if you split the way you do it. > note the values in the output can be negative or really large, as in > PK= -6.08 etc, or Qual= 12.12 so i use (.*) to grab the region. Why not `.+' so not to match an empty string? > Oh one more thing, if you declare a global, can i simply add > dictionary content, or should one declare and then initialise? The latter; but do you really want such a lot of globals? That's ugly IMO. Here a class with the dictionaries as attributes seems to me to be the right thing. Furthermore you can use in Python named groups for your regexps; that's sometimes very convenient (and you needn't split here). [Code] What do you think about: ******************************************************************** class ScoreOrient (object): score_lines = re.compile('''PK= (?P.*) Qual= (?P.*) PMF= (?P.*)\ PMF_rb= (?P.*) SMoG= (?P.*) SMoG_H= (?P.*) \ ChemScore= (?P.*) Clash= (?P.*) Int= (?P.*) \ DockNRG= (?P.*) AutoDock= (?P.*)''') def __init__(self): self.counter = 1 self.tables = dict(\ [(name , {}) for name in ["score", "qual", "pmf", "pmf_rb", "smog", "smog_h", "chemscore", "clash", "int", "docknrg", "autodock"]]) results = False def __str__(self): s = [] for key in self.tables: s.append(key + '\n') s.append("-" * len(key) + '\n') items = self.tables[key].items() items.sort() for key, val in items: s.append(str(key) + ' -> ' + val + '\n') return ''.join(s) def _pull (self, prog = '/Users/kbranson/Desktop/Dock4_osx/bin/scorer'): self.results = os.popen2("%s %s dock_nrg" % (prog, receptor_pdb)) return self.results[1].readlines() def update (self): for line in self._pull(): m = self.score_lines.search(line) if m: for grp, val in m.groupdict().items(): table = self.tables[grp] table[counter] = val self.counter += 1 ******************************************************************** What is convenient here is the usage of the tables as entries in an dictionary; the names are the same names as the names of the named groups. This makes it extremly easy to access the right table for the right value. You just create an instanze of the class and call its update method to fill the tables. If you use named groups within a regexp a match object has an attribute: its groupdict. The key is the name you gave the group, the value is the matched string. That is here convenient since we can use the name of the group to find the right table in the dictionary with the tables since that name gets used as key. The __str__ method is more a bit fun. You can now just print the instance and the values in the tables are printed in a more or less nice fashion. I couldn't really test the code since I don't have yourt programm here so there may be little bugs in the code (but I hope not). Karl -- Please do *not* send copies of replies to me. I read the list From sigurd at 12move.de Wed Feb 4 20:48:29 2004 From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=) Date: Wed Feb 4 20:50:32 2004 Subject: [Tutor] reg exps In-Reply-To: (Karl =?iso-8859-1?q?Pfl=E4sterer's?= message of "Thu, 05 Feb 2004 02:22:30 +0100") References: Message-ID: On 5 Feb 2004, Karl Pfl?sterer <- sigurd@12move.de wrote: The first error :-( > for grp, val in m.groupdict().items(): > table = self.tables[grp] > table[counter] = val That^^^^^^^ must be self.counter > self.counter += 1 Karl -- Please do *not* send copies of replies to me. I read the list From sigurd at 12move.de Wed Feb 4 20:53:58 2004 From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=) Date: Wed Feb 4 20:55:49 2004 Subject: [Tutor] file transfered through ftplib not the right size In-Reply-To: <402196DC.7000106@seidel.ca> (Michel =?iso-8859-1?q?B=E9langer's?= message of "Wed, 04 Feb 2004 20:05:32 -0500") References: <402196DC.7000106@seidel.ca> Message-ID: On 5 Feb 2004, Michel B?langer <- michel.belanger@seidel.ca wrote: > but the file received is not the right size (larger), i.e. 5150 kb > received vs 5136 kb > Any idea why? I'm not sure but you open the file for writing in text mode. Try it with binary mode. Karl -- Please do *not* send copies of replies to me. I read the list From hans at zephyrfalcon.org Wed Feb 4 21:05:23 2004 From: hans at zephyrfalcon.org (Hans Nowak) Date: Wed Feb 4 21:00:54 2004 Subject: [Tutor] Re: file transfered through ftplib not the right size In-Reply-To: <402196DC.7000106@seidel.ca> References: <402196DC.7000106@seidel.ca> Message-ID: <4021A4E3.1060009@zephyrfalcon.org> Michel B?langer wrote: > then the transfer call for a download is as follow: > > getbinary(ftp, row[0], row[0]) > > but the file received is not the right size (larger), i.e. 5150 kb > received vs 5136 kb > Any idea why? > > > def getbinary(ftp, filename, outfile=None): > # fetch a binary file > if outfile is None: > outfile = sys.stdout > f = open(outfile, "w") Try: f = open(outfile, "wb") This opens the output file in binary mode rather than text mode. HTH, -- Hans (hans@zephyrfalcon.org) http://zephyrfalcon.org/ From michel.belanger at seidel.ca Wed Feb 4 21:10:13 2004 From: michel.belanger at seidel.ca (=?ISO-8859-1?Q?Michel_B=E9langer?=) Date: Wed Feb 4 21:10:21 2004 Subject: [Tutor] file transfered through ftplib not the right size In-Reply-To: References: <402196DC.7000106@seidel.ca> Message-ID: <4021A605.1040101@seidel.ca> As you suggested, I open the file in binary and it did it i.e. before: f = open(outfile, "w") after: f = open(outfile, "wb") Thank you very much. I am new in Python and find this usergroup very efficient. I posted several requests this past week, and always received very useful information. michel belanger Karl Pfl?sterer wrote: >On 5 Feb 2004, Michel B?langer <- michel.belanger@seidel.ca wrote: > > > >>but the file received is not the right size (larger), i.e. 5150 kb >>received vs 5136 kb >>Any idea why? >> >> > >I'm not sure but you open the file for writing in text mode. Try it >with binary > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040204/d3d15106/attachment.html From isrgish at fusemail.com Thu Feb 5 00:15:40 2004 From: isrgish at fusemail.com (Isr Gish) Date: Thu Feb 5 00:16:20 2004 Subject: [Tutor] glob module Message-ID: -----Original Message----- >From: "Gerrit" >Sent: 2/4/04 11:30:08 AM >To: "Isr Gish" >Cc: "tutor@python.org" >Subject: Re: [Tutor] glob module >Isr Gish wrote: >> Docs >> recipes >> new >> old >> help >> all >> ... >> I want to find all files with "a*.txt" from whole tree of Docs how would I do that. I understand that I could iterate the whole tree. But what I would like to know, if it can be done, with the glob module. > >If it's always 3 levels deep, you can use '*/*/a*.txt'. >That makes using os.walk unnecesary. Thanks Gerrit, This was only an example in realty I want to get files from all levels. I guess I'll have to do a walk. Isr From gerrit at nl.linux.org Thu Feb 5 08:31:21 2004 From: gerrit at nl.linux.org (Gerrit) Date: Thu Feb 5 08:31:39 2004 Subject: [Tutor] Maths (slightly OT) In-Reply-To: References: <2ksv1090cbgemb7m8grftehtbu5c8tvcfh@4ax.com> Message-ID: <20040205133121.GA3822@nl.linux.org> Danny Yoo wrote: > Math is not an artificial construct, but a very human endeavor: Aren't artificial contructs especially human? ;-) Gerrit. -- PrePEP: Builtin path type http://people.nl.linux.org/~gerrit/creaties/path/pep-xxxx.html Asperger's Syndrome - a personal approach: http://people.nl.linux.org/~gerrit/english/ From Janssen at rz.uni-frankfurt.de Thu Feb 5 09:51:08 2004 From: Janssen at rz.uni-frankfurt.de (Michael Janssen) Date: Thu Feb 5 09:51:23 2004 Subject: [Tutor] reg exps (fwd) Message-ID: On Thu, 5 Feb 2004, Kim Branson wrote: > i have a program which will spit out data like so: > % ~/Desktop/Dock4_osx/bin/scorer 1rx3.pdb dock_nrg.mol2 > PK= 6.08 Qual= 2.12 PMF= -159.15 PMF_rb= -144.15 SMoG= -161.27 > SMoG_H= -7.68 ChemScore= -23.86 Clash= 0.85 Int= 2.58 DockNRG= -24.51 > AutoDock= -20.14 > score_lines = re.compile('PK= (.*) Qual= (.*) PMF= (.*) PMF_rb= > (.*) SMoG= (.*) SMoG_H= (.*) ChemScore= (.*) Clash= (.*) Int= (.*) > DockNRG= (.*) AutoDock= (.*)') The regular expression seems a bit to long for my taste. When you only want to retrieve the numerical values you can much easier do: # untestet reg_values = re.compile('[-0-9.]+') values = re.findall(reg_values, line) for name, val in zip(a_list_of_all_names_in_order, values): print name, val A long regexp is bad, when something in the line changes (you wont' get any output at all then). OTOH Karl's suggestions with named groups has the advantages that you only need to change the regexp, when the output changes. Michael From syn_ack at comcast.net Thu Feb 5 12:53:45 2004 From: syn_ack at comcast.net (Joshua Banks) Date: Thu Feb 5 12:58:12 2004 Subject: [Tutor] Looking for some guidance. Message-ID: <200402050953.48519.syn_ack@comcast.net> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hello, I've embarked upon the Python journey. Running Python 2.3.3 on Gentoo linux. Wahoo... I've been running Linux for almost a yr now and this proves to be a never-ending learning experience. I have absolutely no programming experience at all. Not even shell scripting. Right now I feel it little overwhelmed with all the documentation that I have. I'm sure that I'm not the only one that has felt this way. The frustrating part of my initial step towards learning Python is, almost all of the tutorials that I have seem to wiz through all of the concepts and symantics without reinforcing the newly learned concepts with exercises, exercises, exercises....examples, examples and then the examples explained. I'm finding myself jumping from book to book, tutorial to tutorial feeling like I'll find something eventually that will fit. This is why I'm asking for guidance. At this point I don't know if I'm being to anal retentive thinking that I need to understand every little thing I read, or that maybe there's a tutorial that I'm missing. Is there a proven structured path to Enlightenment?? I guess what I'm asking for is a suggestion of how a non-programmer can best progress from a non-programmer to starting to put these Python concepts to use. Do I just plow through a tutorial and goto the next eventually at some point slowly understanding? Thanks, -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.3 (GNU/Linux) iD8DBQFAIoMqp9X7q/XgeyYRAjmXAJ4mVaJ0aOl39x6fGC3lNGs0jcO6yACgmPB/ 6jyEFRxojGZHOVFjhbl5jPc= =OGlf -----END PGP SIGNATURE----- From Christian.Wyglendowski at greenville.edu Thu Feb 5 13:05:56 2004 From: Christian.Wyglendowski at greenville.edu (Christian Wyglendowski) Date: Thu Feb 5 13:06:04 2004 Subject: [Tutor] RE: [python-win32] Executable file version in windows Message-ID: > -----Original Message----- > How can I query a file executable (exe, dll, com)for its version > including the revision, i.e. > > exemple: > >>>queryVersion("someprog.exe") > 5.1.2 Here is another way: >>> from win32com.client import Dispatch >>> fso = Dispatch('Scripting.FileSystemObject') >>> fso.GetFileVersion(r'c:\windows\system32\cacls.exe') u'5.1.2600.0' >>> fso.GetFileVersion(r'c:\windows\system32\ntdll.dll') u'5.1.2600.1217' > Many thanks You're welcome! Christian http://www.dowski.com From Janssen at rz.uni-frankfurt.de Thu Feb 5 13:59:32 2004 From: Janssen at rz.uni-frankfurt.de (Michael Janssen) Date: Thu Feb 5 13:59:44 2004 Subject: [Tutor] Looking for some guidance. In-Reply-To: <200402050953.48519.syn_ack@comcast.net> References: <200402050953.48519.syn_ack@comcast.net> Message-ID: On Thu, 5 Feb 2004, Joshua Banks wrote: > Right now I feel it little overwhelmed with all the documentation that I > have. I'm sure that I'm not the only one that has felt this way. After reading the "official tutorial" I felt more like "such few concepts can't be programming already, can them?". Indeed it took me some time to accept, that doing a little for-loop, some if-thingies and firing up string and list methods is already the half way to write a script that actually do something what one might expect a script to do. Learnig how to do functions a week after has greatly improven my style ;-) > The > frustrating part of my initial step towards learning Python is, almost > all of the tutorials that I have seem to wiz through all of the > concepts and symantics without reinforcing the newly learned concepts > with exercises, exercises, exercises....examples, examples and then the > examples explained. So you probably can make up the examples for yourself. Just fire up interpreter and do something. In my first month I spent a lot of time with the interpreter cutting&pasting code between it and editor and testing every step I take. Perhaps not the most efficient way to code, but my script I wrote in my second week still do some valueable stuff (and would cost me some hours to write nowadays...) > I'm finding myself jumping from book to book, tutorial to tutorial > feeling like I'll find something eventually that will fit. This is why > I'm asking for guidance. At this point I don't know if I'm being to > anal retentive thinking that I need to understand every little thing I > read, or that maybe there's a tutorial that I'm missing. Is there a > proven structured path to Enlightenment?? > > I guess what I'm asking for is a suggestion of how a non-programmer can > best progress from a non-programmer to starting to put these Python > concepts to use. Do I just plow through a tutorial and goto the next > eventually at some point slowly understanding? I would suggest after reading two or three tutorials look out for a small task and try to code it down. The good thing is that python isn't that hard. Another good thing is that the python community is known as newbie friendly :-) So, whenever you're stuck ask for help. Such a "small task" is an important step on the path to programming, because you won't learn it well without actually trying. One tricky thing is to determine, which task is small but the rest is done with functions, for- and while-loops, if-clauses, string-, lists- and dicts-methods and some helpful functions from os, time, re and sys modul. Michael From marilyn at deliberate.com Thu Feb 5 14:19:46 2004 From: marilyn at deliberate.com (Marilyn Davis) Date: Thu Feb 5 14:20:25 2004 Subject: [Tutor] Looking for some guidance. In-Reply-To: <200402050953.48519.syn_ack@comcast.net> Message-ID: On Thu, 5 Feb 2004, Joshua Banks wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > Hello, > > I've embarked upon the Python journey. Running Python 2.3.3 on Gentoo > linux. Wahoo... Indeed! Congratulations. Do you have idle running too? > > I've been running Linux for almost a yr now and this proves to be a > never-ending learning experience. I have absolutely no programming > experience at all. Not even shell scripting. > > Right now I feel it little overwhelmed with all the documentation that I > have. I'm sure that I'm not the only one that has felt this way. The > frustrating part of my initial step towards learning Python is, almost > all of the tutorials that I have seem to wiz through all of the > concepts and symantics without reinforcing the newly learned concepts > with exercises, exercises, exercises....examples, examples and then the > examples explained. > > I'm finding myself jumping from book to book, tutorial to tutorial > feeling like I'll find something eventually that will fit. This is why > I'm asking for guidance. At this point I don't know if I'm being to I'm aware of 2 books that are aimed at people with no previous programming experience. Neither covers everything. The tutorial covers everything, I think. "Python How to Program" by Deitel, et. al. "Python Programming An Introduction to Computer Science" by Zelle. Although they don't provide solutions to the exercises, I'll bet, if you posted your trial solutions, you'd get lots of help here. > anal retentive thinking that I need to understand every little thing I > read, or that maybe there's a tutorial that I'm missing. Is there a > proven structured path to Enlightenment?? Ha ha. Follow your nose? :^) > > I guess what I'm asking for is a suggestion of how a non-programmer can > best progress from a non-programmer to starting to put these Python > concepts to use. Do I just plow through a tutorial and goto the next > eventually at some point slowly understanding? No. Like you say, a beginner needs practice at every step of the way. Good luck. And prepare to be blown away with your new powers. Marilyn Davis > > Thanks, > -----BEGIN PGP SIGNATURE----- > Version: GnuPG v1.2.3 (GNU/Linux) > > iD8DBQFAIoMqp9X7q/XgeyYRAjmXAJ4mVaJ0aOl39x6fGC3lNGs0jcO6yACgmPB/ > 6jyEFRxojGZHOVFjhbl5jPc= > =OGlf > -----END PGP SIGNATURE----- > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- From syn_ack at comcast.net Thu Feb 5 14:20:58 2004 From: syn_ack at comcast.net (Joshua Banks) Date: Thu Feb 5 14:25:25 2004 Subject: [Tutor] Looking for some guidance. In-Reply-To: References: <200402050953.48519.syn_ack@comcast.net> Message-ID: <200402051121.00634.syn_ack@comcast.net> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On Thursday 05 February 2004 10:59 am, Michael Janssen wrote: > I would suggest after reading two or three tutorials look out for a > small task and try to code it down. The good thing is that python > isn't that hard. Another good thing is that the python community is > known as newbie friendly :-) So, whenever you're stuck ask for help. > > Such a "small task" is an important step on the path to programming, > because you won't learn it well without actually trying. One tricky > thing is to determine, which task is small but the rest is done with > functions, for- and while-loops, if-clauses, string-, lists- and > dicts-methods and some helpful functions from os, time, re and sys > modul. > > Michael Great. Thanks Michael. I'll keep pounding away then. I've looked at the FAQ's and unless I've overlooked something, is there a preferred directory that I can store my Python scripts. I would like to have the ability to place the scripts somewhere where I have the ability to execute them from any directory that I happen to be in. E.G. If I make my *.py scripts executable and place them in /usr/local/bin I can execute them from any directory as a normal user just by name, from eterm or a console shell, instead of having to put in the full path to the file/script. >>> import sys >>> sys.path ['', '/usr/lib/python23.zip', '/usr/lib/python2.3', '/usr/lib/python2.3/plat-linux2', '/usr/lib/python2.3/lib-tk', '/usr/lib/python2.3/lib-dynload', '/usr/lib/python2.3/site-packages', '/usr/lib/portage/pym'] Thanks, Joshua Banks -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.3 (GNU/Linux) iD8DBQFAIpeap9X7q/XgeyYRAsb+AJ9EPQwLteyKB+uv21AcBn/GHt7zlACgjQU2 a7thI103j8Ou9Y0YahqGaUc= =EliO -----END PGP SIGNATURE----- From renderpipe at speedpost.net Thu Feb 5 14:31:24 2004 From: renderpipe at speedpost.net (RenderPipe) Date: Thu Feb 5 14:31:30 2004 Subject: [Tutor] Newbie trying to understand modules and code reuse Message-ID: <20040205193124.8A286154DF0@mail.messagingengine.com> Hello, I'm having a difficult time trying to understand modules with python. I used to write php applications and am used to including files in the header of the document(include "file.php"). This also makes code reuse easier. I'm under the impression modules in python work this way. My problem is, I don't know how to write a module. I have read the manuals and it just doesn't make sense yet. Ultimately I'd like to create 2 "include files". 1 will be a class file that I plan to reuse throughout my application and 1 file will be a list of variables. I tried create a file and putting it in my /python/lib directory and importing it. Surprisingly I was able to import it but I was unable to access the variables or methods in the file. Am I seeking modules incorrectly? Perhaps I should use something else for code reuse? I'm using WindowsXP with ActivePython tia Bobby -- http://www.fastmail.fm - Same, same, but different From zmerch at 30below.com Thu Feb 5 15:17:59 2004 From: zmerch at 30below.com (Roger Merchberger) Date: Thu Feb 5 15:17:45 2004 Subject: [Tutor] Looking for some guidance. In-Reply-To: <200402051121.00634.syn_ack@comcast.net> References: <200402050953.48519.syn_ack@comcast.net> Message-ID: <5.1.0.14.2.20040205150702.04cbe728@mail.30below.com> Rumor has it that Joshua Banks may have mentioned these words: >I've looked at the FAQ's and unless I've overlooked something, is there >a preferred directory that I can store my Python scripts. Nope. Stick 'em anywhere you want... ;-) > I would like >to have the ability to place the scripts somewhere where I have the >ability to execute them from any directory that I happen to be in. E.G. >If I make my *.py scripts executable and place them in /usr/local/bin I >can execute them from any directory as a normal user just by name, from >eterm or a console shell, instead of having to put in the full path to >the file/script. /usr/local/bin is good, but it can get cluttered as you start installing more software on the system... If you want a centralized place to put your scripts in your home directory, you can, like this: /home/zmerch/pyscripts and if you cd to /home/zmerch/pyscripts normally to work on the scripts anyway, all you have to type in is: ./samplescript.py and it will execute, if: 1) you remember to put the bangpath line as the first line of the script, like: #!/usr/bin/python -or- #!/bin/env /usr/bin/python (I think, I don't use this method myself) 2) make sure you set the script executible: chmod 755 samplescript.py --if you want *any* userid to run it, or chmod 744 samplescript.py --if you want only your userid to run it. =-=-=-=-=-=-=-=-=-=-= If you wanted to make a directory for your scripts that's world findable, but not /usr/local/bin for clarity, make one up, like: /usr/local/pyscripts and edit your /etc/profile to say something like this: PATH=${PATH}:/usr/local/pyscripts export PATH [[ the previous line is heavily dependant on the flavor of shell you run. If you're running bash, this *should* work, but it is untested, so YMMV. ;-) ]] HTH, Roger "Merch" Merchberger -- Roger "Merch" Merchberger | A new truth in advertising slogan sysadmin, Iceberg Computers | for MicroSoft: "We're not the oxy... zmerch@30below.com | ...in oxymoron!" From project5 at redrival.net Thu Feb 5 15:16:47 2004 From: project5 at redrival.net (Andrei) Date: Thu Feb 5 15:20:15 2004 Subject: [Tutor] Re: Newbie trying to understand modules and code reuse References: <20040205193124.8A286154DF0@mail.messagingengine.com> Message-ID: RenderPipe wrote on Thu, 05 Feb 2004 14:31:24 -0500: > I'm having a difficult time trying to understand modules with python. I > used to write php applications and am used to including files in the > header of the document(include "file.php"). This also makes code reuse > easier. I'm under the impression modules in python work this way. I don't know about PHP, but modules in Python are not quite the same as copy-pasting the code in that module into your main app. > My problem is, I don't know how to write a module. I have read the > manuals and it just doesn't make sense yet. Ultimately I'd like to create > 2 "include files". Make a file and write some Python in it. It's a module! Write in your "import something" (with being in some path where Python can find it, e.g. in the same folder as or in Python's lib) and that's it. > 1 will be a class file that I plan to reuse throughout my application and > 1 file will be a list of variables. I wouldn't put variables in a seaparate file unless it really makes sense for them to be separated from the main code. Not quite likely I think. > I tried create a file and putting it in my /python/lib directory and > importing it. Surprisingly I was able to import it but I was unable to > access the variables or methods in the file. It depends on how you import. (1) If you do "from somemodule import *" you get its entire contents in your current name. This is a lot like a verbatim copy-pasting of the module contens in your application. You should NOT use this method because it can cause you a lot of problems (e.g. if two modules contain variables or whatever with identical names). (2) If you do "import somemodule", you'll have to access that module's contents by using the dot-notation, e.g. "somemodule.myclass". This is the preferred method of importing modules. (3) Now if your module has some really long name, you can do "import somemodule as m". Then you can access its contents using e.g. "m.myclass". > Am I seeking modules incorrectly? Perhaps I should use something else for > code reuse? No, modules are fine, but they're not as special as you think. ANY Python file is a module and any module is a script (it might just not do anything particularly interesting on its own). Many modules in fact even come with some test code which is only executed if the module is started on its own (not imported). That code is then used by the author of the script/module to demonstrate its uses. -- Yours, Andrei ===== Mail address in header catches spam. Real contact info (decode with rot13): cebwrpg5@jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From karl.fast at pobox.com Thu Feb 5 15:25:17 2004 From: karl.fast at pobox.com (Karl Fast) Date: Thu Feb 5 15:27:04 2004 Subject: [Tutor] Newbie trying to understand modules and code reuse In-Reply-To: <20040205193124.8A286154DF0@mail.messagingengine.com>; from renderpipe@speedpost.net on Thu, Feb 05, 2004 at 02:31:24PM -0500 References: <20040205193124.8A286154DF0@mail.messagingengine.com> Message-ID: <20040205142517.D11400@signal.lights.com> > I tried create a file and putting it in my /python/lib directory and > importing it. Surprisingly I was able to import it but I was unable > to access the variables or methods in the file. Namespaces are an important concept in Python and I suspect that is what's tripping you up. If it gets imported then you should be fine. When you import something all of the variables and functions (or classes) are available in that namespace. Suppose you've for a module called "mymodule.py" and it looks kinda like this: myvar = "something" def myfunction(): print "something else" Now suppose you've got that module somewhere in your python library path (that is, when you importy mymodule, python can find it). So now you write a script called "myscript.py" and you import that module. It looks like this: import mymodule print mymodule.myvar mymodolue.myfunction() When you run this the output should be: something something else The trick is that python imports everything into the mymodule namespace and that's how you access it. You can import them directly into the main namespace by doing something like this: from mymodule import * print myvar myfunction() Note the difference. Now the variable and the function are not qualified as being part of the mymodule namespace. Namespaces are really important in python. They are in most programming languages actually. The syntax is different and some behaviours are slightly different, but the basic concept is pretty universally consistent. --karl From cspears2002 at yahoo.com Thu Feb 5 16:18:07 2004 From: cspears2002 at yahoo.com (Christopher Spears) Date: Thu Feb 5 16:18:14 2004 Subject: [Tutor] printing answers Message-ID: <20040205211807.99141.qmail@web12406.mail.yahoo.com> I'm writing a function that takes a list of strings and finds any identical strings. Case should not matter. For example, in ['one','One', 'two', 'three', 'ThrEE'], one and One and three and ThrEE should be recognized as pairs. I wrote the following code: def findMatch(list_of_strings): import re answers = [] for i in range(len(list_of_strings)): pattern = re.compile(list_of_strings[i], re.I) for i in range(len(list_of_strings)): match = re.match(pattern, list_of_strings[i]) if match != None: answers = answers + [list_of_strings[i]] print answers My problem is printing out the correct answers. When I ran a test, I got the following result: >>> findMatch(['one', 'two', 'One']) ['one', 'One', 'two', 'one', 'One'] What am I doing wrong? I think my logic is correct. -Chris From syn_ack at comcast.net Thu Feb 5 15:41:04 2004 From: syn_ack at comcast.net (Joshua Banks) Date: Thu Feb 5 16:34:10 2004 Subject: [Tutor] Looking for some guidance. In-Reply-To: References: Message-ID: <200402051241.06627.syn_ack@comcast.net> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On Thursday 05 February 2004 11:19 am, Marilyn Davis wrote: > Indeed! Congratulations. Do you have idle running too? Yes. > I'm aware of 2 books that are aimed at people with no previous > programming experience. Neither covers everything. The tutorial > covers everything, I think. > > "Python How to Program" by Deitel, et. al. > > "Python Programming An Introduction to Computer Science" by Zelle. > > Although they don't provide solutions to the exercises, I'll bet, if > you posted your trial solutions, you'd get lots of help here. Thanks. Thats good to know. Right now I've got 2 books. "Learning Python" by Oreilly. This is a pretty good book. And "Learn to Program Using Python" by Alan Gauld. > Ha ha. > > Follow your nose? :^) It was a shot in the dark. :P > No. Like you say, a beginner needs practice at every step of the > way. > > Good luck. And prepare to be blown away with your new powers. > > Marilyn Davis Thanks. That proved to be good moral boost and then some. Joshua Banks -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.3 (GNU/Linux) iD8DBQFAIqpgp9X7q/XgeyYRAnKvAJ9EsUsv7K5l7+YdKC7299l7GiFgogCgjlPj YecSEXybPCW4EwqDT+s/+5A= =aXen -----END PGP SIGNATURE----- From alan.gauld at blueyonder.co.uk Thu Feb 5 16:43:52 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Feb 5 16:45:30 2004 Subject: [Tutor] printing answers References: <20040205211807.99141.qmail@web12406.mail.yahoo.com> Message-ID: <006201c3ec31$25874300$6401a8c0@xp> > for i in range(len(list_of_strings)): > pattern = re.compile(list_of_strings[i], re.I) > for i in range(len(list_of_strings)): You are using the same name for both counters so you will overwrite the fist loop value with the second each time. Very confusing. But why use indexing, you could just use for aString in list_of_strings: pattern = re.compile(aString,re.I) for item in list_of_strings: .... Its clearer and more efficient. Of course you still need two loop variable names to avoid your overwriting issue. Alan G. From brian at connellyman.com Thu Feb 5 16:46:56 2004 From: brian at connellyman.com (Brian Connelly) Date: Thu Feb 5 16:46:54 2004 Subject: [Tutor] Zope and Python... Message-ID: Hey guys and Gals... Just looking for peoples experience on Zope --- What is the tutor thoughts on it ? Those that use it what are your gripes or praises and if you don't like Zope is there something else you would recommend to give a similar functionality. I am finding it hard to find good "easy" beginner documentation on application building in Zope. I've gone through the Devshed documents and the zope book but I have found many problems in the examples and just the version diffs in Zope. Are there any good resources that anyone would suggest for Learning to develop apps under Zope ? Thanks BCC -------------- next part -------------- A non-text attachment was scrubbed... Name: winmail.dat Type: application/ms-tnef Size: 3502 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20040205/c03bcef0/winmail.bin From rmkrauter at yahoo.com Thu Feb 5 16:49:19 2004 From: rmkrauter at yahoo.com (Rich Krauter) Date: Thu Feb 5 16:49:25 2004 Subject: [Tutor] printing answers Message-ID: <20040205214919.7756.qmail@web40109.mail.yahoo.com> I think you are saying you want to eliminate duplicates, without regard to case. That's what I do below. I think you're making it much harder than it needs to be by using regexes and nested loops. Notice I use answers as a dict, not a list. Dicts are nice when you want to get rid of repeats. def findMatch(list_of_strings): answers = {} for s in list_of_strings: try: answers[s.lower()] += 1 except: answers[s.lower()] = 1 print answers.keys() print answers if __name__ == '__main__': list_of_strings = ['one','One', 'two', 'three','ThrEE'] findMatch(list_of_strings) Rich __________________________________ Do you Yahoo!? Yahoo! Finance: Get your refund fast by filing online. http://taxes.yahoo.com/filing.html From alan.gauld at blueyonder.co.uk Thu Feb 5 17:23:31 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Feb 5 17:25:14 2004 Subject: [Tutor] Newbie trying to understand modules and code reuse References: <20040205193124.8A286154DF0@mail.messagingengine.com> Message-ID: <006b01c3ec36$afe4c360$6401a8c0@xp> > I'm having a difficult time trying to understand modules > with python. I used to write php applications and am used > to including files In Python you don't include files you import names. This is an important distinction. > My problem is, I don't know how to write a module. > I have read the manuals and it just doesn't make sense yet. OK, I dunno which bits you read but a module in Python is just a file full of python code. Lets call it mymodule.py If you do import mymodule you make the name of the module available in your file. At the same time Python will execute the file and thus any function or class definitions will be executed and the functions and classes will be available for use. BUT their names will be inside the mymodule object. To access anything inside the module you need to prepend it with the module object name: mymodule.myfunction() If the file name is long you might like to rename the module by importing it like this: import mymodule as m Now we can access the function like this: m.myfunction() The module object remains the same we have just given it a shorter name. The other way to get at the contents of a module is to do this: from mymodule import myfunction This brings the name myfunction into your file but not the name mymodule nor any of the other names within mymodule. You can also "from mymodule import *" but that's usually a bad idea since it brings all the names from mymodule into your file, potentially overwriting some of them. > Ultimately I'd like to create 2 "include files". Two modules > 1 will be a class file that I plan to reuse throughout my application This is a good idea. > 1 file will be a list of variables. THis is an extremely bad idea. The whole idea of modules controlling names is to avoid global variables spilling over from one module to another. Its much better to keep the variables within the modules where they are needed. You can access them by prefixing with the parent module's name. > I tried create a file and putting it in my /python/lib > directory and importing it. Surprisingly I was able to > import it but I was unable to access the variables or > methods in the file. AS I described above you import the name of the module into your local namespace. You do not import the file itself. Thats why we "import mymodule" and not "mymodule.py" > Perhaps I should use something else for code reuse? You have the right idea but just need to adapt from the C/C++/PHP style of copy n paste include to the more theoretically sound importing of names. You might like to read both the modules and namespaces topics in my tutorial. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From syn_ack at comcast.net Thu Feb 5 15:55:52 2004 From: syn_ack at comcast.net (Joshua Banks) Date: Thu Feb 5 17:27:13 2004 Subject: [Tutor] Looking for some guidance. In-Reply-To: <5.1.0.14.2.20040205150702.04cbe728@mail.30below.com> References: <5.1.0.14.2.20040205150702.04cbe728@mail.30below.com> Message-ID: <200402051255.54521.syn_ack@comcast.net> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On Thursday 05 February 2004 12:17 pm, Roger Merchberger wrote: > /usr/local/bin is good, but it can get cluttered as you start > installing more software on the system... Ahhhhh.. I was wondering why this directory was bone dry. All exec's are in "/usr/bin" for normal software that gets installed. It's been like this for 6 mnths. I believe this happend because of the way that I intially partioned my drive..... Anyways, thanks though.. One less think I have to curious about know. Heh.. > 1) you remember to put the bangpath line as the first line of the > script, like: > > #!/usr/bin/python -or- > #!/bin/env /usr/bin/python (I think, I don't use this method myself) Yup. I just use #!/usr/bin/python > 2) make sure you set the script executible: > > chmod 755 samplescript.py --if you want *any* userid to run it, or > chmod 744 samplescript.py --if you want only your userid to run it. I've been using "chmod +x file.py" But I understand what your saying here. > If you wanted to make a directory for your scripts that's world > findable, but not /usr/local/bin for clarity, make one up, like: > > /usr/local/pyscripts > > and edit your /etc/profile to say something like this: > > PATH=${PATH}:/usr/local/pyscripts > export PATH > > [[ the previous line is heavily dependant on the flavor of shell you > run. If you're running bash, this *should* work, but it is untested, > so YMMV. ;-) ]] Ahhhhhh Yesssss. YOU ROCK... that's what I was looking for. Cool. ...... Thanks Roger. -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.3 (GNU/Linux) iD8DBQFAIq3Yp9X7q/XgeyYRAha+AKCYxWUoyYjhZr9HY1syrE02M5sI9QCghMx7 fMoSBCXIQeZNv2zeUFIFaiE= =vLFP -----END PGP SIGNATURE----- From from_python_tutor at SSokolow.com Thu Feb 5 17:34:57 2004 From: from_python_tutor at SSokolow.com (SSokolow) Date: Thu Feb 5 17:35:06 2004 Subject: [Tutor] Newbie trying to understand modules and code reuse In-Reply-To: <006b01c3ec36$afe4c360$6401a8c0@xp> References: <20040205193124.8A286154DF0@mail.messagingengine.com> <006b01c3ec36$afe4c360$6401a8c0@xp> Message-ID: <4022C511.3040605@SSokolow.com> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040205/32087573/attachment.html From alan.gauld at blueyonder.co.uk Thu Feb 5 16:36:26 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Feb 5 17:39:25 2004 Subject: [Tutor] Looking for some guidance. References: Message-ID: <002e01c3ec30$1c3f1f30$6401a8c0@xp> > I'm aware of 2 books that are aimed at people with no previous > programming experience. Neither covers everything. The tutorial > covers everything, I think. > > "Python How to Program" by Deitel, et. al. > > "Python Programming An Introduction to Computer Science" by Zelle. I'll add Teach Yourself Python in 24 Hours by Ivan van Lanningham and my own effort Learn to Program using Python Ivan's book focusses on teaching Python, mine focusses on teching programming and just happens (although not by accident!) to use Python to demonstate the concepts. None of the 4 will make you an expert although the Dietel book will cover more topics than the others - and costs a lot more... > > read, or that maybe there's a tutorial that I'm missing. Is there a > > proven structured path to Enlightenment?? Yes, its called practice! Seriously the best way to learn to program is to take the examples in the boooks and extend them in diffreent ways. If the example prints the 12 times table, change it to print the 9 times table, then to do it in a different format, then to print the squares from 1 to 12 instead. Just little changes but by making those changes you reinforce the ideas and prove to yourself that you really understand what's happening. Finally don't try to run before you walk. A GUI interface may look nice but trying to add one too soon will simply distract you from the fundamentals. Alan G. From renderpipe at speedpost.net Thu Feb 5 17:39:40 2004 From: renderpipe at speedpost.net (RenderPipe) Date: Thu Feb 5 17:39:52 2004 Subject: [Tutor] Newbie trying to understand modules and code reuse In-Reply-To: <006b01c3ec36$afe4c360$6401a8c0@xp> References: <20040205193124.8A286154DF0@mail.messagingengine.com> <006b01c3ec36$afe4c360$6401a8c0@xp> Message-ID: <20040205223940.34881152F51@mail.messagingengine.com> Cool! Now I understand. I'll read up on that tutorial too. Thanks to everyone for their helpful response. Bobby On Thu, 5 Feb 2004 22:23:31 -0000, "Alan Gauld" said: > > I'm having a difficult time trying to understand modules > > with python. I used to write php applications and am used > > to including files > > In Python you don't include files you import names. > This is an important distinction. > > > My problem is, I don't know how to write a module. > > I have read the manuals and it just doesn't make sense yet. > > OK, I dunno which bits you read but a module in Python is > just a file full of python code. Lets call it mymodule.py > > If you do > > import mymodule > > you make the name of the module available in your file. > At the same time Python will execute the file and thus > any function or class definitions will be executed and > the functions and classes will be available for use. > BUT their names will be inside the mymodule object. > > To access anything inside the module you need to prepend > it with the module object name: > > mymodule.myfunction() > > If the file name is long you might like to rename the module > by importing it like this: > > import mymodule as m > > Now we can access the function like this: > > m.myfunction() > > The module object remains the same we have just given it a > shorter name. > > The other way to get at the contents of a module is to do this: > > from mymodule import myfunction > > This brings the name myfunction into your file but not the > name mymodule nor any of the other names within mymodule. > You can also "from mymodule import *" but that's usually > a bad idea since it brings all the names from mymodule into > your file, potentially overwriting some of them. > > > Ultimately I'd like to create 2 "include files". > > Two modules > > > 1 will be a class file that I plan to reuse throughout my > application > > This is a good idea. > > > 1 file will be a list of variables. > > THis is an extremely bad idea. The whole idea of modules > controlling names is to avoid global variables spilling > over from one module to another. Its much better to keep > the variables within the modules where they are needed. > You can access them by prefixing with the parent module's > name. > > > I tried create a file and putting it in my /python/lib > > directory and importing it. Surprisingly I was able to > > import it but I was unable to access the variables or > > methods in the file. > > AS I described above you import the name of the module > into your local namespace. You do not import the file itself. > Thats why we "import mymodule" and not "mymodule.py" > > > Perhaps I should use something else for code reuse? > > You have the right idea but just need to adapt from > the C/C++/PHP style of copy n paste include to the more > theoretically sound importing of names. > > You might like to read both the modules and namespaces topics > in my tutorial. > > Alan G > Author of the Learn to Program web tutor > http://www.freenetpages.co.uk/hp/alan.gauld > -- http://www.fastmail.fm - Choose from over 50 domains or use your own From aschmidt at fredericksburg.com Thu Feb 5 17:55:13 2004 From: aschmidt at fredericksburg.com (Allen) Date: Thu Feb 5 17:55:42 2004 Subject: [Tutor] Zope and Python... In-Reply-To: References: Message-ID: <4022C9D1.4070205@fredericksburg.com> Brian Connelly wrote: > Those that use it what are your gripes or praises and if you don't like Zope I hang out here for Python nuggets to help make my work with Zope more meaningful. I love it and we have had fantastic success with it. Zope is going through some great changes and is improving all the time. Sure it's a lot of work to get going and there is a steep learning curve...but the results are well worth the effort. I will toot our horn here.. take a look at www.fredericksburg.com It is all built with Zope and Python and MySQL for some of the data chunks. It is a newspaper website with a ton more. The new ZPT or zope page templates are really slick. ZPT is used for presentation and all the logic is in Python! Works out well. Most of what we have now is the older DTML which is slowing going away. And some of the new products for Zope like Plone and their CMF for content management are amazing. The Zope Corporation lives right down the street from us here in Fredericksburg, Virginia. And for those that don't know, Zope also 'owns' PythonLabs. (not sure if owns is the right word, hence the quotes) Hope that helps. Would love to discuss Zope off this list with anyone, anytime. The Zope mailing list is very active 24 hours a day. But do Google for answers first, as many newbie issues have been beaten to death. But do feel free to ask... good bunch of folks there. Allen From alan.gauld at blueyonder.co.uk Thu Feb 5 18:00:39 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Feb 5 18:02:15 2004 Subject: [Tutor] Looking for some guidance. References: <5.1.0.14.2.20040205150702.04cbe728@mail.30below.com> <200402051255.54521.syn_ack@comcast.net> Message-ID: <008901c3ec3b$df93b210$6401a8c0@xp> > /usr/local/bin is good, but it can get cluttered as you start > installing more software on the system... Ahhhhh.. I was wondering why this directory was bone dry. All exec's are in "/usr/bin" for normal software that gets installed. usr/bin is usually for system software that users can execute (as opposed to daemons and sys admin type stuff which is uisally in sbin) /usr/local/bin is for stuff you create or install locally. The naming and assumption comes from the days that most computers were running code that was written locally for a specific purpose - ie before shrinkwrap applications were commonplace. Nowadays applications can be found all over the place and it gets confusing :-( > #!/usr/bin/python -or- > #!/bin/env /usr/bin/python (I think, I don't use this method myself) I beliebe that should be /usr/env python which is more portable since it will find python even if its not in the same place as on your machine. > Yup. I just use #!/usr/bin/python But, confession time, so do I formy own programs! :-) Alan G. From alan.gauld at blueyonder.co.uk Thu Feb 5 18:04:51 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Feb 5 18:06:33 2004 Subject: [Tutor] Newbie trying to understand modules and code reuse References: <20040205193124.8A286154DF0@mail.messagingengine.com><006b01c3ec36$afe4c360$6401a8c0@xp> <4022C511.3040605@SSokolow.com> Message-ID: <008d01c3ec3c$75d91620$6401a8c0@xp> > Although the more recent versions of the C++ language > do have a limited implementation of namespaces. Actually its quite a sophisticated namespace mechanism, and in some ways is better than Pythons(IMHO) - you can add names to a namespace retrospectively, modify the scope of namespaces, have multiple namespaces within a file, even within a function etc. But it is entirely separated from the prinitive #include functionality borrowed from C which is what I was referring to. > #include > cout << "Hello World!\n" > is now deprecated in favor of > #include > std::cout << "Hello World!\n" Indeed, although you can work some magic to remove the need for the std:: but it has similar issues to using from module import * in Python. Alan G. From marilyn at deliberate.com Thu Feb 5 18:14:08 2004 From: marilyn at deliberate.com (Marilyn Davis) Date: Thu Feb 5 18:14:28 2004 Subject: [Tutor] fancy list things Message-ID: I'm trying to solidify my understanding of list comprehensions and other fancies. Is it true that you can *always* replace map() and filter() with a list comprehension? But you can never replace reduce()? Can anyone give me a reasonable example of lambda? Thank you for any help. Marilyn Davis From syn_ack at comcast.net Thu Feb 5 18:14:12 2004 From: syn_ack at comcast.net (Joshua Banks) Date: Thu Feb 5 18:18:31 2004 Subject: [Tutor] Looking for some guidance. In-Reply-To: <002e01c3ec30$1c3f1f30$6401a8c0@xp> References: <002e01c3ec30$1c3f1f30$6401a8c0@xp> Message-ID: <200402051514.14108.syn_ack@comcast.net> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On Thursday 05 February 2004 01:36 pm, Alan Gauld wrote: > Yes, its called practice! > Seriously the best way to learn to program is to take the examples > in the boooks and extend them in diffreent ways. > > If the example prints the 12 times table, change it to print > the 9 times table, then to do it in a different format, then to > print the squares from 1 to 12 instead. Just little changes but > by making those changes you reinforce the ideas and prove to > yourself that you really understand what's happening. > > Finally don't try to run before you walk. A GUI interface may > look nice but trying to add one too soon will simply distract > you from the fundamentals. Great. Thanks for the suggestions Alan. Well it looks like I might have found a book thats right up my alley. It looks really good. Its doing Python by example through the whole book.. Called "Python Programming for the absolute beginner" by Michael Dawson I'm running Python 2.3.3 on both Windows and Linux and this book comes with 2.2.3. I'll just make sure that I check out the "Whats New in Python 2.3 .pdf" that came with Python 2.3.3. Joshua Banks -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.2.3 (GNU/Linux) iD8DBQFAIs5Ep9X7q/XgeyYRAvKAAJ9ik+zntRVmLIJpUuQoO/QACwV/SwCdHjU1 mw8EBWz8UrpDfp8t6YG2qmk= =fQWC -----END PGP SIGNATURE----- From cspears2002 at yahoo.com Thu Feb 5 18:44:48 2004 From: cspears2002 at yahoo.com (Christopher Spears) Date: Thu Feb 5 18:44:53 2004 Subject: [Tutor] help with regular expressions Message-ID: <20040205234448.9911.qmail@web12401.mail.yahoo.com> I'm trying to figure out regular expressions and am completely baffled! I understand the concept because there is something similar in UNIX, but for some reason, Python regular expressions don't make any sense to me! Are there some good tutorials that can help explain this subject to me? -Chris From sigurd at 12move.de Thu Feb 5 18:55:29 2004 From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=) Date: Thu Feb 5 18:56:05 2004 Subject: [Tutor] printing answers In-Reply-To: <20040205214919.7756.qmail@web40109.mail.yahoo.com> (Rich Krauter's message of "Thu, 5 Feb 2004 13:49:19 -0800 (PST)") References: <20040205214919.7756.qmail@web40109.mail.yahoo.com> Message-ID: On 5 Feb 2004, Rich Krauter <- rmkrauter@yahoo.com wrote: > I think you're making it much harder than it needs to > be by using regexes and nested loops. > Notice I use answers as a dict, not a list. Dicts are > nice when you want to get rid of repeats. ACK. [Code] But you lose information the way you wrote the code. In the example of the OP the case didn't matter but didn't get lost. Furthermore try / except without an explicit error condition is dangerous. You also catch errors you perhaps didn't think about. So the code should be written a bit different IMO. def find_match(lst): answers = {} res = [] for s in lst: sl = s.lower() answers.setdefault(sl,[]).append(s) for key, val in answers.items(): if len(val) > 1: res.extend(val) return res The lowered string is used as key and a list with the original strings gets used as value. Each value list which has a length > 1 gets pushed into the result list which is finally returned. The setdefault method of dictionaries is very handy here. If called with an existing key it returns the appendant value or the second argument (which is the empty list here); the append method then adds the string to the list. Karl -- Please do *not* send copies of replies to me. I read the list From sigurd at 12move.de Thu Feb 5 19:17:01 2004 From: sigurd at 12move.de (Karl =?iso-8859-1?q?Pfl=E4sterer?=) Date: Thu Feb 5 19:21:21 2004 Subject: [Tutor] fancy list things In-Reply-To: (Marilyn Davis's message of "Thu, 5 Feb 2004 15:14:08 -0800 (PST)") References: Message-ID: On 6 Feb 2004, Marilyn Davis <- marilyn@deliberate.com wrote: > Is it true that you can *always* replace map() and filter() with a > list comprehension? But you can never replace reduce()? Yes. No (well it is possible but extremly ugly): >>> class Foo: ... def __init__(self, x): ... self.x = x ... def set (self, v): ... self.x += v ... return self.x ... >>> [f.set(e) for e in range(10)].pop() 45 >>> reduce(lambda m, n: m+n, range(10), 0) 45 So with some side effects you get something which looks a bit like reduce (but has nothing to do with it). map() and filter() on the other hand can be replaced by list comprehensions. > Can anyone give me a reasonable example of lambda? What do you mean exactly? Lambda calculus? Lambda in Python? In Python lambda can be used to build simple (very simple sadly) anonymous expressions (no statements) which can get used at places where you think it's not worth writing a function with a name. But their usage is very weakly in Python, you can't compare it with languages like Lisp (CL, Scheme) or Haskell. But that's no bug it's a feature :-) Karl -- Please do *not* send copies of replies to me. I read the list From rmkrauter at yahoo.com Thu Feb 5 19:21:47 2004 From: rmkrauter at yahoo.com (Rich Krauter) Date: Thu Feb 5 19:26:42 2004 Subject: [Tutor] printing answers In-Reply-To: References: <20040205214919.7756.qmail@web40109.mail.yahoo.com> Message-ID: <1076026907.4424.136.camel@vaio> On Thu, 2004-02-05 at 18:55, Karl Pfl=C3=A4sterer wrote: > ACK. > That bad, huh? I've made much worse posts than this one. > > But you lose information the way you wrote the code > Well, actually you don't lose any information because you still have list_of_strings available. If you want to append items to arrays in the dict instead of keeping a count in the dict, that's fine too. I guess I misunderstood; I thought he just wanted a list of unique entries, regardless of case.=20 > Furthermore try / except without an explicit error condition is > dangerous. You also catch errors you perhaps didn't think about. >=20 Good point. That was sloppy. I figured I could get away with it in a 5 line program, but you're right.=20 Thanks for the feedback. Rich From pythontutor at venix.com Thu Feb 5 19:29:33 2004 From: pythontutor at venix.com (Lloyd Kvam) Date: Thu Feb 5 19:29:38 2004 Subject: [Tutor] help with regular expressions In-Reply-To: <20040205234448.9911.qmail@web12401.mail.yahoo.com> References: <20040205234448.9911.qmail@web12401.mail.yahoo.com> Message-ID: <4022DFED.9060202@venix.com> I believe that much of David Mertz's book, "Text Processing in PYTHON" is available on-line. He has a good section on regular expressions. Most of the other general Python books including Martelli's and Christopher's cover regular expressions. I believe that Python regular expression syntax matches pretty closely to the extended syntax in egrep, etc and also to Perl's. Google should also be able to help. I've stumbled across lots of regular expression articles over the years. Christopher Spears wrote: > I'm trying to figure out regular expressions and am > completely baffled! I understand the concept because > there is something similar in UNIX, but for some > reason, Python regular expressions don't make any > sense to me! Are there some good tutorials that can > help explain this subject to me? > > -Chris > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-653-8139 fax: 801-459-9582 From dyoo at hkn.eecs.berkeley.edu Thu Feb 5 19:34:25 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Feb 5 19:34:33 2004 Subject: [Tutor] help with regular expressions In-Reply-To: <20040205234448.9911.qmail@web12401.mail.yahoo.com> Message-ID: On Thu, 5 Feb 2004, Christopher Spears wrote: > I'm trying to figure out regular expressions and am completely baffled! > I understand the concept because there is something similar in UNIX, but > for some reason, Python regular expressions don't make any sense to me! > Are there some good tutorials that can help explain this subject to me? Hi Chris, Yes, there's a tutorial-style Regular Expression HOWTO by A.M. Kuchling: http://www.amk.ca/python/howto/regex/ Regular expressions allow us to define text patterns. For example, we can define a pattern of a bunch of 'a's: ### >>> import re >>> pattern = re.compile('a+') >>> pattern <_sre.SRE_Pattern object at 0x8126060> ### 'pattern' is a regular expression that can recognize all continuous patterns of the letter 'a'. That is, if we give it a string with 'a's, it'll recognize exactly where they are. Let's see what it does on a simple example: ### >>> pattern.findall('this is a test') ['a'] ### Here, it found the letter 'a'. Let's try something else: ### >>> pattern.findall('aaabaracccaaaadaabraaaa') ['aaa', 'a', 'a', 'aaaa', 'aa', 'aaaa'] ### And here, it found all 'a' sequences in that string. Does this make sense so far? The pattern above is deliberately simple, but regular expressions can get a little more complicated. For example, here's a regular expression that tries to detect date strings of the form '2/5/2004' (like date strings): ### >>> date_regex = re.compile('[0-9]+/[0-9]+/[0-9]+') >>> date_regex.findall("this is a test on 02/05/2004, right?") ['02/05/2004'] ### The regular expression is trying to say "a bunch of digits, followed by a a slash, followed by another bunch of digits, followed by a slash, and then topped with another bunch of digits". Whew. *grin* Caveat: the pattern above is too lenient for catching date strings. It also catches stuff like 2005/2/5, or even things like: ### >>> date_regex.findall("looky 1/2/3 or /4/5/6/") ['1/2/3', '4/5/6'] ### So there's something of an art to writing good regular expressions that are both general and specific. If you have questions, please feel free to ask. From arkamir at softhome.net Thu Feb 5 19:17:34 2004 From: arkamir at softhome.net (Conrad Koziol) Date: Thu Feb 5 19:35:22 2004 Subject: [Tutor] Sets module/Removing duplicates Message-ID: <1076026653.3792.5.camel@conradpc> Hello, I've been doing some research on the sets module,and everywhere it says its great from removing duplicates from a list, but nowhere actually tells you how (or am i just not looking in the right spot?). Can anyone show me how :) Thanks a lot From dyoo at hkn.eecs.berkeley.edu Thu Feb 5 19:42:59 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Feb 5 19:43:32 2004 Subject: [Tutor] Sets module/Removing duplicates In-Reply-To: <1076026653.3792.5.camel@conradpc> Message-ID: On Thu, 5 Feb 2004, Conrad Koziol wrote: > I've been doing some research on the sets module, and everywhere it says > its great from removing duplicates from a list, but nowhere actually > tells you how (or am i just not looking in the right spot?). Can anyone > show me how :) Hi Conrad, The examples from: http://www.python.org/doc/lib/set-example.html will construct a few sets out of lists of unique elements. But try putting duplicates elements in the lists and see what happens. Good luck! From marilyn at deliberate.com Thu Feb 5 19:48:57 2004 From: marilyn at deliberate.com (Marilyn Davis) Date: Thu Feb 5 19:49:16 2004 Subject: [Tutor] fancy list things In-Reply-To: Message-ID: On Fri, 6 Feb 2004, Karl Pfl?sterer wrote: > On 6 Feb 2004, Marilyn Davis <- marilyn@deliberate.com wrote: > > > Is it true that you can *always* replace map() and filter() with a > > list comprehension? But you can never replace reduce()? > > Yes. No (well it is possible but extremly ugly): > > >>> class Foo: > ... def __init__(self, x): > ... self.x = x > ... def set (self, v): > ... self.x += v > ... return self.x > ... > >>> [f.set(e) for e in range(10)].pop() > 45 > >>> reduce(lambda m, n: m+n, range(10), 0) > 45 > > So with some side effects you get something which looks a bit like > reduce (but has nothing to do with it). I'm sorry, I meant that you can't replace it with a list comprehension of any sort? And zip() can't be replaced with any sort of list comprehension. Right? > > map() and filter() on the other hand can be replaced by list > comprehensions. > > > > Can anyone give me a reasonable example of lambda? > > What do you mean exactly? Lambda calculus? Lambda in Python? > > In Python lambda can be used to build simple (very simple sadly) > anonymous expressions (no statements) which can get used at places where > you think it's not worth writing a function with a name. But their > usage is very weakly in Python, you can't compare it with languages like > Lisp (CL, Scheme) or Haskell. But that's no bug it's a feature :-) Is it only useful in map() and filter() and reduce()? And other places where you want to hand a little function to a function? comp() for example. Is there another class of examples? I'm teaching python for the first time and want to be as solid as possible on this stuff. Thank you. Marilyn > > > > Karl > -- From dyoo at hkn.eecs.berkeley.edu Thu Feb 5 20:22:50 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Feb 5 20:33:00 2004 Subject: [Tutor] fancy list things In-Reply-To: Message-ID: > > In Python lambda can be used to build simple (very simple sadly) > > anonymous expressions (no statements) which can get used at places > > where you think it's not worth writing a function with a name. But > > their usage is very weakly in Python, you can't compare it with > > languages like Lisp (CL, Scheme) or Haskell. But that's no bug it's a > > feature :-) > > Is it only useful in map() and filter() and reduce()? And other places > where you want to hand a little function to a function? comp() for > example. Is there another class of examples? Hi Marilyn, lambda's can also be useful whenever we want to create simpler versions of functions that already have some parameters filled in. Here is a simple example: ### >>> def add(x, y): ... return x + y ... >>> add1 = lambda y: add(1, y) >>> >>> >>> add1(42) 43 ### Another way of saying this is: ### def add1(y): return add(1, y) ### The 'def' statement in Python is sort of a combination of lambda-function-making plus name-binding. > I'm teaching python for the first time and want to be as solid as > possible on this stuff. Hmmm... you may want to avoid talking about lambda, then. Concentrate on what you're comfortable talking about. I'd recommend focusing on the things that people will usually do with Python, so show how to construct functions with 'def'. The advantage that 'lambda' has over 'def' is that it doesn't force us to bind the function value with a name. But Python programmers usually want to give good names our functions to express human intent, anyway. And function values are just function values. *grin* def'ed functions can also be passed around just as easily as values from lambdas: ### >>> def compose(f, g): ... def composed_function(x): ... return f(g(x)) ... return composed_function ... >>> def square(x): ... return x * x ... >>> def sqrt(x): ... return x ** (0.5) ... >>> quad_power = compose(square, square) >>> quad_power(17) 83521 >>> identity = compose(square, sqrt) >>> identity(17) 17.0 ### So there's no need to concentrate on the foreignness of the word 'lambda': lambda just creates function values. But we can get the value of anything by just naming it: ### >>> x = 42 >>> x 42 >>> def square(x): return x * x ... >>> square ### Just for reference: the same thing that we did with 'def' here can be done exclusively with lambda's. ### >>> compose = lambda f, g: lambda x: f(g(x)) >>> square = lambda x: x*x >>> sqrt = lambda x: x**(0.5) >>> quad_power = compose(square, square) >>> quad_power(17) 83521 >>> quarter_power = compose(sqrt, sqrt) ## with cheese? >>> quarter_power(16) 2.0 ### The advantage of lambda here is that it's concise, so this kind of function-fiddling code ends up being really short to write. To a eye trained in functional languages, it looks neater. But there's little that we're doing here that we couldn't do already with 'def'. Hope this helps! From missive at hotmail.com Thu Feb 5 20:45:59 2004 From: missive at hotmail.com (Lee Harr) Date: Thu Feb 5 20:46:05 2004 Subject: [Tutor] Re: Zope and Python... Message-ID: > Just looking for peoples experience on Zope --- What is the >tutor thoughts on it ? > >Those that use it what are your gripes or praises and if you don't like >Zope >is there something else you would recommend to give a > >similar functionality. I am finding it hard to find good "easy" beginner >documentation on application building in Zope. I've gone through the >Devshed > >documents and the zope book but I have found many problems in the examples >and just the version diffs in Zope. > > > >Are there any good resources that anyone would suggest for Learning to >develop apps under Zope ? > I really like zope. We use it for our school website. Some say it has a steep learning curve, but I say it is more of an oddly shaped learning curve. To get started and do simple things with pre-made "products" is really pretty simple. More complex things like creating your own products can take a while to master. Things I really like about zope are zope page templates (zpt) which can actually be used outside of zope, and the ease with which I can delegate different sections of the site to different users/developers. _________________________________________________________________ The new MSN 8: smart spam protection and 2 months FREE* http://join.msn.com/?page=features/junkmail From Harm_Kirchhoff at mail.digital.co.jp Thu Feb 5 21:42:04 2004 From: Harm_Kirchhoff at mail.digital.co.jp (Harm_Kirchhoff@mail.digital.co.jp) Date: Thu Feb 5 21:41:48 2004 Subject: [Tutor] Zope and Python... Message-ID: I am using ZOPE under Win2000 purely as a database and not as a web-based application. I fully concur with your observation that it is difficult to get started. The mailing list on zope is very very high level and the answers you get to beginner questions are sometimes/often too high to understand. I basically bought all books available on ZOPE, but they all focus on the web aspects. There is little available on (mis)-using ZOPE simply as a DB. However, once you find out how to use ZOPE's ZODB purely as a giant python dictionary it becomes really easy to use and is quite fast (at least for my limited amount of data). Regarding the books on ZOPE as a web tool, I personally got started with 2: Zope Bible and Zope: Web Application Development and Content Management, which I found interesting because it discusses many add-in you can use (web-mail, ExternalFS, ...) and, fo course the ZOPE book (which I had to read twice). To my knowledge there is no resource on the net that focuses on absolute ZOPE beginners. It is pretty much a specialists circle that takes some time to get it. I had a frustrating couple of months, but afterwards I could at least do some basic stuff. Regarding ZODB: I do not want to miss it. If you need some code to get started on ZODB, I can post it. From shaleh at speakeasy.net Fri Feb 6 00:38:06 2004 From: shaleh at speakeasy.net (Sean 'Shaleh' Perry) Date: Fri Feb 6 00:38:21 2004 Subject: [Tutor] Visitor Pattern In-Reply-To: <20040202020506.31323.qmail@web41803.mail.yahoo.com> References: <20040202020506.31323.qmail@web41803.mail.yahoo.com> Message-ID: <200402052138.06081.shaleh@speakeasy.net> On Sunday 01 February 2004 18:05, Daniel Ehrenberg wrote: > What is a visitor pattern? I've heard that it shows > how good a language is, and that Lisp is really good > because it can be done in two (cryptic) lines. How can > a visitor pattern be implimented in Python? > It is from the original "Desgin Patterns" book which is one of the bibles of OO coding. An excerpt: Intent Represent an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the class of the elements on which it operates. The idea here is you have an object with "visits" another object and in some way interacts with it. Common example: for window in windowList: display.draw(window) which in functional terms shows up as: map(display.draw, windowList) or in new terms [display.draw(window) for window in windowList] Visitor is a very, very common idiom in functional languages. From isrgish at fusemail.com Fri Feb 6 02:07:57 2004 From: isrgish at fusemail.com (Isr Gish) Date: Fri Feb 6 02:09:11 2004 Subject: [Tutor] How to get variable name from its id() Message-ID: Is it possible to get the variable name or its contents if we know its I?d. Name = 'Isr Gish' ID = id(Name) Now use I?D to either find the variable name (Name), or get the contents of Name. If someone can point me where to find this info. It would be greatly appreciated. All the best Isr From anna at aleax.it Fri Feb 6 03:29:41 2004 From: anna at aleax.it (Anna Ravenscroft) Date: Fri Feb 6 03:29:48 2004 Subject: [Tutor] Looking for some guidance. In-Reply-To: <200402051514.14108.syn_ack@comcast.net> References: <002e01c3ec30$1c3f1f30$6401a8c0@xp> <200402051514.14108.syn_ack@comcast.net> Message-ID: <200402060929.41209.anna@aleax.it> On Friday 06 February 2004 12:14 am, Joshua Banks wrote: > Well it looks like I might have found a book thats right up my alley. It > looks really good. Its doing Python by example through the whole book.. > Called "Python Programming for the absolute beginner" by Michael Dawson Thanks for letting us know what works for you. This is one of those common questions, and getting an idea of what people like and *why* they find them valuable is really helpful! Anna -- There is a type 3 error in which your mind goes totally blank whenever you try to remember which is which of type 1 and type 2. -Richard Dawkins From RobinHood42 at clickta.com Fri Feb 6 05:17:10 2004 From: RobinHood42 at clickta.com (alice) Date: Fri Feb 6 05:15:57 2004 Subject: [tutor] Tkinter 101 In-Reply-To: <00f901c3e917$e7f24600$6401a8c0@xp> References: <20040201023500.51351.qmail@web13608.mail.yahoo.com> <00f901c3e917$e7f24600$6401a8c0@xp> Message-ID: <200402061717.10361.RobinHood42@clickta.com> I don't really know very much about Python or computer programming, but I didn't think that was a good enough reason not to give it a try. Anyway, I've written this program. Its basicially a simulation of Conway's "game of life" It seems to work fine and all, but I'm sure there are better ways of doing what I've done than the way I did it, so I'm posting it to this list in the hope of recieving some constructive criticism. Here it is (sorry, its a bit long): import Tkinter as Tk import random class Menu: def __init__(self, parent): # appearance (inherit from parent): self._background = parent.background self._activebackground = parent.activebackground self._font = parent.font # essential initialization: self._root = parent.root self._menubar = Tk.Menu(self._root) self._root.config(menu=self._menubar) # store all the user created menus in a dictionary: self._menus = {} # appearance self._menubar["background"] = self._background self._menubar["activebackground"] = self._activebackground self._menubar["font"] = self._font def add_menu(self, menu_name): # use the name of the menu as key into menus dict: self._menus[menu_name] = Tk.Menu(self._root) self._menubar.add_cascade(label=menu_name, \ menu=self._menus[menu_name]) # appearance: self._menus[menu_name]["background"] = self._background self._menus[menu_name]["activebackground"] = self._activebackground self._menus[menu_name]["font"] = self._font def add_command(self, menu_name, command_name, command): self._menus[menu_name].add_command(label=command_name, \ command=command) class PopConfig: def __init__(self,parent): # appearance (inherit from parent): self._foreground = parent.foreground self._background = parent.background self._activebackground = parent.activebackground self._font = parent.font self._white = parent.white # pop up a dialog: self._pop = Tk.Toplevel(parent.root) self._pop.grab_set() # make some dictionaries to store user created widgets: self._frames = {} self._labels = {} self._buttons = {} self._entries = {} self._scales = {} # make a frame for user defined buttons: self._frames["buttons"] = Tk.Frame(self._pop) self._frames["buttons"].pack(side=Tk.BOTTOM,padx=5,pady=5) # appearance: self._pop["background"] = self._background def make_button(self, name, command): # use the text on the button as the key into buttons dict: self._buttons[name] = Tk.Button(self._frames["buttons"]) self._buttons[name]["text"] = name self._buttons[name]["command"] = command self._buttons[name].pack(side=Tk.LEFT) # appearance: self._buttons[name]["background"] = self._foreground self._buttons[name]["activebackground"] = self._activebackground self._buttons[name]["font"] = self._font def make_entrybox(self, id, label): # create a label widget and an entry widget # nested inside a frame widget # use user defined id as key into widget dicts: self._frames[id] = Tk.Frame(self._pop) self._frames[id].pack(side=Tk.TOP) self._labels[id] = Tk.Label(self._frames[id]) self._labels[id]["text"] = label self._labels[id].pack(side = Tk.LEFT) self._entries[id] = Tk.Entry(self._frames[id]) self._entries[id].pack(side=Tk.LEFT, padx = 10, pady = 10) # appearance: self._frames[id]["background"] = self._background self._labels[id]["background"] = self._background self._entries[id]["background"] = self._white self._labels[id]["font"] = self._font def make_scale(self, id, label): # create a label widget and a scale widget # nested inside a frame widget # use user defined id as key into widget dicts: self._frames[id] = Tk.Frame(self._pop) self._frames[id].pack(side=Tk.TOP) self._labels[id] = Tk.Label(self._frames[id]) self._labels[id]["text"] = label self._labels[id].pack(side = Tk.LEFT) self._scales[id] = Tk.Scale(self._frames[id]) self._scales[id].pack(side=Tk.LEFT, padx = 10, pady = 10) # appearance: self._frames[id]["background"] = self._background self._labels[id]["background"] = self._background self._scales[id]["background"] = self._background self._scales[id]["activebackground"] = self._activebackground self._scales[id]["troughcolor"] = self._white self._scales[id]["orient"] = "horizontal" self._labels[id]["font"] = self._font def get_entry(self, id): return self._entries[id].get() def get_scale(self, id): return self._scales[id].get() def close(self): self._pop.destroy() class Canvas: def __init__(self, parent, width, height): # inherit from parent: self._root = parent.root self.bg = parent.white self.fg = parent.foreground # make canvas: self.canvas = Tk.Canvas(self._root) self.canvas.pack() # initial dimensions: self._width = width self._height = height # clear canvas: self.clear() def clear(self): self.canvas.destroy() self.canvas = Tk.Canvas(self._root) self.canvas.pack() self.canvas["background"] = self.bg self.canvas["width"] = self._width self.canvas["height"] = self._height def get_width(self): return self._width def get_height(self): return self._height def change_dimensions(self, new_width, new_height): self._width = new_width self._height = new_height self.clear() class GUI: def __init__(self): self.root = Tk.Tk() self.set_colours() def set_colours(self): # default colours: self.foreground = "turquoise" self.background = "aquamarine" self.activebackground = "pale green" self.white = "alice blue" self.font = "courier" def loop(self): self.root.mainloop() def quit(self): self.root.destroy() class Cells: def __init__(self, canvas, x, y): # cell dimensions self._x = x self._y = y # canvas dimensions self._width = canvas.get_width() self._height = canvas.get_height() # canvas and colours: self.canvas = canvas.canvas self.fg = canvas.fg self.bg = canvas.bg # event binding: self.canvas.focus_set() self.canvas.bind("