From sdragon1984 at gmail.com Thu Jan 1 04:51:03 2009 From: sdragon1984 at gmail.com (nathan virgil) Date: Wed, 31 Dec 2008 22:51:03 -0500 Subject: [Tutor] Creating sub-menus? In-Reply-To: <111a9ddb0812302322sdef57daxb3639ff57ef326ab@mail.gmail.com> References: <111a9ddb0812302322sdef57daxb3639ff57ef326ab@mail.gmail.com> Message-ID: <111a9ddb0812311951i45629f16i1e186a14a477b814@mail.gmail.com> Okay, so I changed line 84 from: current_menu to: choice = current_menu, and the menu prtion seems to work fine. Only problem now is, once I select a formula, it repeats that function over and over again, never going back to a menu. Should I just add something like: choice = current_menu to each formula function? -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Jan 1 11:58:44 2009 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Thu, 1 Jan 2009 10:58:44 +0000 (GMT) Subject: [Tutor] Fw: Creating sub-menus? Message-ID: <335258.55060.qm@web86708.mail.ird.yahoo.com> Forwarding to the list.... Please use ReplyAll when responding. On Wed, Dec 31, 2008 at 4:10 AM, Alan Gauld wrote: "nathan virgil" wrote Each menu is a function that prints out options, saves a raw_input as the variable choice, and returns choice. In the main menu, each option leads to a sub-menu. After choice is defined, however, the sub-menu "tags" the value of choice. Yes that can all work. Then create a loop of while choice !=q, run current_menu, and include a bunch of statements along the lines of: if choice == : current_menu = Consider using a dictionary keyed by your combined choice values. Then the big if/elif chain shrinks to returnValue = FuncDict[choice](params) The only challenge with this route is making all the functions take a single input argument. But that argument can be a tuple :-) Dictionaries? Tuples? I just figured out functions, so I'm very new. I'm still working on understanding lists. I know what I have probably isn't the best solution for what I'm trying to do, but I'm trying to work with the little that I know. This seems like it would work, but for some reason, every time I run the code, it freezes after I give input from the main menu. Can anybody help? I can show my source code, but indentation doesn't seem to copy/paste very well, so it may be a bit hard to read... Try putting it on the pastebin web site and sending us the URL. That gives us colour coding of syntax too which helps read it! http://pastebin.com/m252eea7a It's a simple formula calculator, so the point isn't really the content. I don't have all the formulas coded in yet, but the way I see it, if I can't access the sub-menus that lead to the formulas, then it doesn't do me any good to have the formulas. -------------- next part -------------- An HTML attachment was scrubbed... URL: From denis.spir at free.fr Thu Jan 1 13:57:54 2009 From: denis.spir at free.fr (spir) Date: Thu, 1 Jan 2009 13:57:54 +0100 Subject: [Tutor] Fw: Creating sub-menus? In-Reply-To: <335258.55060.qm@web86708.mail.ird.yahoo.com> References: <335258.55060.qm@web86708.mail.ird.yahoo.com> Message-ID: <20090101135754.1155c3a6@o> On Thu, 1 Jan 2009 10:58:44 +0000 (GMT) ALAN GAULD wrote: > Forwarding to the list.... > Please use ReplyAll when responding. > > > > > On Wed, Dec 31, 2008 at 4:10 AM, Alan Gauld wrote: > > "nathan virgil" wrote > > > > Each menu is a function that prints out options, saves a raw_input as the > variable choice, and returns choice. In the main menu, each option leads to > a sub-menu. After choice is defined, however, the sub-menu "tags" the value > of choice. > > > Yes that can all work. > > > > Then create a loop of while choice !=q, run current_menu, and include a > bunch of statements along the lines of: > > if choice == : > current_menu = > > > Consider using a dictionary keyed by your combined choice values. > Then the big if/elif chain shrinks to > > returnValue = FuncDict[choice](params) > > The only challenge with this route is making all the functions > take a single input argument. But that argument can be a tuple :-) > > Dictionaries? Tuples? I just figured out functions, so I'm very new. I'm still working on > understanding lists. I know what I have probably isn't the best solution for what I'm trying to > do, but I'm trying to work with the little that I know. > > > > > This seems like it would work, but for some reason, every time I run the > code, it freezes after I give input from the main menu. Can anybody help? I > can show my source code, but indentation doesn't seem to copy/paste very > well, so it may be a bit hard to read... > > > Try putting it on the pastebin web site and sending us the URL. > That gives us colour coding of syntax too which helps read it! > > > http://pastebin.com/m252eea7a Below a copy of the menu control loop of your code, with some corrections. denis #In development choice = "start" # rather use None or "" as not-yet-setvalue current_menu = main_menu() # current_menu = main_menu : see below while choice != "q": current_menu # current_menu() : it's a call #Main Menu results if choice == "1": current_menu = temp_conv_menu()# idem: rather no '()' for consistency elif choice == "2": current_menu = area_menu() elif choice == "3": current_menu = perim_menu() ### inside sub-menus, you simply forget to process "back to main menu" choices ### in all active branches below, you also forget to go back up a menu level ### after execution of the terminal choice ## so that, once reached, the user is stick in a terminal branch elif choice == "t1": temp = input("Celsius temperature: ") print "Fahrenheit:", celsius_to_fahrenheit(temp) * current_menu = temp_conv_menu / main_menu * [possibly with "x = raw_input("ok?")" before] elif choice == "t2": temp = input("Fahrenheit temperature: ") print "Celsius:", fahrenheit_to_celsius(temp) * elif "t3": * current_menu = main_menu elif choice =="a1": s = input("Width:") print "Square area:", area_s(s) elif choice =="a2": w = input("Width:") h = input("Height:") print "Rectangle area:", area_r(w, h) elif choice =="a3": none elif choice =="a4": r=input("Radius of circle: ") print "Circle area:", area_c(r) In the sub-menus, I would also give a distinctive key for "back to main menu" (eg 'b' or 'm') rather than a number. [all comments / changes / additions untested] ------ la vida e estranya From cmutel at gmail.com Thu Jan 1 15:07:00 2009 From: cmutel at gmail.com (Christopher Mutel) Date: Thu, 1 Jan 2009 15:07:00 +0100 Subject: [Tutor] Distinction between tuples and lists Message-ID: <5e5978e10901010607r6b0e7c5l451326fb2480fb9a@mail.gmail.com> Hello all- I stumbled across some discussion of why the fundamental difference between lists and tuples is not mutability, but hetero- versus homogeneous data, e.g. http://jtauber.com/blog/2006/04/15/python_tuples_are_not_just_constant_lists/ http://pyre.third-bit.com/blog/archives/000450.html However, after reading the cited discussions, my python books, etc., I have to admit I don't really understand this idea. What does it mean that "lists are intended for homogeneous sequences"? What is different about lists that would make them more suited for homogeneous sequences than heterogeneous sequences (or vice-versa for tuples)? In the end, from what I understand, the idea of homo/heterogeneity seems orthogonal to mutability, which is the main distinction emphasized by e.g. Learning Python. I would greatly appreciate any help provided, -Chris Mutel From kent37 at tds.net Thu Jan 1 15:34:24 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 1 Jan 2009 09:34:24 -0500 Subject: [Tutor] Top posters to tutor list for 2008 Message-ID: <1c2a2c590901010634p1d10064bt9289fc952b69d558@mail.gmail.com> For several years I have been using a simple script to find the top 20 posters to the tutor list by web-scraping the archive pages. I thought others might be interested so here is the list for 2008 and the script that generates it. The lists for previous years (back to 2003) are at the end so everyone on the list doesn't hit the archives to find out :-) The script gives a simple example of datetime, urllib2 and BeautifulSoup. It consolidates names that vary by case but other variations are not detected. Alan, I thought you might have passed me this year but we are both off a little :-) Somehow I have posted an average of 2.8 times per day for the last four years... Happy New Year everyone! Kent 2008 ==== Kent Johnson 931 Alan Gauld 820 bob gailer 247 Dick Moores 191 W W 142 Wayne Watson 106 John Fouhy 97 Steve Willoughby 91 Lie Ryan 88 bhaaluu 85 Marc Tompkins 83 Michael Langford 71 Tiger12506 70 Andreas Kostyrka 64 Dinesh B Vadhia 64 wesley chun 58 Tim Golden 57 Chris Fuller 54 Ricardo Aráoz 53 spir 53 ##################################### ''' Counts all posts to Python-tutor by author''' # -*- coding: latin-1 -*- from datetime import date, timedelta import operator, urllib2 from BeautifulSoup import BeautifulSoup today = date.today() for year in [2008]: startDate = date(year, 1, 1) endDate = date(year, 12, 31) thirtyOne = timedelta(days=31) counts = {} # Collect all the counts for a year by scraping the monthly author archive pages while startDate < endDate and startDate < today: dateString = startDate.strftime('%Y-%B') url = 'http://mail.python.org/pipermail/tutor/%s/author.html' % dateString data = urllib2.urlopen(url).read() soup = BeautifulSoup(data) li = soup.findAll('li')[2:-2] for l in li: name = l.i.string.strip() counts[name] = counts.get(name, 0) + 1 startDate += thirtyOne # Consolidate names that vary by case under the most popular spelling nameMap = dict() # Map lower-case name to most popular name for name, count in sorted(counts.iteritems(), key=operator.itemgetter(1), reverse=True): lower = name.lower() if lower in nameMap: # Add counts for a name we have seen already counts[nameMap[lower]] += count else: nameMap[lower] = name print print year print '====' for name, count in sorted(counts.iteritems(), key=operator.itemgetter(1), reverse=True)[:20]: print name.encode('latin-1', 'xmlcharrefreplace'), count print # Results as of 12/31/2008: ''' 2003 ==== Danny Yoo 617 Alan Gauld 421 Jeff Shannon 283 Magnus Lycka 242 Bob Gailer 195 Magnus =?iso-8859-1?Q?Lyck=E5?= 166 alan.gauld at bt.com 161 Kirk Bailey 155 Gregor Lingl 152 Lloyd Kvam 142 Andrei 118 Sean 'Shaleh' Perry 117 Magnus Lyck? 113 Michael Janssen 113 Erik Price 100 Lee Harr 88 Terry Carroll 87 Daniel Ehrenberg 78 Abel Daniel 76 Charlie Clark 74 2004 ==== Alan Gauld 699 Danny Yoo 530 Kent Johnson 451 Lloyd Kvam 146 Dick Moores 145 Liam Clarke 140 Brian van den Broek 122 Karl Pflästerer 109 Jacob S. 101 Andrei 99 Chad Crabtree 93 Bob Gailer 91 Magnus Lycka 91 Terry Carroll 88 Marilyn Davis 84 Gregor Lingl 73 Dave S 73 Bill Mill 71 Isr Gish 71 Lee Harr 67 2005 ==== Kent Johnson 1189 Danny Yoo 767 Alan Gauld 565 Alan G 317 Liam Clarke 298 Max Noel 203 Nathan Pinno 197 Brian van den Broek 190 Jacob S. 154 jfouhy at paradise.net.nz 135 Alberto Troiano 128 Bernard Lebel 119 Joseph Quigley 101 Terry Carroll 93 Andrei 79 D. Hartley 77 John Fouhy 73 bob 73 Hugo González Monteverde 72 Orri Ganel 69 2006 ==== Kent Johnson 913 Alan Gauld 815 Danny Yoo 448 Luke Paireepinart 242 John Fouhy 187 Chris Hengge 166 Bob Gailer 134 Dick Moores 129 Asrarahmed Kadri 119 Terry Carroll 111 Python 94 Mike Hansen 74 Liam Clarke 72 Carroll, Barry 67 Kermit Rose 66 anil maran 66 Hugo González Monteverde 65 wesley chun 63 Christopher Spears 53 Michael Lange 51 2007 ==== Kent Johnson 1052 Alan Gauld 938 Luke Paireepinart 260 Dick Moores 203 Eric Brunson 164 Terry Carroll 128 Tiger12506 112 John Fouhy 105 Bob Gailer 97 Ricardo Aráoz 93 Rikard Bosnjakovic 93 bhaaluu 88 elis aeris 83 Andreas Kostyrka 77 Michael Langford 68 shawn bright 63 Tim Golden 62 Dave Kuhlman 62 wormwood_3 53 wesley chun 53 2008 ==== Kent Johnson 931 Alan Gauld 820 bob gailer 247 Dick Moores 191 W W 142 Wayne Watson 106 John Fouhy 97 Steve Willoughby 91 Lie Ryan 88 bhaaluu 85 Marc Tompkins 83 Michael Langford 71 Tiger12506 70 Andreas Kostyrka 64 Dinesh B Vadhia 64 wesley chun 58 Tim Golden 57 Chris Fuller 54 Ricardo Aráoz 53 spir 53 ''' From jadrifter at gmail.com Thu Jan 1 15:43:50 2009 From: jadrifter at gmail.com (jadrifter) Date: Thu, 01 Jan 2009 06:43:50 -0800 Subject: [Tutor] Distinction between tuples and lists In-Reply-To: <5e5978e10901010607r6b0e7c5l451326fb2480fb9a@mail.gmail.com> References: <5e5978e10901010607r6b0e7c5l451326fb2480fb9a@mail.gmail.com> Message-ID: <1230821030.6159.25.camel@ltop> On Thu, 2009-01-01 at 15:07 +0100, Christopher Mutel wrote: > Hello all- > > I stumbled across some discussion of why the fundamental difference > between lists and tuples is not mutability, but hetero- versus > homogeneous data, e.g. > > http://jtauber.com/blog/2006/04/15/python_tuples_are_not_just_constant_lists/ > > http://pyre.third-bit.com/blog/archives/000450.html > > However, after reading the cited discussions, my python books, etc., I > have to admit I don't really understand this idea. What does it mean > that "lists are intended for homogeneous sequences"? What is different > about lists that would make them more suited for homogeneous sequences > than heterogeneous sequences (or vice-versa for tuples)? In the end, > from what I understand, the idea of homo/heterogeneity seems > orthogonal to mutability, which is the main distinction emphasized by > e.g. Learning Python. > > I would greatly appreciate any help provided, > > -Chris Mutel > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor I read it and don't get their emphasis or perhaps level of concern. As explanatory pieces these two blogs aren't very helpful. They provide a few assertions with no apparent (to me) attempt to support or explain them. Both data types are indexed and both can contain homogeneous (same as) or heterogeneous (different than) data. I get that lists are analogous to a C linked lists as tuples are to C structs. I get that the flexibility of one and the stability of the other makes them useful in different situations. Being able to use struct notation (employee.age instead of employee[4]) would be nice but also not that difficult to implement as a class either. On re-re-re-reading it (I hate it when I don't get the point) I think they're arguing for a more structured "You must use this properly" approach to be built into the language. And that makes some sense. Who would want a database call (say to an employee database table) that returned a record as a list? On the other hand who would want a record set (group of records) returned as a tuple? There's no reason to assume the third record will always be that of John Smith but the 3rd field of John Smiths's record better be his phone number and not his social security number or else wackiness will ensue. Still, aint it great to work with a language that lets us bounce back and forth between structures as we please? John Purser From jadrifter at gmail.com Thu Jan 1 16:23:38 2009 From: jadrifter at gmail.com (jadrifter) Date: Thu, 01 Jan 2009 07:23:38 -0800 Subject: [Tutor] Top posters to tutor list for 2008 In-Reply-To: <1c2a2c590901010634p1d10064bt9289fc952b69d558@mail.gmail.com> References: <1c2a2c590901010634p1d10064bt9289fc952b69d558@mail.gmail.com> Message-ID: <1230823418.6159.29.camel@ltop> On Thu, 2009-01-01 at 09:34 -0500, Kent Johnson wrote: > For several years I have been using a simple script to find the top 20 > posters to the tutor list by web-scraping the archive pages. I thought > others might be interested so here is the list for 2008 and the script > that generates it. The lists for previous years (back to 2003) are at > the end so everyone on the list doesn't hit the archives to find out > :-) > > The script gives a simple example of datetime, urllib2 and > BeautifulSoup. It consolidates names that vary by case but other > variations are not detected. Kent, Thank you for this. I've been thinking about a web scraping script but didn't have a clue how to go about it. Seeing someone else's practical implementation is a huge help! A little serendipity to start 2009 off with. Happy New Year to all. John From andreengels at gmail.com Thu Jan 1 18:33:23 2009 From: andreengels at gmail.com (Andre Engels) Date: Thu, 1 Jan 2009 18:33:23 +0100 Subject: [Tutor] Distinction between tuples and lists In-Reply-To: <6faf39c90901010929we60f904rf86a1afd72f705c7@mail.gmail.com> References: <5e5978e10901010607r6b0e7c5l451326fb2480fb9a@mail.gmail.com> <6faf39c90901010929we60f904rf86a1afd72f705c7@mail.gmail.com> Message-ID: <6faf39c90901010933ydba7a04g737f78c7edb84eac@mail.gmail.com> On Thu, Jan 1, 2009 at 3:07 PM, Christopher Mutel wrote: > Hello all- > > I stumbled across some discussion of why the fundamental difference > between lists and tuples is not mutability, but hetero- versus > homogeneous data, e.g. > > http://jtauber.com/blog/2006/04/15/python_tuples_are_not_just_constant_lists/ > > http://pyre.third-bit.com/blog/archives/000450.html > > However, after reading the cited discussions, my python books, etc., I > have to admit I don't really understand this idea. What does it mean > that "lists are intended for homogeneous sequences"? What is different > about lists that would make them more suited for homogeneous sequences > than heterogeneous sequences (or vice-versa for tuples)? In the end, > from what I understand, the idea of homo/heterogeneity seems > orthogonal to mutability, which is the main distinction emphasized by > e.g. Learning Python. > > I would greatly appreciate any help provided, Lists do have all kinds of operations that tuples do not have. Many of those will change the order of the elements in the list, for example by adding or removing an element, or exchanging some elements. Because of this, many of those operations are only useful on homogenous sequences - which means that the second element could also be the first or the fourth, and would then still mean the same thing, though in another place. On the other hand, if I have a heterogenous sequence, that is, if what is in the second position could either not appear on the fourth position (because the second is an integer and the fourth a string, for example), or would mean something completely different there (for example if the second and fourth were both floats, but the second was a price in dollars and the fourth a mass in kilograms), then many of those operations make no sense (in fact, the only one I think _would_ make sense for heterogenous sequences is changing the value of the element at a specified position). Thus, if you have a heterogenous sequence, all those nifty operations on lists have no use, and dropping them for getting the niceties of immutability (like usage as the key in a dictionary) is getting something for almost nothing, thus you might as well use a tuple. -- Andr? Engels, andreengels at gmail.com From andreengels at gmail.com Thu Jan 1 18:33:43 2009 From: andreengels at gmail.com (Andre Engels) Date: Thu, 1 Jan 2009 18:33:43 +0100 Subject: [Tutor] Distinction between tuples and lists In-Reply-To: <6faf39c90901010932m343de4bau68866d79c612feba@mail.gmail.com> References: <5e5978e10901010607r6b0e7c5l451326fb2480fb9a@mail.gmail.com> <1230821030.6159.25.camel@ltop> <6faf39c90901010932m343de4bau68866d79c612feba@mail.gmail.com> Message-ID: <6faf39c90901010933o47df268fhe9fd90777ec3c8@mail.gmail.com> On Thu, Jan 1, 2009 at 3:43 PM, jadrifter wrote: > Both data types are indexed and both can contain homogeneous (same as) > or heterogeneous (different than) data. I get that lists are analogous > to a C linked lists as tuples are to C structs. I get that the > flexibility of one and the stability of the other makes them useful in > different situations. Being able to use struct notation (employee.age > instead of employee[4]) would be nice but also not that difficult to > implement as a class either. The similar construct in Python to this struct notation would be to use a dictionary rather than a tuple (or list); you could then use employee['age'] etcetera. -- Andr? Engels, andreengels at gmail.com From kent37 at tds.net Thu Jan 1 19:42:32 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 1 Jan 2009 13:42:32 -0500 Subject: [Tutor] Distinction between tuples and lists In-Reply-To: <1230821030.6159.25.camel@ltop> References: <5e5978e10901010607r6b0e7c5l451326fb2480fb9a@mail.gmail.com> <1230821030.6159.25.camel@ltop> Message-ID: <1c2a2c590901011042y6a20ec61yccddc3951f21f2de@mail.gmail.com> On Thu, Jan 1, 2009 at 9:43 AM, jadrifter wrote: > Being able to use struct notation (employee.age > instead of employee[4]) would be nice but also not that difficult to > implement as a class either. Python 2.6 added collections.namedtuple() which is a factory for classes like this: http://docs.python.org/dev/library/collections.html#collections.namedtuple Kent From keith_reed at fastmail.net Thu Jan 1 17:04:42 2009 From: keith_reed at fastmail.net (Keith Reed) Date: Thu, 01 Jan 2009 11:04:42 -0500 Subject: [Tutor] Inserting one dictionary into another Message-ID: <1230825882.6354.1292570031@webmail.messagingengine.com> I'm having trouble assigning a dictionary as a value within another: -------- Code Snippet Start -------- for line in fromchild.readlines(): itemarray = line.strip().split(":") parentdictkey = itemarray[0] print 'parentdictkey = ' + parentdictkey for index in range(len(headerinfo)): nesteddict[headerinfo[index]] = itemarray[index] #print nesteddict parentdict[parentdictkey] = nesteddict nesteddict.clear() print '-------------------------------------------------------------------------\n' print parentdict -------- Code Snippet End -------- -------- Output Start -------- {'24': {}, '25': {}, '26': {}, '27': {}, '20': {}, '21': {}, '22': {}, '23': {}, '28': {}, '29': {}, '1': {}, '0': {}, '3': {}, '2': {}, '5': {}, '4': {}, '7': {}, '6': {}, '9': {}, '8': {}, '11': {}, '10': {}, '13': {}, '12': {}, '15': {}, '14': {}, '17': {}, '16': {}, '19': {}, '18': {}, '31': {}, '30': {}} -------- Output End -------- The key looks correct below (it's a unique ID), but the dictionary inserted below is empty. If I uncomment the print statement above, the nesteddict dictionary displays all the proper keys and values. So I know it's getting filled OK, but it doesn't insert into the parent dictionary at all in the line: parentdict[parentdictkey] = nesteddict Any thoughts on how to properly insert the nested dictionary so that I can refer to it? -- Keith Reed keith_reed at fastmail.net From alan.gauld at btinternet.com Thu Jan 1 19:59:23 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 1 Jan 2009 18:59:23 -0000 Subject: [Tutor] Distinction between tuples and lists References: <5e5978e10901010607r6b0e7c5l451326fb2480fb9a@mail.gmail.com> Message-ID: "Christopher Mutel" wrote > I stumbled across some discussion of why the fundamental difference > between lists and tuples is not mutability, but hetero- versus > homogeneous data, e.g. This is not a discussion about Pythons tuples v lists per se but about how some people think they should be used and their definitions/usage within Computing science generally. lists/tuples serve many purposes in Python but one thing they most definitely do not do is act as hetero/homogenous containers. The authors of the blogs may wish otherwise and indeed their debate seems to be geared around what they would like to see in Python3000 rather than whats there now. > http://jtauber.com/blog/2006/04/15/python_tuples_are_not_just_constant_lists/ > http://pyre.third-bit.com/blog/archives/000450.html > > However, after reading the cited discussions, my python books, etc., > I > have to admit I don't really understand this idea. What does it mean > that "lists are intended for homogeneous sequences"? What is > different > about lists that would make them more suited for homogeneous > sequences Nothing except the typical usage. Normally we use lists where we want to be able to change their content or iterate over them. The type of the data is often the same because the loop will try to treat each item identically. Tuples are often used as "lightweight records" so they hold fields of different type. Thus when accessing a database we get back a list of tuples (records) with each tuple containing the data firlds from the database. But Python does not enforce that and a list of lists would work just as well. And of course you can loop over a tuple as well as a list. I wouldn't get overly hung up on these kinds of debates. I've never seen any of the Python gurus make a big issue of it and experience tends to teach where each type is more appropriate. > from what I understand, the idea of homo/heterogeneity seems > orthogonal to mutability, which is the main distinction emphasized > by > e.g. Learning Python. They are orthogonal concepts, you are quite right. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Thu Jan 1 20:14:20 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 1 Jan 2009 14:14:20 -0500 Subject: [Tutor] Inserting one dictionary into another In-Reply-To: <1230825882.6354.1292570031@webmail.messagingengine.com> References: <1230825882.6354.1292570031@webmail.messagingengine.com> Message-ID: <1c2a2c590901011114m2be6fe74s2023b6318e5f5d02@mail.gmail.com> On Thu, Jan 1, 2009 at 11:04 AM, Keith Reed wrote: > I'm having trouble assigning a dictionary as a value within another: > > > -------- Code Snippet Start -------- > > for line in fromchild.readlines(): > itemarray = line.strip().split(":") > parentdictkey = itemarray[0] > print 'parentdictkey = ' + parentdictkey > for index in range(len(headerinfo)): > nesteddict[headerinfo[index]] = itemarray[index] > #print nesteddict > parentdict[parentdictkey] = nesteddict > nesteddict.clear() > print > '-------------------------------------------------------------------------\n' > print parentdict The problem is that you are re-using the same dict rather than creating a new one each time through the loop. Every value of parentdict is the same; when you clear nesteddict you are clearing the one shared dict. Python assignment copies references, not values. If you don't understand this, read this: http://personalpages.tds.net/~kent37/kk/00012.html The solution is easy; just make a new dict at the start of the loop: nesteddict = {} and get rid of the clear(). Kent From kent37 at tds.net Thu Jan 1 22:47:10 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 1 Jan 2009 16:47:10 -0500 Subject: [Tutor] Distinction between tuples and lists In-Reply-To: References: <5e5978e10901010607r6b0e7c5l451326fb2480fb9a@mail.gmail.com> Message-ID: <1c2a2c590901011347o2a7615f5nd7b5a2c0ca0465a0@mail.gmail.com> On Thu, Jan 1, 2009 at 1:59 PM, Alan Gauld wrote: > lists/tuples serve many purposes in Python but one thing they most > definitely > do not do is act as hetero/homogenous containers. The authors of the blogs > may wish otherwise and indeed their debate seems to be geared around > what they would like to see in Python3000 rather than whats there now. For what it's worth, Guido has explicitly said, "Tuples are for heterogeneous data, list are for homogeneous data. Tuples are *not* read-only lists." http://mail.python.org/pipermail/python-dev/2003-March/033964.html This statement kicked off a very long thread on the python-dev list. For a summary of the discussion, and links to more of it, see the section "Ridiculously minor tweaks?" here: http://groups.google.com/group/comp.lang.python.announce/browse_thread/thread/b2a1ea28a26b3dfb/b2d17a69541e886b?lnk=gst Personally, I take this with a grain of salt. I do tend to use tuples for things that are like records or structs, or often just for pairs of data (e.g. the elements of dict.items()), and lists for homogeneous collections, but that is more a matter of fitness for the purpose than dogma. Kent From alan.gauld at btinternet.com Fri Jan 2 01:10:11 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 2 Jan 2009 00:10:11 -0000 Subject: [Tutor] Distinction between tuples and lists References: <5e5978e10901010607r6b0e7c5l451326fb2480fb9a@mail.gmail.com> <1c2a2c590901011347o2a7615f5nd7b5a2c0ca0465a0@mail.gmail.com> Message-ID: "Kent Johnson" wrote > > For what it's worth, Guido has explicitly said, > "Tuples are for heterogeneous data, list are for homogeneous data. > Tuples are *not* read-only lists." That surprises me, he has always seemed more pragmatist than purist. However even Guido saying it doesn't alter the fact that in practice it is not a part of the language, merely a usage pattern. (Of course that could change in future versions like Python3000 but in the current incarnation, we have what we have) > Personally, I take this with a grain of salt. I do tend to use > tuples > for things that are like records or structs, or often just for pairs > of data (e.g. the elements of dict.items()), and lists for > homogeneous > collections, but that is more a matter of fitness for the purpose > than > dogma. Precisely. That was the point I tried to make earlier that in most usage scenarios lists tend to be used homogenously and tuples heterogenenously. But there is absolutely nothing in Python that mandates it. A good example of a homogenous tuple is a pair of values such as a point's x,y coordinates. And heterogenuous lists are also very useful at times, particularly when the only alternative would be to define a singleton class... Alan G. From rabidpoobear at gmail.com Fri Jan 2 08:06:45 2009 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Fri, 2 Jan 2009 01:06:45 -0600 Subject: [Tutor] Top posters to tutor list for 2008 In-Reply-To: <1230823418.6159.29.camel@ltop> References: <1c2a2c590901010634p1d10064bt9289fc952b69d558@mail.gmail.com> <1230823418.6159.29.camel@ltop> Message-ID: Yeah, I agree. Interesting script, Kent. Surprisingly short. I didn't realize I wasn't in the top 5 posters for 2008! I guess I have a new year's resolution to be more helpful. Happy New Year, everyone! On Thu, Jan 1, 2009 at 9:23 AM, jadrifter wrote: > On Thu, 2009-01-01 at 09:34 -0500, Kent Johnson wrote: >> For several years I have been using a simple script to find the top 20 >> posters to the tutor list by web-scraping the archive pages. I thought >> others might be interested so here is the list for 2008 and the script >> that generates it. The lists for previous years (back to 2003) are at >> the end so everyone on the list doesn't hit the archives to find out >> :-) >> >> The script gives a simple example of datetime, urllib2 and >> BeautifulSoup. It consolidates names that vary by case but other >> variations are not detected. > > Kent, > > Thank you for this. I've been thinking about a web scraping script but > didn't have a clue how to go about it. Seeing someone else's practical > implementation is a huge help! > > A little serendipity to start 2009 off with. > > Happy New Year to all. > > John > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at btinternet.com Fri Jan 2 11:34:46 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 2 Jan 2009 10:34:46 -0000 Subject: [Tutor] Top posters to tutor list for 2008 References: <1c2a2c590901010634p1d10064bt9289fc952b69d558@mail.gmail.com> Message-ID: "Kent Johnson" wrote > that generates it. The lists for previous years (back to 2003) are > at > the end so everyone on the list doesn't hit the archives to find out > Alan, I thought you might have passed me this year but we are both > off > a little :-) I think the figures reflect the general level of activity on the list. We seem to have peaked in 2005... Statistics, don't you love 'em :-) 2003 ==== Danny Yoo 617 Alan Gauld 421 Jeff Shannon 283 Magnus Lycka 242 Total =~ 1500 2004 ==== Alan Gauld 699 Danny Yoo 530 Kent Johnson 451 Lloyd Kvam 146 Total =~ 1800 2005 ==== Kent Johnson 1189 Danny Yoo 767 Alan Gauld 565 Alan G 317 Total =~ 2800 (If you count both of my totals I get back into 2nd place :-) 2006 ==== Kent Johnson 913 Alan Gauld 815 Danny Yoo 448 Luke Paireepinart 242 Total =~ 2400 2007 ==== Kent Johnson 1052 Alan Gauld 938 Luke Paireepinart 260 Dick Moores 203 Total =~ 2400 2008 ==== Kent Johnson 931 Alan Gauld 820 bob gailer 247 Dick Moores 191 Total =~ 2200 Alan G From denis.spir at free.fr Fri Jan 2 13:07:14 2009 From: denis.spir at free.fr (spir) Date: Fri, 2 Jan 2009 13:07:14 +0100 Subject: [Tutor] Inserting one dictionary into another In-Reply-To: <1230825882.6354.1292570031@webmail.messagingengine.com> References: <1230825882.6354.1292570031@webmail.messagingengine.com> Message-ID: <20090102130714.2a12f5b7@o> On Thu, 01 Jan 2009 11:04:42 -0500 "Keith Reed" wrote: > I'm having trouble assigning a dictionary as a value within another: > > > -------- Code Snippet Start -------- > > for line in fromchild.readlines(): > itemarray = line.strip().split(":") > parentdictkey = itemarray[0] > print 'parentdictkey = ' + parentdictkey > for index in range(len(headerinfo)): > nesteddict[headerinfo[index]] = itemarray[index] > #print nesteddict > parentdict[parentdictkey] = nesteddict > nesteddict.clear() > print > '-------------------------------------------------------------------------\n' > print parentdict > > -------- Code Snippet End -------- > > -------- Output Start -------- > {'24': {}, '25': {}, '26': {}, '27': {}, '20': {}, '21': {}, '22': {}, > '23': {}, '28': {}, '29': {}, '1': {}, '0': {}, '3': {}, '2': {}, '5': > {}, '4': {}, '7': {}, '6': {}, '9': {}, '8': {}, '11': {}, '10': {}, > '13': {}, '12': {}, '15': {}, '14': {}, '17': {}, '16': {}, '19': {}, > '18': {}, '31': {}, '30': {}} > -------- Output End -------- Some notes about the code. -1- 'itemarray' actually is a list of data items, right? So why not simply call it 'items'? -2- It seems that 'headerinfo' is a constant list of data field names, that will become (nested) dict keys. If it really is constant, I would thus call it 'KEYS', else 'keys' if it is as computed value instead (e.g. read from a file/table header). -3- As headerinfo/keys is constant /inside the dict filling loop/ anyway, you can use nice built-in functions enumerate() or zip() to make the code much clearer. Below how they work/ -4- 'parentdictkey' is a rather misleading name as I understand it -- isn't it the key of the current nested dict instead? ========================================= keys = ("un","du","tri") items= ("foo","bar","blah") d=dict() for index,key in enumerate(keys): # --> (index,item) tuples d[key]=items[index] print d d.clear() for key,item in zip(keys,items): # --> (key,item) tuples d[key]=item print d ==> {'tri': 'blah', 'du': 'bar', 'un': 'foo'} {'tri': 'blah', 'du': 'bar', 'un': 'foo'} ========================================= So that your nested dict filling loop may change: for index in range(len(headerinfo)): nesteddict[headerinfo[index]] = itemarray[index] for key,item in zip(keys,items): nesteddict[key] = item > The key looks correct below (it's a unique ID), but the dictionary > inserted below is empty. > If I uncomment the print statement above, the nesteddict dictionary > displays all the proper keys and values. So I know it's getting filled > OK, but it doesn't insert into the parent dictionary at all in the line: > parentdict[parentdictkey] = nesteddict > > Any thoughts on how to properly insert the nested dictionary so that I > can refer to it? > The point (always again biting python users) is that you have created a single nesteddict object. And: Python variables simply are name:object bindings -- which is right. So that at the end of your routine, you have a single nesteddict which happens to be empty because you clear it. All parentdict[parentdictkey] references point to a unique object, actually an empty dictionay. The right thing to do is to create a brand new dict at start of each loop -- which by the way is fully consistent because you really n sub-dictionaries: for line in fromchild.readlines(): nested_dict = dict() # new empty sub-dict Then you do not need the final clear()ing anymore. Denis ------ la vida e estranya From iaidas4 at gmail.com Fri Jan 2 13:25:11 2009 From: iaidas4 at gmail.com (i i) Date: Fri, 2 Jan 2009 17:25:11 +0500 Subject: [Tutor] :initialize a for loop Message-ID: <6fb034600901020425v7bb211efn45afbcff190958f6@mail.gmail.com> Hi, i am making an activity in glade.here is the code self.numOne = random.randint(1,10) for i in range(self.numOne): self.image = gtk.Image() self.image.set_from_file("./Pink-Flower-32x32.png") self.fixed.put(self.image, i*25, 0) self.image.show() here u can see i have declared an array and it makes required number of images,i want to initialize the array or empty it before the next loop. how can we initialize or empty a for-in statement in python. thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Fri Jan 2 13:52:56 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 2 Jan 2009 07:52:56 -0500 Subject: [Tutor] Top posters to tutor list for 2008 In-Reply-To: References: <1c2a2c590901010634p1d10064bt9289fc952b69d558@mail.gmail.com> <1230823418.6159.29.camel@ltop> Message-ID: <1c2a2c590901020452m506100fft4106c1a7ce386d7@mail.gmail.com> On Fri, Jan 2, 2009 at 2:06 AM, Luke Paireepinart wrote: > Yeah, I agree. Interesting script, Kent. Surprisingly short. > > I didn't realize I wasn't in the top 5 posters for 2008! I guess I > have a new year's resolution to be more helpful. Or ask more questions, that works too! Kent From kent37 at tds.net Fri Jan 2 14:04:39 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 2 Jan 2009 08:04:39 -0500 Subject: [Tutor] Top posters to tutor list for 2008 In-Reply-To: References: <1c2a2c590901010634p1d10064bt9289fc952b69d558@mail.gmail.com> Message-ID: <1c2a2c590901020504o31bf5436odcb4916bab89a5c2@mail.gmail.com> On Fri, Jan 2, 2009 at 5:34 AM, Alan Gauld wrote: > I think the figures reflect the general level of activity on the list. > We seem to have peaked in 2005... > Statistics, don't you love 'em :-) I couldn't resist adding a total number of posts and percent to the calculations. Statistics + python = time sink :-) I re-ran the program back to 2003. New program and results below. 2005 was a banner year. 2008 was down considerably from 2007 and that does account for our smaller numbers. BTW your historical counts are up a bit in this set because this is the first year I had the name folding. Maybe I should add a set of known aliases also... Kent ''' Counts all posts to Python-tutor by author''' # -*- coding: latin-1 -*- from datetime import date, timedelta import operator, urllib2 from BeautifulSoup import BeautifulSoup today = date.today() for year in range(2003, 2009): startDate = date(year, 1, 1) endDate = date(year, 12, 31) thirtyOne = timedelta(days=31) counts = {} # Collect all the counts for a year by scraping the monthly author archive pages while startDate < endDate and startDate < today: dateString = startDate.strftime('%Y-%B') url = 'http://mail.python.org/pipermail/tutor/%s/author.html' % dateString data = urllib2.urlopen(url).read() soup = BeautifulSoup(data) li = soup.findAll('li')[2:-2] for l in li: name = l.i.string.strip() counts[name] = counts.get(name, 0) + 1 startDate += thirtyOne totalPosts = sum(counts.itervalues()) # Consolidate names that vary by case under the most popular spelling nameMap = dict() # Map lower-case name to most popular name for name, count in sorted(counts.iteritems(), key=operator.itemgetter(1), reverse=True): lower = name.lower() if lower in nameMap: # Add counts for a name we have seen already counts[nameMap[lower]] += count else: nameMap[lower] = name print print '%s (%s posts)' % (year, totalPosts) print '====' for name, count in sorted(counts.iteritems(), key=operator.itemgetter(1), reverse=True)[:20]: pct = round(100.0*count/totalPosts, 1) print '%s %s (%s%%)' % (name.encode('utf-8', 'xmlcharrefreplace'), count, pct) print # Results as of 12/31/2008: ''' 2003 (7745 posts) ==== Danny Yoo 617 (8.0%) Alan Gauld 421 (5.4%) Jeff Shannon 283 (3.7%) Magnus Lycka 242 (3.1%) Bob Gailer 195 (2.5%) Magnus =?iso-8859-1?Q?Lyck=E5?= 166 (2.1%) alan.gauld at bt.com 161 (2.1%) Kirk Bailey 155 (2.0%) Gregor Lingl 152 (2.0%) Lloyd Kvam 142 (1.8%) Andrei 118 (1.5%) Sean 'Shaleh' Perry 117 (1.5%) Magnus Lyck? 113 (1.5%) Michael Janssen 113 (1.5%) Erik Price 100 (1.3%) Lee Harr 88 (1.1%) Terry Carroll 87 (1.1%) Daniel Ehrenberg 78 (1.0%) Abel Daniel 76 (1.0%) Don Arnold 75 (1.0%) 2004 (7178 posts) ==== Alan Gauld 699 (9.7%) Danny Yoo 530 (7.4%) Kent Johnson 451 (6.3%) Lloyd Kvam 146 (2.0%) Dick Moores 145 (2.0%) Liam Clarke 140 (2.0%) Brian van den Broek 122 (1.7%) Karl Pflästerer 109 (1.5%) Jacob S. 101 (1.4%) Andrei 99 (1.4%) Chad Crabtree 93 (1.3%) Bob Gailer 91 (1.3%) Magnus Lycka 91 (1.3%) Terry Carroll 88 (1.2%) Marilyn Davis 84 (1.2%) Gregor Lingl 73 (1.0%) Dave S 73 (1.0%) Bill Mill 71 (1.0%) Isr Gish 71 (1.0%) Lee Harr 67 (0.9%) 2005 (9705 posts) ==== Kent Johnson 1189 (12.3%) Danny Yoo 767 (7.9%) Alan Gauld 565 (5.8%) Alan G 317 (3.3%) Liam Clarke 298 (3.1%) Max Noel 203 (2.1%) Nathan Pinno 197 (2.0%) Brian van den Broek 190 (2.0%) Jacob S. 154 (1.6%) jfouhy at paradise.net.nz 135 (1.4%) Alberto Troiano 128 (1.3%) Bernard Lebel 119 (1.2%) Joseph Quigley 101 (1.0%) Terry Carroll 93 (1.0%) Andrei 79 (0.8%) D. Hartley 77 (0.8%) John Fouhy 73 (0.8%) bob 73 (0.8%) Hugo González Monteverde 72 (0.7%) Orri Ganel 69 (0.7%) 2006 (7521 posts) ==== Kent Johnson 913 (12.1%) Alan Gauld 821 (10.9%) Danny Yoo 448 (6.0%) Luke Paireepinart 242 (3.2%) John Fouhy 187 (2.5%) Chris Hengge 166 (2.2%) Bob Gailer 134 (1.8%) Dick Moores 129 (1.7%) Asrarahmed Kadri 119 (1.6%) Terry Carroll 111 (1.5%) Python 94 (1.2%) Mike Hansen 74 (1.0%) Liam Clarke 72 (1.0%) Carroll, Barry 67 (0.9%) Kermit Rose 66 (0.9%) anil maran 66 (0.9%) Hugo González Monteverde 65 (0.9%) wesley chun 63 (0.8%) Dave S 58 (0.8%) Christopher Spears 53 (0.7%) 2007 (7600 posts) ==== Kent Johnson 1052 (13.8%) Alan Gauld 977 (12.9%) Luke Paireepinart 260 (3.4%) Dick Moores 203 (2.7%) Eric Brunson 164 (2.2%) Bob Gailer 144 (1.9%) Terry Carroll 128 (1.7%) Tiger12506 112 (1.5%) John Fouhy 105 (1.4%) Ricardo Aráoz 93 (1.2%) Rikard Bosnjakovic 93 (1.2%) bhaaluu 88 (1.2%) elis aeris 83 (1.1%) Andreas Kostyrka 77 (1.0%) Michael Langford 68 (0.9%) shawn bright 63 (0.8%) Tim Golden 62 (0.8%) Dave Kuhlman 62 (0.8%) wormwood_3 53 (0.7%) wesley chun 53 (0.7%) 2008 (6624 posts) ==== Kent Johnson 931 (14.1%) Alan Gauld 820 (12.4%) bob gailer 247 (3.7%) Dick Moores 191 (2.9%) W W 142 (2.1%) Wayne Watson 106 (1.6%) John Fouhy 97 (1.5%) Steve Willoughby 91 (1.4%) Lie Ryan 88 (1.3%) bhaaluu 85 (1.3%) Marc Tompkins 83 (1.3%) Michael Langford 71 (1.1%) Tiger12506 70 (1.1%) Andreas Kostyrka 64 (1.0%) Dinesh B Vadhia 64 (1.0%) wesley chun 58 (0.9%) Tim Golden 57 (0.9%) Chris Fuller 54 (0.8%) Ricardo Aráoz 53 (0.8%) spir 53 (0.8%) ''' From sander.sweers at gmail.com Fri Jan 2 14:13:32 2009 From: sander.sweers at gmail.com (Sander Sweers) Date: Fri, 2 Jan 2009 14:13:32 +0100 Subject: [Tutor] Top posters to tutor list for 2008 In-Reply-To: <1c2a2c590901020452m506100fft4106c1a7ce386d7@mail.gmail.com> References: <1c2a2c590901010634p1d10064bt9289fc952b69d558@mail.gmail.com> <1230823418.6159.29.camel@ltop> <1c2a2c590901020452m506100fft4106c1a7ce386d7@mail.gmail.com> Message-ID: On Fri, Jan 2, 2009 at 13:52, Kent Johnson wrote: > Or ask more questions, that works too! So you and Alan ask the most questions ;-) Seriously now, this really shows the power of Python and I'll have a good time figuring out how this exactly works. Thanks to all the Tutors for year of great support :-) Greets Sander From norman at khine.net Fri Jan 2 14:17:23 2009 From: norman at khine.net (Norman Khine) Date: Fri, 02 Jan 2009 14:17:23 +0100 Subject: [Tutor] List of dictionaries membership test Message-ID: <495E13E3.5010902@khine.net> Hello, I have this list >>> currencies = [{'sign': '\xe2\x82\xac', 'id': 'EUR', 'is_selected': False, 'title': 'EURO'}, {'sign': '\xc2\xa3', 'id': 'GBP', 'is_selected': True, 'title': 'Pound'}, {'sign': '$', 'id': 'USD', 'is_selected': False, 'title': 'Dollar'}] What is the simplest way to extract the dictionary that has key 'is_selected'== True? Thanks Norman From rschroev_nospam_ml at fastmail.fm Fri Jan 2 14:26:16 2009 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Fri, 02 Jan 2009 14:26:16 +0100 Subject: [Tutor] Distinction between tuples and lists In-Reply-To: References: <5e5978e10901010607r6b0e7c5l451326fb2480fb9a@mail.gmail.com> <1c2a2c590901011347o2a7615f5nd7b5a2c0ca0465a0@mail.gmail.com> Message-ID: Alan Gauld schreef: > "Kent Johnson" wrote >> For what it's worth, Guido has explicitly said, >> "Tuples are for heterogeneous data, list are for homogeneous data. >> Tuples are *not* read-only lists." > > That surprises me, he has always seemed more pragmatist than purist. > However even Guido saying it doesn't alter the fact that in practice > it is not a part of the language, merely a usage pattern. I think it's more than a usage pattern; I think it is also the idea behind the design decisions of list and tuple behavior. It's why lists have index() methods for example, and tuples don't. > Precisely. That was the point I tried to make earlier that in most > usage scenarios lists tend to be used homogenously and tuples > heterogenenously. But there is absolutely nothing in Python that > mandates it. A good example of a homogenous tuple is a pair of > values such as a point's x,y coordinates. In the point of view taken by Guido and the writer of the blogs mentioned before, a tuple of x, y coordinates is not homogeneous, it's heterogeneous. Both x and y do have the same type, but that's not the point. The point is that the meaning of the two elements is different. It makes, for example, no sense to sort such a tuple. -- The saddest aspect of life right now is that science gathers knowledge faster than society gathers wisdom. -- Isaac Asimov Roel Schroeven From kent37 at tds.net Fri Jan 2 14:28:59 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 2 Jan 2009 08:28:59 -0500 Subject: [Tutor] Top posters to tutor list for 2008 In-Reply-To: References: <1c2a2c590901010634p1d10064bt9289fc952b69d558@mail.gmail.com> <1230823418.6159.29.camel@ltop> <1c2a2c590901020452m506100fft4106c1a7ce386d7@mail.gmail.com> Message-ID: <1c2a2c590901020528w3609e46ch1244cb04577ad48c@mail.gmail.com> On Fri, Jan 2, 2009 at 8:13 AM, Sander Sweers wrote: > On Fri, Jan 2, 2009 at 13:52, Kent Johnson wrote: >> Or ask more questions, that works too! > > So you and Alan ask the most questions ;-) No, that honor goes to Dick Moores. He is in the top 10 in 4 of the last 5 years! > Thanks to all the Tutors for year of great support :-) You're welcome, we couldn't do it without you! Kent From kent37 at tds.net Fri Jan 2 14:42:12 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 2 Jan 2009 08:42:12 -0500 Subject: [Tutor] List of dictionaries membership test In-Reply-To: <495E13E3.5010902@khine.net> References: <495E13E3.5010902@khine.net> Message-ID: <1c2a2c590901020542u2345a358w7ca002af18f8b6ab@mail.gmail.com> On Fri, Jan 2, 2009 at 8:17 AM, Norman Khine wrote: > Hello, > I have this list > >>>> currencies = [{'sign': '\xe2\x82\xac', 'id': 'EUR', 'is_selected': >>>> False, 'title': 'EURO'}, {'sign': '\xc2\xa3', 'id': 'GBP', 'is_selected': >>>> True, 'title': 'Pound'}, {'sign': '$', 'id': 'USD', 'is_selected': False, >>>> 'title': 'Dollar'}] > > What is the simplest way to extract the dictionary that has key > 'is_selected'== True? A list comprehension can extract a list of all dicts with the desired key: In [2]: [ currency for currency in currencies if currency['is_selected'] ] Out[2]: [{'id': 'GBP', 'is_selected': True, 'sign': '\xc2\xa3', 'title': 'Pound'}] A generator expression lets you pick out just the first one without iterating the whole list. This will raise StopIteration if there is no selected item: In [3]: ( currency for currency in currencies if currency['is_selected'] ).next() Out[3]: {'id': 'GBP', 'is_selected': True, 'sign': '\xc2\xa3', 'title': 'Pound'} Of course a for loop works. You can use the else clause to handle the case of no selection: for currency in currencies: if currency['is_selected']: # Do something with currency print currency break else: # this matches the indentation of 'for', it is not an 'elif' # Handle 'not found' case print 'No currency selected' Kent From denis.spir at free.fr Fri Jan 2 17:10:59 2009 From: denis.spir at free.fr (spir) Date: Fri, 2 Jan 2009 17:10:59 +0100 Subject: [Tutor] object's attributes Message-ID: <20090102171059.25aec893@o> Can someone explain the following? ============================ class Type(object): pass o = Type() o.a = 1 print o, o.a print dir(object) ==> ['__class__', '__delattr__', '__doc__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__'] ==> no problem o = object() o.a = 1 ==> AttributeError: 'object' object has no attribute 'a' ================================ Type does not create any additional attribute or member, or what? Does this mean that the type 'object' has a hidden __slots__ attr? Then why doesn't Type inherit it, like any attribute? Denis ------ la vida e estranya From alan.gauld at btinternet.com Fri Jan 2 17:41:13 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 2 Jan 2009 16:41:13 -0000 Subject: [Tutor] Distinction between tuples and lists References: <5e5978e10901010607r6b0e7c5l451326fb2480fb9a@mail.gmail.com> <1c2a2c590901011347o2a7615f5nd7b5a2c0ca0465a0@mail.gmail.com> Message-ID: "Roel Schroeven" wrote > In the point of view taken by Guido and the writer of the blogs > mentioned before, a tuple of x, y coordinates is not homogeneous, > it's > heterogeneous. Both x and y do have the same type, but that's not > the > point. The point is that the meaning of the two elements is > different. > It makes, for example, no sense to sort such a tuple. Yes, I spotted Guido making that point shortly after posting :-) I guess its more a case of thinking of tuples as lightweight records rather that strictly heterogenuous(*) types (which is a somewhat moot issue in Python). So the significant point is that in a tuple each "field" has a meaning specific to its position. The big problem is that they are also immutable which greatly reduces their effectiveness in that role. So the alternatives are create a class - for possibly a single instance - or use a list as a writable record. (*) Although heterogenuous does not really debar same type items but the focus on type is I suspect misleading in terms of understanding the role of tuples. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Fri Jan 2 17:45:16 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 2 Jan 2009 16:45:16 -0000 Subject: [Tutor] :initialize a for loop References: <6fb034600901020425v7bb211efn45afbcff190958f6@mail.gmail.com> Message-ID: "i i" wrote in > self.numOne = random.randint(1,10) > for i in range(self.numOne): > self.image = gtk.Image() > self.image.set_from_file("./Pink-Flower-32x32.png") > self.fixed.put(self.image, i*25, 0) > self.image.show() > > images,i want to initialize the array or empty it before the next > loop. > how can we initialize or empty a for-in statement in python. I don't understand the question? What is it you want to initialise or empty? Do you just want to break out of the loop? Do you want to clear the images you have already created at some point? Can you show us some pseudo code that would illustrate how you would like the program to work? -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Fri Jan 2 17:56:16 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 2 Jan 2009 16:56:16 -0000 Subject: [Tutor] object's attributes References: <20090102171059.25aec893@o> Message-ID: "spir" wrote > Can someone explain the following? Not really an explanation but I did notice when repeating your experiment that your class instance has a __dict__ attribute but object does not. The new attribute a is apparently located in the dict. >>> class C(object): pass ... >>> o = object() >>> c = C() >>> c.a = 6 >>> dir(c) ['__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__', '__hash_ _', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr_ _', '__setattr__', '__str__', '__weakref__', 'a'] >>> dir(o) ['__class__', '__delattr__', '__doc__', '__getattribute__', '__hash__', '__init_ _', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str_ _'] >>> print c.__dict__ {'a': 6} And the dict exists before the new attribuite is created: >>> d = C() >>> dir(d) ['__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__', '__hash_ _', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr_ _', '__setattr__', '__str__', '__weakref__'] Does that help? I don't know. Why does a class inheriting from object acquire a dict when object doesn't have one? I'm sure somebody can explain but its not me... Alan G. From kent37 at tds.net Fri Jan 2 17:57:32 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 2 Jan 2009 11:57:32 -0500 Subject: [Tutor] object's attributes In-Reply-To: <20090102171059.25aec893@o> References: <20090102171059.25aec893@o> Message-ID: <1c2a2c590901020857y1c89a453qb5f8357f50488933@mail.gmail.com> On Fri, Jan 2, 2009 at 11:10 AM, spir wrote: > Can someone explain the following? > > ============================ > class Type(object): > pass > o = Type() > o.a = 1 > print o, o.a > print dir(object) > ==> ['__class__', '__delattr__', '__doc__', '__getattribute__', '__hash__', '__init__', '__new__', > '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__'] > ==> no problem > o = object() > o.a = 1 > ==> AttributeError: 'object' object has no attribute 'a' > ================================ > > Type does not create any additional attribute or member, or what? > Does this mean that the type 'object' has a hidden __slots__ attr? > Then why doesn't Type inherit it, like any attribute? I'm no expert on this so take this with salt... IIUC the attributes of built-in objects are hard-coded in tables. The hard-coded tables don't include __dict__ attributes so you can't add attributes to instances of built-in types. This is similar to what __slots__ does for user-defined classes though the implementation is different. The special behaviour of a class with a __slots__ attribute only affects the class that defines __slots__, not subclasses. See http://docs.python.org/reference/datamodel.html#id3: "The action of a __slots__ declaration is limited to the class where it is defined. As a result, subclasses will have a __dict__ unless they also define __slots__." Kent From alan.gauld at btinternet.com Fri Jan 2 17:58:55 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 2 Jan 2009 16:58:55 -0000 Subject: [Tutor] List of dictionaries membership test References: <495E13E3.5010902@khine.net> Message-ID: "Norman Khine" wrote > >>> currencies = [{'sign': '\xe2\x82\xac', 'id': 'EUR', > >>> 'is_selected': > False, 'title': 'EURO'}, {'sign': '\xc2\xa3', 'id': 'GBP', > 'is_selected': True, 'title': 'Pound'}, {'sign': '$', 'id': 'USD', > 'is_selected': False, 'title': 'Dollar'}] > > What is the simplest way to extract the dictionary that has key > 'is_selected'== True? I'd use a list comprehension: selected = [d for d in currencies if d['is_selected'] == True] HTH -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From ptmcg at austin.rr.com Fri Jan 2 19:36:42 2009 From: ptmcg at austin.rr.com (Paul McGuire) Date: Fri, 2 Jan 2009 12:36:42 -0600 Subject: [Tutor] object's attributes In-Reply-To: References: Message-ID: <565B8985529F487188A7CC4F980ECBC2@AWA2> Denis - What you are seeing is standard procedure for any built-in type - no dynamic assignment of attributes allowed. Here is an analogous case to your example, but based on str instead of object: greeting = "bon jour" greeting.language = "French" # raises AttributeError: 'str' object has no attribute 'language' class I18NString(str): pass greeting = I18NString("bon jour") greeting.language = "French" # OK The example you cited of creating a thin derived class from object, for the simple purpose of supporting dynamically assigned attributes, sometimes goes by the name Bag, from the Smalltalk object framework. The Traits framework uses a "root" class HasTraits so that you can easily attach attributes, and then use the traits.ui package to bring up a GUI editor. Here is a recipe from the Python Cookbook: http://code.activestate.com/recipes/259174/ There is also the new namedtuple type in the Python 2.6 collections module, which started out as this recipe: http://code.activestate.com/recipes/500261/. Happy New Year! -- Paul From denis.spir at free.fr Fri Jan 2 20:05:16 2009 From: denis.spir at free.fr (spir) Date: Fri, 2 Jan 2009 20:05:16 +0100 Subject: [Tutor] object's attributes In-Reply-To: <565B8985529F487188A7CC4F980ECBC2@AWA2> References: <565B8985529F487188A7CC4F980ECBC2@AWA2> Message-ID: <20090102200516.0cf2a3c6@o> On Fri, 2 Jan 2009 12:36:42 -0600 "Paul McGuire" wrote: > Denis - Hello Paul, pleased to read you again ;-) > What you are seeing is standard procedure for any built-in type - no dynamic > assignment of attributes allowed. Here is an analogous case to your > example, but based on str instead of object: > > greeting = "bon jour" > greeting.language = "French" # raises AttributeError: 'str' object has no > attribute 'language' > > class I18NString(str): > pass > > greeting = I18NString("bon jour") > greeting.language = "French" # OK Yep! I should have remembered that, as I have met this issue precisely with strings. But this limitation is True only for the kind of built-in types that I personly call 'values': numbers, strings etc... The following prints "I'm f!": def f(): pass f.view = "I'm %s!" % f.__name__ print f.view [This is one more illustration that "values" are *not* standard objects, as I see it: both conceptually (they represent qualities like qualifiers in human languages, while classes/types represent.. classes, methods represent events and standard objects represents things) and practically.] > The example you cited of creating a thin derived class from object, for the > simple purpose of supporting dynamically assigned attributes, sometimes goes > by the name Bag, from the Smalltalk object framework. The Traits framework > uses a "root" class HasTraits so that you can easily attach attributes, and > then use the traits.ui package to bring up a GUI editor. > > Here is a recipe from the Python Cookbook: > http://code.activestate.com/recipes/259174/ > There is also the new namedtuple type in the Python 2.6 collections module, > which started out as this recipe: > http://code.activestate.com/recipes/500261/. I'll have a look at that. > Happy New Year! Wish you many sweet things. I take the occasion to inform you I have a first version of parser generator ready. [Still without text grammar translation.] Someone (Eike) who works on parsers too pointed me to EasyExtend: http://www.fiber-space.de/EasyExtend/doc/EE.html Think you would find it interesting to allow for syntax freedom *inside* python. (but requires preprocessing) > -- Paul Denis ------ la vida e estranya From kent37 at tds.net Fri Jan 2 20:29:35 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 2 Jan 2009 14:29:35 -0500 Subject: [Tutor] object's attributes In-Reply-To: <565B8985529F487188A7CC4F980ECBC2@AWA2> References: <565B8985529F487188A7CC4F980ECBC2@AWA2> Message-ID: <1c2a2c590901021129v5fbe184cxbceb9cc511104112@mail.gmail.com> On Fri, Jan 2, 2009 at 1:36 PM, Paul McGuire wrote: > The example you cited of creating a thin derived class from object, for the > simple purpose of supporting dynamically assigned attributes, sometimes goes > by the name Bag, from the Smalltalk object framework. Another variation is Bunch, though perhaps namedtuple() makes this obsolete: http://code.activestate.com/recipes/52308/ Kent From norman at khine.net Fri Jan 2 20:53:29 2009 From: norman at khine.net (Norman Khine) Date: Fri, 02 Jan 2009 20:53:29 +0100 Subject: [Tutor] format currency Message-ID: <495E70B9.5020404@khine.net> Hello, I have this code, is there a better way to get the desired output. http://paste.lisp.org/display/72966 Thanks From bgailer at gmail.com Fri Jan 2 21:05:24 2009 From: bgailer at gmail.com (bob gailer) Date: Fri, 02 Jan 2009 15:05:24 -0500 Subject: [Tutor] format currency In-Reply-To: <495E70B9.5020404@khine.net> References: <495E70B9.5020404@khine.net> Message-ID: <495E7384.3080906@gmail.com> Norman Khine wrote: > Hello, > I have this code, is there a better way to get the desired output. > > http://paste.lisp.org/display/72966 I'd add the variable information e g. ('fr', 'ascii', '%.2f', '%s %s']) to the individual dictionaries. Then all the relevant data is in one place. Then you need no if statement. I also assume that only one dictionary will be selected. Then you don't need the for loop. x = [d for d in currencies if d['is_selected'] == True][0] This could be a great application for the recently discussed namedtuples, to be used in lieu of the dictionaries. -- Bob Gailer Chapel Hill NC 919-636-4239 From kent37 at tds.net Fri Jan 2 22:37:13 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 2 Jan 2009 16:37:13 -0500 Subject: [Tutor] tuple & object's attributes (changed) In-Reply-To: <20090102204748.04f2b997@o> References: <20090102171059.25aec893@o> <1c2a2c590901020857y1c89a453qb5f8357f50488933@mail.gmail.com> <20090102204748.04f2b997@o> Message-ID: <1c2a2c590901021337v495d7d89t8799ba105a7c55a3@mail.gmail.com> Forwarding to the list with comments. On Fri, Jan 2, 2009 at 2:47 PM, spir wrote: > On Fri, 2 Jan 2009 11:57:32 -0500 > "Kent Johnson" wrote: > >> On Fri, Jan 2, 2009 at 11:10 AM, spir wrote: >> > Can someone explain the following? >> > >> > ============================ >> > class Type(object): >> > pass >> > o = Type() >> > o.a = 1 >> > print o, o.a >> > print dir(object) >> > ==> ['__class__', '__delattr__', '__doc__', '__getattribute__', '__hash__', '__init__', >> > '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__'] >> > ==> no problem >> > o = object() >> > o.a = 1 >> > ==> AttributeError: 'object' object has no attribute 'a' >> > ================================ >> > >> > Type does not create any additional attribute or member, or what? >> > Does this mean that the type 'object' has a hidden __slots__ attr? >> > Then why doesn't Type inherit it, like any attribute? >> >> I'm no expert on this so take this with salt... >> >> IIUC the attributes of built-in objects are hard-coded in tables. The >> hard-coded tables don't include __dict__ attributes so you can't add >> attributes to instances of built-in types. This is similar to what >> __slots__ does for user-defined classes though the implementation is >> different. >> >> The special behaviour of a class with a __slots__ attribute only >> affects the class that defines __slots__, not subclasses. See >> http://docs.python.org/reference/datamodel.html#id3: "The action of a >> __slots__ declaration is limited to the class where it is defined. As >> a result, subclasses will have a __dict__ unless they also define >> __slots__." >> >> Kent >> > Thank you Kent, Alan & Paul. > > Actually, this question arose when I tried to tweak around the topic "distinction between list & > tuple". I read the pointed docs and some more information. Finally, I think I caught the point > that (with my words): > << tuples are a light, simple, direct way of building a value "pack" >> > Which puts the notion of tuple in the same category as struct, record and dict -- except that > a dict's items are named, which is a super important feature. > > Now, what is a pack? It's an easy structure aimed to allow putting things together /because it > makes sense/. For instance, in the structure above, position and color do not help at all coding > (they rather make the code more complex), but thay make sense conceptually and thus help the > developper think -- this is how I see it. > > point > position > x > y > color > r > g > b > > The point is that python does not allow setting object attributes in its definition -- except for > modules which are both code and scopes/namespaces -- and moreover it does not allow creating an > object without first definig a class. What I mean is that one caanot simply write from scratch > something like > > object centre # <==> tuple > 33 > 77 > or > object centre # <==> dict > x = 33 > y = 77 > > But python is extremely supple for attribute setting in the sense that one can invent an attribute > for an object that the object's class has never heard of. So that I thought at this feature as > another alternative to tuples or structs, or dicts, in python: > > centre = object() > centre.x, center.y = 33, 77 > > But as seen this does not work. This may be a good reason to define a "record" or "card" (in the > sense of theat kind of things in a file -- "fiche" in french) sub-type of object. Fortunately, due > to > python's > huper > flexibility, this is not much work: > > class Card(object): pass > and now: > centre = Card() > centre.x, center.y = 33, 77 > > We could go a bit farther: > > class Card(object): > def __init__(self,**fields): > for name,value in fields.items(): > setattr(self,name,value) > > centre = Card(x=33,y=33) > print "centre: %s,%s" %(centre.x,centre.y) > # ==> centre: 33,33 The Bunch class does this a little more elegantly: http://code.activestate.com/recipes/52308/ but I think this is a good use case for collections.namedtuple(); something like Card = namedtuple('Card', 'x y') > The point is to find an alternative to the largely misunderstood (first, by myself, before the > debate reached the tutor list) tuple / list difference. With such a data structure it is possible > to manipulate a pass "packs" in an explicit and obvious manner, for a rather low price in typing. > For instance: > > def get_coords(...): > ... > return Card(x=..., y=...) > location = get_coords(...) > if location.x == 0 and location.y == 0: > ... > > > I think that once we have understood that tuple are here for that kind of purpose, the confusion > disappears. Now, remains one major question: > Why do lists hold heterogeneous items? (Why did Guido do that choice, and then assert that > lists are for homogeneous sequences). To actually *constrain* a collection to be homogeneous seems extremely un-pythonic. In actual fact all containers can hold whatever you want to put in them without restriction (except hashability requirements for sets and dict keys). Kent > denis > > ------ > la vida e estranya > From alan.gauld at btinternet.com Fri Jan 2 22:55:30 2009 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Fri, 2 Jan 2009 21:55:30 +0000 (GMT) Subject: [Tutor] Fw: :initialize a for loop Message-ID: <859572.90158.qm@web86704.mail.ird.yahoo.com> Forwarding to list... ----- Forwarded Message ---- yes i want to clear the images before the next iteration,here is the pseudo code what i want to do a = [ ] for i in range(self.numOne) a.append([i]) to create an empty array, and append the index i to the array and pass this index to gtk image,how i can do this in for-in statement 0 for i in range (self.numOne) self.numOne = random.randint(1,10) for i in range(self.numOne): self.image = gtk.Image() self.image.set_from_file("./ Pink-Flower-32x32.png") self.fixed.put(self.image, i*25, 0) self.image.show() thanks On Fri, Jan 2, 2009 at 9:45 PM, Alan Gauld wrote: "i i" wrote in self.numOne = random.randint(1,10) for i in range(self.numOne): self.image = gtk.Image() self.image.set_from_file("./Pink-Flower-32x32.png") self.fixed.put(self.image, i*25, 0) self.image.show() images,i want to initialize the array or empty it before the next loop. how can we initialize or empty a for-in statement in python. I don't understand the question? What is it you want to initialise or empty? Do you just want to break out of the loop? Do you want to clear the images you have already created at some point? Can you show us some pseudo code that would illustrate how you would like the program to work? -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From andreengels at gmail.com Sat Jan 3 00:04:24 2009 From: andreengels at gmail.com (Andre Engels) Date: Sat, 3 Jan 2009 00:04:24 +0100 Subject: [Tutor] tuple & object's attributes (changed) In-Reply-To: <1c2a2c590901021337v495d7d89t8799ba105a7c55a3@mail.gmail.com> References: <20090102171059.25aec893@o> <1c2a2c590901020857y1c89a453qb5f8357f50488933@mail.gmail.com> <20090102204748.04f2b997@o> <1c2a2c590901021337v495d7d89t8799ba105a7c55a3@mail.gmail.com> Message-ID: <6faf39c90901021504s3220cbb2p81f8ca5180fa2b03@mail.gmail.com> On Fri, Jan 2, 2009 at 10:37 PM, Kent Johnson wrote: > Forwarding to the list with comments. > > On Fri, Jan 2, 2009 at 2:47 PM, spir wrote: >> Now, remains one major question: >> Why do lists hold heterogeneous items? (Why did Guido do that choice, and then assert that >> lists are for homogeneous sequences). I think that this mostly shows that 'homogenous' and 'heterogenous' are a bad choice of words here. What really is the issue here, is not so much whether or not the elements are of the same type, but whether or not they are 'interchangeable'. That is, if something could be the second element, it could be the first or fourth element as well, and it would mean basically the same thing. In fact, a list where every element could be anything is _homogenous_, so there is no real way of restricting lists to only hold homogeneous items (and that apart from Kent's fully correct statement that such a restriction would be very unpythonic). -- Andr? Engels, andreengels at gmail.com From bgailer at gmail.com Sat Jan 3 00:11:42 2009 From: bgailer at gmail.com (bob gailer) Date: Fri, 02 Jan 2009 18:11:42 -0500 Subject: [Tutor] tuple & object's attributes (changed) In-Reply-To: <1c2a2c590901021337v495d7d89t8799ba105a7c55a3@mail.gmail.com> References: <20090102171059.25aec893@o> <1c2a2c590901020857y1c89a453qb5f8357f50488933@mail.gmail.com> <20090102204748.04f2b997@o> <1c2a2c590901021337v495d7d89t8799ba105a7c55a3@mail.gmail.com> Message-ID: <495E9F2E.7070907@gmail.com> Kent Johnson wrote: > [snip] > To actually *constrain* a collection to be homogeneous seems extremely > un-pythonic. In actual fact all containers can hold whatever you want > to put in them without restriction (except hashability requirements > for sets and dict keys). > Well, the array module offers only an homogeneous (numeric only, all elements the same type) collection. -- Bob Gailer Chapel Hill NC 919-636-4239 From sander.sweers at gmail.com Sat Jan 3 00:12:41 2009 From: sander.sweers at gmail.com (Sander Sweers) Date: Sat, 3 Jan 2009 00:12:41 +0100 Subject: [Tutor] Kent's top poster script operator.itemgetter() Message-ID: Hello All, While trying to inderstand Kent's script [1] I struggle on the use of operator.itemgetter(1) from the following piece of code. I understand it makes it sort on the second value of the counts.iteritems but I do not understand how operator.itemgetter(1) works. for name, count in sorted(counts.iteritems(),key=operator.itemgetter(1), reverse=True): Could someone help me understand this? Thanks Sander [1] http://mail.python.org/pipermail/tutor/2009-January/065986.html From alan.gauld at btinternet.com Sat Jan 3 00:26:07 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 2 Jan 2009 23:26:07 -0000 Subject: [Tutor] tuple & object's attributes (changed) References: <20090102171059.25aec893@o><1c2a2c590901020857y1c89a453qb5f8357f50488933@mail.gmail.com><20090102204748.04f2b997@o> <1c2a2c590901021337v495d7d89t8799ba105a7c55a3@mail.gmail.com> Message-ID: "Kent Johnson" wrote > To actually *constrain* a collection to be homogeneous seems > extremely > un-pythonic. In actual fact all containers can hold whatever you > want > to put in them without restriction (except hashability requirements > for sets and dict keys). And strings which are kind of a collection but only hold characters... Personally I like to think of Python collections as being like Smalltalk or ObjectiveC collections. They hold objects. And since everything is a subclass of object they hold anything... It doesn't work completely but it mostly keeps me sane... :-) But it does mean that anything more fine grained than object is down to the programmer. Alan G. From damontimm at gmail.com Sat Jan 3 00:32:53 2009 From: damontimm at gmail.com (Damon Timm) Date: Fri, 2 Jan 2009 18:32:53 -0500 Subject: [Tutor] Better way - fnmatch with list ? Message-ID: <262679b50901021532o1d878effq3ae91b776cbf7548@mail.gmail.com> Hi - am learning Pythong and loving it! Anyhow, what I have works, but I wondered if there was a "better" (more python-y) way. Here is what I am doing with fnmatch ... am thinking there has to be a one-line way to do this with a lambda or list comprehension ... but my mind can't get around it ... I have other code, but the main part is that I have a list of files that I am going through to check if they have a given extension ... in this part, if the file matches any of the extension I am looking for, I want it to do some stuff ... later I check it against some other extensions to do "other" stuff: for file in files: for ext in ['*.flac','*.mp3','*.m4a']: if fnmatch.fnmatch(someFile, ext): #do some stuff if the someFile matches one of the items in the list Can it get any better ? I was hoping fnmatch would *accept* a list instead of a string ... but it didn't (frown). I thought maybe: if fnmatch(someFile, ['*.flac','*.mp3','*.m4a']): But that didn't work. Thanks in advance, Damon PS: just reading the conversations on this list is a little like taking a python class (only the classes don't progress in any particular order!). From bgailer at gmail.com Sat Jan 3 00:44:06 2009 From: bgailer at gmail.com (bob gailer) Date: Fri, 02 Jan 2009 18:44:06 -0500 Subject: [Tutor] Better way - fnmatch with list ? In-Reply-To: <262679b50901021532o1d878effq3ae91b776cbf7548@mail.gmail.com> References: <262679b50901021532o1d878effq3ae91b776cbf7548@mail.gmail.com> Message-ID: <495EA6C6.5080105@gmail.com> Damon Timm wrote: > Hi - am learning Pythong and loving it! Anyhow, what I have works, > but I wondered if there was a "better" (more python-y) way. > > Here is what I am doing with fnmatch ... am thinking there has to be a > one-line way to do this with a lambda or list comprehension ... but my > mind can't get around it ... I have other code, but the main part is > that I have a list of files that I am going through to check if they > have a given extension ... in this part, if the file matches any of > the extension I am looking for, I want it to do some stuff ... later I > check it against some other extensions to do "other" stuff: > > for file in files: > for ext in ['*.flac','*.mp3','*.m4a']: > if fnmatch.fnmatch(someFile, ext): > #do some stuff if the someFile matches one of the items in the list > Since file is a built-in function it is a good idea to not use it as a variable name. for fn in files: base, ext = os.path.splitext(fn) if ext in ['*.flac','*.mp3','*.m4a']: #do some stuff if the someFile matches one of the items in the list > Can it get any better ? I was hoping fnmatch would *accept* a list > instead of a string ... but it didn't (frown). I thought maybe: > > if fnmatch(someFile, ['*.flac','*.mp3','*.m4a']): > > But that didn't work. Thanks in advance, > > Damon > > PS: just reading the conversations on this list is a little like > taking a python class (only the classes don't progress in any > particular order!). > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Bob Gailer Chapel Hill NC 919-636-4239 From bgailer at gmail.com Sat Jan 3 00:48:48 2009 From: bgailer at gmail.com (bob gailer) Date: Fri, 02 Jan 2009 18:48:48 -0500 Subject: [Tutor] Better way - fnmatch with list ? CORRECTION In-Reply-To: <495EA6C6.5080105@gmail.com> References: <262679b50901021532o1d878effq3ae91b776cbf7548@mail.gmail.com> <495EA6C6.5080105@gmail.com> Message-ID: <495EA7E0.50202@gmail.com> bob gailer wrote: > Damon Timm wrote: >> Hi - am learning Pythong and loving it! Anyhow, what I have works, >> but I wondered if there was a "better" (more python-y) way. >> >> Here is what I am doing with fnmatch ... am thinking there has to be a >> one-line way to do this with a lambda or list comprehension ... but my >> mind can't get around it ... I have other code, but the main part is >> that I have a list of files that I am going through to check if they >> have a given extension ... in this part, if the file matches any of >> the extension I am looking for, I want it to do some stuff ... later I >> check it against some other extensions to do "other" stuff: >> >> for file in files: >> for ext in ['*.flac','*.mp3','*.m4a']: >> if fnmatch.fnmatch(someFile, ext): >> #do some stuff if the someFile matches one of the items >> in the list >> > > Since file is a built-in function it is a good idea to not use it as a > variable name. > > for fn in files: > base, ext = os.path.splitext(fn) > if ext in ['.flac','.mp3','.m4a']: ## CORRECTION removed * > #do some stuff if the someFile matches one of the items in the > list >> Can it get any better ? I was hoping fnmatch would *accept* a list >> instead of a string ... but it didn't (frown). I thought maybe: >> >> if fnmatch(someFile, ['*.flac','*.mp3','*.m4a']): >> >> But that didn't work. Thanks in advance, >> >> Damon >> >> PS: just reading the conversations on this list is a little like >> taking a python class (only the classes don't progress in any >> particular order!). >> _______________________________________________ -- Bob Gailer Chapel Hill NC 919-636-4239 From damontimm at gmail.com Sat Jan 3 01:06:06 2009 From: damontimm at gmail.com (Damon Timm) Date: Fri, 2 Jan 2009 19:06:06 -0500 Subject: [Tutor] Better way - fnmatch with list ? In-Reply-To: <495EA6C6.5080105@gmail.com> References: <262679b50901021532o1d878effq3ae91b776cbf7548@mail.gmail.com> <495EA6C6.5080105@gmail.com> Message-ID: <262679b50901021606r7801ac00j5de2e785ca1c7922@mail.gmail.com> On Fri, Jan 2, 2009 at 6:44 PM, bob gailer wrote: > Since file is a built-in function it is a good idea to not use it as a > variable name. Oooh! I did not know that ... thanks ... went through and changed them all. > for fn in files: > base, ext = os.path.splitext(fn) > if ext in ['*.flac','*.mp3','*.m4a']: > #do some stuff if the someFile matches one of the items in the list I caught the * bit - I must be learning! One thought though ... because fnmatch ignores case I could get away with: .FLAC, .flac, .FLac, or any other such foolishness for file extensions ... Using the above approach, however, matches by case ... so, I think, to be safe, I would have to list each iteration of the case in the list ... is there a way to account for that ? Thanks again - Damon From jervisau at gmail.com Sat Jan 3 01:16:50 2009 From: jervisau at gmail.com (Jervis Whitley) Date: Sat, 3 Jan 2009 11:16:50 +1100 Subject: [Tutor] Better way - fnmatch with list ? CORRECTION In-Reply-To: <495EA7E0.50202@gmail.com> References: <262679b50901021532o1d878effq3ae91b776cbf7548@mail.gmail.com> <495EA6C6.5080105@gmail.com> <495EA7E0.50202@gmail.com> Message-ID: <8e63a5ce0901021616s64965240ydf1b1815f22c371e@mail.gmail.com> On Sat, Jan 3, 2009 at 10:48 AM, bob gailer wrote: > bob gailer wrote: >> >> >> for fn in files: >> base, ext = os.path.splitext(fn) >> if ext in ['.flac','.mp3','.m4a']: ## CORRECTION removed * >> >> > for fn in files: base, ext = os.path.splitext(fn) if ext.lower() in ['.flac', '.mp3', '.mp4']: takes into account systems with case sensitive filenames. cheers, Jervis -------------- next part -------------- An HTML attachment was scrubbed... URL: From norman at khine.net Sat Jan 3 01:53:55 2009 From: norman at khine.net (Norman Khine) Date: Sat, 03 Jan 2009 01:53:55 +0100 Subject: [Tutor] check to see if email host has an MX record by using dns.resolve Message-ID: <495EB723.8040601@khine.net> Hi again, I need to check the validity of the email of the user before data is written onto the system. http://paste.lisp.org/display/72986 Is this a correct method to proceed or is there a better solution. Thanks Norman From kent37 at tds.net Sat Jan 3 05:15:18 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 2 Jan 2009 23:15:18 -0500 Subject: [Tutor] Kent's top poster script operator.itemgetter() In-Reply-To: References: Message-ID: <1c2a2c590901022015q1fc2d89dnc9973a235fea0a4f@mail.gmail.com> On Fri, Jan 2, 2009 at 6:12 PM, Sander Sweers wrote: > Hello All, > > While trying to inderstand Kent's script [1] I struggle on the use of > operator.itemgetter(1) from the following piece of code. I understand > it makes it sort on the second value of the counts.iteritems but I do > not understand how operator.itemgetter(1) works. See http://personalpages.tds.net/~kent37/kk/00007.html#e7the-operator-module Kent From iaidas4 at gmail.com Sat Jan 3 09:16:00 2009 From: iaidas4 at gmail.com (i i) Date: Sat, 3 Jan 2009 13:16:00 +0500 Subject: [Tutor] create an empty array of images Message-ID: <6fb034600901030016y388c2c21rb5d94a957eb7bf20@mail.gmail.com> yes i want to clear the images before the next iteration,here is the pseudo code what i want to do a = [ ] for i in range(self.numOne) a.append([i]) to create an empty array, and append the index i to the array and pass this index to gtk image,how i can do this in *for-in* statement 0 for i in range (self.numOne) self.numOne = random.randint(1,10) for i in range(self.numOne): self.image = gtk.Image() self.image.set_from_file("./Pink-Flower-32x32.png") self.fixed.put(self.image, i*25, 0) self.image.show() thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Sat Jan 3 14:01:22 2009 From: kent37 at tds.net (Kent Johnson) Date: Sat, 3 Jan 2009 08:01:22 -0500 Subject: [Tutor] create an empty array of images In-Reply-To: <6fb034600901030016y388c2c21rb5d94a957eb7bf20@mail.gmail.com> References: <6fb034600901030016y388c2c21rb5d94a957eb7bf20@mail.gmail.com> Message-ID: <1c2a2c590901030501q672ba83bq3034acc0eba26b38@mail.gmail.com> On Sat, Jan 3, 2009 at 3:16 AM, i i wrote: > yes i want to clear the images before the next iteration,here is the pseudo > code what i want to do > > a = [ ] > for i in range(self.numOne) > a.append([i]) > to create an empty array, and append the index i to the array and pass this > index to gtk image,how i can do this in for-in statement I don't understand your question but I will make a few guesses. The code you show above creates a list whose elements are also lists: In [12]: a = [] In [13]: for i in range(5): ....: a.append([i]) In [14]: a Out[14]: [[0], [1], [2], [3], [4]] If you want a list containing all the values of i, just use the range() function directly: In [15]: range(5) Out[15]: [0, 1, 2, 3, 4] If you want a list containing a single value of i, create a new list each time through the loop: In [16]: for i in range(5): ....: a = [i] ....: print a [0] [1] [2] [3] [4] HTH, Kent From sander.sweers at gmail.com Sat Jan 3 15:34:26 2009 From: sander.sweers at gmail.com (Sander Sweers) Date: Sat, 3 Jan 2009 15:34:26 +0100 Subject: [Tutor] Kent's top poster script operator.itemgetter() In-Reply-To: <1c2a2c590901022015q1fc2d89dnc9973a235fea0a4f@mail.gmail.com> References: <1c2a2c590901022015q1fc2d89dnc9973a235fea0a4f@mail.gmail.com> Message-ID: On Sat, Jan 3, 2009 at 05:15, Kent Johnson wrote: > On Fri, Jan 2, 2009 at 6:12 PM, Sander Sweers wrote: >> not understand how operator.itemgetter(1) works. > > See > http://personalpages.tds.net/~kent37/kk/00007.html#e7the-operator-module Ok, if I understand this correctly counts.iteritems() creates a tuple (name, count) and this is passed to operator.itemgetter() which take the second value to sort the list. Previously I used a function with cmp to sort datetime.date objects but this works way better :-) Thanks Sander From bgailer at gmail.com Sat Jan 3 16:24:47 2009 From: bgailer at gmail.com (bob gailer) Date: Sat, 03 Jan 2009 10:24:47 -0500 Subject: [Tutor] create an empty array of images In-Reply-To: <6fb034600901030016y388c2c21rb5d94a957eb7bf20@mail.gmail.com> References: <6fb034600901030016y388c2c21rb5d94a957eb7bf20@mail.gmail.com> Message-ID: <495F833F.5070607@gmail.com> i i wrote: > yes i want to clear the images before the next iteration,here is the > pseudo code what i want to do > > a = [ ] > > for i in range(self.numOne) > a.append([i]) > to create an empty array, and append the index i to the array and > pass this index to gtk image,how i can do this in *for-in* statement > > > > 0 for i in range (self.numOne) > > self.numOne = random.randint(1,10) > for i in range(self.numOne): > self.image = gtk.Image() > self.image.set_from_file("./ > Pink-Flower-32x32.png") > self.fixed.put(self.image, i*25, 0) > self.image.show() > > I also don't understand your question. In addition to pseudocode would you give a description of what the user sees and does and how the end result looks to the user. From your code I think I would see a pink flower flashed numOne times. Also please clean up the code. The indentations are messy. -- Bob Gailer Chapel Hill NC 919-636-4239 From sbjaved at gmail.com Sat Jan 3 17:00:20 2009 From: sbjaved at gmail.com (Saad Javed) Date: Sat, 3 Jan 2009 21:00:20 +0500 Subject: [Tutor] Help with a simple problem Message-ID: <3c10cd400901030800k64832a77g679b51b84b82097e@mail.gmail.com> Hi Tutors, I'm trying to create a simple GUI using pyqt4 in which pressing a button causes execution of a system command. Here's the code, please help me out. I can't figure out whats wrong. Thanks import sys import os from PyQt4 import QtGui, QtCore class TestGui(QtGui.QWidget): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) self.setGeometry(300, 300, 140, 50) self.setWindowTitle('testing') self.setWindowIcon(QtGui.QIcon('/usr/share/pixmaps/blueradio-48.png')) *dial = QtGui.QPushButton('Dial', self) dial.setGeometry(10, 10, 60, 35) self.connect(dial, QtCore.SIGNAL('clicked()'), QtGui.qApp, QtCore.SLOT(os.system('wvdial ptcl')))* quit = QtGui.QPushButton('Quit', self) quit.setGeometry(70, 10, 60, 35) self.connect(quit, QtCore.SIGNAL('clicked()'), QtGui.qApp, QtCore.SLOT('quit()')) app = QtGui.QApplication(sys.argv) testgui = TestGui() testgui.show() sys.exit(app.exec_()) -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Sat Jan 3 17:18:37 2009 From: bgailer at gmail.com (bob gailer) Date: Sat, 03 Jan 2009 11:18:37 -0500 Subject: [Tutor] Help with a simple problem In-Reply-To: <3c10cd400901030800k64832a77g679b51b84b82097e@mail.gmail.com> References: <3c10cd400901030800k64832a77g679b51b84b82097e@mail.gmail.com> Message-ID: <495F8FDD.4060002@gmail.com> An HTML attachment was scrubbed... URL: From sbjaved at gmail.com Sat Jan 3 17:39:30 2009 From: sbjaved at gmail.com (Saad Javed) Date: Sat, 3 Jan 2009 21:39:30 +0500 Subject: [Tutor] Help with a simple problem In-Reply-To: <495F8FDD.4060002@gmail.com> References: <3c10cd400901030800k64832a77g679b51b84b82097e@mail.gmail.com> <495F8FDD.4060002@gmail.com> Message-ID: <3c10cd400901030839u7232c58arba37ab60628e7f67@mail.gmail.com> The bold was intentional. I was trying to get a shell command (wvdial) to run when a button is pressed. The error I get is: Traceback (most recent call last): File "testgui.py", line 26, in testgui = TestGui() File "testgui.py", line 19, in __init__ self.connect(dial, QtCore.SIGNAL('clicked()'), QtGui.qApp, QtCore.SLOT(os.system('wvdial'))) TypeError: argument 1 of SLOT() has an invalid type Was that helpful? On Sat, Jan 3, 2009 at 9:18 PM, bob gailer wrote: > Saad Javed wrote: > > Hi Tutors, > > > Hi and welcome to the tutor list. We can help you better if you tell us > what the problem is. What did you expect? What did you get? > > Most of us don't have the time or energy to read code when we don't know > what we are looking for. > > Some of your code is bold. Why? What does that mean? > > Please think about this and repost with more information. > > If you get an "error" (exception) please post the traceback > > > I'm trying to create a simple GUI using pyqt4 in which pressing a button > causes execution of a system command. Here's the code, please help me out. I > can't figure out whats wrong. Thanks > > import sys > import os > from PyQt4 import QtGui, QtCore > > class TestGui(QtGui.QWidget): > def __init__(self, parent=None): > QtGui.QWidget.__init__(self, parent) > self.setGeometry(300, 300, 140, 50) > self.setWindowTitle('testing') > > > self.setWindowIcon(QtGui.QIcon('/usr/share/pixmaps/blueradio-48.png')) > > *dial = QtGui.QPushButton('Dial', self) > dial.setGeometry(10, 10, 60, 35) > self.connect(dial, QtCore.SIGNAL('clicked()'), > QtGui.qApp, QtCore.SLOT(os.system('wvdial ptcl')))* > > quit = QtGui.QPushButton('Quit', self) > quit.setGeometry(70, 10, 60, 35) > self.connect(quit, QtCore.SIGNAL('clicked()'), QtGui.qApp, > QtCore.SLOT('quit()')) > > app = QtGui.QApplication(sys.argv) > testgui = TestGui() > testgui.show() > sys.exit(app.exec_()) > > ------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.orghttp://mail.python.org/mailman/listinfo/tutor > > > > -- > Bob Gailer > Chapel Hill NC > 919-636-4239 > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Sat Jan 3 17:46:09 2009 From: kent37 at tds.net (Kent Johnson) Date: Sat, 3 Jan 2009 11:46:09 -0500 Subject: [Tutor] Kent's top poster script operator.itemgetter() In-Reply-To: References: <1c2a2c590901022015q1fc2d89dnc9973a235fea0a4f@mail.gmail.com> Message-ID: <1c2a2c590901030846u44f0a00et9375d5d8fd5560a9@mail.gmail.com> On Sat, Jan 3, 2009 at 9:34 AM, Sander Sweers wrote: > On Sat, Jan 3, 2009 at 05:15, Kent Johnson wrote: >> On Fri, Jan 2, 2009 at 6:12 PM, Sander Sweers wrote: >>> not understand how operator.itemgetter(1) works. >> >> See >> http://personalpages.tds.net/~kent37/kk/00007.html#e7the-operator-module > > Ok, if I understand this correctly counts.iteritems() creates a tuple > (name, count) and this is passed to operator.itemgetter() which take > the second value to sort the list. Almost right. The (name, count) tuple is passed to the function returned by operator.itemgetter(). > > Previously I used a function with cmp to sort datetime.date objects > but this works way better :-) Yes, the key= parameter to sort() pretty much obsoletes the use of a comparison function. Kent From alan.gauld at btinternet.com Sat Jan 3 18:28:08 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 3 Jan 2009 17:28:08 -0000 Subject: [Tutor] Help with a simple problem References: <3c10cd400901030800k64832a77g679b51b84b82097e@mail.gmail.com> Message-ID: "Saad Javed" wrote > I'm trying to create a simple GUI using pyqt4 in which pressing a > button > causes execution of a system command. Here's the code, please help > me out. I > can't figure out whats wrong. Thanks Caveat: I have never used Qt in my life so this is based on guesswork and experience of other GUI tookits.... > class TestGui(QtGui.QWidget): > def __init__(self, parent=None): > QtGui.QWidget.__init__(self, parent) > *dial = QtGui.QPushButton('Dial', self) > dial.setGeometry(10, 10, 60, 35) > self.connect(dial, QtCore.SIGNAL('clicked()'), > QtGui.qApp, QtCore.SLOT(os.system('wvdial ptcl')))* I think the SIGNAL('clicked()') bit is probably supposed to be: SIGNAL('clicked') It would be unusual to pass the string representation of a function *call* into a SIGNAL handler, usually you would pass either the function object or the function name. > self.connect(quit, QtCore.SIGNAL('clicked()'), QtGui.qApp, > QtCore.SLOT('quit()')) And the same here... Also in the SLOT call you do something inconsistent. In the first case you do not quote the action in the other you do quote it. So I suspect that they should both be quoted? But as I say thats guesswork! Alan G. From alan.gauld at btinternet.com Sat Jan 3 18:29:21 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 3 Jan 2009 17:29:21 -0000 Subject: [Tutor] Help with a simple problem References: <3c10cd400901030800k64832a77g679b51b84b82097e@mail.gmail.com><495F8FDD.4060002@gmail.com> <3c10cd400901030839u7232c58arba37ab60628e7f67@mail.gmail.com> Message-ID: "Saad Javed" wrote > self.connect(dial, QtCore.SIGNAL('clicked()'), QtGui.qApp, > QtCore.SLOT(os.system('wvdial'))) > TypeError: argument 1 of SLOT() has an invalid type > > Was that helpful? Yes, it confirms my earlier email that you should probably quote the argument to SLOT() Alan G. From kent37 at tds.net Sat Jan 3 18:33:25 2009 From: kent37 at tds.net (Kent Johnson) Date: Sat, 3 Jan 2009 12:33:25 -0500 Subject: [Tutor] Help with a simple problem In-Reply-To: <3c10cd400901030839u7232c58arba37ab60628e7f67@mail.gmail.com> References: <3c10cd400901030800k64832a77g679b51b84b82097e@mail.gmail.com> <495F8FDD.4060002@gmail.com> <3c10cd400901030839u7232c58arba37ab60628e7f67@mail.gmail.com> Message-ID: <1c2a2c590901030933n2ac0041w9bba04e42ab6411d@mail.gmail.com> On Sat, Jan 3, 2009 at 11:39 AM, Saad Javed wrote: > The bold was intentional. I was trying to get a shell command (wvdial) to > run when a button is pressed. The error I get is: > > Traceback (most recent call last): > File "testgui.py", line 26, in > testgui = TestGui() > File "testgui.py", line 19, in __init__ > self.connect(dial, QtCore.SIGNAL('clicked()'), QtGui.qApp, > QtCore.SLOT(os.system('wvdial'))) > TypeError: argument 1 of SLOT() has an invalid type > > Was that helpful? Maybe :-) >From a quick look at the docs, it seems that QtCore.SLOT() is used to get a reference to a Qt function. When you want to use your own function as the target of an action, you just pass the function directly. Try this: self.connect(dial, QtCore.SIGNAL('clicked()'), QtGui.qApp, lambda: os.system('wvdial')) or define a named function that calls os.system() and pass the function to connect(). Kent From kent37 at tds.net Sat Jan 3 18:42:08 2009 From: kent37 at tds.net (Kent Johnson) Date: Sat, 3 Jan 2009 12:42:08 -0500 Subject: [Tutor] Help with a simple problem In-Reply-To: References: <3c10cd400901030800k64832a77g679b51b84b82097e@mail.gmail.com> Message-ID: <1c2a2c590901030942p645c5a69le43f5956cb94baa2@mail.gmail.com> On Sat, Jan 3, 2009 at 12:28 PM, Alan Gauld wrote: > I think the SIGNAL('clicked()') bit is probably supposed to be: > > SIGNAL('clicked') I think the parens are correct, see http://docs.huihoo.com/pyqt/pyqt4.html#id10 Kent From sbjaved at gmail.com Sat Jan 3 18:45:56 2009 From: sbjaved at gmail.com (Saad Javed) Date: Sat, 3 Jan 2009 22:45:56 +0500 Subject: [Tutor] Help with a simple problem In-Reply-To: <1c2a2c590901030933n2ac0041w9bba04e42ab6411d@mail.gmail.com> References: <3c10cd400901030800k64832a77g679b51b84b82097e@mail.gmail.com> <495F8FDD.4060002@gmail.com> <3c10cd400901030839u7232c58arba37ab60628e7f67@mail.gmail.com> <1c2a2c590901030933n2ac0041w9bba04e42ab6411d@mail.gmail.com> Message-ID: <3c10cd400901030945g48f2c606hdea8347d3cddf026@mail.gmail.com> I implemented a dial function and passed it to the QtCore.SLOT(), which worked fine. Thanks everyone! On Sat, Jan 3, 2009 at 10:33 PM, Kent Johnson wrote: > On Sat, Jan 3, 2009 at 11:39 AM, Saad Javed wrote: > > The bold was intentional. I was trying to get a shell command (wvdial) to > > run when a button is pressed. The error I get is: > > > > Traceback (most recent call last): > > File "testgui.py", line 26, in > > testgui = TestGui() > > File "testgui.py", line 19, in __init__ > > self.connect(dial, QtCore.SIGNAL('clicked()'), QtGui.qApp, > > QtCore.SLOT(os.system('wvdial'))) > > TypeError: argument 1 of SLOT() has an invalid type > > > > Was that helpful? > > Maybe :-) > > From a quick look at the docs, it seems that QtCore.SLOT() is used to > get a reference to a Qt function. When you want to use your own > function as the target of an action, you just pass the function > directly. Try this: > self.connect(dial, QtCore.SIGNAL('clicked()'), > QtGui.qApp, lambda: os.system('wvdial')) > > or define a named function that calls os.system() and pass the > function to connect(). > > Kent > -------------- next part -------------- An HTML attachment was scrubbed... URL: From iaidas4 at gmail.com Sat Jan 3 20:53:06 2009 From: iaidas4 at gmail.com (i i) Date: Sun, 4 Jan 2009 00:53:06 +0500 Subject: [Tutor] create an empty array of images In-Reply-To: <1c2a2c590901030501q672ba83bq3034acc0eba26b38@mail.gmail.com> References: <6fb034600901030016y388c2c21rb5d94a957eb7bf20@mail.gmail.com> <1c2a2c590901030501q672ba83bq3034acc0eba26b38@mail.gmail.com> Message-ID: <6fb034600901031153r31f9a46ds5fd1c41fa8eda969@mail.gmail.com> Hi tutor, thanks for the help ,u dont understand cause i have given the psudo code,i have not given the full code only apart of it. I only want an emptty array and put the value [i] in it. This [i] value is the one that i want to show.Im making this activity in glade ,the set function in image widget do not replace the previous value but in the next loop it shows the previous images as well as the new one .It dont replace,but set again and again. So i want to declare an empty array then i want to give it a value[i] ,this [i] is the number of images that i want to show, but on next loop i want the array to be empty,and then sets new value of [i]. self.fixed = self.wTree.get_widget("fixed1") self.numOne = random.randint(1,10) for i in [ ]: for i in range(self.numOne): a = [i] self.image = gtk.Image() self.image.set_from_file("./Pink-Flower-32x32.png") self.fixed.put(self.image, i*25, 0) self.image.show() thanks On Sat, Jan 3, 2009 at 6:01 PM, Kent Johnson wrote: > On Sat, Jan 3, 2009 at 3:16 AM, i i wrote: > > yes i want to clear the images before the next iteration,here is the > pseudo > > code what i want to do > > > > a = [ ] > > for i in range(self.numOne) > > a.append([i]) > > to create an empty array, and append the index i to the array and pass > this > > index to gtk image,how i can do this in for-in statement > > I don't understand your question but I will make a few guesses. > > The code you show above creates a list whose elements are also lists: > In [12]: a = [] > > In [13]: for i in range(5): > ....: a.append([i]) > > In [14]: a > Out[14]: [[0], [1], [2], [3], [4]] > > If you want a list containing all the values of i, just use the > range() function directly: > In [15]: range(5) > Out[15]: [0, 1, 2, 3, 4] > > If you want a list containing a single value of i, create a new list > each time through the loop: > In [16]: for i in range(5): > ....: a = [i] > ....: print a > > [0] > [1] > [2] > [3] > [4] > > HTH, > Kent > -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Sat Jan 3 22:15:09 2009 From: bgailer at gmail.com (bob gailer) Date: Sat, 03 Jan 2009 16:15:09 -0500 Subject: [Tutor] Help with a simple problem In-Reply-To: <3c10cd400901030839u7232c58arba37ab60628e7f67@mail.gmail.com> References: <3c10cd400901030800k64832a77g679b51b84b82097e@mail.gmail.com> <495F8FDD.4060002@gmail.com> <3c10cd400901030839u7232c58arba37ab60628e7f67@mail.gmail.com> Message-ID: <495FD55D.6050401@gmail.com> Saad Javed wrote: > The bold was intentional. I was trying to get a shell command (wvdial) > to run when a button is pressed. The error I get is: > > Traceback (most recent call last): > File "testgui.py", line 26, in > testgui = TestGui() > File "testgui.py", line 19, in __init__ > self.connect(dial, QtCore.SIGNAL('clicked()'), QtGui.qApp, > QtCore.SLOT(os.system('wvdial'))) > TypeError: argument 1 of SLOT() has an invalid type > > Was that helpful? Yes. When calling self.connect all of its arguments are evaluated. This means that QtCore.SLOT is called with an argument of os.system('wvdial') which in turn means that os.system is called with an argument of 'wvdial'. Thus wvdial is run as part of creating an instance of the class; os.system then returns an integer (see docs for explanation). self.connect is expecting "os.system('wvdial')" (character string). So try self.connect(dial, QtCore.SIGNAL('clicked()'), QtGui.qApp, QtCore.SLOT("os.system('wvdial')")). -- Bob Gailer Chapel Hill NC 919-636-4239 From bgailer at gmail.com Sat Jan 3 22:20:18 2009 From: bgailer at gmail.com (bob gailer) Date: Sat, 03 Jan 2009 16:20:18 -0500 Subject: [Tutor] create an empty array of images In-Reply-To: <6fb034600901031153r31f9a46ds5fd1c41fa8eda969@mail.gmail.com> References: <6fb034600901030016y388c2c21rb5d94a957eb7bf20@mail.gmail.com> <1c2a2c590901030501q672ba83bq3034acc0eba26b38@mail.gmail.com> <6fb034600901031153r31f9a46ds5fd1c41fa8eda969@mail.gmail.com> Message-ID: <495FD692.3030703@gmail.com> i i wrote: > Hi tutor, > thanks for the help ,u dont understand cause i have given > the psudo code,i have not given the full code only apart of it. I > only want an emptty array and put the value [i] in it. This [i] value > is the one that i want to show.Im making this activity in glade ,the > set function in image widget do not replace the previous value but in > the next loop it shows the previous images as well as the new one .It > dont replace,but set again and again. So i want to declare an empty > array then i want to give it a value[i] ,this [i] is the number of > images that i want to show, but on next loop i want the array to be > empty,and then sets new value of [i]. > > > self.fixed = self.wTree.get_widget("fixed1") > self.numOne = random.randint(1,10) > for i in [ ]: > for i in range(self.numOne): Don't use i as the loop variable for the inner for. Pick some other name. > a = [i] > self.image = gtk.Image() > > self.image.set_from_file("./Pink-Flower-32x32.png") > > self.fixed.put(self.image, i*25, 0) > > self.image.show() > -- Bob Gailer Chapel Hill NC 919-636-4239 From damontimm at gmail.com Sat Jan 3 22:27:47 2009 From: damontimm at gmail.com (Damon Timm) Date: Sat, 3 Jan 2009 16:27:47 -0500 Subject: [Tutor] Better way - fnmatch with list ? CORRECTION In-Reply-To: <8e63a5ce0901021616s64965240ydf1b1815f22c371e@mail.gmail.com> References: <262679b50901021532o1d878effq3ae91b776cbf7548@mail.gmail.com> <495EA6C6.5080105@gmail.com> <495EA7E0.50202@gmail.com> <8e63a5ce0901021616s64965240ydf1b1815f22c371e@mail.gmail.com> Message-ID: <262679b50901031327n23b2f754l62fe0cf98751c1e5@mail.gmail.com> On Fri, Jan 2, 2009 at 7:16 PM, Jervis Whitley wrote: > for fn in files: > base, ext = os.path.splitext(fn) > if ext.lower() in ['.flac', '.mp3', '.mp4']: > > takes into account systems with case sensitive filenames. Thanks! Will throw that in there. I'm getting it ... bit by little bit. > > cheers, > > Jervis > > From metolone+gmane at gmail.com Sat Jan 3 22:35:51 2009 From: metolone+gmane at gmail.com (Mark Tolonen) Date: Sat, 3 Jan 2009 13:35:51 -0800 Subject: [Tutor] Better way - fnmatch with list ? CORRECTION References: <262679b50901021532o1d878effq3ae91b776cbf7548@mail.gmail.com><495EA6C6.5080105@gmail.com> <495EA7E0.50202@gmail.com><8e63a5ce0901021616s64965240ydf1b1815f22c371e@mail.gmail.com> <262679b50901031327n23b2f754l62fe0cf98751c1e5@mail.gmail.com> Message-ID: "Damon Timm" wrote in message news:262679b50901031327n23b2f754l62fe0cf98751c1e5 at mail.gmail.com... > On Fri, Jan 2, 2009 at 7:16 PM, Jervis Whitley wrote: >> for fn in files: >> base, ext = os.path.splitext(fn) >> if ext.lower() in ['.flac', '.mp3', '.mp4']: >> >> takes into account systems with case sensitive filenames. > > Thanks! Will throw that in there. I'm getting it ... bit by little bit. fnmatch already takes into account systems with case-sensitive filenames: >>> help(fnmatch.fnmatch) Help on function fnmatch in module fnmatch: fnmatch(name, pat) Test whether FILENAME matches PATTERN. Patterns are Unix shell style: * matches everything ? matches any single character [seq] matches any character in seq [!seq] matches any char not in seq An initial period in FILENAME is not special. Both FILENAME and PATTERN are first case-normalized if the operating system requires it. If you don't want this, use fnmatchcase(FILENAME, PATTERN). -Mark From damontimm at gmail.com Sun Jan 4 00:57:52 2009 From: damontimm at gmail.com (Damon Timm) Date: Sat, 3 Jan 2009 18:57:52 -0500 Subject: [Tutor] Better way - fnmatch with list ? CORRECTION In-Reply-To: References: <262679b50901021532o1d878effq3ae91b776cbf7548@mail.gmail.com> <495EA6C6.5080105@gmail.com> <495EA7E0.50202@gmail.com> <8e63a5ce0901021616s64965240ydf1b1815f22c371e@mail.gmail.com> <262679b50901031327n23b2f754l62fe0cf98751c1e5@mail.gmail.com> Message-ID: <262679b50901031557m3513a6c5q7d5ea521e3135d42@mail.gmail.com> On Sat, Jan 3, 2009 at 4:35 PM, Mark Tolonen wrote: > fnmatch already takes into account systems with case-sensitive filenames: > >>>> help(fnmatch.fnmatch) > > Help on function fnmatch in module fnmatch: > > fnmatch(name, pat) > Test whether FILENAME matches PATTERN. > > Patterns are Unix shell style: > > * matches everything > ? matches any single character > [seq] matches any character in seq > [!seq] matches any char not in seq > > An initial period in FILENAME is not special. > Both FILENAME and PATTERN are first case-normalized > if the operating system requires it. > If you don't want this, use fnmatchcase(FILENAME, PATTERN). > > -Mark Hey Mark - thanks for your reply and the details ... I saw fnmatch did *not* match case (which was great) ... but it also couldn't match any item from another list of items ... had to do a single PATTERN at a time ... that's why it was suggested I try to use the ext matching from os.path.splitext() ... and why I needed to drop it to lowercase. It seems like that is the easiest way to search for a match among a list of file systems ... Thanks! Damon > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From benjamin.serrato at gmail.com Sun Jan 4 01:06:03 2009 From: benjamin.serrato at gmail.com (Benjamin Serrato) Date: Sat, 3 Jan 2009 18:06:03 -0600 Subject: [Tutor] Add all natural numbers that are multiples of 3 and 5 Message-ID: Hello, I'm trying to correctly solve the first projecteuler.net problem. The question is as so: Find the sum of all the multiples of 3 or 5 below 1000. I wrote the following program, but the number found is incorrect. I created a function that adds multiples of a given number to a global variable until the multiples are greater than 1000. The solution I get with my code is "1224". This is incorrect, but I am having trouble understanding why my code is wrong... it's very simple. My code: #!!/usr/local/bin/python3.0 #problem1.py """Lists the sum of all multiples of 3 and 5 less than 1000.""" # Initialize variable 'total'. total = 0 # I wanted this to be 'None', is that wrong? def sumTotal(multiple): global total # Brings total into the local scope so it # can be written to. n = 2 while multiple < 1000: total = total + multiple multiple = multiple * n n = n + 1 # I wanted this to be += but I'm not sure # that is right. # Now I call the function with the two arguments I need, 3 # and 5. Since total is a global variable it retains its value # at the end of the first function call, the next call adds to # the total value. Thus print(total) should give me the correct # value. sumTotal(3) sumTotal(5) print(total) ----- I think I have made a mistake with scope. Or some other syntactic error, because I don't see anything wrong with the code. Please make it obvious for me. -------------- next part -------------- An HTML attachment was scrubbed... URL: From andreengels at gmail.com Sun Jan 4 01:43:36 2009 From: andreengels at gmail.com (Andre Engels) Date: Sun, 4 Jan 2009 01:43:36 +0100 Subject: [Tutor] Add all natural numbers that are multiples of 3 and 5 In-Reply-To: References: Message-ID: <6faf39c90901031643s1ad58a03g280f603e8ac08ef3@mail.gmail.com> On Sun, Jan 4, 2009 at 1:06 AM, Benjamin Serrato wrote: > Hello, > > I'm trying to correctly solve the first projecteuler.net problem. The > question is as so: Find the sum of all the multiples of 3 or 5 below 1000. > > I wrote the following program, but the number found is incorrect. I created > a function that adds multiples of a given number to a global variable until > the multiples are greater than 1000. The solution I get with my code is > "1224". This is incorrect, but I am having trouble understanding why my code > is wrong... it's very simple. > My code: > > #!!/usr/local/bin/python3.0 > #problem1.py > > """Lists the sum of all multiples of 3 and 5 less than 1000.""" > > # Initialize variable 'total'. > total = 0 # I wanted this to be 'None', is that wrong? > > def sumTotal(multiple): > global total # Brings total into the local scope so it > # can be written to. > n = 2 > while multiple < 1000: > total = total + multiple > multiple = multiple * n > n = n + 1 # I wanted this to be += but I'm not sure > # that is right. > > # Now I call the function with the two arguments I need, 3 > # and 5. Since total is a global variable it retains its value > # at the end of the first function call, the next call adds to > # the total value. Thus print(total) should give me the correct > # value. > > sumTotal(3) > sumTotal(5) > > print(total) > > ----- > I think I have made a mistake with scope. Or some other syntactic error, > because I don't see anything wrong with the code. Please make it obvious for > me. There is an error with the code. The line multiple = multiple * n is not doing what you want it to do. See what is happening each time you go through this line: first time: * multiple = 3 * n = 2 * multiple changed to 6 second time: * multiple = 6 * n = 3 * multiple changed to 18 third time: * multiple = 18 * n = 4 * multiple changed to 72 etcetera You will have to keep the number to multiply by in a separate variable to avoid this. Apart from that, I think your usage of a global variable total, although correct, is ugly and error-prone. I would do away with a global variable total, add a local variable total, and end defSum with "return total". Then the main body can be changed to: print (sumTotal(3) + sumTotal(5)) -- Andr? Engels, andreengels at gmail.com From kent37 at tds.net Sun Jan 4 01:57:18 2009 From: kent37 at tds.net (Kent Johnson) Date: Sat, 3 Jan 2009 19:57:18 -0500 Subject: [Tutor] Add all natural numbers that are multiples of 3 and 5 In-Reply-To: <6faf39c90901031643s1ad58a03g280f603e8ac08ef3@mail.gmail.com> References: <6faf39c90901031643s1ad58a03g280f603e8ac08ef3@mail.gmail.com> Message-ID: <1c2a2c590901031657hb90fe45u67ba3fab1a63925e@mail.gmail.com> On Sat, Jan 3, 2009 at 7:43 PM, Andre Engels wrote: > On Sun, Jan 4, 2009 at 1:06 AM, Benjamin Serrato > wrote: >> Hello, >> >> I'm trying to correctly solve the first projecteuler.net problem. The >> question is as so: Find the sum of all the multiples of 3 or 5 below 1000. > Then the main body can be changed to: > > print (sumTotal(3) + sumTotal(5)) This will double-count numbers which are multiples of both 3 and 5 such as 15 which I don't think the problem intends. Kent From bgailer at gmail.com Sun Jan 4 04:10:49 2009 From: bgailer at gmail.com (bob gailer) Date: Sat, 03 Jan 2009 22:10:49 -0500 Subject: [Tutor] Add all natural numbers that are multiples of 3 and 5 In-Reply-To: References: Message-ID: <496028B9.2040505@gmail.com> An HTML attachment was scrubbed... URL: From benjamin.serrato at gmail.com Sun Jan 4 03:43:31 2009 From: benjamin.serrato at gmail.com (Benjamin Serrato) Date: Sat, 3 Jan 2009 20:43:31 -0600 Subject: [Tutor] Add all natural numbers that are multiples of 3 and 5 In-Reply-To: <6faf39c90901031643s1ad58a03g280f603e8ac08ef3@mail.gmail.com> References: <6faf39c90901031643s1ad58a03g280f603e8ac08ef3@mail.gmail.com> Message-ID: I changed it to this: #!/usr/local/bin/python3.0 #problem1.py """Lists the sum of all multiples of 3 and 5 less than 1000.""" def sumTotal(multipleInitial, multiple): # This awkward solution because total = 0 # mulitipleInitial = multiple just points n = 2 # a new variable to the same memory while multiple < 1000: # space total = total + multiple multiple = multipleInitial * n n = n + 1 return total print(sumTotal (3, 3) + sumTotal(5,5)) ----- I think it does what I wanted it to do, but Kent pointed out I wanted it to do was a false solution. So, I can create a list of all common multiples below 1000, sum them, subtract them from 266 333. Or, what I prefer, create a list of all multiples, checking against that list for a multiple before adding a new multiple. But, I don't know how to work with lists so I'll be back in a day or two. On Sat, Jan 3, 2009 at 6:43 PM, Andre Engels wrote: > > On Sun, Jan 4, 2009 at 1:06 AM, Benjamin Serrato > wrote: > > Hello, > > > > I'm trying to correctly solve the first projecteuler.net problem. The > > question is as so: Find the sum of all the multiples of 3 or 5 below 1000. > > > > I wrote the following program, but the number found is incorrect. I created > > a function that adds multiples of a given number to a global variable until > > the multiples are greater than 1000. The solution I get with my code is > > "1224". This is incorrect, but I am having trouble understanding why my code > > is wrong... it's very simple. > > My code: > > > > #!!/usr/local/bin/python3.0 > > #problem1.py > > > > """Lists the sum of all multiples of 3 and 5 less than 1000.""" > > > > # Initialize variable 'total'. > > total = 0 # I wanted this to be 'None', is that wrong? > > > > def sumTotal(multiple): > > global total # Brings total into the local scope so it > > # can be written to. > > n = 2 > > while multiple < 1000: > > total = total + multiple > > multiple = multiple * n > > n = n + 1 # I wanted this to be += but I'm not sure > > # that is right. > > > > # Now I call the function with the two arguments I need, 3 > > # and 5. Since total is a global variable it retains its value > > # at the end of the first function call, the next call adds to > > # the total value. Thus print(total) should give me the correct > > # value. > > > > sumTotal(3) > > sumTotal(5) > > > > print(total) > > > > ----- > > I think I have made a mistake with scope. Or some other syntactic error, > > because I don't see anything wrong with the code. Please make it obvious for > > me. > > There is an error with the code. The line > > multiple = multiple * n > > is not doing what you want it to do. > > See what is happening each time you go through this line: > > first time: > * multiple = 3 > * n = 2 > * multiple changed to 6 > > second time: > * multiple = 6 > * n = 3 > * multiple changed to 18 > > third time: > * multiple = 18 > * n = 4 > * multiple changed to 72 > > etcetera > > You will have to keep the number to multiply by in a separate variable > to avoid this. > > Apart from that, I think your usage of a global variable total, > although correct, is ugly and error-prone. I would do away with a > global variable total, add a local variable total, and end defSum with > "return total". > > Then the main body can be changed to: > > print (sumTotal(3) + sumTotal(5)) > > -- > Andr? Engels, andreengels at gmail.com From kent37 at tds.net Sun Jan 4 04:43:08 2009 From: kent37 at tds.net (Kent Johnson) Date: Sat, 3 Jan 2009 22:43:08 -0500 Subject: [Tutor] Add all natural numbers that are multiples of 3 and 5 In-Reply-To: References: <6faf39c90901031643s1ad58a03g280f603e8ac08ef3@mail.gmail.com> Message-ID: <1c2a2c590901031943pc93b3a4u778d53eb048c8a9d@mail.gmail.com> On Sat, Jan 3, 2009 at 9:43 PM, Benjamin Serrato wrote: > I changed it to this: > > #!/usr/local/bin/python3.0 > #problem1.py > > """Lists the sum of all multiples of 3 and 5 less than 1000.""" > > def sumTotal(multipleInitial, multiple): # This awkward solution because > total = 0 # > mulitipleInitial = multiple just points > n = 2 # a new > variable to the same memory You don't have to pass the duplicate arguments. It's true that multipleInitial=multiple makes multipleInitial reference the same value as multiple, but multiple = multipleInitial * n make mulltiple refer to a new value while leaving multipleInitial alone. This might help: http://personalpages.tds.net/~kent37/kk/00012.html > while multiple < 1000: # space > total = total + multiple > multiple = multipleInitial * n > n = n + 1 > return total > > print(sumTotal (3, 3) + sumTotal(5,5)) > > ----- > I think it does what I wanted it to do, but Kent pointed out I wanted > it to do was a false solution. So, I can create a list of all common > multiples below 1000, sum them, subtract them from 266 333. Or, what > I prefer, create a list of all multiples, checking against that list > for a multiple before adding a new multiple. But, I don't know how to > work with lists so I'll be back in a day or two. You might want to look at the sum() and range() functions. Kent PS Please subscribe to the list. From andreengels at gmail.com Sun Jan 4 10:40:52 2009 From: andreengels at gmail.com (Andre Engels) Date: Sun, 4 Jan 2009 10:40:52 +0100 Subject: [Tutor] Add all natural numbers that are multiples of 3 and 5 In-Reply-To: References: <6faf39c90901031643s1ad58a03g280f603e8ac08ef3@mail.gmail.com> Message-ID: <6faf39c90901040140j67fbddffrde90e29bac4c3f09@mail.gmail.com> On Sun, Jan 4, 2009 at 3:43 AM, Benjamin Serrato wrote: > I think it does what I wanted it to do, but Kent pointed out I wanted > it to do was a false solution. So, I can create a list of all common > multiples below 1000, sum them, subtract them from 266 333. Or, what > I prefer, create a list of all multiples, checking against that list > for a multiple before adding a new multiple. But, I don't know how to > work with lists so I'll be back in a day or two. Removing this double counting can be done easily if you realize that the double multiples are exactly 15 and its multiples. -- Andr? Engels, andreengels at gmail.com From prasadaraon50 at gmail.com Sun Jan 4 11:23:10 2009 From: prasadaraon50 at gmail.com (prasad rao) Date: Sun, 4 Jan 2009 02:23:10 -0800 Subject: [Tutor] project euler Message-ID: <9e3fac840901040223s290ed031ua0362d7b9cf097d1@mail.gmail.com> hello! I got it 266333. My code====== t=0 for x in range(1000): if divmod(x,3)[1]==0:t+=x if divmod(x,5)[1]==0:t+=x t=266333 Am I correct in comprehention of the problem? Prasad -------------- next part -------------- An HTML attachment was scrubbed... URL: From rschroev_nospam_ml at fastmail.fm Sun Jan 4 12:57:37 2009 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Sun, 04 Jan 2009 12:57:37 +0100 Subject: [Tutor] project euler In-Reply-To: <9e3fac840901040223s290ed031ua0362d7b9cf097d1@mail.gmail.com> References: <9e3fac840901040223s290ed031ua0362d7b9cf097d1@mail.gmail.com> Message-ID: prasad rao schreef: > hello! > I got it 266333. > My code====== > > t=0 > for x in range(1000): > if divmod(x,3)[1]==0:t+=x > if divmod(x,5)[1]==0:t+=x > t=266333 > > Am I correct in comprehention of the problem? Not entirely: you're counting numbers that are multiples of both 3 and 5 double, which is not the intention. BTW, instead of divmod(x, 3)[1] you can use x % 3. divmod() is nice if you need both quotient and remainder, but if you only need the remainder the % operator is simpler. -- The saddest aspect of life right now is that science gathers knowledge faster than society gathers wisdom. -- Isaac Asimov Roel Schroeven From s4027340 at student.uq.edu.au Sun Jan 4 14:07:04 2009 From: s4027340 at student.uq.edu.au (Mr Gerard Kelly) Date: Sun, 04 Jan 2009 23:07:04 +1000 Subject: [Tutor] Sound, frequencies and chords Message-ID: <6dcce6d418.6d4186dcce@uq.edu.au> Hi everyone, I'm a python noob but I have an ambitious (for me) goal: I want to make a simple program that allows you to hear combinations of notes according to a vector of frequencies. Does anybody know any module that allows you to input a frequency in Hz and returns a sound with that frequency, and lets you do that with multiple frequencies, so that you can build chords? I've googled around but I can't find what I'm looking for. I don't want MIDI since from what I know it only lets you choose from 12 notes (C, C#, D, D#) etc., but I want the full range of frequencies. If you can let me know about anything, I'd really appreciate it, thanks! From prasadaraon50 at gmail.com Sun Jan 4 14:18:47 2009 From: prasadaraon50 at gmail.com (prasad rao) Date: Sun, 4 Jan 2009 05:18:47 -0800 Subject: [Tutor] repply Message-ID: <9e3fac840901040518q232f13f7j9b25ffe891dd6fc4@mail.gmail.com> hi I got it right. >>> z=[] >>> for x in range(1000): if divmod(x,3)[1]==0:z.append(x) if divmod(x,5)[1]==0:z.append(x) >>> sum(set(z)) 233168 I am sorry if this is outside the perimeter of this list. -------------- next part -------------- An HTML attachment was scrubbed... URL: From sander.sweers at gmail.com Sun Jan 4 14:31:16 2009 From: sander.sweers at gmail.com (Sander Sweers) Date: Sun, 4 Jan 2009 14:31:16 +0100 Subject: [Tutor] repply In-Reply-To: <9e3fac840901040518q232f13f7j9b25ffe891dd6fc4@mail.gmail.com> References: <9e3fac840901040518q232f13f7j9b25ffe891dd6fc4@mail.gmail.com> Message-ID: On Sun, Jan 4, 2009 at 14:18, prasad rao wrote: >>>> z=[] >>>> for x in range(1000): > if divmod(x,3)[1]==0:z.append(x) > if divmod(x,5)[1]==0:z.append(x) >>>> sum(set(z)) > 233168 This can be done in one line of python. >>> sum([x for x in range(1000) if x %3 == 0 or x % 5 == 0]) 233168 Greets Sander From kent37 at tds.net Sun Jan 4 14:47:20 2009 From: kent37 at tds.net (Kent Johnson) Date: Sun, 4 Jan 2009 08:47:20 -0500 Subject: [Tutor] Sound, frequencies and chords In-Reply-To: <6dcce6d418.6d4186dcce@uq.edu.au> References: <6dcce6d418.6d4186dcce@uq.edu.au> Message-ID: <1c2a2c590901040547v67d1d825m73c18ec6e5c3594f@mail.gmail.com> On Sun, Jan 4, 2009 at 8:07 AM, Mr Gerard Kelly wrote: > Hi everyone, I'm a python noob but I have an ambitious (for me) goal: I > want to make a simple program that allows you to hear combinations of > notes according to a vector of frequencies. > > Does anybody know any module that allows you to input a frequency in Hz > and returns a sound with that frequency, and lets you do that with > multiple frequencies, so that you can build chords? Have you found this page? http://wiki.python.org/moin/PythonInMusic Several items in the "Playing & creating sound" and following sections look promising: audiolab Loris MusicKit PyMedia Pyper PySndObj PythonSound/Csound Kent From tjampman at gmail.com Sun Jan 4 17:06:12 2009 From: tjampman at gmail.com (Ole Henning Jensen) Date: Sun, 04 Jan 2009 17:06:12 +0100 Subject: [Tutor] repply In-Reply-To: <9e3fac840901040518q232f13f7j9b25ffe891dd6fc4@mail.gmail.com> References: <9e3fac840901040518q232f13f7j9b25ffe891dd6fc4@mail.gmail.com> Message-ID: <4960DE74.5010703@gmail.com> prasad rao wrote: > hi > I got it right. > > >>> z=[] > >>> for x in range(1000): > if divmod(x,3)[1]==0:z.append(x) > if divmod(x,5)[1]==0:z.append(x) > > >>> sum(set(z)) > 233168 > Instead of using the set function you could just use an elif in your for loop. >>> z=[] >>> for x in range(1000): if divmod(x,3)[1]==0:z.append(x) elif divmod(x,5)[1]==0:z.append(x) >>> sum(z) 233168 or as somebody else suggested use an OR operator >>> z=[] >>> for x in range(1000): if (divmod(x,3)[1]==0) or (divmod(x,5)[1]==0): z.append(x) >>> sum(z) 233168 just some variations... On an other wise correct anwser. From alan.gauld at btinternet.com Sun Jan 4 18:57:16 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 4 Jan 2009 17:57:16 -0000 Subject: [Tutor] Add all natural numbers that are multiples of 3 and 5 References: <496028B9.2040505@gmail.com> Message-ID: "bob gailer" wrote > Also consider that the sum of consecutive integers between 1 and n > is n*(n+1)/2. > Calculate that for 1..333 then multiply by 3 > Calculate that for 1..199 then multiply by 5 > add those > Calculate that for 1..66 then multiply by 15 > subtract that from the total Ooh, that's sneaky! I haven't seen that before. Took me a couple of reads through to figure out how it worked :-) -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk From Jaggojaggo+Py at gmail.com Sun Jan 4 19:07:31 2009 From: Jaggojaggo+Py at gmail.com (Omer) Date: Sun, 4 Jan 2009 20:07:31 +0200 Subject: [Tutor] RE Silliness Message-ID: <515008f10901041007s1670d6b0v5ac53978ce0a0e1c@mail.gmail.com> I'm sorry, burrowed into the reference until my eyes bled. What I want is to have a regular expression with an optional ending of "
" (For those interested, urlMask = r"http://[\w\Q./\?=\R]+" is ther version w/o the optional
ending.) I can't seem to make a string optional- only a single character via []s. I for some reason thuoght it'll be ()s, but no help there- it just returns only the
. Anybody? Thx, Omer. -------------- next part -------------- An HTML attachment was scrubbed... URL: From airchia at gmail.com Sun Jan 4 19:25:33 2009 From: airchia at gmail.com (Nick Scholtes) Date: Sun, 4 Jan 2009 12:25:33 -0600 Subject: [Tutor] Python - Data Mining? Message-ID: Hi, I'm still very, very new to Python and programming. I was wondering if anyone can point me in the right direction. As I gradually learn Python, one of the things I want to be able to do is take a database, run queries and extract information and then graph that information visually to see patterns in the data. Where should I start? Does Python do this? If not, what language is used for this? Thank you very much, Nick -- Art: http://www.coroflot.com/bellsoffreedom -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Sun Jan 4 19:54:36 2009 From: bgailer at gmail.com (bob gailer) Date: Sun, 04 Jan 2009 13:54:36 -0500 Subject: [Tutor] Add all natural numbers that are multiples of 3 and 5 In-Reply-To: References: <496028B9.2040505@gmail.com> Message-ID: <496105EC.4080604@gmail.com> Alan Gauld wrote: > "bob gailer" wrote > >> Also consider that the sum of consecutive integers between 1 and n is >> n*(n+1)/2. >> Calculate that for 1..333 then multiply by 3 >> Calculate that for 1..199 then multiply by 5 >> add those >> Calculate that for 1..66 then multiply by 15 >> subtract that from the total > > Ooh, that's sneaky! I haven't seen that before. Guess you did not study number theory. Standard algorithm. Google sum of consecutive integers. Regarding Project Euler - I believe one of the objectives is to find solutions that are not just brute force. Some of the problems can be solved by brute force but will take too much computer time. Sphere Online Judge www.spoj.pl is even more rigorous in that it runs your program and if run time is too long the solution is considered not correct. -- Bob Gailer Chapel Hill NC 919-636-4239 From sierra_mtnview at sbcglobal.net Sun Jan 4 19:49:23 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sun, 04 Jan 2009 10:49:23 -0800 Subject: [Tutor] WinMerge -- I'm Impressed Message-ID: <496104B3.1080108@sbcglobal.net> An HTML attachment was scrubbed... URL: From bgailer at gmail.com Sun Jan 4 20:09:53 2009 From: bgailer at gmail.com (bob gailer) Date: Sun, 04 Jan 2009 14:09:53 -0500 Subject: [Tutor] RE Silliness In-Reply-To: <515008f10901041007s1670d6b0v5ac53978ce0a0e1c@mail.gmail.com> References: <515008f10901041007s1670d6b0v5ac53978ce0a0e1c@mail.gmail.com> Message-ID: <49610981.5070708@gmail.com> Omer wrote: > I'm sorry, burrowed into the reference until my eyes bled. > > What I want is to have a regular expression with an optional ending of > "
" > > (For those interested, > urlMask = r"http://[\w\Q./\?=\R]+" > is ther version w/o the optional
ending.) > > I can't seem to make a string optional- only a single character via > []s. I for some reason thuoght it'll be ()s, but no help there- it > just returns only the
. Anybody? > urlMask = r"http://[\w\Q./\?=\R]+(
)?" From the docs: ? Causes the resulting RE to match 0 or 1 repetitions of the preceding RE. ab? will match either 'a' or 'ab'. -- Bob Gailer Chapel Hill NC 919-636-4239 From emmanuel.ruellan at gmail.com Sun Jan 4 20:25:44 2009 From: emmanuel.ruellan at gmail.com (Emmanuel Ruellan) Date: Sun, 4 Jan 2009 20:25:44 +0100 Subject: [Tutor] Tutor Digest, Vol 59, Issue 16 In-Reply-To: References: Message-ID: <7296745c0901041125y61f7ea49j972dc89b6bf8e9a1@mail.gmail.com> Gerard Kelly wrote: > Hi everyone, I'm a python noob but I have an ambitious (for me) goal: I > want to make a simple program that allows you to hear combinations of > notes according to a vector of frequencies. > > Does anybody know any module that allows you to input a frequency in Hz > and returns a sound with that frequency, and lets you do that with > multiple frequencies, so that you can build chords? The recipe linked below plays sounds composed of a fundamental and a few harmonics. It requires Pygame and NumPy. http://osdir.com/ml/culture.people.kragen.hacks/2007-11/msg00000.html It is out of date, though. I had to change 'Numeric' to 'numpy' and 'Int16' to 'int16' to get it to work. Moreover NumPy doesn't seem to work with Python 2.6. You can also use TkSnack (http://www.speech.kth.se/snack/). Check the example named 'notescale' that comes with the module: it defines a function that receives a frequency as an input and plays a sound; there is also a graphical interface. Regards, Emmanuel -------------- next part -------------- An HTML attachment was scrubbed... URL: From dorseye at gmail.com Sun Jan 4 20:32:12 2009 From: dorseye at gmail.com (Eric Dorsey) Date: Sun, 4 Jan 2009 12:32:12 -0700 Subject: [Tutor] Python - Data Mining? In-Reply-To: References: Message-ID: Hi Nick, I don't know about the graphing portion of your question, but yes Python does interact very well with databases. I have been working on a workout tracking program the last two months or so, and I'm new to programming. I'd highly recommend SQLite as a built-in database solution. I know it's included in Python version 2.5 which is what i'm currently running. You can call it at the top of your program with "import sqlite3", then you can run queries and create tables, etc. Here is some example code of SQLite usage in my program: #create the database, or connect if it already exists conn = sqlite3.connect('workoutstats.db') #create a variable called cursor to use, since its easier than typing out conn.cursor() all the time.. cursor = conn.cursor() #create a table cursor.execute(''' CREATE TABLE WR (id INTEGER PRIMARY KEY, reps SMALLINT(1000), weight SMALLINT(1000), exer VARCHAR(30), date DATE) ''') #query the WR table, feeding it the 'srch' variable which fills in where the SQL has a ? cursor.execute( "SELECT SUM(REPS) FROM WR WHERE EXER=?", (srch,) ) -Eric On Sun, Jan 4, 2009 at 11:25 AM, Nick Scholtes wrote: > Hi, > I'm still very, very new to Python and programming. I was wondering if > anyone can point me in the right direction. > > As I gradually learn Python, one of the things I want to be able to do is > take a database, run queries and extract information and then graph that > information visually to see patterns in the data. Where should I start? > Does Python do this? If not, what language is used for this? > > Thank you very much, > Nick > > > -- > Art: http://www.coroflot.com/bellsoffreedom > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- (e) -------------- next part -------------- An HTML attachment was scrubbed... URL: From wormwood_3 at yahoo.com Sun Jan 4 21:07:27 2009 From: wormwood_3 at yahoo.com (wormwood_3) Date: Sun, 4 Jan 2009 12:07:27 -0800 (PST) Subject: [Tutor] Python - Data Mining? References: Message-ID: <916480.35636.qm@web110802.mail.gq1.yahoo.com> I have done some data analysis work with Python, mostly with MySQL databases. Just as easy as the examples Eric mentioned with SQLite. All depends on what database you have to work with. Did you have any in mind or just wondering about data mining and Python in general? Regarding graphing, I have had great luck with using pylab ( http://www.scipy.org/PyLab ). Here is a simple example to create graphs of a thing being counted per unit: # Grab the needed module: from pylab import * def GraphData(time_and_count): """ Creates graph image of counts per time. """ # Set axis labels and their properties: x = xlabel('Time') setp(x, fontweight='bold') y = ylabel('Count') setp(y, fontweight='bold') # Plot: plotted = plot(time_and_count.keys(), time_and_count.values(), '--') setp(plotted, marker='s') title('Count over Time') grid(True) savefig('results.png', dpi=100) # Make a test dictionary of counts per time: time_and_count = dict(enumerate('4 5 3 4 6 7 8 9 3'.split())) # Make a graph: graphData(time_and_count) If all goes well, you should end up with a file "results.png" in the dir you ran this script. There is a LOT more you can do with pylab, but this sort of function should get you going for simple graphs. _______________________ Samuel Huckins Homepage - http://samuelhuckins.com Tech blog - http://dancingpenguinsoflight.com/ Photos - http://www.flickr.com/photos/samuelhuckins/ AIM - samushack | Gtalk - samushack | Skype - shuckins ________________________________ From: Eric Dorsey To: Nick Scholtes Cc: tutor at python.org Sent: Sunday, January 4, 2009 2:32:12 PM Subject: Re: [Tutor] Python - Data Mining? Hi Nick, I don't know about the graphing portion of your question, but yes Python does interact very well with databases. I have been working on a workout tracking program the last two months or so, and I'm new to programming. I'd highly recommend SQLite as a built-in database solution. I know it's included in Python version 2.5 which is what i'm currently running. You can call it at the top of your program with "import sqlite3", then you can run queries and create tables, etc. Here is some example code of SQLite usage in my program: #create the database, or connect if it already exists conn = sqlite3.connect('workoutstats.db') #create a variable called cursor to use, since its easier than typing out conn.cursor() all the time.. cursor = conn.cursor() #create a table cursor.execute(''' CREATE TABLE WR (id INTEGER PRIMARY KEY, reps SMALLINT(1000), weight SMALLINT(1000), exer VARCHAR(30), date DATE) ''') #query the WR table, feeding it the 'srch' variable which fills in where the SQL has a ? cursor.execute( "SELECT SUM(REPS) FROM WR WHERE EXER=?", (srch,) ) -Eric On Sun, Jan 4, 2009 at 11:25 AM, Nick Scholtes wrote: Hi, I'm still very, very new to Python and programming. I was wondering if anyone can point me in the right direction. As I gradually learn Python, one of the things I want to be able to do is take a database, run queries and extract information and then graph that information visually to see patterns in the data. Where should I start? Does Python do this? If not, what language is used for this? Thank you very much, Nick -- Art: http://www.coroflot.com/bellsoffreedom _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor -- (e) -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Sun Jan 4 21:10:14 2009 From: kent37 at tds.net (Kent Johnson) Date: Sun, 4 Jan 2009 15:10:14 -0500 Subject: [Tutor] Python - Data Mining? In-Reply-To: References: Message-ID: <1c2a2c590901041210q36a71b9fpae8ab62599c78cb2@mail.gmail.com> On Sun, Jan 4, 2009 at 1:25 PM, Nick Scholtes wrote: > Hi, > I'm still very, very new to Python and programming. I was wondering if > anyone can point me in the right direction. Welcome! > As I gradually learn Python, one of the things I want to be able to do is > take a database, run queries and extract information and then graph that > information visually to see patterns in the data. Where should I start? > Does Python do this? If not, what language is used for this? Yes, you can do this in Python. Python has a standard for interfacing to databases called DB-API: http://www.python.org/dev/peps/pep-0249/ You will have to obtain and install a DB-API module for the specific database you want to query: http://wiki.python.org/moin/DatabaseInterfaces The docs for the individual modules tend to be sparse because they follow the DB-API. For graphing, there are several options: http://wiki.python.org/moin/NumericAndScientific/Plotting I recommend matplotlib. You should probably start with a basic Python tutorial, though; both DB-API and matplotlib will be difficult if you don't have a basic understanding of Python. Pick a tutorial here: http://wiki.python.org/moin/BeginnersGuide/NonProgrammers Kent From wormwood_3 at yahoo.com Sun Jan 4 21:18:39 2009 From: wormwood_3 at yahoo.com (wormwood_3) Date: Sun, 4 Jan 2009 12:18:39 -0800 (PST) Subject: [Tutor] Documentation and top matter Message-ID: <863197.44515.qm@web110809.mail.gq1.yahoo.com> While PEP 8 and PEP 257 provide ample helpful information on the recommended ways to document classes, functions, and comments within code, I am having a hard time finding recommendations on how to document scripts by way of top matter. For example, I used this format for a while: #!/usr/bin/env python #----------------------------------------------------------------------------- # Name: my_cool_name # Purpose: My awesome purpose. # # Author: My Name # # Started: 01/01/01 #----------------------------------------------------------------------------- # IMPORT STUFF REST OF CODE This made it *really* easy to see what was going on as soon as you opened the file. Then I started shifting to something more like this: #!/usr/bin/env python #----------------------------------------------------------------------------- """ My awesome purpose. """ author = "My Name" date_started = "2001-01-01" version = 0.1 #----------------------------------------------------------------------------- IMPORT STUFF REST OF CODE This format is still readable and distinct, but by putting the information into attributes, they are accessible in an interpreter, by external tools, etc. Also putting the purpose in the first docstring allowed for use of .__doc__. But are there more generally accepted means of defining this information that are highly readable? I have also seen attributes in the form of "__author__ = 'My Name'", for which I found some discussion on comp.lang.python ( http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0128.html ). Recommendations? _______________________ Samuel Huckins Homepage - http://samuelhuckins.com Tech blog - http://dancingpenguinsoflight.com/ Photos - http://www.flickr.com/photos/samuelhuckins/ AIM - samushack | Gtalk - samushack | Skype - shuckins -------------- next part -------------- An HTML attachment was scrubbed... URL: From airchia at gmail.com Sun Jan 4 21:43:44 2009 From: airchia at gmail.com (Nick Scholtes) Date: Sun, 4 Jan 2009 14:43:44 -0600 Subject: [Tutor] Python - Data Mining? In-Reply-To: <1c2a2c590901041210q36a71b9fpae8ab62599c78cb2@mail.gmail.com> References: <1c2a2c590901041210q36a71b9fpae8ab62599c78cb2@mail.gmail.com> Message-ID: Thank you all so much for the great information so far. I really appreciate it. I'm going over it now. And sample code helps TON! That really allows me to see what happens with a program. In reference to wormwood_3's question about my intentions for data mining; I want to know this stuff in general, but I also have some applications in mind. For instance, I work with some groups that rescue homeless animals. It would be wonderful if I could compile a thorough database, then mine the data and create graphs to troubleshoot issues. As an example, we might find that more homeless animals show up in "x" location, or at "xyz" time of year. This could help in re-focuses efforts more efficiently. I'm going to start going over those links and sample code, but beware! I'll probably be dropping a bunch more questions soon! Take care, Nick On Sun, Jan 4, 2009 at 2:10 PM, Kent Johnson wrote: > On Sun, Jan 4, 2009 at 1:25 PM, Nick Scholtes wrote: > > Hi, > > I'm still very, very new to Python and programming. I was wondering if > > anyone can point me in the right direction. > > Welcome! > > > As I gradually learn Python, one of the things I want to be able to do is > > take a database, run queries and extract information and then graph that > > information visually to see patterns in the data. Where should I start? > > Does Python do this? If not, what language is used for this? > > Yes, you can do this in Python. > > Python has a standard for interfacing to databases called DB-API: > http://www.python.org/dev/peps/pep-0249/ > > You will have to obtain and install a DB-API module for the specific > database you want to query: > http://wiki.python.org/moin/DatabaseInterfaces > > The docs for the individual modules tend to be sparse because they > follow the DB-API. > > For graphing, there are several options: > http://wiki.python.org/moin/NumericAndScientific/Plotting > > I recommend matplotlib. > > You should probably start with a basic Python tutorial, though; both > DB-API and matplotlib will be difficult if you don't have a basic > understanding of Python. Pick a tutorial here: > http://wiki.python.org/moin/BeginnersGuide/NonProgrammers > > Kent > -- Art: http://www.coroflot.com/bellsoffreedom -------------- next part -------------- An HTML attachment was scrubbed... URL: From srilyk at gmail.com Sun Jan 4 22:23:13 2009 From: srilyk at gmail.com (W W) Date: Sun, 4 Jan 2009 15:23:13 -0600 Subject: [Tutor] Top posters to tutor list for 2008 In-Reply-To: <1c2a2c590901020528w3609e46ch1244cb04577ad48c@mail.gmail.com> References: <1c2a2c590901010634p1d10064bt9289fc952b69d558@mail.gmail.com> <1230823418.6159.29.camel@ltop> <1c2a2c590901020452m506100fft4106c1a7ce386d7@mail.gmail.com> <1c2a2c590901020528w3609e46ch1244cb04577ad48c@mail.gmail.com> Message-ID: <333efb450901041323x30e4e5b9ue42b35d7eb938c35@mail.gmail.com> I think I find it most interesting that the greatest percent is still under 15% and then it tapers rapidly. I'm curious what % of people posted 5 or less messages... perhaps it will become a personal project somewhere down the road ;) -Wayne On Fri, Jan 2, 2009 at 7:28 AM, Kent Johnson wrote: > On Fri, Jan 2, 2009 at 8:13 AM, Sander Sweers > wrote: > > On Fri, Jan 2, 2009 at 13:52, Kent Johnson wrote: > >> Or ask more questions, that works too! > > > > So you and Alan ask the most questions ;-) > > No, that honor goes to Dick Moores. He is in the top 10 in 4 of the > last 5 years! > > > Thanks to all the Tutors for year of great support :-) > > You're welcome, we couldn't do it without you! > > Kent > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn't. - Primo Levi -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sun Jan 4 22:41:04 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 4 Jan 2009 21:41:04 -0000 Subject: [Tutor] WinMerge -- I'm Impressed References: <496104B3.1080108@sbcglobal.net> Message-ID: "Wayne Watson" wrote > It took me 15 minutes to merge the two in an acceptable manner. > I just tried the result and am happy to report that it works as > expected. Glad to hear it, there are many such merge tools around some more automated than others. > Doing this by inspection of printed lists or holding two windows > (in IDLE, Notepad or whatever) In emacs or vim you could do the merge in place and edit the merge display. Its a standard feature of both. (I think eclipse can do it too although I haven't used it for that...). search the respective help systems for diff... And for those who prefer command line tools sdiff on *nix will do the job too. Alan G. From alan.gauld at btinternet.com Sun Jan 4 22:45:43 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 4 Jan 2009 21:45:43 -0000 Subject: [Tutor] Python - Data Mining? References: <1c2a2c590901041210q36a71b9fpae8ab62599c78cb2@mail.gmail.com> Message-ID: "Nick Scholtes" wrote > mind. For instance, I work with some groups that rescue homeless > animals. It > would be wonderful if I could compile a thorough database, then mine > the > data and create graphs to troubleshoot issues. As an example, we > might find > that more homeless animals show up in "x" location, or at "xyz" time > of > year. This could help in re-focuses efforts more efficiently. While I'm a big fan of Python and its powers I'm also a big fan of using the right tool for the job. I'd start with a spereadsheet, possibly with a database back end. Excel or OpenOffice would be adequate for that kind of data mining and graphing. Python would be more suited (IMHO) for more complex searches where you aren't able to simply filter or aggregate values. Just a thought, Alan G. From alan.gauld at btinternet.com Sun Jan 4 22:55:02 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 4 Jan 2009 21:55:02 -0000 Subject: [Tutor] Documentation and top matter References: <863197.44515.qm@web110809.mail.gq1.yahoo.com> Message-ID: "wormwood_3" wrote > #!/usr/bin/env python > #----------------------------------------------------------------------------- > """ > My awesome purpose. > """ > author = "My Name" > date_started = "2001-01-01" > version = 0.1 > #----------------------------------------------------------------------------- > IMPORT STUFF > REST OF CODE > > This format is still readable and distinct, but by putting the > information into attributes, > they are accessible in an interpreter, Neat I hadn't thought of that. The other thing thats often useful is to use your version control tool to insert the keystrings for you. They virtually all have similar features for auto-insertting the version number, filename, update comments and dates. For example in SCCS ( I know, but I had the docs handy! :-): %M% = Module name %R% - Release Number %L% - Level number %E% - Date newest delta was created etc etc. I don't use SVN but I'm sure it will have similar capabilities. Just some thoughts, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk From denis.spir at free.fr Sun Jan 4 23:08:07 2009 From: denis.spir at free.fr (spir) Date: Sun, 4 Jan 2009 23:08:07 +0100 Subject: [Tutor] RE Silliness In-Reply-To: <49610981.5070708@gmail.com> References: <515008f10901041007s1670d6b0v5ac53978ce0a0e1c@mail.gmail.com> <49610981.5070708@gmail.com> Message-ID: <20090104230807.1b128435@o> On Sun, 04 Jan 2009 14:09:53 -0500 bob gailer wrote: > Omer wrote: > > I'm sorry, burrowed into the reference until my eyes bled. > > > > What I want is to have a regular expression with an optional ending of > > "
" > > > > (For those interested, > > urlMask = r"http://[\w\Q./\?=\R]+" > > is ther version w/o the optional
ending.) > > > > I can't seem to make a string optional- only a single character via > > []s. I for some reason thuoght it'll be ()s, but no help there- it > > just returns only the
. Anybody? > > > urlMask = r"http://[\w\Q./\?=\R]+(
)?" > > From the docs: ? Causes the resulting RE to match 0 or 1 repetitions of > the preceding RE. ab? will match either 'a' or 'ab'. > > Maybe Omer had not noted that a sub-expression can be grouped in () so that an operator (?+*) applies on the whole group. Denis ------ la vida e estranya From airchia at gmail.com Mon Jan 5 01:16:16 2009 From: airchia at gmail.com (Nick Scholtes) Date: Sun, 4 Jan 2009 18:16:16 -0600 Subject: [Tutor] Python - Data Mining? In-Reply-To: References: <1c2a2c590901041210q36a71b9fpae8ab62599c78cb2@mail.gmail.com> Message-ID: Thanks, Alan. Good to know. I think I'll explore both routes, as it will at least get me some practice with Python. Nick On Sun, Jan 4, 2009 at 3:45 PM, Alan Gauld wrote: > > "Nick Scholtes" wrote > > mind. For instance, I work with some groups that rescue homeless animals. >> It >> would be wonderful if I could compile a thorough database, then mine the >> data and create graphs to troubleshoot issues. As an example, we might >> find >> that more homeless animals show up in "x" location, or at "xyz" time of >> year. This could help in re-focuses efforts more efficiently. >> > > While I'm a big fan of Python and its powers I'm also a big fan of using > the right tool for the job. I'd start with a spereadsheet, possibly with a > database back end. Excel or OpenOffice would be adequate for that kind > of data mining and graphing. > > Python would be more suited (IMHO) for more complex searches where > you aren't able to simply filter or aggregate values. > > Just a thought, > > Alan G. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Art: http://www.coroflot.com/bellsoffreedom -------------- next part -------------- An HTML attachment was scrubbed... URL: From airchia at gmail.com Mon Jan 5 01:33:13 2009 From: airchia at gmail.com (Nick Scholtes) Date: Sun, 4 Jan 2009 18:33:13 -0600 Subject: [Tutor] Python - Data Mining? In-Reply-To: References: <1c2a2c590901041210q36a71b9fpae8ab62599c78cb2@mail.gmail.com> Message-ID: Thanks, Alan. Good to know. I think I'll explore both routes, as it will at least get me some practice with Python. Oh, wait. Can Python be used to mine an Openoffice spreadsheet or database? Nick On Sun, Jan 4, 2009 at 3:45 PM, Alan Gauld wrote: > > "Nick Scholtes" wrote > > mind. For instance, I work with some groups that rescue homeless animals. >> It >> would be wonderful if I could compile a thorough database, then mine the >> data and create graphs to troubleshoot issues. As an example, we might >> find >> that more homeless animals show up in "x" location, or at "xyz" time of >> year. This could help in re-focuses efforts more efficiently. >> > > While I'm a big fan of Python and its powers I'm also a big fan of using > the right tool for the job. I'd start with a spereadsheet, possibly with a > database back end. Excel or OpenOffice would be adequate for that kind > of data mining and graphing. > > Python would be more suited (IMHO) for more complex searches where > you aren't able to simply filter or aggregate values. > > Just a thought, > > Alan G. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Art: http://www.coroflot.com/bellsoffreedom -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Jan 5 01:47:11 2009 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Mon, 5 Jan 2009 00:47:11 +0000 (GMT) Subject: [Tutor] Python - Data Mining? Message-ID: <660952.58082.qm@web86702.mail.ird.yahoo.com> > Can Python be used to mine an Openoffice spreadsheet > or database? There are Python - OO links. I've never used them but a Google search will throw them up I'm sure. But the easiest way is probably either to export the data as a CSV file and use the csv module or to put the data in a database and use OO or Python to access the databae directly. The latter approach is better if you have a large number of records or if there are many relationships in your data. Alan Gauld Author of the Learn To Program website http://www.alan-g.me.uk -------------- next part -------------- An HTML attachment was scrubbed... URL: From s4027340 at student.uq.edu.au Mon Jan 5 08:59:06 2009 From: s4027340 at student.uq.edu.au (Mr Gerard Kelly) Date: Mon, 05 Jan 2009 17:59:06 +1000 Subject: [Tutor] extreme basics Message-ID: <881ed86af5.86af5881ed@uq.edu.au> This is extremely weird, I think. Here is a tiny program: from math import * from Numeric import * x=[0]*10 for counter in rangelen((x)): x[counter]=counter*0.1 print x Here is what I get: [0.0, 0.10000000000000001, 0.20000000000000001, 0.30000000000000004, 0.40000000000000002, 0.5, 0.60000000000000009, 0.70000000000000007, 0.80000000000000004, 0.90000000000000002] What on Earth is going on with those decimals at the end? Is this a floating point thing? From dextrous85 at gmail.com Mon Jan 5 10:04:34 2009 From: dextrous85 at gmail.com (vishwajeet singh) Date: Mon, 5 Jan 2009 14:34:34 +0530 Subject: [Tutor] Question regarding win32com getting ldap object Message-ID: <5487b3060901050104g3d10c577s1ee0bc8303712ae4@mail.gmail.com> Hi List, I am running following code to get ldap com object but the result I am getting is unknown I am using Python 25 and win32 bindings available at http://downloads.sourceforge.net/pywin32/pywin32-212.win32-py2.2.exe?modtime=1217535908&big_mirror=0 *adsi = win32com.client.Dispatch('ADsNameSpaces') print adsi ldap = adsi.getobject('', 'LDAP:') print ldap* OutPut: > Any ideas what I am doing wrong ? -- Cheers, Vishwajeet http://www.singhvishwajeet.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From a.t.hofkamp at tue.nl Mon Jan 5 10:58:04 2009 From: a.t.hofkamp at tue.nl (A.T.Hofkamp) Date: Mon, 05 Jan 2009 10:58:04 +0100 Subject: [Tutor] extreme basics In-Reply-To: <881ed86af5.86af5881ed@uq.edu.au> References: <881ed86af5.86af5881ed@uq.edu.au> Message-ID: <4961D9AC.7050409@tue.nl> Mr Gerard Kelly wrote: > This is extremely weird, I think. > > Here is a tiny program: > > from math import * > from Numeric import * > > x=[0]*10 > > > for counter in rangelen((x)): > x[counter]=counter*0.1 > > print x > > Here is what I get: > > [0.0, 0.10000000000000001, 0.20000000000000001, 0.30000000000000004, > 0.40000000000000002, 0.5, 0.60000000000000009, 0.70000000000000007, > 0.80000000000000004, 0.90000000000000002] > > What on Earth is going on with those decimals at the end? Is this a > floating point thing? You can find the answer in the Python FAQ (although it is not a Python thing): http://www.python.org/doc/faq/general/#why-are-floating-point-calculations-so-inaccurate Sincerely, Albert From raghavendra.gv.vanam at gmail.com Mon Jan 5 14:19:47 2009 From: raghavendra.gv.vanam at gmail.com (vanam) Date: Mon, 5 Jan 2009 18:49:47 +0530 Subject: [Tutor] Usage of for loop Message-ID: <4499cb6a0901050519p1c0feb32odd987b5fea718ecf@mail.gmail.com> Hi all, i am beginner to this python language and slowing learning the language by referring docs.I am trying to understand the for loop i.e., usage of for loop in python,unlike c where i can give condition in python it is simple iterating over sequence. I am trying tounderstand the below lines of code but of no avail. a = ["cat", "window","defenestrate"] for x in a: print x, len(x) i cant understand what x is doing here and what is the purpose of it can anyone help me out here? -- Raghavendra Vanam -------------- next part -------------- An HTML attachment was scrubbed... URL: From sander.sweers at gmail.com Mon Jan 5 14:45:16 2009 From: sander.sweers at gmail.com (Sander Sweers) Date: Mon, 5 Jan 2009 14:45:16 +0100 Subject: [Tutor] Usage of for loop In-Reply-To: <4499cb6a0901050519p1c0feb32odd987b5fea718ecf@mail.gmail.com> References: <4499cb6a0901050519p1c0feb32odd987b5fea718ecf@mail.gmail.com> Message-ID: On Mon, Jan 5, 2009 at 14:19, vanam wrote: > I am trying tounderstand the below lines of code but of no avail. Python can loop over many types of sequences.. This can be a list, tuple or string and in your example a list. > a = ["cat", "window","defenestrate"] > for x in a: > print x, len(x) > i cant understand what x is doing here and what is the purpose of it > can anyone help me out here? In the example for every loop x becomes 1 of the values in the list (3 in total). So in the first loop it has value "cat", second "window" and third "defenestrate". How loops work in python is part of most python beginners guides, for example "Dive into Python" [1]. Greets Sander [1] http://diveintopython.org/toc/index.html From denis.spir at free.fr Mon Jan 5 14:50:22 2009 From: denis.spir at free.fr (spir) Date: Mon, 5 Jan 2009 14:50:22 +0100 Subject: [Tutor] extreme basics In-Reply-To: <881ed86af5.86af5881ed@uq.edu.au> References: <881ed86af5.86af5881ed@uq.edu.au> Message-ID: <20090105145022.7d47eb8a@o> Le Mon, 05 Jan 2009 17:59:06 +1000, Mr Gerard Kelly a ?crit : > This is extremely weird, I think. > > Here is a tiny program: > > from math import * > from Numeric import * > > x=[0]*10 > > > for counter in rangelen((x)): > x[counter]=counter*0.1 > > print x > > Here is what I get: > > [0.0, 0.10000000000000001, 0.20000000000000001, 0.30000000000000004, > 0.40000000000000002, 0.5, 0.60000000000000009, 0.70000000000000007, > 0.80000000000000004, 0.90000000000000002] > > What on Earth is going on with those decimals at the end? Is this a > floating point thing? I will take the opportunity to try and explain that "weird" issue, because I explored the topic a long time ago. If you /really/ know what "base n", "floating point", and "scientific notation" mean, just skip first section. denis -1- bases We are so used to the decimal notation that we do not think anymore what it actually means. In fact, "decimal" both means in base 10 (from latin root dec- = ten) and fractional (from decim- = tenth). A decimal notation like "1.2" represents 12/10, where /10 expresses the base number and the fractional feature. in that case, "10" mean ten only because the base is ten: "10" mean sixteen in base sixteen, three in base three, two in base two. To generalize the decimal pattern, consider 123.45678 This expresses a number equal to 12345678/100000 = 12345678/(10^5) = 12345678*(10^-5). The so-called scientific notation represents this as 12345678e-5, or else 1.2345678e2. "e^n" mean "*base^n". Now, if we change to another base b, the pattern is exactly the same, except that: * each digit is a digit in base b * b is exponentiated For instance: base 16: 123af.59 = 123af59 / (16^2) = 123af59e-2 base 3: 123.31 = 12331 / (3^2) = 12331e-2 base 2: 101.01 = 10101 / (2^2) = 10101e-2 (=21/4=5.25) -2- exactitude When we write down a number, whatever the notation, it can only be an exact number in the sense that it has a finite number of digits. The point is that an exact number in decimal base must not be exact (in that sense) in another base -- and conversely. This may seem weird indeed (I had a hard time understanding it). Below, the first version of each number representation (silently given by repr()) shows a real internal value, while the second (str()) is nicely arranged for normal humans. >>> 0.5; print 0.5 0.5 0.5 >>> 0.7; print 0.7 0.69999999999999996 0.7 Python computes in base 2, so that each non-integer number is represented as mantissa / 2^n For a number to be exact for python, this number must then be so that we can find a proper mantissa and a proper exponent n that satisfies number = mantissa / 2^n or mantissa/number = 2^n As 2^n can only only be 1,2,4,8... there is no garanty that it is possible at all (in a reasonable number of digits -- because both mantissa and n must be ints). The output of Gerard's code indeed shows that a/10 will be an exact number in base 2 only for a=5. Why 0.5? 0.5 = 5/10 ==> base 2: 101/1010 We can see above that the denominator is a multiple of the numerator, so that we can simplify: 101/1010 = 1/10 (base10:1/2) = 1/2^1 = 1e-1 = 0.1 So that 0.5 in base 10 can be expressed as the exact number 0.1 in base 2. Now, let us try 0.7: 0.7 = 7/10 ==> base 2: 111/1010 too bad! It won't match so easily. To express 0.7, we must try and find a proper (mantissa,exponent) pair that together express a result of 0.7. Good luck! Conversely, as I see it, there is no exact binary number which can't be exactly expressed in decimal base. The reason simply is, I guess, that 10 is a multiple of 2. Fractions based on 2 (0.1, 0.01, 0.001...) are not as simple in base 10, but they can be written: >>> for e in range(1,10): print repr(1.0 * 2**(-e)), ... ... 0.5 0.25 0.125 0.0625 0.03125 0.015625 0.0078125 0.00390625 0.001953125 On the contrary, we find problems at once when starting from base 3, as a base three decimal number expression means mantissa/3^n and 1/3 is already inexact in base 10: base3: 0.1 = 1/10 ==> base10: 1/3 = 0.333333... base3: 1.2 = 12/10 ==> base10: 5/3 = 1.666666... ------ la vida e estranya From wferguson1 at socal.rr.com Mon Jan 5 14:56:46 2009 From: wferguson1 at socal.rr.com (WM.) Date: Mon, 05 Jan 2009 05:56:46 -0800 Subject: [Tutor] Wayne's waning list. Message-ID: <4962119E.3070004@socal.rr.com> As a BASIC, hobby programmer, (long since), I get so jargonized here that I seldom ask about anything any more. The only useful bit I have gleaned from reading many, many posts is the URL for projecteuler. Maybe, after I get past the baby steps and start using the libraries, I will benefit more. Now, the opaque questions and bewildering responses leave me in a very passive state. From a.t.hofkamp at tue.nl Mon Jan 5 15:14:56 2009 From: a.t.hofkamp at tue.nl (A.T.Hofkamp) Date: Mon, 05 Jan 2009 15:14:56 +0100 Subject: [Tutor] Usage of for loop In-Reply-To: <4499cb6a0901050519p1c0feb32odd987b5fea718ecf@mail.gmail.com> References: <4499cb6a0901050519p1c0feb32odd987b5fea718ecf@mail.gmail.com> Message-ID: <496215E0.30704@tue.nl> vanam wrote: > Hi all, > i am beginner to this python language and slowing learning the language by > referring docs.I am trying to understand the for loop i.e., usage of for > loop in python,unlike c where i can give condition in python it is simple In C, the for-loop is just a hidden 'while'. You can think of (I dropped the variable declaration stuff, and the cumbersome ";" and printf() syntax for clarity) a = ["cat", "window","defenestrate"] for (i=0; i < len(a) ; i = i + 1) { x = a[i] print x } as the equivalent of a = ["cat", "window","defenestrate"] i = 0 while i < len(a): x = a[i] print x i = i + 1 Now take a step back. What are you aiming to achieve here? If you look carefully, the whole i variable is not relevant. The aim of the code is to get each element of the list a in x (one element with each iteration), and do something with it, in this case, printing it. To demonstrate, let's sum all values of list b: b = [1, 2, 3] total = 0 i = 0 while i < len(b): y = b[i] total = total + y i = i + 1 If you compare both pieces, you see the same pieces of boilerplate code appear: i = 0 while i < len(): = [i] and i = i + 1 This happens at every loop that you write. The Python developers decided that Python should take care of the boilerplate code. Of the first 3 lines, the interesting pieces are only (the list you get values from), and (the name of variable where you put each element in with each iteration). The line at the bottom is always the same, no need to enter that each time. What you are left with after throwing out the boilerplate code (in pseudo english/Python), for your original problem, is something like "for each element" x "from the list" a "do" print x which is shortened in Python to for x in a: print x ('in' is ASCII for the 'element of' symbol U+2208). Not only is this much shorter, it is also more powerful. Python has many rich data structures (such as lists, tuples, sets, dictionaries), and the above construct can be used for all of them. Sincerely, Albert From a.t.hofkamp at tue.nl Mon Jan 5 16:01:56 2009 From: a.t.hofkamp at tue.nl (A.T.Hofkamp) Date: Mon, 05 Jan 2009 16:01:56 +0100 Subject: [Tutor] Wayne's waning list. In-Reply-To: <4962119E.3070004@socal.rr.com> References: <4962119E.3070004@socal.rr.com> Message-ID: <496220E4.2040106@tue.nl> WM. wrote: > As a BASIC, hobby programmer, (long since), I get so jargonized here > that I seldom ask about anything any more. The only useful bit I have > gleaned from reading many, many posts is the URL for projecteuler. > Maybe, after I get past the baby steps and start using the libraries, I > will benefit more. Now, the opaque questions and bewildering responses > leave me in a very passive state. Sorry to hear that. We do not intend to scare you away, on the contrary. It is just that there is a wide range of people posting here with all kinds of different backgrounds with questions on widely different topics. When answering a question (in a single post), one often has to hook into terms and bodies of knowledge that the questioner seems to understand judging by phrases that are used in the question. Given the wide range of background and experience of the readers, several readers will not or only partly understand what is being written. While that is regrettable, I believe it is unavoidable. (And if it is any comfort to you, it happens to me too. I have read several discussions about the "@" operator, and still don't understand why you'd want to have it. No doubt it is a fantastic operator with many uses, but apparently, not for me.) However, you are free to ask questions here, and that includes questions about answers. (It is not until you ask, that we become aware of your need for further clarification.) Sincerely, Albert From denis.spir at free.fr Mon Jan 5 16:22:15 2009 From: denis.spir at free.fr (spir) Date: Mon, 5 Jan 2009 16:22:15 +0100 Subject: [Tutor] Wayne's waning list. In-Reply-To: <496220E4.2040106@tue.nl> References: <4962119E.3070004@socal.rr.com> <496220E4.2040106@tue.nl> Message-ID: <20090105162215.3073458b@o> Le Mon, 05 Jan 2009 16:01:56 +0100, "A.T.Hofkamp" a ?crit : > > (And if it is any comfort to you, it happens to me too. I have read several > discussions about the "@" operator, and still don't understand why you'd want > to have it. No doubt it is a fantastic operator with many uses, but > apparently, not for me.) There may be a question of personal programmer style, and a question of personal history as programmer. I know people for whom OO is weird, useless, and... abstract (which is very true imo -- and even: the better you use it, the more abstract it is). There have learnt without it. When they must use it, e.g. for linking to modules, it's painful. I have learnt without OO (C,pascal) but it seems to fits my brain's "Weltanschauung" (way of watching the world?), as to say my style. But I had hard time with it a start, especially because of the high inconstency of all the various systems that wish to be called OO, and the inconstency of the OO lexicon. About @, it seems not to be style at all, as for you. Ditto for meta-classes (the few I have tried lead me to endless MRO problems). > Sincerely, > Albert > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > ------ la vida e estranya From Jaggojaggo+Py at gmail.com Mon Jan 5 17:16:13 2009 From: Jaggojaggo+Py at gmail.com (Omer) Date: Mon, 5 Jan 2009 18:16:13 +0200 Subject: [Tutor] RE Silliness In-Reply-To: <20090104230807.1b128435@o> References: <515008f10901041007s1670d6b0v5ac53978ce0a0e1c@mail.gmail.com> <49610981.5070708@gmail.com> <20090104230807.1b128435@o> Message-ID: <515008f10901050816k385ebc52i9d688e580fbadc29@mail.gmail.com> Bob, I tried your way. >>> import re >>> urlMask = r"http://[\w\Q./\?=\R]+(
)?" >>> text=u"Not working example
http://this.is.a/url?header=null
And another line
http://and.another.url" >>> re.findall(urlMask,text) [u'
', u''] spir, I did understand it. What I'm not understanding is why isn't this working. (Whereas, >>> OldurlMask = r"http://[\w\Q./\?=\R]+" #Not f-ing working. >>> re.findall(OldurlMask,text) ['http://this.is.a/url?header=null', 'http://and.another.url'] does work. Which is what had me frowning. Also, this ugly url mask is working: >>> UglyUrlMask = r"(http://[\w\Q./\?=\R]+
|http://[\w\Q./\?=\R]+)" >>> re.findall(UglyUrlMask,text) ['http://this.is.a/url?header=null
', 'http://and.another.url'] Anyone?) On Mon, Jan 5, 2009 at 12:08 AM, spir wrote: > On Sun, 04 Jan 2009 14:09:53 -0500 > bob gailer wrote: > > > Omer wrote: > > > I'm sorry, burrowed into the reference until my eyes bled. > > > > > > What I want is to have a regular expression with an optional ending of > > > "
" > > > > > > (For those interested, > > > urlMask = r"http://[\w\Q./\?=\R]+" > > > is ther version w/o the optional
ending.) > > > > > > I can't seem to make a string optional- only a single character via > > > []s. I for some reason thuoght it'll be ()s, but no help there- it > > > just returns only the
. Anybody? > > > > > urlMask = r"http://[\w\Q./\?=\R]+(
)?" > > > > From the docs: ? Causes the resulting RE to match 0 or 1 repetitions of > > the preceding RE. ab? will match either 'a' or 'ab'. > > > > > > Maybe Omer had not noted that a sub-expression can be grouped in () so that > an operator (?+*) applies on the whole group. > Denis > > ------ > la vida e estranya > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Mon Jan 5 17:45:56 2009 From: kent37 at tds.net (Kent Johnson) Date: Mon, 5 Jan 2009 11:45:56 -0500 Subject: [Tutor] RE Silliness In-Reply-To: <515008f10901050816k385ebc52i9d688e580fbadc29@mail.gmail.com> References: <515008f10901041007s1670d6b0v5ac53978ce0a0e1c@mail.gmail.com> <49610981.5070708@gmail.com> <20090104230807.1b128435@o> <515008f10901050816k385ebc52i9d688e580fbadc29@mail.gmail.com> Message-ID: <1c2a2c590901050845l605e3639m64debd3ec9c788a5@mail.gmail.com> On Mon, Jan 5, 2009 at 11:16 AM, Omer wrote: > Bob, I tried your way. > >>>> import re >>>> urlMask = r"http://[\w\Q./\?=\R]+(
)?" >>>> text=u"Not working example
http://this.is.a/url?header=null
And >>>> another line
http://and.another.url" >>>> re.findall(urlMask,text) > [u'
', u''] > > spir, I did understand it. What I'm not understanding is why isn't this > working. There is a bit of a gotcha in re.findall() - its behaviour changes depending on whether there are groups in the re. If the re contains groups, re.findall() only returns the matches for the groups. If you enclose the entire re in parentheses (making it a group) you get a better result: In [2]: urlMask = r"(http://[\w\Q./\?=\R]+(
)?)" In [3]: text=u"Not working example
http://this.is.a/url?header=null
And another line
http://and.another.url" In [4]: re.findall(urlMask,text) Out[4]: [(u'http://this.is.a/url?header=null
', u'
'), (u'http://and.another.url', u'')] You can also use non-grouping parentheses around the
: In [5]: urlMask = r"http://[\w\Q./\?=\R]+(?:
)?" In [6]: re.findall(urlMask,text) Out[6]: [u'http://this.is.a/url?header=null
', u'http://and.another.url'] Kent From bgailer at gmail.com Mon Jan 5 18:19:32 2009 From: bgailer at gmail.com (bob gailer) Date: Mon, 05 Jan 2009 12:19:32 -0500 Subject: [Tutor] RE Silliness In-Reply-To: <515008f10901050816k385ebc52i9d688e580fbadc29@mail.gmail.com> References: <515008f10901041007s1670d6b0v5ac53978ce0a0e1c@mail.gmail.com> <49610981.5070708@gmail.com> <20090104230807.1b128435@o> <515008f10901050816k385ebc52i9d688e580fbadc29@mail.gmail.com> Message-ID: <49624124.7080500@gmail.com> Omer wrote: > Bob, I tried your way. > > >>> import re > >>> urlMask = r"http://[\w\Q./\?=\R]+(
)?" > >>> text=u"Not working > example
http://this.is.a/url?header=null
And another > line
http://and.another.url" > >>> re.findall(urlMask,text) > [u'
', u''] Oops I failed to notice you were using findall. Kent explained it. Another way to fix it is to make (
) a non-group: (?:
) -- Bob Gailer Chapel Hill NC 919-636-4239 From alan.gauld at btinternet.com Mon Jan 5 19:25:18 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 5 Jan 2009 18:25:18 -0000 Subject: [Tutor] extreme basics References: <881ed86af5.86af5881ed@uq.edu.au> Message-ID: "Mr Gerard Kelly" wrote > This is extremely weird, I think. No, its normal and you got the right reason.... its due to floating point binary representation issues. > Here is a tiny program: > > from math import * > from Numeric import * This is probably a bad idea here (in fact its usually a bad idea!) since both math and numeric are likely to have similar names in them By importing all names from the modules there is a high chance of name clashes causing strange behaviour. Better to use import math, Numeric Or, if that's too much typing, use import math as M import Numeric as N > x=[0]*10 > > > for counter in rangelen((x)): > x[counter]=counter*0.1 > > print x Although of course you are not using anything from either math or Numeric in this example, but I assume you intend to!? HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk From alan.gauld at btinternet.com Mon Jan 5 19:33:46 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 5 Jan 2009 18:33:46 -0000 Subject: [Tutor] Wayne's waning list. References: <4962119E.3070004@socal.rr.com> Message-ID: "WM." wrote > As a BASIC, hobby programmer, (long since), I get so jargonized here > that I seldom ask about anything any more. Have you tried my tutorial, it compares VBScript (somewhat like BASIC) with Python. It might help. > gleaned from reading many, many posts is the URL for projecteuler. > Maybe, after I get past the baby steps and start using the > libraries, I will benefit more. Now, the opaque questions and > bewildering responses leave me in a very passive state. As somebody else said we cover everything from newbies to programming through to experts ion other languages whjo are new to Python and even some experts(ish) in Python who are new to a specific area(like GUI or web programming) As a result the questions range from the trivial to the esoteric. If you think you should know whats being discussed don't be afraid to jump in and ask for clarification in plain English. Either in the same thread or if its looking like a biggie as a separate thread. We aim to help and a background in BASIC should help not hinder! :-) -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From jervisau at gmail.com Mon Jan 5 20:58:45 2009 From: jervisau at gmail.com (Jervis Whitley) Date: Tue, 6 Jan 2009 06:58:45 +1100 Subject: [Tutor] Question regarding win32com getting ldap object In-Reply-To: <5487b3060901050104g3d10c577s1ee0bc8303712ae4@mail.gmail.com> References: <5487b3060901050104g3d10c577s1ee0bc8303712ae4@mail.gmail.com> Message-ID: <8e63a5ce0901051158i32b2af2al24cb89db54182c0e@mail.gmail.com> On Mon, Jan 5, 2009 at 8:04 PM, vishwajeet singh wrote: > Hi List, > > I am running following code to get ldap com object but the result I am > getting is unknown > I am using Python 25 and win32 bindings available at > http://downloads.sourceforge.net/pywin32/pywin32-212.win32-py2.2.exe?modtime=1217535908&big_mirror=0 > > *adsi = win32com.client.Dispatch('ADsNameSpaces') > print adsi > ldap = adsi.getobject('', 'LDAP:') > print ldap* > > OutPut: > > > > > Any ideas what I am doing wrong ? > > -- > Cheers, > Vishwajeet > http://www.singhvishwajeet.com > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > Hi, try the following from the archive: http://mail.python.org/pipermail/python-list/1999-December/018594.html Cheers, Jervis -------------- next part -------------- An HTML attachment was scrubbed... URL: From jadrifter at gmail.com Tue Jan 6 00:07:07 2009 From: jadrifter at gmail.com (jadrifter) Date: Mon, 05 Jan 2009 15:07:07 -0800 Subject: [Tutor] Usage of for loop In-Reply-To: <4499cb6a0901050519p1c0feb32odd987b5fea718ecf@mail.gmail.com> References: <4499cb6a0901050519p1c0feb32odd987b5fea718ecf@mail.gmail.com> Message-ID: <1231196827.6180.15.camel@ltop> On Mon, 2009-01-05 at 18:49 +0530, vanam wrote: > Hi all, > i am beginner to this python language and slowing learning the > language by referring docs.I am trying to understand the for loop > i.e., usage of for loop in python,unlike c where i can give condition > in python it is simple iterating over sequence. > > I am trying tounderstand the below lines of code but of no avail. > > a = ["cat", "window","defenestrate"] > for x in a: > print x, len(x) > i cant understand what x is doing here and what is the purpose of it > can anyone help me out here? > > -- > Raghavendra Vanam > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor x is a new variable and when used this way it holds one of the members of "a" for each trip through the loop. After your for loop is done there will be two new names in a "dir()" listing if you're using the interactive python shell. There will be a name "a" and a name "x". If you type "print x" it will output "defenestrate" because it still holds the last value of a from the for loop. John Purser From sander.sweers at gmail.com Tue Jan 6 01:52:32 2009 From: sander.sweers at gmail.com (Sander Sweers) Date: Tue, 6 Jan 2009 01:52:32 +0100 Subject: [Tutor] Convert values in a list back and forth from ints and time Message-ID: Hello Tutors, I use the csv module to read and write a csv file. When I read the file into a new list I convert the ints and the dates to int and time objects so I can do calculations. I use the below function which works. def convertValue(value, dateformat, reverse=False): if reverse: try: return strftime(dateformat, value) except TypeError: return str(value) else: try: return int(float(value)) except ValueError: try: return strptime(value, dateformat) except: return value When writing the lines back to a csv file I loop over the lists and convert the values back with the same function but in reverse but.... I was just wondering if there is another way of dealing with this. Should I pass the strings to the calculation function (not written yet), do my calculations and have it return strings? Or do you have another way? Thanks Sander From bgailer at gmail.com Tue Jan 6 04:38:03 2009 From: bgailer at gmail.com (bob gailer) Date: Mon, 05 Jan 2009 22:38:03 -0500 Subject: [Tutor] Convert values in a list back and forth from ints and time In-Reply-To: References: Message-ID: <4962D21B.1070702@gmail.com> Sander Sweers wrote: > Hello Tutors, > > I use the csv module to read and write a csv file. When I read the > file into a new list I convert the ints and the dates to int and time > objects so I can do calculations. I use the below function which > works. > > def convertValue(value, dateformat, reverse=False): > if reverse: > try: > return strftime(dateformat, value) > except TypeError: > return str(value) > else: > try: > return int(float(value)) > except ValueError: > try: > return strptime(value, dateformat) > except: > return value > > When writing the lines back to a csv file I loop over the lists and > convert the values back with the same function but in reverse but.... > > I was just wondering if there is another way of dealing with this. > Should I pass the strings to the calculation function (not written > yet), do my calculations and have it return strings? I prefer separation of tasks. Let the calculation routines expect and return numbers. I also suggest splitting convertValue into two functions, one that takes strings and one that takes numbers. A lot easier to read and maintain. FWIW you could dispense with reverse in convertValue by testing the type of value for int or str. -- Bob Gailer Chapel Hill NC 919-636-4239 From dextrous85 at gmail.com Tue Jan 6 06:01:34 2009 From: dextrous85 at gmail.com (vishwajeet singh) Date: Tue, 6 Jan 2009 10:31:34 +0530 Subject: [Tutor] Question regarding win32com getting ldap object In-Reply-To: <8e63a5ce0901051158i32b2af2al24cb89db54182c0e@mail.gmail.com> References: <5487b3060901050104g3d10c577s1ee0bc8303712ae4@mail.gmail.com> <8e63a5ce0901051158i32b2af2al24cb89db54182c0e@mail.gmail.com> Message-ID: <5487b3060901052101l7af23ba8x7a52d514d81f42a2@mail.gmail.com> Thanks for the help. It worked for me. On Tue, Jan 6, 2009 at 1:28 AM, Jervis Whitley wrote: > > > On Mon, Jan 5, 2009 at 8:04 PM, vishwajeet singh wrote: > >> Hi List, >> >> I am running following code to get ldap com object but the result I am >> getting is unknown >> I am using Python 25 and win32 bindings available at >> http://downloads.sourceforge.net/pywin32/pywin32-212.win32-py2.2.exe?modtime=1217535908&big_mirror=0 >> >> *adsi = win32com.client.Dispatch('ADsNameSpaces') >> print adsi >> ldap = adsi.getobject('', 'LDAP:') >> print ldap* >> >> OutPut: >> >> > >> >> Any ideas what I am doing wrong ? >> >> -- >> Cheers, >> Vishwajeet >> http://www.singhvishwajeet.com >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> >> Hi, > try the following from the archive: > > http://mail.python.org/pipermail/python-list/1999-December/018594.html > > Cheers, > > Jervis > -- Cheers, Vishwajeet http://www.singhvishwajeet.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Jan 6 09:46:16 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 6 Jan 2009 08:46:16 -0000 Subject: [Tutor] Convert values in a list back and forth from ints and time References: Message-ID: "Sander Sweers" wrote > I use the csv module to read and write a csv file. When I read the > file into a new list I convert the ints and the dates to int and > time > When writing the lines back to a csv file I loop over the lists and > convert the values back with the same function but in reverse > but.... > > I was just wondering if there is another way of dealing with this. If you always convert the values back to strings then you could just hold onto the original strings by storing them in a (str, val) tuple. If you do calculations and modify anmy of them then convert the value/string there and then and modify the tuple. You could even make it a class with the convertion fiunctions being methods. But whether the extra complexity is worthwhile will depend on what proportion of values get modified. If its a small proportion then the gain in speed from not doing the reverse convertion might be worth it. In most cases what you have done is probably the simplest approach and if its fast enough then don't worry about it! PS. I agree with Bob about splitting the function in two... -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk From wferguson1 at socal.rr.com Tue Jan 6 18:53:00 2009 From: wferguson1 at socal.rr.com (WM.) Date: Tue, 06 Jan 2009 09:53:00 -0800 Subject: [Tutor] WAYNE'S WAINING... Message-ID: <49639A7C.5040400@socal.rr.com> One of the replies to my post explained how difficult it is to address an audience composed of several levels of skill. I understand that, nor was I condemning anyone who has a better command of jargon than I have. Jargon is essential to any trade. What I wanted to do was give Wayne the POV of someone who posted for a while, then gave up. I have plenty of questions, I shall try to put some of them in intelligible form, for your amusement. From sander.sweers at gmail.com Tue Jan 6 19:30:31 2009 From: sander.sweers at gmail.com (Sander Sweers) Date: Tue, 6 Jan 2009 19:30:31 +0100 Subject: [Tutor] Convert values in a list back and forth from ints and time In-Reply-To: <4962D21B.1070702@gmail.com> References: <4962D21B.1070702@gmail.com> Message-ID: On Tue, Jan 6, 2009 at 04:38, bob gailer wrote: > I also suggest splitting convertValue into two functions, one that takes > strings and one that takes numbers. A lot easier to read and maintain. > > FWIW you could dispense with reverse in convertValue by testing the type of > value for int or str. Thanks for feedback and suggestions. Below is the function split in 2. def convertToString(value, dateformat): print value if type(value) == int: return str(value) else: try: return strftime(dateformat, value) except TypeError: return value def convertFromString(value, dateformat): try: return int(float(value)) except ValueError: try: return strptime(value, dateformat) except: return value Greets Sander From sander.sweers at gmail.com Tue Jan 6 19:43:16 2009 From: sander.sweers at gmail.com (Sander Sweers) Date: Tue, 6 Jan 2009 19:43:16 +0100 Subject: [Tutor] Convert values in a list back and forth from ints and time In-Reply-To: References: Message-ID: On Tue, Jan 6, 2009 at 09:46, Alan Gauld wrote: > If you always convert the values back to strings then you could > just hold onto the original strings by storing them in a (str, val) tuple. > If you do calculations and modify anmy of them then convert the > value/string there and then and modify the tuple. You could even > make it a class with the convertion fiunctions being methods. > But whether the extra complexity is worthwhile will depend on > what proportion of values get modified. If its a small proportion > then the gain in speed from not doing the reverse convertion might > be worth it. In most cases what you have done is probably the > simplest approach and if its fast enough then don't worry about it! This is too complex and the speed is good enough for 2000 lines in the file. however... I am doing this to learn about python and programming. So I am interested how this class would look like. Could you give an example or point me in the right direction how I can figure it out for myself? Thanks Sander From bgailer at gmail.com Tue Jan 6 19:55:50 2009 From: bgailer at gmail.com (bob gailer) Date: Tue, 06 Jan 2009 13:55:50 -0500 Subject: [Tutor] Convert values in a list back and forth from ints and time In-Reply-To: References: <4962D21B.1070702@gmail.com> Message-ID: <4963A936.1010805@gmail.com> An HTML attachment was scrubbed... URL: From wferguson1 at socal.rr.com Tue Jan 6 20:12:16 2009 From: wferguson1 at socal.rr.com (WM.) Date: Tue, 06 Jan 2009 11:12:16 -0800 Subject: [Tutor] Interactive programming. Message-ID: <4963AD10.4060003@socal.rr.com> >>> i = 5 >>> j = 7 >>> if i <= j: print 'nudge, nudge' else: File "", line 3 else: ^ IndentationError: unexpected indent Running in IDLE, all is well until "else:". IDLE seems perplexed about the >>>s. I try to de-dent else via the backspace key, after that there is no way to avoid an error message. From norman at khine.net Tue Jan 6 20:41:49 2009 From: norman at khine.net (Norman Khine) Date: Tue, 06 Jan 2009 20:41:49 +0100 Subject: [Tutor] Interactive programming. In-Reply-To: <4963AD10.4060003@socal.rr.com> References: <4963AD10.4060003@socal.rr.com> Message-ID: <4963B3FD.1010504@khine.net> >>> i = 5 >>> j = 7 >>> if i <= j: ... print 'nudge', 'nudge' ... else: ... print 'whatever' ... nudge nudge >>> WM. wrote: > >>> i = 5 > >>> j = 7 > >>> if i <= j: > print 'nudge, nudge' > else: > > File "", line 3 > else: > ^ > IndentationError: unexpected indent > > Running in IDLE, all is well until "else:". IDLE seems perplexed about > the >>>s. I try to de-dent else via the backspace key, after that there > is no way to avoid an error message. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at btinternet.com Tue Jan 6 20:40:13 2009 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Tue, 6 Jan 2009 19:40:13 +0000 (GMT) Subject: [Tutor] Convert values in a list back and forth from ints and time Message-ID: <592976.37391.qm@web86704.mail.ird.yahoo.com> > > If you always convert the values back to strings then you could > > just hold onto the original strings by storing them in a (str, val) tuple. > > If you do calculations and modify anmy of them then convert the > > value/string there and then and modify the tuple. You could even > > make it a class with the convertion fiunctions being methods. > This is too complex and the speed is good enough for 2000 lines in the > file. however... Fair enough, I suspected as much. > I am doing this to learn about python and programming. So I am > interested how this class would look like. Could you give an example > or point me in the right direction how I can figure it out for myself? You just nered to define a class that can take a string and has methods to return the value. You could store both string and value as attributes and have two methods to convert between them. Here is a very simple example: >>> class Value: ... def __init__(self, vs = ""): ... self.vs = vs ... self.v = self.asInt() ... def asInt(self): ... try: self.v = int(self.vs) ... except: self.v = None ... return self.v ... def asString(self): ... vs = str(self.vs) ... return self.vs ... def setStringValue(self, s): ... self.vs = s ... self.asInt() ... def setIntValue(self, i): ... self.v = int(i) ... self.vs = str(self.v) ... >>> v = Value('42') >>> print v.v, v.vs 42 42 >>> v.setStringValue('66') >>> print v.v, v.vs 66 66 >>> v.setIntValue(7) >>> print v.v, v.vs 7 7 >>> HTH, Alan G. From alan.gauld at btinternet.com Tue Jan 6 20:57:39 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 6 Jan 2009 19:57:39 -0000 Subject: [Tutor] Interactive programming. References: <4963AD10.4060003@socal.rr.com> Message-ID: "WM." wrote > >>> i = 5 > >>> j = 7 > >>> if i <= j: > print 'nudge, nudge' > else: > > File "", line 3 > else: > ^ > IndentationError: unexpected indent > > Running in IDLE, all is well until "else:". IDLE seems perplexed This is, in my view, a long standing bug in IDLE. It doesn't show indentation properly in the shell window. If possible I'd suggest you try using Pythonwin or PyCrust or IPython or any of the other 3rd party shell windows. If you use them they will typically insert three dots as a secondary prompt which keeps everything lined up properly. The else should align with the if but in Idle it has to align to the left margin because the if is only indented due to >>> prompt! This is confusing, and effectively a bug in my opinion. Your if statement in IDLE should look like: >>> if i <= j: print 'nudge, nudge' else: ie the print should be indented and the else not be. Without the >>> it becomes sane: if i <= j: print 'nudge, nudge' else: -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk From sander.sweers at gmail.com Tue Jan 6 21:16:41 2009 From: sander.sweers at gmail.com (Sander Sweers) Date: Tue, 6 Jan 2009 21:16:41 +0100 Subject: [Tutor] Interactive programming. In-Reply-To: <4963AD10.4060003@socal.rr.com> References: <4963AD10.4060003@socal.rr.com> Message-ID: On Tue, Jan 6, 2009 at 20:12, WM. wrote: >>>> i = 5 >>>> j = 7 >>>> if i <= j: > print 'nudge, nudge' > else: > > File "", line 3 > else: > ^ > IndentationError: unexpected indent Python uses indentation to seperate code blocks and will throw an error if it finds inconsistancies. In your example else is indented while it sould not be. There is also a second error in the code. If you have an else you need to do something in the else block. Below is a working version. >>> i = 5 >>> j = 7 >>> if i <= j: print 'Nudge nudge' else: print 'Icecream' Nudge nudge I know it looks weird in idle as the original if i <= j is to the right of the else but both are *not* indented. Greets Sander From marc.tompkins at gmail.com Tue Jan 6 21:24:07 2009 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Tue, 6 Jan 2009 12:24:07 -0800 Subject: [Tutor] WAYNE'S WANING... Message-ID: <40af687b0901061224n2103cbbbi7a5832c74de99f56@mail.gmail.com> Sorry - forgot to Reply All... On Tue, Jan 6, 2009 at 9:53 AM, WM. wrote: > One of the replies to my post explained how difficult it is to address an > audience composed of several levels of skill. I understand that, nor was I > condemning anyone who has a better command of jargon than I have. Jargon is > essential to any trade. What I wanted to do was give Wayne the POV of > someone who posted for a while, then gave up. I have plenty of questions, I > shall try to put some of them in intelligible form, for your amusement. > One thing that tends to happen here results from the fact that in Python (as in Perl) there's always more than one way to do it, and each method has its enthusiasts. So Original Poster will ask a question - possibly fairly basic - Tutor A will chime in with an answer; Tutor B will chime in with a totally different approach; Tutor C will point out a third way that's more elegant but requires understanding of advanced CS concepts; eventually the thread becomes totally incomprehensible to Original Poster. Please bear with us - we all love the language and want other people to love it too. -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From wferguson1 at socal.rr.com Tue Jan 6 22:10:13 2009 From: wferguson1 at socal.rr.com (WM.) Date: Tue, 06 Jan 2009 13:10:13 -0800 Subject: [Tutor] Interactive programming. In-Reply-To: <4963B3FD.1010504@khine.net> References: <4963AD10.4060003@socal.rr.com> <4963B3FD.1010504@khine.net> Message-ID: <4963C8B5.6070600@socal.rr.com> Norman Khine wrote: > >>> i = 5 > >>> j = 7 > >>> if i <= j: > ... print 'nudge', 'nudge' > ... else: > ... print 'whatever' > ... > nudge nudge > >>> > > > WM. wrote: >> >>> i = 5 >> >>> j = 7 >> >>> if i <= j: >> print 'nudge, nudge' >> else: >> File "", line 3 >> else: >> ^ >> IndentationError: unexpected indent >> >> Running in IDLE, all is well until "else:". IDLE seems perplexed about >> the >>>s. I try to de-dent else via the backspace key, after that >> there is no way to avoid an error message. >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> > > Yes, I understand how your program works. What I do not understand is how you got it. My program came out in IDLE as you see it. No ..., different indentation, an error message before I could add the else alternative. (Which, as a Pythonista, one should know, is "Wink-wink".) From david at abbottdavid.com Wed Jan 7 01:34:28 2009 From: david at abbottdavid.com (David) Date: Tue, 06 Jan 2009 19:34:28 -0500 Subject: [Tutor] Linux tail -f multiple log files Message-ID: <4963F894.4050001@abbottdavid.com> Hi, This works fine if I don't use the -f option; #!/usr/bin/python from subprocess import call from termcolor import colored def slog(): sudo = "sudo" tail = "tail" sfile = "/var/log/messages" print colored("", "blue") call([sudo, tail, sfile]) def alog(): sudo = "sudo" tail = "tail" afile = "/var/log/apache2/access_log" print colored("", "green") call([sudo, tail, afile]) def elog(): sudo = "sudo" tail = "tail" afile = "/var/log/apache2/error_log" print colored("", "red") call([sudo, tail, afile]) def main(): slog() alog() elog() if __name__ == "__main__": main() Now if I do this to all the functions; def slog(): sudo = "sudo" tail = "tail" targ = "-f" # output appended data as the file grows sfile = "/var/log/messages" print colored("", "blue") call([sudo, tail, sfile]) Only the first function will print to the screen. thanks in advance, -david -- Powered by Gentoo GNU/LINUX http://www.linuxcrazy.com pgp.mit.edu From david at abbottdavid.com Wed Jan 7 01:40:50 2009 From: david at abbottdavid.com (David) Date: Tue, 06 Jan 2009 19:40:50 -0500 Subject: [Tutor] Linux tail -f multiple log files In-Reply-To: <4963F894.4050001@abbottdavid.com> References: <4963F894.4050001@abbottdavid.com> Message-ID: <4963FA12.8020507@abbottdavid.com> > > Now if I do this to all the functions; > def slog(): > sudo = "sudo" > tail = "tail" > targ = "-f" # output appended data as the file grows > sfile = "/var/log/messages" > print colored("", "blue") > call([sudo, tail, sfile]) > > Only the first function will print to the screen. > > thanks in advance, > -david > oops should be; def slog(): sudo = "sudo" tail = "tail" targ = "-f" # output appended data as the file grows sfile = "/var/log/messages" print colored("", "blue") call([sudo, tail, targ, sfile]) -- Powered by Gentoo GNU/LINUX http://www.linuxcrazy.com pgp.mit.edu From bill at celestial.net Wed Jan 7 01:46:41 2009 From: bill at celestial.net (Bill Campbell) Date: Tue, 6 Jan 2009 16:46:41 -0800 Subject: [Tutor] Linux tail -f multiple log files In-Reply-To: <4963FA12.8020507@abbottdavid.com> References: <4963F894.4050001@abbottdavid.com> <4963FA12.8020507@abbottdavid.com> Message-ID: <20090107004641.GA12255@ayn.mi.celestial.com> On Tue, Jan 06, 2009, David wrote: >> >> Now if I do this to all the functions; >> def slog(): >> sudo = "sudo" >> tail = "tail" >> targ = "-f" # output appended data as the file grows >> sfile = "/var/log/messages" >> print colored("", "blue") >> call([sudo, tail, sfile]) >> >> Only the first function will print to the screen. >> >> thanks in advance, >> -david >> > oops should be; > def slog(): > sudo = "sudo" > tail = "tail" > targ = "-f" # output appended data as the file grows > sfile = "/var/log/messages" > print colored("", "blue") > call([sudo, tail, targ, sfile]) Looking at how swatch does this I think the command you want to use is: cmd = 'sudo tail --follow=name --lines=1 %s' % ' '.join(args) tail = os.popen(cmd) # process output ... Bill -- INTERNET: bill at celestial.com Bill Campbell; Celestial Software LLC URL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way Voice: (206) 236-1676 Mercer Island, WA 98040-0820 Fax: (206) 232-9186 It does not require a majority to prevail, but rather an irate, tireless minority keen to set brush fires in people's minds. -- Samuel Adams From kent37 at tds.net Wed Jan 7 03:10:50 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 6 Jan 2009 21:10:50 -0500 Subject: [Tutor] Linux tail -f multiple log files In-Reply-To: <4963F894.4050001@abbottdavid.com> References: <4963F894.4050001@abbottdavid.com> Message-ID: <1c2a2c590901061810pe13046bl8586c107cc3f09c5@mail.gmail.com> On Tue, Jan 6, 2009 at 7:34 PM, David wrote: > Hi, > This works fine if I don't use the -f option; > #!/usr/bin/python > from subprocess import call > from termcolor import colored > > def slog(): > sudo = "sudo" > tail = "tail" > sfile = "/var/log/messages" > print colored("", "blue") > call([sudo, tail, sfile]) > > > def alog(): > sudo = "sudo" > tail = "tail" > afile = "/var/log/apache2/access_log" > print colored("", "green") > call([sudo, tail, afile]) > > def elog(): > sudo = "sudo" > tail = "tail" > afile = "/var/log/apache2/error_log" > print colored("", "red") > call([sudo, tail, afile]) > > def main(): > slog() > alog() > elog() > > if __name__ == "__main__": > main() > > Now if I do this to all the functions; > def slog(): > sudo = "sudo" > tail = "tail" > targ = "-f" # output appended data as the file grows > sfile = "/var/log/messages" > print colored("", "blue") > call([sudo, tail, sfile]) > > Only the first function will print to the screen. subprocess.call() does not return until the spawned process terminates. tail -f does not terminate so the later functions are never called. You need to use a non-blocking operation to spawn the subprocess. Kent From wormwood_3 at yahoo.com Wed Jan 7 04:18:12 2009 From: wormwood_3 at yahoo.com (wormwood_3) Date: Tue, 6 Jan 2009 19:18:12 -0800 (PST) Subject: [Tutor] Getting multi-line input from user Message-ID: <769354.18027.qm@web110814.mail.gq1.yahoo.com> Hello everyone, I'd like to prompt the user for input and get back multiple lines, for example if someone wanted to enter a few paragraphs. Then I'd like to be able to print their input out and preserve formatting. Here's what I have so far: control = True user_input = [] while control: if not user_input: entry = raw_input("Enter text, 'done' on its own line to quit: \n") user_input.append(entry) else: entry = raw_input("") user_input.append(entry) if entry == "done": del user_input[-1] control = False user_input = ' '.join(user_input) print user_input So you end up with: Enter text, 'done' on its own line to quit: I am some text. And I am more. I am a new paragraph. done I am some text. And I am more. I am a new paragraph. 1) Is there a more elegant/common way to get multi-line user input than this sort of thing? 2) How can I combine and print the output so that paragraphs and the like are preserved? Thanks, Sam _______________________ Samuel Huckins Homepage - http://samuelhuckins.com Tech blog - http://dancingpenguinsoflight.com/ Photos - http://www.flickr.com/photos/samuelhuckins/ AIM - samushack | Gtalk - samushack | Skype - shuckins -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Wed Jan 7 04:24:26 2009 From: bgailer at gmail.com (bob gailer) Date: Tue, 06 Jan 2009 22:24:26 -0500 Subject: [Tutor] Getting multi-line input from user In-Reply-To: <769354.18027.qm@web110814.mail.gq1.yahoo.com> References: <769354.18027.qm@web110814.mail.gq1.yahoo.com> Message-ID: <4964206A.7060500@gmail.com> wormwood_3 wrote: > Hello everyone, > > I'd like to prompt the user for input and get back multiple lines, for > example if someone wanted to enter a few paragraphs. Then I'd like to > be able to print their input out and preserve formatting. Here's what > I have so far: > > control = True > user_input = [] > while control: > if not user_input: > entry = raw_input("Enter text, 'done' on its own line to quit: > \n") > user_input.append(entry) > else: > entry = raw_input("") > user_input.append(entry) > if entry == "done": > del user_input[-1] > control = False > user_input = ' '.join(user_input) > print user_input > > So you end up with: > > Enter text, 'done' on its own line to quit: > I am some text. > And I am more. > > I am a new paragraph. > done > I am some text. And I am more. I am a new paragraph. > > 1) Is there a more elegant/common way to get multi-line user input > than this sort of thing? For starters you can simplify things a lot: user_input = [] entry = raw_input("Enter text, 'done' on its own line to quit: \n") while entry != "done": user_input.append(entry) entry = raw_input("") user_input = ' '.join(user_input) print user_input > 2) How can I combine and print the output so that paragraphs and the > like are preserved? I don't understand. Please give an example. -- Bob Gailer Chapel Hill NC 919-636-4239 From wormwood_3 at yahoo.com Wed Jan 7 04:31:59 2009 From: wormwood_3 at yahoo.com (wormwood_3) Date: Tue, 6 Jan 2009 19:31:59 -0800 (PST) Subject: [Tutor] Getting multi-line input from user References: <769354.18027.qm@web110814.mail.gq1.yahoo.com> <4964206A.7060500@gmail.com> Message-ID: <594795.97475.qm@web110807.mail.gq1.yahoo.com> >>> For starters you can simplify things a lot: >>> >>> user_input = [] >>> entry = raw_input("Enter text, 'done' on its own line to quit: \n") >>> while entry != "done": >>> user_input.append(entry) >>> entry = raw_input("") >>> user_input = ' '.join(user_input) >>> print user_input >>> >>> 2) How can I combine and print the output so that paragraphs and the like are preserved? >>> >>> I don't understand. Please give an example. That is much cleaner, thanks! On point 2, say I enter: Enter text, 'done' on its own line to quit: I am a sentence. I am another sentence. I am a new paragraph. done What I get out is: I am a sentence. I am another sentence. I am a new paragraph. But that just shows the double new lines of my new paragraph as an extra space. I'd like to print it out so it appears just as it was typed in, with appropriate newlines. -Sam -------------- next part -------------- An HTML attachment was scrubbed... URL: From andreengels at gmail.com Wed Jan 7 07:19:23 2009 From: andreengels at gmail.com (Andre Engels) Date: Wed, 7 Jan 2009 07:19:23 +0100 Subject: [Tutor] Getting multi-line input from user In-Reply-To: <594795.97475.qm@web110807.mail.gq1.yahoo.com> References: <769354.18027.qm@web110814.mail.gq1.yahoo.com> <4964206A.7060500@gmail.com> <594795.97475.qm@web110807.mail.gq1.yahoo.com> Message-ID: <6faf39c90901062219o66cfd382p7b3c00199a1addd3@mail.gmail.com> On Wed, Jan 7, 2009 at 4:31 AM, wormwood_3 wrote: > On point 2, say I enter: > Enter text, 'done' on its own line to quit: > I am a sentence. I am another sentence. > > I am a new paragraph. > done > > What I get out is: > I am a sentence. I am another sentence. I am a new paragraph. > > But that just shows the double new lines of my new paragraph as an extra > space. I'd like to print it out so it appears just as it was typed in, with > appropriate newlines. The newline character is written \n in Python, so if you replace ' '.join(user_input) by '\n'.join(user_input) you should be getting what you want. -- Andr? Engels, andreengels at gmail.com From prasadaraon50 at gmail.com Wed Jan 7 09:45:57 2009 From: prasadaraon50 at gmail.com (prasad rao) Date: Wed, 7 Jan 2009 00:45:57 -0800 Subject: [Tutor] Convert values in a list back and forth from ints Message-ID: <9e3fac840901070045vdbe1cabv97648e12def79dda@mail.gmail.com> .>>>> class Value:.... def __init__(self, vs = ""): >... self.vs = vs >... self.v = self.asInt() >... def asInt(self): >... try: self.v = int(self.vs) >... except: self.v = None >... return self.v >... def asString(self): >... vs = str(self.vs) >... return self.vs >... def setStringValue(self, s): >... self.vs = s >... self.asInt() >... def setIntValue(self, i): >... self.v = int(i) >... self.vs = str(self.v) hello Sorry to interject. This class seems asymmetric. Class Value: def __init__(self,inte='',stri=''): self.inte=inte self.stri=stri def setvalue(inte='',stri=''): self.stri=str(self.inte) self.int=int(self.stri) I tried. But failed.What is wrong with above code? >>> Class Value: def __init__(self,inte='',stri=''): self.inte=inte self.stri=stri def setvalue(inte='',stri=''): self.stri=str(self.inte) self.int=int(self.stri) SyntaxError: invalid syntax Prasad -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Wed Jan 7 09:56:21 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 7 Jan 2009 08:56:21 -0000 Subject: [Tutor] Getting multi-line input from user References: <769354.18027.qm@web110814.mail.gq1.yahoo.com><4964206A.7060500@gmail.com> <594795.97475.qm@web110807.mail.gq1.yahoo.com> Message-ID: "wormwood_3" wrote > On point 2, say I enter: > Enter text, 'done' on its own line to quit: > I am a sentence. I am another sentence. > > I am a new paragraph. > done > > What I get out is: > I am a sentence. I am another sentence. I am a new paragraph. > > But that just shows the double new lines of my new paragraph as an > extra space. raw_input strips off the newline character created by Enter. You need to add it back in: entry = raw_input() user_input.append(entry+'\n') HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk From alan.gauld at btinternet.com Wed Jan 7 09:58:18 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 7 Jan 2009 08:58:18 -0000 Subject: [Tutor] Getting multi-line input from user References: <769354.18027.qm@web110814.mail.gq1.yahoo.com><4964206A.7060500@gmail.com><594795.97475.qm@web110807.mail.gq1.yahoo.com> <6faf39c90901062219o66cfd382p7b3c00199a1addd3@mail.gmail.com> Message-ID: "Andre Engels" wrote > The newline character is written \n in Python, so if you replace > > ' '.join(user_input) > > by > > '\n'.join(user_input) Yep, that's better than my suggestion of adding the \n at append time. :-) Alan G. From marco.m.petersen at gmail.com Tue Jan 6 10:45:01 2009 From: marco.m.petersen at gmail.com (Marco Petersen) Date: Tue, 06 Jan 2009 17:45:01 +0800 Subject: [Tutor] SMTP Module Help Message-ID: <4963281D.9070009@gmail.com> I'm using Python 2.5.4. I wanted to try out the SMTP module. I tried to send an email through my Gmail account but it keeps saying that the connection was refused. This is the code that I used : import smtplib msg = 'Test' server = smtplib.SMTP('smtp.gmail.com') server.set_debuglevel(1) server.ehlo() server.starttls() server.ehlo() server.login('marco.m.petersen at gmail.com', 'password') server.sendmail('marco.m.petersen at gmail.com', 'marcoleepetersen at gmail.com', msg) server.close() This error message keeps coming up: Traceback (most recent call last): File "C:/Python25/send_mail.py", line 5, in server = smtplib.SMTP('smtp.gmail.com') File "C:\Python25\Lib\smtplib.py", line 244, in __init__ (code, msg) = self.connect(host, port) File "C:\Python25\Lib\smtplib.py", line 310, in connect raise socket.error, msg error: (10061, 'Connection refused') Can anyone help me with this? Thanks. -Marco From andreengels at gmail.com Wed Jan 7 10:51:56 2009 From: andreengels at gmail.com (Andre Engels) Date: Wed, 7 Jan 2009 10:51:56 +0100 Subject: [Tutor] Convert values in a list back and forth from ints In-Reply-To: <9e3fac840901070045vdbe1cabv97648e12def79dda@mail.gmail.com> References: <9e3fac840901070045vdbe1cabv97648e12def79dda@mail.gmail.com> Message-ID: <6faf39c90901070151u13410945m962a5cf7290bcbfb@mail.gmail.com> On Wed, Jan 7, 2009 at 9:45 AM, prasad rao wrote: > hello > Sorry to interject. > This class seems asymmetric. > Class Value: > def __init__(self,inte='',stri=''): > self.inte=inte > self.stri=stri > def setvalue(inte='',stri=''): > self.stri=str(self.inte) > self.int=int(self.stri) > I tried. But failed.What is wrong with above code? > > >>> Class Value: > def __init__(self,inte='',stri=''): > self.inte=inte > self.stri=stri > def setvalue(inte='',stri=''): > self.stri=str(self.inte) > self.int=int(self.stri) > > SyntaxError: invalid syntax 'class' should not start with a capital. I do by the way wonder what your code is supposed to accomplish - why have arguments inte and stri for setvalue when you don't use them (you use the existing value of self.stri). -- Andr? Engels, andreengels at gmail.com From prasadaraon50 at gmail.com Wed Jan 7 10:57:35 2009 From: prasadaraon50 at gmail.com (prasad rao) Date: Wed, 7 Jan 2009 01:57:35 -0800 Subject: [Tutor] re Message-ID: <9e3fac840901070157p5b15d256g40db2be09611e61d@mail.gmail.com> Hello I am trying to get a value as integer and a string. >>> class Value: def __init__(self,inte='',stri=''): self.inte=inte self.stri=stri def setvalue(self,inte='',stri=''): self.stri=str(self.inte) self.inte=int(self.stri) >>> v=Value(45) >>> print v.stri >>> v.inte 45 >>> v.stri '' >>> c=Value('36') >>> c.stri '' >>> But it is not converting.How can I do it? Prasad -------------- next part -------------- An HTML attachment was scrubbed... URL: From KLegodi at csir.co.za Wed Jan 7 10:46:05 2009 From: KLegodi at csir.co.za (Kgotlelelo Legodi) Date: Wed, 07 Jan 2009 11:46:05 +0200 Subject: [Tutor] good day Message-ID: <496495FD0200004000022646@pta-emo.csir.co.za> good day I just started using python and i want to know how can i solve a boundary value problem for ordinary differential equations using shooting method in python.use the general equation to demonstrate the python code. Thank you -- This message is subject to the CSIR's copyright terms and conditions, e-mail legal notice, and implemented Open Document Format (ODF) standard. The full disclaimer details can be found at http://www.csir.co.za/disclaimer.html. This message has been scanned for viruses and dangerous content by MailScanner, and is believed to be clean. MailScanner thanks Transtec Computers for their support. From andreengels at gmail.com Wed Jan 7 11:09:51 2009 From: andreengels at gmail.com (Andre Engels) Date: Wed, 7 Jan 2009 11:09:51 +0100 Subject: [Tutor] re In-Reply-To: <9e3fac840901070157p5b15d256g40db2be09611e61d@mail.gmail.com> References: <9e3fac840901070157p5b15d256g40db2be09611e61d@mail.gmail.com> Message-ID: <6faf39c90901070209r17c0ec27s138d4f2034747c44@mail.gmail.com> On Wed, Jan 7, 2009 at 10:57 AM, prasad rao wrote: > Hello > I am trying to get a value as integer and a string. >>>> class Value: > def __init__(self,inte='',stri=''): > self.inte=inte > self.stri=stri > def setvalue(self,inte='',stri=''): > self.stri=str(self.inte) > self.inte=int(self.stri) > >>>> v=Value(45) >>>> print v.stri >>>> v.inte > 45 >>>> v.stri > '' >>>> c=Value('36') >>>> c.stri > '' >>>> > But it is not converting.How can I do it? > Prasad > Let's take a step back, and see what is happening here. >>>> v=Value(45) This means that you create a Value object. If you create an object, its __init__ is called. What does that ini look like? def __init__(self,inte='',stri='') We disregard the 'self' for now, and look at the other arguments. The _first_ argument of your function will be mapped to inte, the second to stri. In this case you have only one argument, so this argument (45) will be mapped to inte, and stri will take its default value (which is '') > self.inte=inte > self.stri=stri So after this, self.inte will be set to inte (that is 45), and self.stri to stri (that is ''). Which indeed is exactly what you get when you look up v.inte and v.stri. >>>> c=Value('36') If we go through the analysis above, you will find that after this c.inte = '36' c.stri = '' What would you _want_ to do? I think what you want is the following: you give a single argument, which can either be an integer or a string representing an integer, and the local variables inte and string should then give the integer and string representation of that argument. This can be done in the following way: class Value: def __init__(self,val): # I do not add a default value for val, because I will always call Value(somevalue), not Value() self.inte = int(val) # Whether val is a string or an integer, this will be its integer representation self.stri = str(val) # similar (when typing this in you can of course do without the #s and whatever I have written after that) -- Andr? Engels, andreengels at gmail.com From a.t.hofkamp at tue.nl Wed Jan 7 11:28:29 2009 From: a.t.hofkamp at tue.nl (A.T.Hofkamp) Date: Wed, 07 Jan 2009 11:28:29 +0100 Subject: [Tutor] Interactive programming. In-Reply-To: <4963C8B5.6070600@socal.rr.com> References: <4963AD10.4060003@socal.rr.com> <4963B3FD.1010504@khine.net> <4963C8B5.6070600@socal.rr.com> Message-ID: <496483CD.3040806@tue.nl> WM. wrote: > Norman Khine wrote: >> >>> i = 5 >> >>> j = 7 >> >>> if i <= j: >> ... print 'nudge', 'nudge' >> ... else: >> ... print 'whatever' >> ... >> nudge nudge >> >>> > Yes, I understand how your program works. What I do not understand is > how you got it. My program came out in IDLE as you see it. No ..., > different indentation, an error message before I could add the else > alternative. (Which, as a Pythonista, one should know, is "Wink-wink".) In IDLE in the window with the ">>>" prompt: After the colon at the 'if' line, you press ENTER (ie you tell Python 'the line has ended here'). The interpreter then supplies the "..." to denote that you are entering a multi-line statement. You then continue entering the next lines (with some indenting for both branches!!), pressing ENTER after each line. At the end (just above the "nudge nudge" output), Python also gives a "..." prompt, to give you the option to enter more statements under the last print. Since you don't have any more statements, just press ENTER (saying, 'I am finished'). Then Python will execute the complete if statement (and one of the branches), and output the result. The normal approach however for entering a program is to use an editor window. Click on 'new file' somewhere in IDLE (I am not an IDLE user nor do I have the program around, so I cannot give you more precise directions unfortunately), and enter the Python program without the ">>>" and "..." stuff at the start of the line. Once you are finished, save it, and press 'run' (it is in a menu somewhere if I remember correctly). Then the Python interpreter will run all statements in the file. With this approach you can also load (and run) previous made programs (which is a quite useful feature, I might add :) ). (Instead of 'new file', use 'load file' or 'edit file'). Good luck, Albert From a.t.hofkamp at tue.nl Wed Jan 7 11:35:23 2009 From: a.t.hofkamp at tue.nl (A.T.Hofkamp) Date: Wed, 07 Jan 2009 11:35:23 +0100 Subject: [Tutor] good day In-Reply-To: <496495FD0200004000022646@pta-emo.csir.co.za> References: <496495FD0200004000022646@pta-emo.csir.co.za> Message-ID: <4964856B.5050005@tue.nl> Kgotlelelo Legodi wrote: > good day > > I just started using python and i want to know how can i solve a boundary value problem for ordinary differential equations using shooting method in python.use the general equation to demonstrate the python code. I have no background in numeric calculations, but for starters, you may want to investigate the numpy and/or scipy Python packages. Google will probably also give you good starting points of existing numeric code/libraries. As for actually writing the program, I am afraid you'll have to do that yourself. Sincerely, Albert From a.t.hofkamp at tue.nl Wed Jan 7 11:49:25 2009 From: a.t.hofkamp at tue.nl (A.T.Hofkamp) Date: Wed, 07 Jan 2009 11:49:25 +0100 Subject: [Tutor] SMTP Module Help In-Reply-To: <4963281D.9070009@gmail.com> References: <4963281D.9070009@gmail.com> Message-ID: <496488B5.9040206@tue.nl> Marco Petersen wrote: > I'm using Python 2.5.4. I wanted to try out the SMTP module. I tried to > send an email through my Gmail account but it keeps saying that the > connection was refused. > > This is the code that I used : > > import smtplib > msg = 'Test' > > > server = smtplib.SMTP('smtp.gmail.com') > server.set_debuglevel(1) > server.ehlo() > server.starttls() > server.ehlo() > server.login('marco.m.petersen at gmail.com', 'password') > server.sendmail('marco.m.petersen at gmail.com', > 'marcoleepetersen at gmail.com', msg) > server.close() > > This error message keeps coming up: > > > Traceback (most recent call last): > File "C:/Python25/send_mail.py", line 5, in > server = smtplib.SMTP('smtp.gmail.com') > File "C:\Python25\Lib\smtplib.py", line 244, in __init__ > (code, msg) = self.connect(host, port) > File "C:\Python25\Lib\smtplib.py", line 310, in connect > raise socket.error, msg > error: (10061, 'Connection refused') 'Connection refused' usually means that the other side doesn't like you for some reason. (In other words, it doesn't look like a Python problem but like a network problem.) Since it happens before you can start the protocol, my guess is that smtp.gmail.com does not accept your machine as valid to speak SMTP with (at least not at the port you are trying). The person to talk to would be the owner/admin of smtp.gmail.com. Sincerely, Albert From david at hlacik.eu Wed Jan 7 11:59:05 2009 From: david at hlacik.eu (=?ISO-8859-2?Q?David_Hl=E1=E8ik?=) Date: Wed, 7 Jan 2009 11:59:05 +0100 Subject: [Tutor] linked list with cycle structure In-Reply-To: References: Message-ID: Hello guys, I have a linked list where *number of elements is unlimited* and **last element points on random (can be first, last, in middle , anywhere) element within linked list** - this is important . My goals is to create an architecture /scheme for **algoritmus which will count total number of elements** of such linked list. Yes , maybe it sounds strange, but we need to implement this and i would be very gladfull for your toughts. Thanks in advance and wishing you a sucessfull year! David From mickmick at hotmail.co.uk Wed Jan 7 07:06:30 2009 From: mickmick at hotmail.co.uk (mickth) Date: Tue, 6 Jan 2009 22:06:30 -0800 (PST) Subject: [Tutor] Brand new to python have simple problem Message-ID: <21325502.post@talk.nabble.com> I'm brand new to python and every time i start to learn it i get the same problem and end up giving up and moving on to another language. the print statement doesn't work in either the comand line or IDLE i get this in IDLE: SyntaxError: invalid syntax (, line 1) and just SyntaxError: invalid syntax in the command line. Even doing the hello world or doing simple sums. If I type "hello, world" i get the right outcome but print "Hello world" i get the error. When i type print it's purple in IDLE if that means anything. I've tried reinstalling python and tried an earlier version with same results. i'm running windows vista home prem 32bit I know i may seem an imbecile for posting such a simple thing but i'm determined to learn it this time i've already learnt vb and C and want to broaden out! Thanks for any help -- View this message in context: http://www.nabble.com/Brand-new-to-python-have-simple-problem-tp21325502p21325502.html Sent from the Python - tutor mailing list archive at Nabble.com. From iamscifius at yahoo.com Wed Jan 7 07:39:38 2009 From: iamscifius at yahoo.com (Michael Lam) Date: Tue, 6 Jan 2009 22:39:38 -0800 (PST) Subject: [Tutor] Opening a window to fit an image Message-ID: <708336.86242.qm@web111316.mail.gq1.yahoo.com> I got a similar problem, except that calling it twice wouldn't work for me. I tried looking everywhere and I seemed to be doing everything exactly like other people..... After fiddling around, I got this order: pygame.init() pygame.display.set_icon(pygame.image.load("image.bmp")) window = pygame.display.set_mode((640, 480 pygame.display.set_caption('Caption') Something wrong with using Surface.convert() as I originally used a load_image() function that did that. Michael From kent37 at tds.net Wed Jan 7 12:32:01 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 7 Jan 2009 06:32:01 -0500 Subject: [Tutor] Interactive programming. In-Reply-To: <496483CD.3040806@tue.nl> References: <4963AD10.4060003@socal.rr.com> <4963B3FD.1010504@khine.net> <4963C8B5.6070600@socal.rr.com> <496483CD.3040806@tue.nl> Message-ID: <1c2a2c590901070332o5807c4d3pffee564834ffb2bf@mail.gmail.com> On Wed, Jan 7, 2009 at 5:28 AM, A.T.Hofkamp wrote: > WM. wrote: >> >> Norman Khine wrote: >>> >>> >>> i = 5 >>> >>> j = 7 >>> >>> if i <= j: >>> ... print 'nudge', 'nudge' >>> ... else: >>> ... print 'whatever' >>> ... >>> nudge nudge >>> >>> > >> Yes, I understand how your program works. What I do not understand is how >> you got it. My program came out in IDLE as you see it. No ..., different >> indentation, an error message before I could add the else alternative. >> (Which, as a Pythonista, one should know, is "Wink-wink".) > > In IDLE in the window with the ">>>" prompt: > > After the colon at the 'if' line, you press ENTER (ie you tell Python 'the > line has ended here'). > The interpreter then supplies the "..." to denote that you are entering a > multi-line statement. No, IDLE does not supply the ..., that is the source of the confusion. If you use the interpreter directly from a command/terminal window it will supply the ... continuation prompt but the IDLE shell will not. Kent From KLegodi at csir.co.za Wed Jan 7 12:31:52 2009 From: KLegodi at csir.co.za (Kgotlelelo Legodi) Date: Wed, 07 Jan 2009 13:31:52 +0200 Subject: [Tutor] shooting method in python code Message-ID: <4964AEC8020000400002267D@pta-emo.csir.co.za> good day I just started using python and i want to know how can i solve a boundary value problem for ordinary differential equations using shooting method in python.use the general equation to demonstrate the python code. Thank you Kgotlelelo Legodi Natural Resources and the Environment CSIR 012 841 3402 (Tel) 012 841 4322 (Fax) 072 344 3846 (Cell) KLegod at csir.co.za -- This message is subject to the CSIR's copyright terms and conditions, e-mail legal notice, and implemented Open Document Format (ODF) standard. The full disclaimer details can be found at http://www.csir.co.za/disclaimer.html. This message has been scanned for viruses and dangerous content by MailScanner, and is believed to be clean. MailScanner thanks Transtec Computers for their support. From a.t.hofkamp at tue.nl Wed Jan 7 12:46:07 2009 From: a.t.hofkamp at tue.nl (A.T.Hofkamp) Date: Wed, 07 Jan 2009 12:46:07 +0100 Subject: [Tutor] linked list with cycle structure In-Reply-To: References: Message-ID: <496495FF.9050509@tue.nl> David Hl??ik wrote: > Hello guys, > > I have a linked list where *number of elements is unlimited* and > **last element points on random (can be first, last, in middle , > anywhere) element within linked list** - this is important . My goals > is to create an architecture /scheme for **algoritmus which will count > total number of elements** of such linked list. > Yes , maybe it sounds strange, but we need to implement this and i > would be very gladfull for your toughts. Python supplies a list data structure for you, so in 'normal' Python, you wouldn't bother with linked lists and all the assoicated problems. However, if you really want: Make a class for a list-element, with a next/prev variable (if you have a double-linked list). Instantiate as many objects as you like from that class, and let the next/prev variables from one object refer to other objects that you instantiated. (Python doesn't care where a variable refers to.) For the NULL value you can use None. Sincerely, Albert From andreengels at gmail.com Wed Jan 7 12:48:09 2009 From: andreengels at gmail.com (Andre Engels) Date: Wed, 7 Jan 2009 12:48:09 +0100 Subject: [Tutor] Brand new to python have simple problem In-Reply-To: <21325502.post@talk.nabble.com> References: <21325502.post@talk.nabble.com> Message-ID: <6faf39c90901070348ide09b5fk83131f618abce10b@mail.gmail.com> On Wed, Jan 7, 2009 at 7:06 AM, mickth wrote: > > I'm brand new to python and every time i start to learn it i get the same > problem and end up giving up and moving on to another language. > > the print statement doesn't work in either the comand line or IDLE i get > this in IDLE: > SyntaxError: invalid syntax (, line 1) > > and just SyntaxError: invalid syntax in the command line. > > Even doing the hello world or doing simple sums. If I type "hello, world" i > get the right outcome but print "Hello world" i get the error. When i type > print it's purple in IDLE if that means anything. > > I've tried reinstalling python and tried an earlier version with same > results. i'm running windows vista home prem 32bit > > I know i may seem an imbecile for posting such a simple thing but i'm > determined to learn it this time i've already learnt vb and C and want to > broaden out! Could you please give an exact copy (both your commands and the reactions, with copy and paste) of the idle session that leads to the error message? Here is what I get (working), you might be able to find from this where it goes wrong, but if not, please show what you get so we can look at it: >>> "Hello world" 'Hello world' >>> print "Hello world" Hello world >>> -- Andr? Engels, andreengels at gmail.com From kent37 at tds.net Wed Jan 7 12:48:32 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 7 Jan 2009 06:48:32 -0500 Subject: [Tutor] good day In-Reply-To: <496495FD0200004000022646@pta-emo.csir.co.za> References: <496495FD0200004000022646@pta-emo.csir.co.za> Message-ID: <1c2a2c590901070348n1e6877d6y3b5cf2960edfa1fc@mail.gmail.com> On Wed, Jan 7, 2009 at 4:46 AM, Kgotlelelo Legodi wrote: > good day > > I just started using python and i want to know how can i solve a boundary value problem for ordinary differential equations using shooting method in python.use the general equation to demonstrate the python code. Googling "python boundary value problem" finds these: http://books.google.com/books?id=WiDie-hev1kC&pg=PA295&lpg=PA295&dq=python+boundary+value+problem&source=web&ots=naWIAjsXpq&sig=lw9U0c-lQe1rUtlWv8W0cKXUGHI&hl=en&sa=X&oi=book_result&resnum=1&ct=result#PPA295,M1 http://lbolla.wordpress.com/2008/04/14/bvp/ http://www.scilab.org/doc/manual/Docu-html659.html http://projects.scipy.org/pipermail/scipy-user/2006-October/009483.html Kent From kent37 at tds.net Wed Jan 7 12:54:56 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 7 Jan 2009 06:54:56 -0500 Subject: [Tutor] SMTP Module Help In-Reply-To: <4963281D.9070009@gmail.com> References: <4963281D.9070009@gmail.com> Message-ID: <1c2a2c590901070354p7a519612j4ff12e6db1e44c08@mail.gmail.com> On Tue, Jan 6, 2009 at 4:45 AM, Marco Petersen wrote: > I'm using Python 2.5.4. I wanted to try out the SMTP module. I tried to send > an email through my Gmail account but it keeps saying that the connection > was refused. > > This is the code that I used : > > import smtplib > msg = 'Test' > > > server = smtplib.SMTP('smtp.gmail.com') >From the docs here http://mail.google.com/support/bin/answer.py?answer=77662 Google SMTP uses port 587, not the standard SMTP port 25. Try server = smtplib.SMTP('smtp.gmail.com', 587) Kent From a.t.hofkamp at tue.nl Wed Jan 7 12:56:28 2009 From: a.t.hofkamp at tue.nl (A.T.Hofkamp) Date: Wed, 07 Jan 2009 12:56:28 +0100 Subject: [Tutor] Interactive programming. In-Reply-To: <1c2a2c590901070332o5807c4d3pffee564834ffb2bf@mail.gmail.com> References: <4963AD10.4060003@socal.rr.com> <4963B3FD.1010504@khine.net> <4963C8B5.6070600@socal.rr.com> <496483CD.3040806@tue.nl> <1c2a2c590901070332o5807c4d3pffee564834ffb2bf@mail.gmail.com> Message-ID: <4964986C.9070309@tue.nl> Kent Johnson wrote: > On Wed, Jan 7, 2009 at 5:28 AM, A.T.Hofkamp wrote: >> WM. wrote: >>> Norman Khine wrote: >>>> >>> i = 5 >>>> >>> j = 7 >>>> >>> if i <= j: >>>> ... print 'nudge', 'nudge' >>>> ... else: >>>> ... print 'whatever' >>>> ... >>>> nudge nudge >>>> >>> >>> Yes, I understand how your program works. What I do not understand is how >>> you got it. My program came out in IDLE as you see it. No ..., different >>> indentation, an error message before I could add the else alternative. >>> (Which, as a Pythonista, one should know, is "Wink-wink".) >> In IDLE in the window with the ">>>" prompt: >> >> After the colon at the 'if' line, you press ENTER (ie you tell Python 'the >> line has ended here'). >> The interpreter then supplies the "..." to denote that you are entering a >> multi-line statement. > > No, IDLE does not supply the ..., that is the source of the confusion. > > If you use the interpreter directly from a command/terminal window it > will supply the ... continuation prompt but the IDLE shell will not. Thank you Kent, I didn't know that. The story stays the same, except that you don't get the "... " from Python. That means that the second line and further are all shifted 4 positions to the left, so you'd need to enter something like: >>> i = 5 >>> j = 7 >>> if i <= j: print 'nudge', 'nudge' else: print 'whatever' I agree that this is highly confusing. The best solution is probably to use the editor window instead, and save/run your programs from there. Sincerely, Albert From kent37 at tds.net Wed Jan 7 12:57:21 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 7 Jan 2009 06:57:21 -0500 Subject: [Tutor] linked list with cycle structure In-Reply-To: References: Message-ID: <1c2a2c590901070357s728c7b09ydabbd6fc41bf79d5@mail.gmail.com> On Wed, Jan 7, 2009 at 5:59 AM, David Hl??ik wrote: > Hello guys, > > I have a linked list where *number of elements is unlimited* and > **last element points on random (can be first, last, in middle , > anywhere) element within linked list** - this is important . My goals > is to create an architecture /scheme for **algoritmus which will count > total number of elements** of such linked list. So the list is effectively endless because it has a cycle? You could walk the list, adding elements (or their ids) to a set, stopping when you get to an element that is in the set already. Then the size of the set is the size of the list. Kent From kent37 at tds.net Wed Jan 7 13:00:33 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 7 Jan 2009 07:00:33 -0500 Subject: [Tutor] Brand new to python have simple problem In-Reply-To: <21325502.post@talk.nabble.com> References: <21325502.post@talk.nabble.com> Message-ID: <1c2a2c590901070400n294205fbg9872504eb83387cf@mail.gmail.com> On Wed, Jan 7, 2009 at 1:06 AM, mickth wrote: > > I'm brand new to python and every time i start to learn it i get the same > problem and end up giving up and moving on to another language. > > the print statement doesn't work in either the comand line or IDLE i get > this in IDLE: > SyntaxError: invalid syntax (, line 1) > > and just SyntaxError: invalid syntax in the command line. > > Even doing the hello world or doing simple sums. If I type "hello, world" i > get the right outcome but print "Hello world" i get the error. When i type > print it's purple in IDLE if that means anything. What version of Python are you using? In Python 3.0, print is a function, not a statement, so you need parentheses: print("Hello world") Most Python books and tutorials are written for Python 2.x. Make sure your references match the Python version you are using, there are significant changes in 3.0. Kent From wormwood_3 at yahoo.com Wed Jan 7 13:57:29 2009 From: wormwood_3 at yahoo.com (wormwood_3) Date: Wed, 7 Jan 2009 04:57:29 -0800 (PST) Subject: [Tutor] Getting multi-line input from user References: <769354.18027.qm@web110814.mail.gq1.yahoo.com><4964206A.7060500@gmail.com><594795.97475.qm@web110807.mail.gq1.yahoo.com> <6faf39c90901062219o66cfd382p7b3c00199a1addd3@mail.gmail.com> Message-ID: <585915.34965.qm@web110808.mail.gq1.yahoo.com> Joining with newline works perfectly. Thanks everyone! _______________________ Samuel Huckins Homepage - http://samuelhuckins.com Tech blog - http://dancingpenguinsoflight.com/ Photos - http://www.flickr.com/photos/samuelhuckins/ AIM - samushack | Gtalk - samushack | Skype - shuckins ________________________________ From: Alan Gauld To: tutor at python.org Sent: Wednesday, January 7, 2009 3:58:18 AM Subject: Re: [Tutor] Getting multi-line input from user "Andre Engels" wrote > The newline character is written \n in Python, so if you replace > > ' '.join(user_input) > > by > > '\n'.join(user_input) Yep, that's better than my suggestion of adding the \n at append time. :-) Alan G. _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjampman at gmail.com Wed Jan 7 15:47:25 2009 From: tjampman at gmail.com (Ole Henning Jensen) Date: Wed, 07 Jan 2009 15:47:25 +0100 Subject: [Tutor] SMTP Module Help In-Reply-To: <4963281D.9070009@gmail.com> References: <4963281D.9070009@gmail.com> Message-ID: <4964C07D.3050607@gmail.com> Marco Petersen wrote: > I'm using Python 2.5.4. I wanted to try out the SMTP module. I tried to > send an email through my Gmail account but it keeps saying that the > connection was refused. > > This is the code that I used : > > import smtplib > msg = 'Test' > > > server = smtplib.SMTP('smtp.gmail.com') > server.set_debuglevel(1) > server.ehlo() > server.starttls() > server.ehlo() > server.login('marco.m.petersen at gmail.com', 'password') > server.sendmail('marco.m.petersen at gmail.com', > 'marcoleepetersen at gmail.com', msg) > server.close() > > This error message keeps coming up: > > > Traceback (most recent call last): > File "C:/Python25/send_mail.py", line 5, in > server = smtplib.SMTP('smtp.gmail.com') > File "C:\Python25\Lib\smtplib.py", line 244, in __init__ > (code, msg) = self.connect(host, port) > File "C:\Python25\Lib\smtplib.py", line 310, in connect > raise socket.error, msg > error: (10061, 'Connection refused') > > > Can anyone help me with this? > I must admit that I know nothing of the SMTP module, but I do know that with gmail you need to use an SSL secure connection on port 995. I doesn't seem to be aplied in your script as far as I can tell. Best Regards Ole From alpanachaturvedi at yahoo.com Wed Jan 7 16:14:43 2009 From: alpanachaturvedi at yahoo.com (CHATURVEDI ALPANA) Date: Wed, 7 Jan 2009 07:14:43 -0800 (PST) Subject: [Tutor] New to tkSnack In-Reply-To: Message-ID: <418961.90915.qm@web33607.mail.mud.yahoo.com> Hi All, I am very new to tkSnack. Trying to understand it. Please help me out. I thought of a very simple scenario. I would like to play a audio from line-in and then check if the audio is present. If there is no audio for 20 seconds then i need to raise an error. Is it possible to do this with tkSnack?If yes, then how can we do it? Regards, Alpana From damontimm at gmail.com Wed Jan 7 16:48:36 2009 From: damontimm at gmail.com (Damon Timm) Date: Wed, 7 Jan 2009 10:48:36 -0500 Subject: [Tutor] SMTP Module Help In-Reply-To: <4963281D.9070009@gmail.com> References: <4963281D.9070009@gmail.com> Message-ID: <262679b50901070748r4c27e6fco4ac15ee4f20c5e88@mail.gmail.com> On 1/6/09, Marco Petersen wrote: > I'm using Python 2.5.4. I wanted to try out the SMTP module. I tried to send > an email through my Gmail account but it keeps saying that the connection > was refused. I used this example to get emailing from python through gmail smtp to work: http://codecomments.wordpress.com/2008/01/04/python-gmail-smtp-example/ Note, there are a couple errors in the code that prevent it from working out-of-the-box ... however, if you read the comments they get worked out. Also, I think I would echo what the other folks mentioned here, is that you probably need to specify the port (587) as in: server = smtplib.SMTP('smtp.gmail.com', 587) Damon > > This is the code that I used : > > import smtplib > msg = 'Test' > > > server = smtplib.SMTP('smtp.gmail.com') > server.set_debuglevel(1) > server.ehlo() > server.starttls() > server.ehlo() > server.login('marco.m.petersen at gmail.com', 'password') > server.sendmail('marco.m.petersen at gmail.com', > 'marcoleepetersen at gmail.com', msg) > server.close() > > This error message keeps coming up: > > > Traceback (most recent call last): > File "C:/Python25/send_mail.py", line 5, in > server = smtplib.SMTP('smtp.gmail.com') > File "C:\Python25\Lib\smtplib.py", line 244, in __init__ > (code, msg) = self.connect(host, port) > File "C:\Python25\Lib\smtplib.py", line 310, in connect > raise socket.error, msg > error: (10061, 'Connection refused') > > > Can anyone help me with this? > > Thanks. > > -Marco > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From cbabcock at asciiking.com Wed Jan 7 17:17:47 2009 From: cbabcock at asciiking.com (Chris Babcock) Date: Wed, 7 Jan 2009 09:17:47 -0700 Subject: [Tutor] SMTP Module Help In-Reply-To: <4964C07D.3050607@gmail.com> References: <4963281D.9070009@gmail.com> <4964C07D.3050607@gmail.com> Message-ID: <20090107091747.774d1c3c@mail.asciiking.com> On Wed, 07 Jan 2009 15:47:25 +0100 Ole Henning Jensen wrote: > Marco Petersen wrote: > > I'm using Python 2.5.4. I wanted to try out the SMTP module. I > > tried to send an email through my Gmail account but it keeps saying > > that the connection was refused. > > error: (10061, 'Connection refused') > > > > > > Can anyone help me with this? > > > > I must admit that I know nothing of the SMTP module, but I do know > that with gmail you need to use an SSL secure connection on port 995. Yes, 995 is the port for POPS. For inbound mail, you probably want to use IMAPS on port 993. The original question is about SMTP, however. Google is offering SMTP submission over TLS on ports 465 and 587. Port 465 was defined as SMTP over SSL in some reference works, but the IETF still has it listed for a router protocol. Port 587 has been reserved for mail submission. More importantly for home users, your ISP should NOT block port 587 (RFC 4409). Best, Chris -- Thank you everyone! USAK is live on its new connection. So far you have given $198 towards next quarter. To make a donation, use this link (opens on PayPal): http://tinyurl.com/USAK2009 -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 489 bytes Desc: not available URL: From inthefridge at gmail.com Wed Jan 7 17:42:09 2009 From: inthefridge at gmail.com (Spencer Parker) Date: Wed, 7 Jan 2009 09:42:09 -0700 Subject: [Tutor] df type function in python Message-ID: I am looking for a function in python that would operate similar to df. I would use df, but I am unable to parse the data that it gives me from there. If it would give me a single line I could then split it out if I needed to, but I can't see how to actually do that. What I am trying to do is get some information on a drive I have mounted. I have a disk image that I have mounted on temp folder that I need to see how much total pace it is taking up. It gives me a more accurate representation of my xen disk images that just an ls -sk or something on the file. -- Spencer Parker -------------- next part -------------- An HTML attachment was scrubbed... URL: From wferguson1 at socal.rr.com Wed Jan 7 17:46:51 2009 From: wferguson1 at socal.rr.com (WM.) Date: Wed, 07 Jan 2009 08:46:51 -0800 Subject: [Tutor] Interactive programming. In-Reply-To: <4964986C.9070309@tue.nl> References: <4963AD10.4060003@socal.rr.com> <4963B3FD.1010504@khine.net> <4963C8B5.6070600@socal.rr.com> <496483CD.3040806@tue.nl> <1c2a2c590901070332o5807c4d3pffee564834ffb2bf@mail.gmail.com> <4964986C.9070309@tue.nl> Message-ID: <4964DC7B.6060703@socal.rr.com> IDLE 2.6 >>> i = 1 >>> j = 11 >>> if j > 1: print j else: SyntaxError: invalid syntax >>> I am getting a little dizzy here. I know about text editor, code, save, F5. Many tutorials say that it is funner and faster to test an idea 'interactively', using IDLE. Nothing is said about fiddling the output. In the above bit the 'else' is in the wrong place because IDLE or PYTHON terminated the script. I hate to be a bore here, but if the mechanics of the program are not as they are said to be in the tutorials, how am I to proceed? From rabidpoobear at gmail.com Wed Jan 7 17:58:03 2009 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Wed, 7 Jan 2009 10:58:03 -0600 Subject: [Tutor] good day In-Reply-To: <4964856B.5050005@tue.nl> References: <496495FD0200004000022646@pta-emo.csir.co.za> <4964856B.5050005@tue.nl> Message-ID: On Wed, Jan 7, 2009 at 4:35 AM, A.T.Hofkamp wrote: > Kgotlelelo Legodi wrote: >> >> good day >> >> I just started using python and i want to know how can i solve a boundary > > value problem for ordinary differential equations using shooting method in > python.use the general equation to demonstrate the python code. > > > I have no background in numeric calculations, but for starters, you may want > to investigate the numpy and/or scipy Python packages. Google will probably > also give you good starting points of existing numeric code/libraries. > > > As for actually writing the program, I am afraid you'll have to do that > yourself. > Also, this sounds a lot like you just copied and pasted it from a homework assignment. We're not going to be able to provide you with code samples in that case, but you're welcome to ask more questions and post about any problems you run into. From kent37 at tds.net Wed Jan 7 18:08:17 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 7 Jan 2009 12:08:17 -0500 Subject: [Tutor] Interactive programming. In-Reply-To: <4964DC7B.6060703@socal.rr.com> References: <4963AD10.4060003@socal.rr.com> <4963B3FD.1010504@khine.net> <4963C8B5.6070600@socal.rr.com> <496483CD.3040806@tue.nl> <1c2a2c590901070332o5807c4d3pffee564834ffb2bf@mail.gmail.com> <4964986C.9070309@tue.nl> <4964DC7B.6060703@socal.rr.com> Message-ID: <1c2a2c590901070908s493fe05dyd0e04e75c29ad4cf@mail.gmail.com> On Wed, Jan 7, 2009 at 11:46 AM, WM. wrote: > IDLE 2.6 >>>> i = 1 >>>> j = 11 >>>> if j > 1: > print j > else: > > SyntaxError: invalid syntax >>>> > > I am getting a little dizzy here. > > I know about text editor, code, save, F5. > > Many tutorials say that it is funner and faster to test an idea > 'interactively', using IDLE. Nothing is said about fiddling the output. > > In the above bit the 'else' is in the wrong place because IDLE or PYTHON > terminated the script. You have to backspace before typing 'else:' to remove the (automatic) block indentation. IDLE auto-indents after the 'if:' and it will continue to indent each line until you tell it to stop by backspacing over the indent. Kent From edwin_boyette at yahoo.com Wed Jan 7 18:13:54 2009 From: edwin_boyette at yahoo.com (Edwin Boyette) Date: Wed, 7 Jan 2009 09:13:54 -0800 (PST) Subject: [Tutor] Interactive programming. Message-ID: <128547.28733.qm@web53703.mail.re2.yahoo.com> --- On Wed, 1/7/09, WM. wrote: From: WM. Subject: Re: [Tutor] Interactive programming. To: "A.T.Hofkamp" Cc: tutor at python.org Date: Wednesday, January 7, 2009, 11:46 AM IDLE 2.6 >>> i = 1 >>> j = 11 >>> if? j > 1: ??? print j ??? else: ??? ??? SyntaxError: invalid syntax >>> I am getting a little dizzy here. I know about text editor, code, save, F5. Many tutorials say that it is funner and faster to test an idea 'interactively', using IDLE.? Nothing is said about fiddling the output. In the above bit the 'else' is in the wrong place because IDLE or PYTHON terminated the script. I hate to be a bore here, but if the mechanics of the program are not as they are said to be in the tutorials, how am I to proceed? _______________________________________________ Tutor maillist? -? Tutor at python.org http://mail.python.org/mailman/listinfo/tutor ? ? You could wrapt it all up in a function and then call the function in idle. ? ? >>> def nudge_nudge(): ?i = 5 ?j = 7 ?if i <= j: ??print "nudge","nudge" ?else: ??print "whatever" nudge_nudge() -------------- next part -------------- An HTML attachment was scrubbed... URL: From inthefridge at gmail.com Wed Jan 7 19:08:52 2009 From: inthefridge at gmail.com (Spencer Parker) Date: Wed, 7 Jan 2009 11:08:52 -0700 Subject: [Tutor] df type function in python In-Reply-To: <4964EE33.6010600@sjsears.com> References: <4964EE33.6010600@sjsears.com> Message-ID: Is there anyway to get rid of the header information? I just want the output that it gives me for the device. On Wed, Jan 7, 2009 at 11:02 AM, Stuart Sears wrote: > On 07/01/09 16:42, Spencer Parker wrote: > >> I am looking for a function in python that would operate similar to df. >> I would use df, but I am unable to parse the data that it gives me >> from there. If it would give me a single line I could then split it out >> if I needed to, but I can't see how to actually do that. What I am >> trying to do is get some information on a drive I have mounted. I have a >> disk image that I have mounted on temp folder that I need to see how >> much total pace it is taking up. It gives me a more accurate >> representation of my xen disk images that just an ls -sk or something on >> the file. >> > > Which version of df do you have? Which OS is this on? > > If you want one line per device/mountpoint, df -P will do so on linux > systems nowadays. I have no idea whether any of this has been ported across > to other *NIX systems. > > Regards, > > Stuart > -- > Stuart Sears RHCA etc. > "It's today!" said Piglet. > "My favourite day," said Pooh. > -- Spencer Parker -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Wed Jan 7 19:33:40 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 7 Jan 2009 13:33:40 -0500 Subject: [Tutor] df type function in python In-Reply-To: References: <4964EE33.6010600@sjsears.com> Message-ID: <1c2a2c590901071033q39bb61eg65d69eed5bd5a543@mail.gmail.com> On Wed, Jan 7, 2009 at 1:08 PM, Spencer Parker wrote: > Is there anyway to get rid of the header information? I just want the > output that it gives me for the device. If you know how to get the output of df into Python (e.g. with the subprocess module or a pipe) then you can use the str.splitlines() method to divide it into lines and pick out the line you want. Kent From inthefridge at gmail.com Wed Jan 7 19:36:53 2009 From: inthefridge at gmail.com (Spencer Parker) Date: Wed, 7 Jan 2009 11:36:53 -0700 Subject: [Tutor] df type function in python In-Reply-To: <1c2a2c590901071033q39bb61eg65d69eed5bd5a543@mail.gmail.com> References: <4964EE33.6010600@sjsears.com> <1c2a2c590901071033q39bb61eg65d69eed5bd5a543@mail.gmail.com> Message-ID: What I did was just grep for anything starting with "/" It then just outputs it to a single line now...and I can split it as needed. Thanks again!!1 On Wed, Jan 7, 2009 at 11:33 AM, Kent Johnson wrote: > On Wed, Jan 7, 2009 at 1:08 PM, Spencer Parker > wrote: > > Is there anyway to get rid of the header information? I just want the > > output that it gives me for the device. > > If you know how to get the output of df into Python (e.g. with the > subprocess module or a pipe) then you can use the str.splitlines() > method to divide it into lines and pick out the line you want. > > Kent > -- Spencer Parker -------------- next part -------------- An HTML attachment was scrubbed... URL: From stuart at sjsears.com Wed Jan 7 19:30:54 2009 From: stuart at sjsears.com (Stuart Sears) Date: Wed, 07 Jan 2009 18:30:54 +0000 Subject: [Tutor] df type function in python In-Reply-To: References: Message-ID: <4964F4DE.9050105@sjsears.com> Redirecting to the list as I seem to have replied off-list rather inadvertently... On 07/01/09 16:42, Spencer Parker wrote: > I am looking for a function in python that would operate similar to df. > I would use df, but I am unable to parse the data that it gives me > from there. If it would give me a single line I could then split it out > if I needed to, but I can't see how to actually do that. What I am > trying to do is get some information on a drive I have mounted. I have a > disk image that I have mounted on temp folder that I need to see how > much total pace it is taking up. It gives me a more accurate > representation of my xen disk images that just an ls -sk or something on > the file. Which version of df do you have? Which OS is this on? If you want one line per device/mountpoint, df -P will do so on linux systems nowadays. I have no idea whether any of this has been ported across to other *NIX systems. Regards, Stuart -- Stuart Sears RHCA etc. "It's today!" said Piglet. "My favourite day," said Pooh. From stuart at sjsears.com Wed Jan 7 19:27:56 2009 From: stuart at sjsears.com (Stuart Sears) Date: Wed, 07 Jan 2009 18:27:56 +0000 Subject: [Tutor] df type function in python In-Reply-To: References: <4964EE33.6010600@sjsears.com> Message-ID: <4964F42C.1070105@sjsears.com> On 07/01/09 18:08, Spencer Parker wrote: > Is there anyway to get rid of the header information? I just want > the output that it gives me for the device. parse the output and junk the first line? I'm no subprocess expert, but a bit of playing about suggests this would work: from subprocess import Popen, PIPE df = Popen('df -P', shell=True, stdout=PIPE) no_header = df.stdout.readlines()[1:] I'm sure there are more elegant ways to do this, but it does work. tuning the df -P command to only give you the device your are interested in should reduce the output a little more. Regards, Stuart ps there's need to reply to me directly, I'm subscribed to the list, albeit mostly to cower at the feet of those who inhabit it :) -- Stuart Sears RHCA etc. "It's today!" said Piglet. "My favourite day," said Pooh. From rschroev_nospam_ml at fastmail.fm Wed Jan 7 20:51:02 2009 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Wed, 07 Jan 2009 20:51:02 +0100 Subject: [Tutor] df type function in python In-Reply-To: References: Message-ID: Spencer Parker schreef: > I am looking for a function in python that would operate similar to df. > I would use df, but I am unable to parse the data that it gives me from > there. If it would give me a single line I could then split it out if I > needed to, but I can't see how to actually do that. What I am trying to > do is get some information on a drive I have mounted. I have a disk > image that I have mounted on temp folder that I need to see how much > total pace it is taking up. It gives me a more accurate representation > of my xen disk images that just an ls -sk or something on the file. Some time ago I wrote something like that for a script of mine: import subprocess def df(filesystem): """Report disk usage. Return a dictionary with total, used, available. Sizes are reported in blocks of 1024 bytes.""" output = subprocess.Popen( ['/bin/df', '-B 1024', filesystem], stdout=subprocess.PIPE).communicate()[0] lines = output.split('\n') fs, blocks_total, blocks_used, blocks_available, used, mount = lines[1].split() blocks_total = int(blocks_total) blocks_used = int(blocks_used) blocks_available = int(blocks_available) return dict( total=blocks_total, used=blocks_used, available=blocks_available) I use from a cronjob in a script that monitors the disk usage and sends me a mail if the disk gets too full. -- The saddest aspect of life right now is that science gathers knowledge faster than society gathers wisdom. -- Isaac Asimov Roel Schroeven From ksarikhani at gmail.com Wed Jan 7 22:04:28 2009 From: ksarikhani at gmail.com (Kayvan Sarikhani) Date: Wed, 7 Jan 2009 16:04:28 -0500 Subject: [Tutor] Opsware Global Shell Scripting Message-ID: Hi there...I'm new to Python scripting, with maybe 3 days under my belt thus far. Besides the occasional shell script, the last time I ever touched a programming language was probably at least 12 years ago, if that gives you any indication of my experience. :) I don't know if this is the proper place to ask, but I've run into the problem below. Right now I'm beginning to work within the Opsware Global Shell, which if you're unfamiliar with it, basically is exactly what it sounds like...the goal is to launch a script which changes directories to a list of servers, prints the server name, remotes into managed virtual servers, checks the date, and outputs this into a file. I do have a bash script as follows, which does the job: #!/bin/bash # # This script checks the dates on all managed systems. OUTFILE="/home/ksarikhani/public/bin/timecheck.txt" rm -f $OUTFILE cd "/opsw/Server/@/" for SERVER_NAME in * do echo ---- $SERVER_NAME echo ---- $SERVER_NAME >> $OUTFILE rosh -n $SERVER_NAME -l $LOGNAME \ "date" >> $OUTFILE done # Last line in date.sh. Even though the above does what I need it to do, I'd REALLY like to determine the equivalent in Python...I've tried several different methods, but about as far as I get is printing the server name. This is what I've cobbled together so far. #!/usr/bin/python import os, sys sys.stdout = open('timecheck.txt','w') for servername in os.listdir('/opsw/Server/@'): print '---', servername os.system('rosh -n $SERVER_NAME -l $LOGNAME') os.system('date') sys.stdout.close() The problem is this...for logging into systems via the global shell, one has to change directories to the one with the list of all managed servers (or specify the path for each one), and then launch a "rosh -n -l " to be able to get into it. However, when I launch the script, what happens is the following message: *rosh: Username must be specified with -l or via path* And this is a continual loop that I can't break. This is of course not a Python error, but as you might guess from looking at the script, the whole $SERVER_NAME piece is probably wrong. I thought maybe I could do something like this... *os.system('rosh -n', servername, '-l $LOGNAME')* But of course os.system allows exactly one argument, and not three. This is where I'm stuck, and I've been digging into the books and examples and forums and just not quite sure what to look for. I would have liked to have completed the script without asking for help, but nothing quite seems to fit what I'm doing. Any suggestions or guidance would be highly appreciated. Thanks! K -------------- next part -------------- An HTML attachment was scrubbed... URL: From wferguson1 at socal.rr.com Wed Jan 7 22:45:35 2009 From: wferguson1 at socal.rr.com (WM.) Date: Wed, 07 Jan 2009 13:45:35 -0800 Subject: [Tutor] Interactive programming. In-Reply-To: <4963B3FD.1010504@khine.net> References: <4963AD10.4060003@socal.rr.com> <4963B3FD.1010504@khine.net> Message-ID: <4965227F.608@socal.rr.com> Norman Khine wrote: > >>> i = 5 > >>> j = 7 > >>> if i <= j: > ... print 'nudge', 'nudge' > ... else: > ... print 'whatever' > ... > nudge nudge The above is just what the tutorials said would happen. Can anyone give me a step-by-step in IDLE 2.6 that would make this happen? From sander.sweers at gmail.com Wed Jan 7 23:09:09 2009 From: sander.sweers at gmail.com (Sander Sweers) Date: Wed, 7 Jan 2009 23:09:09 +0100 Subject: [Tutor] Opsware Global Shell Scripting In-Reply-To: References: Message-ID: On Wed, Jan 7, 2009 at 22:04, Kayvan Sarikhani wrote: > #!/usr/bin/python > import os, sys > sys.stdout = open('timecheck.txt','w') > for servername in os.listdir('/opsw/Server/@'): > print '---', servername > os.system('rosh -n $SERVER_NAME -l $LOGNAME') > os.system('date') > sys.stdout.close() > > The problem is this...for logging into systems via the global shell, one has > to change directories to the one with the list of all managed servers (or > specify the path for each one), and then launch a "rosh -n -l > " to be able to get into it. > > This is of course not a Python error, but as you might guess from looking at > the script, the whole $SERVER_NAME piece is probably wrong. Indeed the variables are wrong > I thought maybe > I could do something like this... > > os.system('rosh -n', servername, '-l $LOGNAME') > > But of course os.system allows exactly one argument, and not three. Almost, look at the below session in idle. The %s are replaced by the variables servername and logname. See string formatting [1] for more info. >>> servername = 'testserver' >>> logname = 'logname' >>> print 'rosh -m %s -l %s' % (servername, logname) rosh -m testserver -l logname So you need to use something like below in your loop. roshCommand = 'rosh -m %s -l %s' % (servername, logname) os.system(roshCommand) I do not see the servername variable being assigned a value in your script so the above will fail. I assume it will be something like logname = '/var/log/somelogfile' You might want to look at the subprocess module as this gives you a lot more control but is also more complicated. Greets Sander [1] http://docs.python.org/library/stdtypes.html#string-formatting-operations From david at hlacik.eu Wed Jan 7 23:13:57 2009 From: david at hlacik.eu (=?ISO-8859-2?Q?David_Hl=E1=E8ik?=) Date: Wed, 7 Jan 2009 23:13:57 +0100 Subject: [Tutor] linked list with cycle structure In-Reply-To: <6sjok8F6dqciU1@mid.uni-berlin.de> References: <6sjok8F6dqciU1@mid.uni-berlin.de> Message-ID: Hi, so okay, i will create a helping set, where i will be adding elements ID, when element ID will be allready in my helping set i will stop and count number of elements in helping set. This is how long my cycled linked list is. But what if i have another condition , and that is *i can use only helping memory with constant size* ? This means i am not able to create any set and adding elements there. I need to have a constant size variables . This is complication a complication for me. Thanks in advance! David On Wed, Jan 7, 2009 at 2:22 PM, Diez B. Roggisch wrote: > > David Hl??ik wrote: > > > dictionary with cycle structure > > > > Hello guys, > > > > I have a linked list where *number of elements is unlimited* and > > **last element points on random (can be first, last, in middle , > > anywhere) element within linked list** - this is important . My goals > > is to create an architecture /scheme for **algoritmus which will count > > total number of elements** of such linked list. > > Yes , maybe it sounds strange, but we need to implement this and i > > would be very gladfull for your toughts. > > Time for homework again? Last time sorting in O(n), now this. How about you > try something yourself and show us the results - then we might comment on > enhancements or problems. > > Diez > -- > http://mail.python.org/mailman/listinfo/python-list From sander.sweers at gmail.com Wed Jan 7 23:21:53 2009 From: sander.sweers at gmail.com (Sander Sweers) Date: Wed, 7 Jan 2009 23:21:53 +0100 Subject: [Tutor] Interactive programming. In-Reply-To: <4965227F.608@socal.rr.com> References: <4963AD10.4060003@socal.rr.com> <4963B3FD.1010504@khine.net> <4965227F.608@socal.rr.com> Message-ID: On Wed, Jan 7, 2009 at 22:45, WM. wrote: > Norman Khine wrote: >> >> >>> i = 5 >> >>> j = 7 >> >>> if i <= j: >> ... print 'nudge', 'nudge' >> ... else: >> ... print 'whatever' >> ... >> nudge nudge > > The above is just what the tutorials said would happen. > Can anyone give me a step-by-step in IDLE 2.6 that would make this happen? The above is not from idle but from the interactive python command line. If you are on windows it is an entry in the python 2.6 start menu entry. Greets Sander From wferguson1 at socal.rr.com Wed Jan 7 23:36:07 2009 From: wferguson1 at socal.rr.com (WM.) Date: Wed, 07 Jan 2009 14:36:07 -0800 Subject: [Tutor] Interactive programming. In-Reply-To: References: <4963AD10.4060003@socal.rr.com> <4963B3FD.1010504@khine.net> <4965227F.608@socal.rr.com> Message-ID: <49652E57.8060000@socal.rr.com> IDLE 2.6 >>> i = 1 >>> if i > 1: print 'x' else: print 'y' y >>> Last post on this topic, I guess. I think that the script looks pretty lame, though. From kent37 at tds.net Wed Jan 7 23:37:46 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 7 Jan 2009 17:37:46 -0500 Subject: [Tutor] Interactive programming. In-Reply-To: <4965227F.608@socal.rr.com> References: <4963AD10.4060003@socal.rr.com> <4963B3FD.1010504@khine.net> <4965227F.608@socal.rr.com> Message-ID: <1c2a2c590901071437w30a8e0f4obaa0a245bcc1de89@mail.gmail.com> On Wed, Jan 7, 2009 at 4:45 PM, WM. wrote: > Norman Khine wrote: >> >> >>> i = 5 >> >>> j = 7 >> >>> if i <= j: >> ... print 'nudge', 'nudge' >> ... else: >> ... print 'whatever' >> ... >> nudge nudge > > The above is just what the tutorials said would happen. > Can anyone give me a step-by-step in IDLE 2.6 that would make this happen? Type these characters exactly into the IDLE shell window, where is the return or Enter key and is the backspace or delete key (the one next to the ]} key not the one in the numeric keypad): if i<=j:print 'nudge'else:print 'whatever' Kent From kent37 at tds.net Wed Jan 7 23:38:28 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 7 Jan 2009 17:38:28 -0500 Subject: [Tutor] Interactive programming. In-Reply-To: <49652E57.8060000@socal.rr.com> References: <4963AD10.4060003@socal.rr.com> <4963B3FD.1010504@khine.net> <4965227F.608@socal.rr.com> <49652E57.8060000@socal.rr.com> Message-ID: <1c2a2c590901071438s5a835bb3k5dae898d34222127@mail.gmail.com> On Wed, Jan 7, 2009 at 5:36 PM, WM. wrote: > IDLE 2.6 >>>> i = 1 >>>> if i > 1: > print 'x' > else: > print 'y' > > > y >>>> > Last post on this topic, I guess. > I think that the script looks pretty lame, though. It was always lame :-) but you got it to work... Kent From ksarikhani at gmail.com Wed Jan 7 23:50:12 2009 From: ksarikhani at gmail.com (Kayvan Sarikhani) Date: Wed, 7 Jan 2009 17:50:12 -0500 Subject: [Tutor] Opsware Global Shell Scripting In-Reply-To: <20090107225747.502df1d0@o> References: <20090107225747.502df1d0@o> Message-ID: On Wed, Jan 7, 2009 at 4:57 PM, spir wrote: > Le Wed, 7 Jan 2009 16:04:28 -0500, > "Kayvan Sarikhani" a ?crit : > > > #!/bin/bash > > # > > # This script checks the dates on all managed systems. > > OUTFILE="/home/ksarikhani/public/bin/timecheck.txt" > > rm -f $OUTFILE > > cd "/opsw/Server/@/" > > for SERVER_NAME in * > > do > > echo ---- $SERVER_NAME > > echo ---- $SERVER_NAME >> $OUTFILE > > rosh -n $SERVER_NAME -l $LOGNAME \ > > "date" >> $OUTFILE > > done > > # Last line in date.sh. > > > #!/usr/bin/python > > import os, sys > > sys.stdout = open('timecheck.txt','w') > > for servername in os.listdir('/opsw/Server/@'): > > print '---', servername > > os.system('rosh -n $SERVER_NAME -l $LOGNAME') > > os.system('date') > > sys.stdout.close() > > > > The issue is, when comparing the bash script to the python one, that > $SERVER_NAME makes sense only > for bash -- as well as $LOGNAME that you properly changed. > > > *os.system('rosh -n', servername, '-l $LOGNAME')* > > This goes on the right way. Actually, os.system's arg is a plain string. To > construct it out of > several substrings you have to use matching string operators (actually > methods). To be explicit: > > string_shell_command = 'rosh -n' + servername + '-l $LOGNAME' > or > string_shell_command = 'rosh -n %s -l $LOGNAME' %servername > and then: > os.system(string_shell_command) > > Than, I'm not fully sure this will be enough unless $LOGNAME is an env > variable known by the > system (I don't know well linux yet). It seems to be, as it is not defined > in your bash script. > > Denis Ah, that makes sense...I didn't know we could devise our own commands in strings like that. That helps me quite a lot, actually. Thank you very much, Denis! For the record, $LOGNAME works fine as a variable...it's a standard env variable in Linux to display the current user's username. There's other ways of getting it, but that seems to be the most exact from what I can gather. Thanks again, when I make some progress or complete it (hopefully), I'll post further. Kayvan PS - Sorry for the re-send, forgot to include the tutor list. -------------- next part -------------- An HTML attachment was scrubbed... URL: From ksarikhani at gmail.com Wed Jan 7 23:51:13 2009 From: ksarikhani at gmail.com (Kayvan Sarikhani) Date: Wed, 7 Jan 2009 17:51:13 -0500 Subject: [Tutor] Opsware Global Shell Scripting In-Reply-To: References: Message-ID: On Wed, Jan 7, 2009 at 5:09 PM, Sander Sweers wrote: > On Wed, Jan 7, 2009 at 22:04, Kayvan Sarikhani > wrote: > > > > This is of course not a Python error, but as you might guess from looking > at > > the script, the whole $SERVER_NAME piece is probably wrong. > > Indeed the variables are wrong > Right...I thought so, but wasn't sure if there was any kind of equivalent within Python...couldn't hurt to try. :) > Almost, look at the below session in idle. The %s are replaced by the > variables servername and logname. See string formatting [1] for more > info. > > >>> servername = 'testserver' > >>> logname = 'logname' > >>> print 'rosh -m %s -l %s' % (servername, logname) > rosh -m testserver -l logname > > So you need to use something like below in your loop. > > roshCommand = 'rosh -m %s -l %s' % (servername, logname) > > os.system(roshCommand) > > I do not see the servername variable being assigned a value in your > script so the above will fail. I assume it will be something like > > logname = '/var/log/somelogfile' > > You might want to look at the subprocess module as this gives you a > lot more control but is also more complicated. > > Greets > Sander > > [1] > http://docs.python.org/library/stdtypes.html#string-formatting-operations > Yes, it did fail...rosh needs the full path or the -n identifier to remote shell into the VM's, and you're right that it didn't find it. As for the $LOGNAME variable, that piece works for identifying the username which is what I needed for that...it doesn't actually point to a log file or the like. If I misunderstood what you meant, my apologies. Thanks very much though, this is also a lot of help and definitely points me in the right direction. I'll certainly check out string formating and see where I can go from there. I did look at the subprocess module but I'm still not sure I understand it...seems to have a lot of options and is flexible, but I still need to examine how it's used. Thanks! Kayvan -------------- next part -------------- An HTML attachment was scrubbed... URL: From edwin_boyette at yahoo.com Thu Jan 8 00:13:17 2009 From: edwin_boyette at yahoo.com (Edwin Boyette) Date: Wed, 7 Jan 2009 15:13:17 -0800 (PST) Subject: [Tutor] Interactive programming. Message-ID: <499143.66868.qm@web53702.mail.re2.yahoo.com> Don't try to make interactive programming something its not. It's handy if you have something short to try out, want to evaluate a function at some value etc.? Don't?rage at the hammer for not being an allen wrench ---- get an allen wrench. --- On Wed, 1/7/09, Kent Johnson wrote: From: Kent Johnson Subject: Re: [Tutor] Interactive programming. To: "WM." Cc: "Sander Sweers" , tutor at python.org Date: Wednesday, January 7, 2009, 5:38 PM -----Inline Attachment Follows----- On Wed, Jan 7, 2009 at 5:36 PM, WM. wrote: > IDLE 2.6 >>>> i = 1 >>>> if i > 1: >? ? ? ? print 'x' > else: >? ? ? ? print 'y' > > > y >>>> > Last post on this topic, I guess. > I think that the script looks pretty lame, though. It was always lame :-) but you got it to work... Kent _______________________________________________ Tutor maillist? -? Tutor at python.org http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From damontimm at gmail.com Thu Jan 8 01:02:48 2009 From: damontimm at gmail.com (Damon Timm) Date: Wed, 7 Jan 2009 19:02:48 -0500 Subject: [Tutor] Can subprocess run functions ? Message-ID: <262679b50901071602p5c3c61c5iebf650244b78b1f@mail.gmail.com> Hi everyone - I was playing with subprocess (with some success, I might add) to implement threading in my script (audio conversion). My goal is to be able to spawn off threads to make use of my multiprocessor system (and speed up encoding). With your help, I was successful. Anyhow, subprocess is working -- but I wonder if there is a way I can send the entire *function* into its own subprocess ? Because, in my case, I want my function to: [a] convert files, [b] tag files, [c] do some other stuff to files. Steps [b] and [c] require step [a] to be complete ... but the minute I spawn off step [a] it acts like it is already done (even though it is still working) ... I was hoping they could all run in a single thread, one after another ... I tried just giving subprocess.Popen the function name (rather than the external program) but that didn't work; and I read through the docs over at python.org ... but I can't find my answer. With the code I have, I am not sure how to both wait for my subprocess to finish (in the function) and allow the multithreading bit to work together ... I have experimented myself but didn't really get anywhere. I commented in where I want to "do other stuff" before it finishes ... wonder if you can take a look and show me where I may try to head next? Thanks! ------------------ import time import subprocess totProcs = 2 #number of processes to spawn before waiting flacFiles = [["test.flac","test.mp3"],["test2.flac","test2.mp3"],\ ["test3.flac","test3.mp3"],["test4.flac","test4.mp3"],\ ["test5.flac","test5.mp3"],["test6.flac","test6.mp3"]] procs = [] def flac_to_mp3(flacfile,mp3file): print "beginning to process " + flacfile p = subprocess.Popen(["flac","--decode","--stdout","--silent",flacfile], stdout=subprocess.PIPE) p1 = subprocess.Popen(["lame","--silent","-",mp3file], stdin=p.stdout) # I want to do more stuff before this function ends, but need to wait for p1 to finish first; # and, at the same time, I need to "return" p1 so the while loop (below) works [I think] return p1 while flacFiles or procs: procs = [p for p in procs if p.poll() is None] while flacFiles and len(procs) < totProcs: file = flacFiles.pop(0) procs.append(flac_to_mp3(file[0],file[1])) time.sleep(1) From robert.kern at gmail.com Thu Jan 8 01:23:24 2009 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 07 Jan 2009 19:23:24 -0500 Subject: [Tutor] linked list with cycle structure In-Reply-To: References: <6sjok8F6dqciU1@mid.uni-berlin.de> Message-ID: Terry Reedy wrote: > David Hl??ik wrote: >> But what if i have another condition , and that is *i can use only >> helping memory with constant size* ? This means i am not able to >> create any set and adding elements there. I need to have a constant >> size variables . This is complication a complication for me. > > Interesting problem. If it is homework, there must be an answer. It's also an interview question I've seen reasonably often, particularly with that last complication. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From wescpy at gmail.com Thu Jan 8 01:36:38 2009 From: wescpy at gmail.com (wesley chun) Date: Wed, 7 Jan 2009 16:36:38 -0800 Subject: [Tutor] Can subprocess run functions ? In-Reply-To: <262679b50901071602p5c3c61c5iebf650244b78b1f@mail.gmail.com> References: <262679b50901071602p5c3c61c5iebf650244b78b1f@mail.gmail.com> Message-ID: <78b3a9580901071636v49dac9f2g3ee561634fe475bc@mail.gmail.com> > Anyhow, subprocess is working -- but I wonder if there is a way I can > send the entire *function* into its own subprocess ? this has been a highly-desired feature for quite awhile. starting in 2.6, you can use the new multiprocessing module (originally called pyprocessing): http://docs.python.org/library/multiprocessing.html there is a backport to 2.4 and 2.5 here: http://pypi.python.org/pypi/multiprocessing/2.6.0.2 there are similar packages called pypar and pprocess: http://datamining.anu.edu.au/~ole/pypar/ http://www.boddie.org.uk/python/pprocess.html hope this helps! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 "Python Fundamentals", Prentice Hall, (c)2009 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From damontimm at gmail.com Thu Jan 8 01:43:56 2009 From: damontimm at gmail.com (Damon Timm) Date: Wed, 7 Jan 2009 19:43:56 -0500 Subject: [Tutor] Can subprocess run functions ? In-Reply-To: <78b3a9580901071636v49dac9f2g3ee561634fe475bc@mail.gmail.com> References: <262679b50901071602p5c3c61c5iebf650244b78b1f@mail.gmail.com> <78b3a9580901071636v49dac9f2g3ee561634fe475bc@mail.gmail.com> Message-ID: <262679b50901071643h335998ffm2508e0631be3a9aa@mail.gmail.com> On Wed, Jan 7, 2009 at 7:36 PM, wesley chun wrote: > this has been a highly-desired feature for quite awhile. > > starting in 2.6, you can use the new multiprocessing module > (originally called pyprocessing): > http://docs.python.org/library/multiprocessing.html > > there is a backport to 2.4 and 2.5 here: > http://pypi.python.org/pypi/multiprocessing/2.6.0.2 > > there are similar packages called pypar and pprocess: > http://datamining.anu.edu.au/~ole/pypar/ > http://www.boddie.org.uk/python/pprocess.html > > hope this helps! Thanks Wesley - it does! As is often the case, the minute I ask a question like this I have some anxiety that the answer must be right under my nose and I rush about the tubes of the internet searching for a clue ... I also found: http://chrisarndt.de/projects/threadpool/threadpool.py.html Since I have been doing a bit of reading since I started, I was able to download this "threadpool", import it, and it actually get it to work. Here is what I messily put together (using my first referenced script, as an example) ... I think I may stick with this for a while, since it seems well-thought out and, as far as I can tell, works! (No shame in "borrowing" ... though not as cool as making it up myself.) import subprocess import threadpool import os totProcs = 2 #number of processes to spawn before waiting flacFiles = ["test.flac","test2.flac","test3.flac","test4.flac","test5.flac","test6.flac"] def flac_to_mp3(flacfile): print "Processing: " + flacfile mp3file = flacfile.rsplit('.', 1)[0] + '.mp3' p = subprocess.Popen(["flac","--decode","--stdout","--silent",flacfile], stdout=subprocess.PIPE) p1 = subprocess.Popen(["lame","--silent","-",mp3file], stdin=p.stdout) p1.communicate() #Test file size so we know it is actually waiting until it has been created. size = os.path.getsize(mp3file) return str("File: " + mp3file + "* Size: " + str(size)) def print_result(request, result): print "* Result from request #%s: %r" % (request.requestID, result) pool = threadpool.ThreadPool(totProcs) convert = threadpool.makeRequests(flac_to_mp3,flacFiles,print_result) [pool.putRequest(req) for req in convert] pool.wait() print "All Done!" > -- wesley > - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - > "Core Python Programming", Prentice Hall, (c)2007,2001 > "Python Fundamentals", Prentice Hall, (c)2009 > http://corepython.com > > wesley.j.chun :: wescpy-at-gmail.com > python training and technical consulting > cyberweb.consulting : silicon valley, ca > http://cyberwebconsulting.com > From alan.gauld at btinternet.com Thu Jan 8 02:21:24 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 8 Jan 2009 01:21:24 -0000 Subject: [Tutor] Interactive programming. References: <499143.66868.qm@web53702.mail.re2.yahoo.com> Message-ID: "Edwin Boyette" wrote > Don't try to make interactive programming something its not. > It's handy if you have something short to try out, want to > evaluate a function at some value etc. > Don't rage at the hammer for not being an allen wrench But in this case it is a valid complaint. Almost every other IDE with an interactive prompt does pro[per indentation, IDLE is the exception. Yet IDLE is theone most beginners use first! I think this is a really serious bug in Idle and is one of the main reasons I always recommend beginners use Pythonwin or PyCrust or some other shell window. The Idle editor windows are fine but the shell window sucks! -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Thu Jan 8 02:37:27 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 8 Jan 2009 01:37:27 -0000 Subject: [Tutor] Opsware Global Shell Scripting References: <20090107225747.502df1d0@o> Message-ID: "Kayvan Sarikhani" wrote > For the record, $LOGNAME works fine as a variable...it's a standard > env > variable in Linux to display the current user's username. In that case os.getenv('LOGNAME') should retrieve it for you HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk From artie.ziff at gmail.com Thu Jan 8 03:12:15 2009 From: artie.ziff at gmail.com (Artie Ziff) Date: Wed, 07 Jan 2009 18:12:15 -0800 Subject: [Tutor] simple array access Message-ID: <496560FF.2000201@gmail.com> Hello, I used python list comprehension to create a grid (list of lists) of Objects (instances of MyItem class). Can anyone make recommendations to achieve a simple access to the elements. My attempt at array access (like this: array[1,2] ) does not work. What am I overlooking? Thanks in advance! :) If anyone has time to show a better way to achieve same, then I am interested to learn! :) ### from pprint import * class MyItem: def __init__(self, value): self.data=value def __repr__(self): return 'MyItem(%s)' % (self.data) class Grid: def __init__(self, x, y, value): self.data = [[MyItem(float(value)) for i in range(x)] for j in range(y)] if __name__ == "__main__": grid = Grid(2, 3, 0.42) pprint(grid) pprint(grid.data) # next line fails to access array element pprint (grid.data[1,2]) # EOF # OUTPUT: <__main__.Grid instance at 0x7beb8> [[MyItem(0.42), MyItem(0.42)], [MyItem(0.42), MyItem(0.42)], [MyItem(0.42), MyItem(0.42)]] Traceback (most recent call last): File "multidim04.py", line 20, in pprint (grid.data[1,2]) TypeError: list indices must be integers Cheers, Art From jadrifter at gmail.com Thu Jan 8 03:24:51 2009 From: jadrifter at gmail.com (jadrifter) Date: Wed, 07 Jan 2009 18:24:51 -0800 Subject: [Tutor] simple array access In-Reply-To: <496560FF.2000201@gmail.com> References: <496560FF.2000201@gmail.com> Message-ID: <1231381491.6446.30.camel@ltop> On Wed, 2009-01-07 at 18:12 -0800, Artie Ziff wrote: > Hello, > > I used python list comprehension to create a grid (list of lists) of > Objects (instances of MyItem class). Can anyone make recommendations to > achieve a simple access to the elements. My attempt at array access > (like this: array[1,2] ) does not work. What am I overlooking? Thanks in > advance! :) > Hello, You might want to take a look at NumPy http://numpy.scipy.org/ John Purser From wescpy at gmail.com Thu Jan 8 03:45:13 2009 From: wescpy at gmail.com (wesley chun) Date: Wed, 7 Jan 2009 18:45:13 -0800 Subject: [Tutor] simple array access In-Reply-To: <496560FF.2000201@gmail.com> References: <496560FF.2000201@gmail.com> Message-ID: <78b3a9580901071845y3de4034aqcfd789eaf8030cd5@mail.gmail.com> > My attempt at array access (like this: array[1,2] ) does not work. What am > I overlooking? Thanks in advance! :) > : > pprint (grid.data[1,2]) is that really your name?!? you're famous! ;-) welcome to python! i'd try... pprint(grid.data[0][1]) ... as many languages start counting at 0 instead of 1, and you needed a quick syntax fix too. hope this helps! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 "Python Fundamentals", Prentice Hall, (c)2009 http://corepython.com "Python Web Development with Django", Addison Wesley, (c) 2009 http://withdjango.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From s4027340 at student.uq.edu.au Thu Jan 8 03:41:10 2009 From: s4027340 at student.uq.edu.au (Mr Gerard Kelly) Date: Thu, 08 Jan 2009 12:41:10 +1000 Subject: [Tutor] variable number of inputs Message-ID: How can you make a function accept a variable number of inputs without any particular limit? Like when you define a function you usually go: def func(a,b,c,d,e) and if you want to give a default value for e you can use e=0 for example. But what if you want to be able to call the function and put in as many arguments as you want. Say it's a really simple function just adding them all together or something (I know sum does that, but I'm just thinking of a simple example). From bgailer at gmail.com Thu Jan 8 04:01:42 2009 From: bgailer at gmail.com (bob gailer) Date: Wed, 07 Jan 2009 22:01:42 -0500 Subject: [Tutor] variable number of inputs In-Reply-To: References: Message-ID: <49656C96.5070707@gmail.com> Mr Gerard Kelly wrote: > How can you make a function accept a variable number of inputs without > any particular limit? > > Like when you define a function you usually go: > > def func(a,b,c,d,e) > > and if you want to give a default value for e you can use e=0 for example. > > But what if you want to be able to call the function and put in as many > arguments as you want. Say it's a really simple function just adding > them all together or something (I know sum does that, but I'm just > thinking of a simple example). > def func(*a) # a will be a tuple of whatever arguments are passed in the call. -- Bob Gailer Chapel Hill NC 919-636-4239 From wescpy at gmail.com Thu Jan 8 04:22:50 2009 From: wescpy at gmail.com (wesley chun) Date: Wed, 7 Jan 2009 19:22:50 -0800 Subject: [Tutor] variable number of inputs In-Reply-To: <49656C96.5070707@gmail.com> References: <49656C96.5070707@gmail.com> Message-ID: <78b3a9580901071922s584aafcby12bcc5865dd37263@mail.gmail.com> On Wed, Jan 7, 2009 at 7:01 PM, bob gailer wrote: > Mr Gerard Kelly wrote: >> >> How can you make a function accept a variable number of inputs without >> any particular limit? >> : >> But what if you want to be able to call the function and put in as many >> arguments as you want. > > def func(*a) # a will be a tuple of whatever arguments are passed in the call. if any of the variables are keyworded, you'll need a vararg dictionary too, **kwargs. a very popular idiom you'll see in function signatures looks like this: def func(*args, **kwargs) this is the most flexible Python function definition because this function can accept *any* number and type of arguments you can give it, i.e., func() func(a) func(a, b) func(a, b, c, d, e) func(a, b, c, d, e=0) func(a, b, 999, xxx=['foo', 'bar'], yyy=42) : hope this helps! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 "Python Fundamentals", Prentice Hall, (c)2009 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From edwin_boyette at yahoo.com Thu Jan 8 08:30:48 2009 From: edwin_boyette at yahoo.com (Edwin Boyette) Date: Wed, 7 Jan 2009 23:30:48 -0800 (PST) Subject: [Tutor] simple array access Message-ID: <707706.95402.qm@web53712.mail.re2.yahoo.com> --- On Wed, 1/7/09, Artie Ziff wrote: From: Artie Ziff Subject: [Tutor] simple array access To: Tutor at python.org Date: Wednesday, January 7, 2009, 9:12 PM Hello, I used python list comprehension to create a grid (list of lists) of Objects (instances of MyItem class). Can anyone make recommendations to achieve a simple access to the elements. My attempt at array access (like this: array[1,2] ) does not work. What am I overlooking? Thanks in advance! :) If anyone has time to show a better way to achieve same, then I am interested to learn! :) ### from pprint import * class MyItem: ? def __init__(self, value): ? ? self.data=value ? def __repr__(self): ? ? return 'MyItem(%s)' % (self.data) class Grid: ? def __init__(self, x, y, value): ? ? self.data = [[MyItem(float(value)) ? ? ? ? ? ? ? ? ? for i in range(x)] for j in range(y)] if __name__ == "__main__": ? grid = Grid(2, 3, 0.42) ? pprint(grid) ? pprint(grid.data) ? # next line fails to access array element ? pprint (grid.data[1,2]) # EOF # OUTPUT: <__main__.Grid instance at 0x7beb8> [[MyItem(0.42), MyItem(0.42)], [MyItem(0.42), MyItem(0.42)], [MyItem(0.42), MyItem(0.42)]] Traceback (most recent call last): ? File "multidim04.py", line 20, in ? ? pprint (grid.data[1,2]) TypeError: list indices must be integers Cheers, Art ? ## There are probably much easier, elegant ways to populate a list ## This is fast enough to generate to express the idea ## There is a row/col method also but I haven't used it ## List comprehensions may be prettier/faster (check Kent's page I believe he has ## write up on them some_sequence = [] i = 0 k = [] for i in range (10): ?k.append(i) for i in range (10): ??? some_sequence.append(k) for stuff in some_sequence: ??? print stuff ??? print "Some sequence has 10 outer indexes beginning at [0] and ending at [9]" print "The first element of index [0] is the value 0, and can be accessed at some_sequence[0][0] :" + str(some_sequence[0][0]) print "The last element of index [9] ## the 10th line or index is the value 9, and can be accessed at some_sequence[9][9] :" + str(some_sequence[9][9]) ?????????????????????????????????????????????????????????????????????????????????????????????????????? ??????????????????? ? ? ? -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Jan 8 10:22:07 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 8 Jan 2009 09:22:07 -0000 Subject: [Tutor] variable number of inputs References: <49656C96.5070707@gmail.com> <78b3a9580901071922s584aafcby12bcc5865dd37263@mail.gmail.com> Message-ID: "wesley chun" wrote > a very popular idiom you'll see in function signatures looks like > this: > > def func(*args, **kwargs) > > this is the most flexible Python function definition because this > function can accept *any* number and type of arguments you can give But the caveat: With power comes responsibility. You need to make sure your function can cope with this potential wealth of data being thrown at it! Othewise its all a bit pointless! :-) -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From s4027340 at student.uq.edu.au Thu Jan 8 13:12:10 2009 From: s4027340 at student.uq.edu.au (Mr Gerard Kelly) Date: Thu, 08 Jan 2009 22:12:10 +1000 Subject: [Tutor] Chord player Message-ID: I want to thank Emmanuel from the tutor mailing list for showing me a piece of code that let me do exactly what I wanted - making Python play a chord from a input of frequencies. I only needed to make a few adjustments. The code (below) uses Numeric. Emmanuel said that Numeric is out of date and should be replaced everywhere by numpy. When I do that there is no error message but the code doesn't play any sound. So I'm keeping Numeric in there (although I read somewhere that Python automatically converts Numeric to numpy anyway). I did have one problem, which is when you play a chord, you hear a clipping sound every second. I assume that is because of this line: def sine_array(hz, peak, n_samples = sample_rate): #Compute N samples of a sine wave with given frequency and peak amplitude (defaults to one second). return Numeric.resize(sine_array_onecycle(hz, peak), (n_samples,)) I thought I could get rid of the clipping noise by making it return more samples than just for one second. For instance if I put in 2*(n_samples) instead of the default sample_rate value, it might make the clipping sound come every 2 seconds etc. However, I have found that if I put in any other value other than the default value, it cannot calculate. The dimensions are wrong or there is a memory problem or something. I'm not sure how the resize method works and I was wondering if it is actually possible to fix this problem this way. Here's the whole code: *** import pygame, time, random, Numeric, pygame, pygame.sndarray sample_rate = 44100 def sine_array_onecycle(hz, peak): #Compute one cycle of an N-Hz sine wave with given peak amplitude length = sample_rate / float(hz) omega = Numeric.pi * 2 / length xvalues = Numeric.arange(int(length)) * omega return (peak * Numeric.sin(xvalues)).astype(Numeric.Int16) def sine_array(hz, peak, n_samples = sample_rate): #Compute N samples of a sine wave with given frequency and peak amplitude (defaults to one second). return Numeric.resize(sine_array_onecycle(hz, peak), (n_samples,)) def waves(*chord): #Compute the harmonic series for a vector of frequencies #Create square-like waves by adding odd-numbered overtones for each fundamental tone in the chord #the amplitudes of the overtones are inverse to their frequencies. h=9 ot=3 harmonic=sine_array(chord[0],4096) while (ot Hi everyone, I'm a python noob but I have an ambitious (for me) goal: I > want to make a simple program that allows you to hear combinations of > notes according to a vector of frequencies. > > Does anybody know any module that allows you to input a frequency in Hz > and returns a sound with that frequency, and lets you do that with > multiple frequencies, so that you can build chords? The recipe linked below plays sounds composed of a fundamental and a few harmonics. It requires Pygame and NumPy. http://osdir.com/ml/culture.people.kragen.hacks/2007-11/msg00000.html It is out of date, though. I had to change 'Numeric' to 'numpy' and 'Int16' to 'int16' to get it to work. Moreover NumPy doesn't seem to work with Python 2.6. You can also use TkSnack (http://www.speech.kth.se/snack/). Check the example named 'notescale' that comes with the module: it defines a function that receives a frequency as an input and plays a sound; there is also a graphical interface. Regards, Emmanuel -------------- next part -------------- An HTML attachment was scrubbed... URL: From s4027340 at student.uq.edu.au Thu Jan 8 13:38:34 2009 From: s4027340 at student.uq.edu.au (Mr Gerard Kelly) Date: Thu, 08 Jan 2009 22:38:34 +1000 Subject: [Tutor] Chord player Message-ID: Actually, I think I can minimize the clipping sound by setting the sample_rate to be one hundred times the value of the highest frequency in the chord. But it's still there for the notes underneath. Oh well, better than nothing! ----- Original Message ----- From: Mr Gerard Kelly Date: Thursday, January 8, 2009 10:12 pm Subject: [Tutor] Chord player > I want to thank Emmanuel from the tutor mailing list for showing me a > piece of code that let me do exactly what I wanted - making Python > playa chord from a input of frequencies. I only needed to make a few > adjustments. > > The code (below) uses Numeric. Emmanuel said that Numeric is out of > dateand should be replaced everywhere by numpy. When I do that > there is no > error message but the code doesn't play any sound. So I'm keeping > Numeric in there (although I read somewhere that Python automatically > converts Numeric to numpy anyway). > > I did have one problem, which is when you play a chord, you hear a > clipping sound every second. I assume that is because of this line: > > def sine_array(hz, peak, n_samples = sample_rate): > #Compute N samples of a sine wave with given frequency and peak > amplitude (defaults to one second). > return Numeric.resize(sine_array_onecycle(hz, peak), (n_samples,)) > > I thought I could get rid of the clipping noise by making it return > moresamples than just for one second. For instance if I put in > 2*(n_samples)instead of the default sample_rate value, it might > make the clipping > sound come every 2 seconds etc. However, I have found that if I put in > any other value other than the default value, it cannot calculate. The > dimensions are wrong or there is a memory problem or something. I'm > notsure how the resize method works and I was wondering if it is > actuallypossible to fix this problem this way. > > Here's the whole code: > > > *** > > import pygame, time, random, Numeric, pygame, pygame.sndarray > sample_rate = 44100 > > def sine_array_onecycle(hz, peak): > #Compute one cycle of an N-Hz sine wave with given peak amplitude > length = sample_rate / float(hz) > omega = Numeric.pi * 2 / length > xvalues = Numeric.arange(int(length)) * omega > return (peak * Numeric.sin(xvalues)).astype(Numeric.Int16) > > def sine_array(hz, peak, n_samples = sample_rate): > #Compute N samples of a sine wave with given frequency and peak > amplitude (defaults to one second). > > return Numeric.resize(sine_array_onecycle(hz, peak), (n_samples,)) > > def waves(*chord): > #Compute the harmonic series for a vector of frequencies > #Create square-like waves by adding odd-numbered overtones for each > fundamental tone in the chord > #the amplitudes of the overtones are inverse to their frequencies. > h=9 > ot=3 > harmonic=sine_array(chord[0],4096) > while (ot if (ot*chord[0])<(sample_rate/2): > harmonic=harmonic+(sine_array(chord[0]*ot, 4096/(2*ot))) > else: > harmonic=harmonic+0 > ot+=2 > for i in range(1,len(chord)): > harmonic+=(sine_array(chord[i], 4096)) > > > if (ot*chord[i])<(sample_rate/2): > harmonic=harmonic+(sine_array(chord[i]*ot, 4096/(2*ot))) > else: > harmonic=harmonic+0 > ot+=2 > return harmonic > > def play_for(sample_array, ms): > #Play the sample array as a sound for N ms. > pygame.mixer.pre_init(sample_rate, -16, 1) # 44.1kHz, 16-bit > signed, mono > pygame.init() > sound = pygame.sndarray.make_sound(sample_array) > sound.play(-1) > pygame.time.delay(ms) > sound.stop() > > def main(): > #Play a single sine wave, followed by a chord with overtones. > > pygame.mixer.pre_init(sample_rate, -16, 1) # 44.1kHz, 16-bit > signed, mono > pygame.init() > play_for(sine_array(440, 4096), 2500) > play_for(waves(440,550,660,770,880), 5000) > > > if __name__ == '__main__': main() > > > *** > > Thanks for having a look! > > Gerard. > -------------- next part -------------- Gerard Kelly wrote: > Hi everyone, I'm a python noob but I have an ambitious (for me) goal: I > want to make a simple program that allows you to hear combinations of > notes according to a vector of frequencies. > > Does anybody know any module that allows you to input a frequency in Hz > and returns a sound with that frequency, and lets you do that with > multiple frequencies, so that you can build chords? The recipe linked below plays sounds composed of a fundamental and a few harmonics. It requires Pygame and NumPy. http://osdir.com/ml/culture.people.kragen.hacks/2007-11/msg00000.html It is out of date, though. I had to change 'Numeric' to 'numpy' and 'Int16' to 'int16' to get it to work. Moreover NumPy doesn't seem to work with Python 2.6. You can also use TkSnack (http://www.speech.kth.se/snack/). Check the example named 'notescale' that comes with the module: it defines a function that receives a frequency as an input and plays a sound; there is also a graphical interface. Regards, Emmanuel -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From bermanrl at cfl.rr.com Thu Jan 8 16:49:10 2009 From: bermanrl at cfl.rr.com (Robert Berman) Date: Thu, 08 Jan 2009 10:49:10 -0500 Subject: [Tutor] Suggestions for more efficient and optimized coding technique, Message-ID: <49662076.3040200@cfl.rr.com> Hi, One of the challenges on the challenge you web page appropriately titled 'Brute force' reads as follows: "The password you have to guess is 'loner' . Try all combinations of lowercase letters until you guess it. Try not to loop much for example, save all used combinations in an array so you don't repeat." My code is as follows: #!/usr/bin/env python import random def GetString(): alphabet='abcdefghijklmnopqrstuvwxyz' return ''.join(random.sample(alphabet,5)) def main(): password='loner' errknt = 0 control = True while control is True: if GetString() != password: errknt +=1 else: print 'Password found in ',errknt,' tries.' control = False if __name__ == '__main__': main() The code does work. I am looking for suggestions to learn more about both efficiency and optimization of code. Since the challenge revolves around the use of randomized retrieval, I'm not too sure how to optimize the process. The authors concept of using arrays seem a bit superfluous as I think it takes longer to add an item to a dictionary and retrieve an item from a dictionary than it does to do an if compare of two 5 character strings. So, I left that code out of the program entirely. If that was wrong, or there is a better way to avoid duplication, please point me in the right direction. I think, perhaps, I could make it a tad more efficient if I changed 'alphabet' from a string to a list as I remember reading that lists are significantly faster to manipulate than are strings. Is that true and is it a viable change. I realize my code looks like modified C++ structured code. I am trying to become more Python concise but I think that is a matter of writing more and more python code. All suggestions, ideas, critiques are most welcome. Thank you, Robert From wferguson1 at socal.rr.com Thu Jan 8 17:30:07 2009 From: wferguson1 at socal.rr.com (WM.) Date: Thu, 08 Jan 2009 08:30:07 -0800 Subject: [Tutor] Thank you, Alan. Message-ID: <49662A0F.4080509@socal.rr.com> I felt such a monkey until Kent convinced me that the 'else' only appeared to be un-indented. From michael.langford at gmail.com Thu Jan 8 17:34:49 2009 From: michael.langford at gmail.com (Michael Langford) Date: Thu, 8 Jan 2009 11:34:49 -0500 Subject: [Tutor] Suggestions for more efficient and optimized coding technique, In-Reply-To: <49662076.3040200@cfl.rr.com> References: <49662076.3040200@cfl.rr.com> Message-ID: <82b4f5810901080834j28a668cbq1a1e22bd8d79a7b6@mail.gmail.com> Here is your algorithm made more pythonic. Notice the use of default parameters, doc strings, not abbreviated variable names, unix C style capitolization (very subjective, but often the one found in python libs), the avoidance of control variables when possible, the use of ascii_lowercase instead of your own string and the not calling functions main that aren't __main__. #!/usr/bin/env python import string import random def rand_string(length = 5): """returns a random string of numbers""" return ''.join(random.sample(string.ascii_lowercase,length)) def try_password(match="loner"): """randomly tries 5 letter long passwords until the user finds the correct one""" tries = 0 while True: tries += 1 if rand_string() == match: print 'Password found in ' + str(tries) + ' tries.' return if __name__ == '__main__': try_password() Note: I do not think you're doing the problem the way the author intended. As it wants you to try all combinations, and it's about brute force, not finding it quickly, you most likely should start at "aaaaa" and move to "zzzzz", and cache the results in a list like they ask you too. At the very least, you should be saving these combinations you are generating randomly in a list (as it asks you to) and not testing the password if the generated string was already in the list (as in a real application, that is the time consuming or dangerous operation). --Michael PS: If you wish to assure direct replies reach me On Thu, Jan 8, 2009 at 10:49 AM, Robert Berman wrote: > Hi, > > One of the challenges on the challenge you web page appropriately titled > 'Brute force' reads as follows: > > "The password you have to guess is 'loner' . Try all combinations of > lowercase letters until you guess it. Try not to loop much for example, > save all used combinations in an array so you don't repeat." > > My code is as follows: > > #!/usr/bin/env python > > import random > > def GetString(): > alphabet='abcdefghijklmnopqrstuvwxyz' > return ''.join(random.sample(alphabet,5)) > def main(): > password='loner' > errknt = 0 > control = True > while control is True: > if GetString() != password: > errknt +=1 > else: > print 'Password found in ',errknt,' tries.' > control = False > > if __name__ == '__main__': main() > The code does work. I am looking for suggestions to learn more about both > efficiency and optimization of code. > > Since the challenge revolves around the use of randomized retrieval, I'm not > too sure how to optimize the process. The authors concept of using arrays > seem a bit superfluous as I think it takes longer to add an item to a > dictionary and retrieve an item from a dictionary than it does to do an if > compare of two 5 character strings. So, I left that code out of the program > entirely. If that was wrong, or there is a better way to avoid duplication, > please point me in the right direction. > > I think, perhaps, I could make it a tad more efficient if I changed > 'alphabet' from a string to a list as I remember reading that lists are > significantly faster to manipulate than are strings. Is that true and is it > a viable change. > > I realize my code looks like modified C++ structured code. I am trying to > become more Python concise but I think that is a matter of writing more and > more python code. > > All suggestions, ideas, critiques are most welcome. > > Thank you, > > Robert > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Michael Langford Phone: 404-386-0495 Consulting: http://www.RowdyLabs.com From kent37 at tds.net Thu Jan 8 18:28:20 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 8 Jan 2009 12:28:20 -0500 Subject: [Tutor] Suggestions for more efficient and optimized coding technique, In-Reply-To: <49662076.3040200@cfl.rr.com> References: <49662076.3040200@cfl.rr.com> Message-ID: <1c2a2c590901080928p4bf1907fy602b5d57c7fd4617@mail.gmail.com> On Thu, Jan 8, 2009 at 10:49 AM, Robert Berman wrote: > Hi, > > One of the challenges on the challenge you web page appropriately titled > 'Brute force' reads as follows: > > "The password you have to guess is 'loner' . Try all combinations of > lowercase letters until you guess it. Try not to loop much for example, > save all used combinations in an array so you don't repeat." This is a strange requirement. If you want to try all combinations of lowercase letters, the simplest way to do that is with nested loops. The loops will generate all combinations without repeating, so there is no need to save the used combinations. > Since the challenge revolves around the use of randomized retrieval, I'm not > too sure how to optimize the process. The authors concept of using arrays > seem a bit superfluous as I think it takes longer to add an item to a > dictionary and retrieve an item from a dictionary than it does to do an if > compare of two 5 character strings. So, I left that code out of the program > entirely. If that was wrong, or there is a better way to avoid duplication, > please point me in the right direction. To avoid duplication you should use a set to hold the passwords already tried. It is probably faster to just compare, but if you are supposed to imagine a true brute-force password attack, the set test would be faster than a failed login. > I think, perhaps, I could make it a tad more efficient if I changed > 'alphabet' from a string to a list as I remember reading that lists are > significantly faster to manipulate than are strings. Is that true and is it > a viable change. I don't think it will make any difference. The place where lists are preferred is when you are concatenating strings in a loop. Kent From roadierich at googlemail.com Thu Jan 8 18:58:33 2009 From: roadierich at googlemail.com (Richard Lovely) Date: Thu, 8 Jan 2009 17:58:33 +0000 Subject: [Tutor] Suggestions for more efficient and optimized coding technique, In-Reply-To: <1c2a2c590901080928p4bf1907fy602b5d57c7fd4617@mail.gmail.com> References: <49662076.3040200@cfl.rr.com> <1c2a2c590901080928p4bf1907fy602b5d57c7fd4617@mail.gmail.com> Message-ID: 2009/1/8 Kent Johnson : > > This is a strange requirement. If you want to try all combinations of > lowercase letters, the simplest way to do that is with nested loops. > The loops will generate all combinations without repeating, so there > is no need to save the used combinations. > or itertools.product --- Richard "Roadie Rich" Lovely, part of the JNP|UK Famile www.theJNP.com From bermanrl at cfl.rr.com Thu Jan 8 19:31:51 2009 From: bermanrl at cfl.rr.com (Robert Berman) Date: Thu, 08 Jan 2009 13:31:51 -0500 Subject: [Tutor] Suggestions for more efficient and optimized coding technique, In-Reply-To: <82b4f5810901080834j28a668cbq1a1e22bd8d79a7b6@mail.gmail.com> References: <49662076.3040200@cfl.rr.com> <82b4f5810901080834j28a668cbq1a1e22bd8d79a7b6@mail.gmail.com> Message-ID: <49664697.8080700@cfl.rr.com> An HTML attachment was scrubbed... URL: From bermanrl at cfl.rr.com Thu Jan 8 19:44:59 2009 From: bermanrl at cfl.rr.com (Robert Berman) Date: Thu, 08 Jan 2009 13:44:59 -0500 Subject: [Tutor] Suggestions for more efficient and optimized coding technique, In-Reply-To: <1c2a2c590901080928p4bf1907fy602b5d57c7fd4617@mail.gmail.com> References: <49662076.3040200@cfl.rr.com> <1c2a2c590901080928p4bf1907fy602b5d57c7fd4617@mail.gmail.com> Message-ID: <496649AB.2060201@cfl.rr.com> An HTML attachment was scrubbed... URL: From bermanrl at cfl.rr.com Thu Jan 8 19:49:35 2009 From: bermanrl at cfl.rr.com (Robert Berman) Date: Thu, 08 Jan 2009 13:49:35 -0500 Subject: [Tutor] Suggestions for more efficient and optimized coding technique, In-Reply-To: References: <49662076.3040200@cfl.rr.com> <1c2a2c590901080928p4bf1907fy602b5d57c7fd4617@mail.gmail.com> Message-ID: <49664ABF.8070302@cfl.rr.com> An HTML attachment was scrubbed... URL: From finde.m at gmail.com Thu Jan 8 20:30:02 2009 From: finde.m at gmail.com (Jonathan Balkind) Date: Thu, 8 Jan 2009 19:30:02 +0000 Subject: [Tutor] Functions and Mainloop() Message-ID: <19a0f0fc0901081130y3471b6aq1be5f469f7e18bac@mail.gmail.com> Hi tutor list, I haven't been programming for long with Python, and I'm currently trying to make a simple game using Tkinter. I was wondering whether it is possible to submit a function to the mainloop so it will run every time the loop goes around? I thought about adding the function to the event handler, but I was hoping I could just submit the function to the mainloop. Thanks in advance, Jonathan. -------------- next part -------------- An HTML attachment was scrubbed... URL: From john at fouhy.net Thu Jan 8 21:14:45 2009 From: john at fouhy.net (John Fouhy) Date: Fri, 9 Jan 2009 09:14:45 +1300 Subject: [Tutor] Functions and Mainloop() In-Reply-To: <19a0f0fc0901081130y3471b6aq1be5f469f7e18bac@mail.gmail.com> References: <19a0f0fc0901081130y3471b6aq1be5f469f7e18bac@mail.gmail.com> Message-ID: <5e58f2e40901081214s85d74f7ye1777a3ff0f4ffd0@mail.gmail.com> 2009/1/9 Jonathan Balkind : > Hi tutor list, > I haven't been programming for long with Python, and I'm currently trying to > make a simple game using Tkinter. I was wondering whether it is possible to > submit a function to the mainloop so it will run every time the loop goes > around? I thought about adding the function to the event handler, but I was > hoping I could just submit the function to the mainloop. Hi Jonathan, You can use the after() method. See here: http://www.pythonware.com/library/tkinter/introduction/x9507-alarm-handlers-and-other.htm -- John. From ig2ar-saf1 at yahoo.co.uk Thu Jan 8 20:51:01 2009 From: ig2ar-saf1 at yahoo.co.uk (culpritNr1) Date: Thu, 8 Jan 2009 11:51:01 -0800 (PST) Subject: [Tutor] casting string to integer in a list of lists Message-ID: <21359600.post@talk.nabble.com> Hi All, Say I have this nice list of lists: LoL = [['chrX', '160944034', '160944035', 'gnfX.145.788', '63.60'], ['chrX', '161109992', '161109993', 'rs13484104', '63.60'], ['chrX', '161414112', '161414113', 'rs13484105', '63.60'], ['chrX', '161544071', '161544072', 'rs13484106', '63.60'], ['chrX', '162030736', '162030737', 'gnfX.146.867', '67.05'], ['chrX', '164171913', '164171914', 'gnfX.148.995', '70.45']] Now I want to cast the second and third "columns" from string to integer, like this LoL = [['chrX', 160944034, 160944035, 'gnfX.145.788', '63.60'], ['chrX', 161109992, 161109993, 'rs13484104', '63.60'], ['chrX', 161414112, 161414113, 'rs13484105', '63.60'], ['chrX', 161544071, 161544072, 'rs13484106', '63.60'], ['chrX', 162030736, 162030737, 'gnfX.146.867', '67.05'], ['chrX', 164171913, 164171914, 'gnfX.148.995', '70.45']] Is there any elegant way to do this? I can't assume that all lines will have the same number of elements. Thank you, Your Culprit -- View this message in context: http://www.nabble.com/casting-string-to-integer-in-a-list-of-lists-tp21359600p21359600.html Sent from the Python - tutor mailing list archive at Nabble.com. From michael.langford at rowdylabs.com Thu Jan 8 21:20:12 2009 From: michael.langford at rowdylabs.com (Michael Langford) Date: Thu, 8 Jan 2009 15:20:12 -0500 Subject: [Tutor] Suggestions for more efficient and optimized coding technique, In-Reply-To: <49664697.8080700@cfl.rr.com> References: <49662076.3040200@cfl.rr.com> <82b4f5810901080834j28a668cbq1a1e22bd8d79a7b6@mail.gmail.com> <49664697.8080700@cfl.rr.com> Message-ID: <11fb08580901081220r4339dd16kf7bac4c876e32f8e@mail.gmail.com> I understand that each response is unique Robert and no caching is required to solve the problem at hand. However in a real program, the chance you're brute forcing just one password is small (usually you would brute force many); additionally, the question posted specifically asked that the trials be cached, which is why I suggest you do so, not out of any real need for just testing on the "loner" testcase. Additionally, the reason the aaaaa->zzzzz method is suggested is that it a much faster algorithm to test every available combination than the random method. The random method may never find the data. I've created a frame work for you to play around with on this problem. It shows how long different methods take in a more realistic scenario. Try some other methods if you want, as well play around with password length, the aaaaa->zzzzz method, etc. I've shorted then password length to 3 to make it run faster as well. Enough procrastination, back to google app engine stuff. --Michael #!/usr/bin/env python import string import random # test code to simulate a computer system under # attack, no need to understand now class Computer(object): def __init__(self): self.reset_password() def reset_password(self,length=3): self.secret_password=''.join(random.sample(string.ascii_lowercase,length)) print('The new password is: ' + self.secret_password) def enter_password(self,teststr): """returns true if the password was correct""" return teststr==self.secret_password # end test code def rand_string(length = 3): """generates a random string of the given length""" return ''.join(random.sample(string.ascii_lowercase,length)) passcache = list() def crack_password(comp): """repeatedly tries passwords on the given computer""" tries = 0 while True: tries += 1 if comp.enter_password(rand_string()): print( 'Password found in ' + str(tries) + ' tries.') return def crack_password_cached(comp): """repeatedly tries passwords on the given computer""" for password in passcache: if comp.enter_password(password): print 'Password found in cache' return tries = 0 while True: tries += 1 s = rand_string() passcache.append(s) if comp.enter_password(s): print( 'Password found in ' + str(tries) + ' tries.') return def hack(): """hacks a computer via a brute force method""" my_computer = Computer() crack_password(my_computer) def hack_cached(): """hacks a computer via a brute force method with cached results""" my_computer = Computer() crack_password_cached(my_computer) def mean(ls): """finds the mean of a list of numbers""" return sum(ls)/len(ls) def test_case(funcname, repeats): """ timeit is a python library for timing code. No need to understand how this works, just that its repeating the command given the number times specified by repeats. It's returning a list of the execution times of each of the trials """ import timeit timer = timeit.Timer("%s()"%funcname,"from __main__ import %s"%funcname) return timer.repeat(number=repeats) if __name__ == '__main__': times_to_repeat = 100 uc_results = test_case("hack",times_to_repeat) c_results = test_case("hack_cached", times_to_repeat) print( "Cached mean time: " + repr(mean(c_results)) ) print( "Cached min. time: " + repr(min(c_results)) ) print( "Uncached mean time: " + repr(mean(uc_results)) ) print( "Uncached min. time: " + repr(min(uc_results)) ) On Thu, Jan 8, 2009 at 1:31 PM, Robert Berman wrote: > Michael, > > Thank you for your code and your commentary. The code tells me this is > really an ongoing learning process; almost as convoluted as linguistics and > certainly every bit as interesting. > > Your concept of brute force in this example is intriguing. It is as if I > have five cogs spinning, 'a' the slowest and 'e' flying as fast as its > spokes can engage, and every click of every wheel produces a viable but > possibly wrong response. However, each response is unique and in the nth > iteration where password is found, all previous iterations are unique so > there is certainly no need to carry the previous responses in either a list > or a dictionary. They do not duplicate since they cannot repeat. Other than > to include extraneous code, why include repetitive checking at all? > > In spite of that, your code and your remarks are most appreciated. > > Robert > > Michael Langford wrote: > > Here is your algorithm made more pythonic. Notice the use of default > parameters, doc strings, not abbreviated variable names, unix C style > capitolization (very subjective, but often the one found in python > libs), the avoidance of control variables when possible, the use of > ascii_lowercase instead of your own string and the not calling > functions main that aren't __main__. > > #!/usr/bin/env python > import string > import random > > def rand_string(length = 5): > """returns a random string of numbers""" > return ''.join(random.sample(string.ascii_lowercase,length)) > > def try_password(match="loner"): > """randomly tries 5 letter long passwords until the user finds the > correct one""" > tries = 0 > while True: > tries += 1 > if rand_string() == match: > print 'Password found in ' + str(tries) + ' tries.' > return > > if __name__ == '__main__': > try_password() > > > Note: I do not think you're doing the problem the way the author > intended. As it wants you to try all combinations, and it's about > brute force, not finding it quickly, you most likely should start at > "aaaaa" and move to "zzzzz", and cache the results in a list like they > ask you too. At the very least, you should be saving these > combinations you are generating randomly in a list (as it asks you to) > and not testing the password if the generated string was already in > the list (as in a real application, that is the time consuming or > dangerous operation). > > --Michael > > PS: If you wish to assure direct replies reach me > > On Thu, Jan 8, 2009 at 10:49 AM, Robert Berman wrote: > > > Hi, > > One of the challenges on the challenge you web page appropriately titled > 'Brute force' reads as follows: > > "The password you have to guess is 'loner' . Try all combinations of > lowercase letters until you guess it. Try not to loop much for example, > save all used combinations in an array so you don't repeat." > > My code is as follows: > > #!/usr/bin/env python > > import random > > def GetString(): > alphabet='abcdefghijklmnopqrstuvwxyz' > return ''.join(random.sample(alphabet,5)) > def main(): > password='loner' > errknt = 0 > control = True > while control is True: > if GetString() != password: > errknt +=1 > else: > print 'Password found in ',errknt,' tries.' > control = False > > if __name__ == '__main__': main() > The code does work. I am looking for suggestions to learn more about both > efficiency and optimization of code. > > Since the challenge revolves around the use of randomized retrieval, I'm not > too sure how to optimize the process. The authors concept of using arrays > seem a bit superfluous as I think it takes longer to add an item to a > dictionary and retrieve an item from a dictionary than it does to do an if > compare of two 5 character strings. So, I left that code out of the program > entirely. If that was wrong, or there is a better way to avoid duplication, > please point me in the right direction. > > I think, perhaps, I could make it a tad more efficient if I changed > 'alphabet' from a string to a list as I remember reading that lists are > significantly faster to manipulate than are strings. Is that true and is it > a viable change. > > I realize my code looks like modified C++ structured code. I am trying to > become more Python concise but I think that is a matter of writing more and > more python code. > > All suggestions, ideas, critiques are most welcome. > > Thank you, > > Robert > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > > -- Michael Langford Phone: 404-386-0495 Web: http://www.RowdyLabs.com From bermanrl at cfl.rr.com Thu Jan 8 21:46:57 2009 From: bermanrl at cfl.rr.com (Robert Berman) Date: Thu, 08 Jan 2009 15:46:57 -0500 Subject: [Tutor] Suggestions for more efficient and optimized coding technique, In-Reply-To: <11fb08580901081220r4339dd16kf7bac4c876e32f8e@mail.gmail.com> References: <49662076.3040200@cfl.rr.com> <82b4f5810901080834j28a668cbq1a1e22bd8d79a7b6@mail.gmail.com> <49664697.8080700@cfl.rr.com> <11fb08580901081220r4339dd16kf7bac4c876e32f8e@mail.gmail.com> Message-ID: <49666641.2090401@cfl.rr.com> Thank you again. I now have enough to keep me happily busy for days. Robert Michael Langford wrote: > I understand that each response is unique Robert and no caching is > required to solve the problem at hand. However in a real program, the > chance you're brute forcing just one password is small (usually you > would brute force many); additionally, the question posted > specifically asked that the trials be cached, which is why I suggest > you do so, not out of any real need for just testing on the "loner" > testcase. > > Additionally, the reason the aaaaa->zzzzz method is suggested is that > it a much faster algorithm to test every available combination than > the random method. The random method may never find the data. > > I've created a frame work for you to play around with on this problem. > It shows how long different methods take in a more realistic scenario. > Try some other methods if you want, as well play around with password > length, the aaaaa->zzzzz method, etc. I've shorted then password > length to 3 to make it run faster as well. Enough procrastination, > back to google app engine stuff. > > --Michael > > #!/usr/bin/env python > import string > import random > > # test code to simulate a computer system under > # attack, no need to understand now > class Computer(object): > def __init__(self): > self.reset_password() > > def reset_password(self,length=3): > self.secret_password=''.join(random.sample(string.ascii_lowercase,length)) > print('The new password is: ' + self.secret_password) > > def enter_password(self,teststr): > """returns true if the password was correct""" > return teststr==self.secret_password > > # end test code > > > def rand_string(length = 3): > """generates a random string of the given length""" > return ''.join(random.sample(string.ascii_lowercase,length)) > > passcache = list() > > def crack_password(comp): > """repeatedly tries passwords on the given computer""" > tries = 0 > while True: > tries += 1 > if comp.enter_password(rand_string()): > print( 'Password found in ' + str(tries) + ' tries.') > return > > def crack_password_cached(comp): > """repeatedly tries passwords on the given computer""" > for password in passcache: > if comp.enter_password(password): > print 'Password found in cache' > return > > tries = 0 > while True: > tries += 1 > s = rand_string() > passcache.append(s) > if comp.enter_password(s): > print( 'Password found in ' + str(tries) + ' tries.') > return > > > def hack(): > """hacks a computer via a brute force method""" > my_computer = Computer() > crack_password(my_computer) > > def hack_cached(): > """hacks a computer via a brute force method with cached results""" > my_computer = Computer() > crack_password_cached(my_computer) > > > def mean(ls): > """finds the mean of a list of numbers""" > return sum(ls)/len(ls) > > > def test_case(funcname, repeats): > """ > timeit is a python library for timing code. No need to > understand how this works, just that its repeating the > command given the number times specified by repeats. It's > returning a list of the execution times of each of the trials > """ > import timeit > timer = timeit.Timer("%s()"%funcname,"from __main__ import %s"%funcname) > return timer.repeat(number=repeats) > > > if __name__ == '__main__': > > > times_to_repeat = 100 > > uc_results = test_case("hack",times_to_repeat) > c_results = test_case("hack_cached", times_to_repeat) > > print( "Cached mean time: " + repr(mean(c_results)) ) > print( "Cached min. time: " + repr(min(c_results)) ) > print( "Uncached mean time: " + repr(mean(uc_results)) ) > print( "Uncached min. time: " + repr(min(uc_results)) ) > > > > > > > > > > On Thu, Jan 8, 2009 at 1:31 PM, Robert Berman wrote: > >> Michael, >> >> Thank you for your code and your commentary. The code tells me this is >> really an ongoing learning process; almost as convoluted as linguistics and >> certainly every bit as interesting. >> >> Your concept of brute force in this example is intriguing. It is as if I >> have five cogs spinning, 'a' the slowest and 'e' flying as fast as its >> spokes can engage, and every click of every wheel produces a viable but >> possibly wrong response. However, each response is unique and in the nth >> iteration where password is found, all previous iterations are unique so >> there is certainly no need to carry the previous responses in either a list >> or a dictionary. They do not duplicate since they cannot repeat. Other than >> to include extraneous code, why include repetitive checking at all? >> >> In spite of that, your code and your remarks are most appreciated. >> >> Robert >> >> Michael Langford wrote: >> >> Here is your algorithm made more pythonic. Notice the use of default >> parameters, doc strings, not abbreviated variable names, unix C style >> capitolization (very subjective, but often the one found in python >> libs), the avoidance of control variables when possible, the use of >> ascii_lowercase instead of your own string and the not calling >> functions main that aren't __main__. >> >> #!/usr/bin/env python >> import string >> import random >> >> def rand_string(length = 5): >> """returns a random string of numbers""" >> return ''.join(random.sample(string.ascii_lowercase,length)) >> >> def try_password(match="loner"): >> """randomly tries 5 letter long passwords until the user finds the >> correct one""" >> tries = 0 >> while True: >> tries += 1 >> if rand_string() == match: >> print 'Password found in ' + str(tries) + ' tries.' >> return >> >> if __name__ == '__main__': >> try_password() >> >> >> Note: I do not think you're doing the problem the way the author >> intended. As it wants you to try all combinations, and it's about >> brute force, not finding it quickly, you most likely should start at >> "aaaaa" and move to "zzzzz", and cache the results in a list like they >> ask you too. At the very least, you should be saving these >> combinations you are generating randomly in a list (as it asks you to) >> and not testing the password if the generated string was already in >> the list (as in a real application, that is the time consuming or >> dangerous operation). >> >> --Michael >> >> PS: If you wish to assure direct replies reach me >> >> On Thu, Jan 8, 2009 at 10:49 AM, Robert Berman wrote: >> >> >> Hi, >> >> One of the challenges on the challenge you web page appropriately titled >> 'Brute force' reads as follows: >> >> "The password you have to guess is 'loner' . Try all combinations of >> lowercase letters until you guess it. Try not to loop much for example, >> save all used combinations in an array so you don't repeat." >> >> My code is as follows: >> >> #!/usr/bin/env python >> >> import random >> >> def GetString(): >> alphabet='abcdefghijklmnopqrstuvwxyz' >> return ''.join(random.sample(alphabet,5)) >> def main(): >> password='loner' >> errknt = 0 >> control = True >> while control is True: >> if GetString() != password: >> errknt +=1 >> else: >> print 'Password found in ',errknt,' tries.' >> control = False >> >> if __name__ == '__main__': main() >> The code does work. I am looking for suggestions to learn more about both >> efficiency and optimization of code. >> >> Since the challenge revolves around the use of randomized retrieval, I'm not >> too sure how to optimize the process. The authors concept of using arrays >> seem a bit superfluous as I think it takes longer to add an item to a >> dictionary and retrieve an item from a dictionary than it does to do an if >> compare of two 5 character strings. So, I left that code out of the program >> entirely. If that was wrong, or there is a better way to avoid duplication, >> please point me in the right direction. >> >> I think, perhaps, I could make it a tad more efficient if I changed >> 'alphabet' from a string to a list as I remember reading that lists are >> significantly faster to manipulate than are strings. Is that true and is it >> a viable change. >> >> I realize my code looks like modified C++ structured code. I am trying to >> become more Python concise but I think that is a matter of writing more and >> more python code. >> >> All suggestions, ideas, critiques are most welcome. >> >> Thank you, >> >> Robert >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> >> >> >> >> > > > > From denis.spir at free.fr Thu Jan 8 22:06:30 2009 From: denis.spir at free.fr (spir) Date: Thu, 8 Jan 2009 22:06:30 +0100 Subject: [Tutor] Suggestions for more efficient and optimized coding technique, In-Reply-To: <82b4f5810901080834j28a668cbq1a1e22bd8d79a7b6@mail.gmail.com> References: <49662076.3040200@cfl.rr.com> <82b4f5810901080834j28a668cbq1a1e22bd8d79a7b6@mail.gmail.com> Message-ID: <20090108220630.14a899a7@o> Le Thu, 8 Jan 2009 11:34:49 -0500, "Michael Langford" a ?crit : > Here is your algorithm made more pythonic. Notice the use of default > parameters, doc strings, not abbreviated variable names, unix C style > capitolization (very subjective, but often the one found in python > libs), the avoidance of control variables when possible, the use of > ascii_lowercase instead of your own string and the not calling > functions main that aren't __main__. > > #!/usr/bin/env python > import string > import random > > def rand_string(length = 5): > """returns a random string of numbers""" > return ''.join(random.sample(string.ascii_lowercase,length)) Since you wish to use (not necessary) optional args, it may be worth defining def rand_string(length = 5): """returns a random string of numbers""" return ''.join(random.sample(string.ascii_lowercase,length)) which also avoids reading string.ascii_lowercase in each loop denis From marc.tompkins at gmail.com Thu Jan 8 22:26:28 2009 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Thu, 8 Jan 2009 13:26:28 -0800 Subject: [Tutor] casting string to integer in a list of lists In-Reply-To: <21359600.post@talk.nabble.com> References: <21359600.post@talk.nabble.com> Message-ID: <40af687b0901081326l93a793mb9b0158ba7c71373@mail.gmail.com> On Thu, Jan 8, 2009 at 11:51 AM, culpritNr1 wrote: > > Hi All, > > Say I have this nice list of lists: > > LoL = [['chrX', '160944034', '160944035', 'gnfX.145.788', '63.60'], > ['chrX', '161109992', '161109993', 'rs13484104', '63.60'], > ['chrX', '161414112', '161414113', 'rs13484105', '63.60'], > ['chrX', '161544071', '161544072', 'rs13484106', '63.60'], > ['chrX', '162030736', '162030737', 'gnfX.146.867', '67.05'], > ['chrX', '164171913', '164171914', 'gnfX.148.995', '70.45']] > > Now I want to cast the second and third "columns" from string to integer, > like this > > LoL = [['chrX', 160944034, 160944035, 'gnfX.145.788', '63.60'], > ['chrX', 161109992, 161109993, 'rs13484104', '63.60'], > ['chrX', 161414112, 161414113, 'rs13484105', '63.60'], > ['chrX', 161544071, 161544072, 'rs13484106', '63.60'], > ['chrX', 162030736, 162030737, 'gnfX.146.867', '67.05'], > ['chrX', 164171913, 164171914, 'gnfX.148.995', '70.45']] > > Is there any elegant way to do this? I can't assume that all lines will > have > the same number of elements. > Maybe not the most elegant way, but here's a quickie: print(LoL) for lstA in LoL: try: lstA[1] = int(lstA[1]) except: pass try: lstA[2] = int(lstA[2]) except: pass print(LoL) I put them in separate try/excepts in case the first one's not an integer but the second one is. -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From denis.spir at free.fr Thu Jan 8 22:57:52 2009 From: denis.spir at free.fr (spir) Date: Thu, 8 Jan 2009 22:57:52 +0100 Subject: [Tutor] casting string to integer in a list of lists In-Reply-To: <21359600.post@talk.nabble.com> References: <21359600.post@talk.nabble.com> Message-ID: <20090108225752.2977c752@o> Le Thu, 8 Jan 2009 11:51:01 -0800 (PST), culpritNr1 a ?crit : > > Hi All, > > Say I have this nice list of lists: > > LoL = [['chrX', '160944034', '160944035', 'gnfX.145.788', '63.60'], > ['chrX', '161109992', '161109993', 'rs13484104', '63.60'], > ['chrX', '161414112', '161414113', 'rs13484105', '63.60'], > ['chrX', '161544071', '161544072', 'rs13484106', '63.60'], > ['chrX', '162030736', '162030737', 'gnfX.146.867', '67.05'], > ['chrX', '164171913', '164171914', 'gnfX.148.995', '70.45']] > > Now I want to cast the second and third "columns" from string to integer, > like this > > LoL = [['chrX', 160944034, 160944035, 'gnfX.145.788', '63.60'], > ['chrX', 161109992, 161109993, 'rs13484104', '63.60'], > ['chrX', 161414112, 161414113, 'rs13484105', '63.60'], > ['chrX', 161544071, 161544072, 'rs13484106', '63.60'], > ['chrX', 162030736, 162030737, 'gnfX.146.867', '67.05'], > ['chrX', 164171913, 164171914, 'gnfX.148.995', '70.45']] > > Is there any elegant way to do this? I can't assume that all lines will have > the same number of elements. In you do not need checking whether specific items are "castable" (i.e. you really know what's in the list) you may use such a pattern: lol = [[1,2,3],[4,5,6],[7,8,9]] new_lol = [[a,b**3,c] for [a,b,c] in lol] print lol print new_lol ==> [[1, 2, 3], [4, 5, 6], [7, 8, 9]] [[1, 8, 3], [4, 125, 6], [7, 512, 9]] denis > Thank you, > > Your Culprit > > ------ la vida e estranya From wescpy at gmail.com Thu Jan 8 23:21:39 2009 From: wescpy at gmail.com (wesley chun) Date: Thu, 8 Jan 2009 14:21:39 -0800 Subject: [Tutor] casting string to integer in a list of lists In-Reply-To: <40af687b0901081326l93a793mb9b0158ba7c71373@mail.gmail.com> References: <21359600.post@talk.nabble.com> <40af687b0901081326l93a793mb9b0158ba7c71373@mail.gmail.com> Message-ID: <78b3a9580901081421q7086bakbdd2a9b54bcfd060@mail.gmail.com> >> LoL = [['chrX', '160944034', '160944035', 'gnfX.145.788', '63.60'], >> : >> Now I want to cast the second and third "columns" from string to integer, >> like this >> >> LoL = [['chrX', 160944034, 160944035, 'gnfX.145.788', '63.60'], >> : >> Is there any elegant way to do this? I can't assume that all lines will >> have the same number of elements. the easiest way to do it is using int(), as in the below. > for lstA in LoL: > try: > lstA[1] = int(lstA[1]) > except: > pass > try: > lstA[2] = int(lstA[2]) > except: > pass it's definitely a *good* idea to check and make sure the numbers are legit, meaning that int() won't throw an exception, but it is a *bad* idea to have any code anywhere that looks like: except: pass try not to code these 2 lines in anything that you do because it will come back to haunt you when something is not working right but you can't find any errors. that's because this code masks and throws away everything!! if you are guaranteed that the strings all contain valid integers, then you don't have to worry about problems calling int(). hope this helps! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 "Python Fundamentals", Prentice Hall, (c)2009 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From david at hlacik.eu Thu Jan 8 23:24:21 2009 From: david at hlacik.eu (=?ISO-8859-2?Q?David_Hl=E1=E8ik?=) Date: Thu, 8 Jan 2009 23:24:21 +0100 Subject: [Tutor] linked list with cycle structure In-Reply-To: <6smp37F763pbU2@mid.uni-berlin.de> References: <6sjok8F6dqciU1@mid.uni-berlin.de> <6smp37F763pbU2@mid.uni-berlin.de> Message-ID: Hi, well i am able to find a loop in a list using two iterators.One iterator runs "two times faster than the other", and if he encounters the first, it means that there is a loop. Example : 1,2,3,4,5,6,7,8,9,5 the algorithm would generate: start - 1,2 iteration 1- 2, 4 iteration 2- 3, 6 iteration 3- 4, 8 iteration 4- 5, 5 ( match) But how can this help me with counting list elements? :( Thanks, D. On Thu, Jan 8, 2009 at 5:48 PM, Diez B. Roggisch wrote: > > David Hl??ik wrote: > > > Hi, > > > > so okay, i will create a helping set, where i will be adding elements > > ID, when element ID will be allready in my helping set i will stop and > > count number of elements in helping set. This is how long my cycled > > linked list is. > > > But what if i have another condition , and that is *i can use only > > helping memory with constant size* ? This means i am not able to > > create any set and adding elements there. I need to have a constant > > size variables . This is complication a complication for me. > > This isn't to hard - think about what you are really interested in - knowing > if *all* other elements are already counted, or a specific one? You can get > away with only one, to detect the cycle and abort. > > Diez > -- > http://mail.python.org/mailman/listinfo/python-list From marc.tompkins at gmail.com Fri Jan 9 00:11:13 2009 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Thu, 8 Jan 2009 15:11:13 -0800 Subject: [Tutor] casting string to integer in a list of lists In-Reply-To: <78b3a9580901081421q7086bakbdd2a9b54bcfd060@mail.gmail.com> References: <21359600.post@talk.nabble.com> <40af687b0901081326l93a793mb9b0158ba7c71373@mail.gmail.com> <78b3a9580901081421q7086bakbdd2a9b54bcfd060@mail.gmail.com> Message-ID: <40af687b0901081511r5530db39kc03ce880ead73a22@mail.gmail.com> On Thu, Jan 8, 2009 at 2:21 PM, wesley chun wrote: > except: > pass > > try not to code these 2 lines in anything that you do because it will > come back to haunt you when something is not working right but you > can't find any errors. that's because this code masks and throws away > everything!! > > if you are guaranteed that the strings all contain valid integers, > then you don't have to worry about problems calling int(). > OP said we couldn't be sure that all rows would have the same number of elements; I'm afraid I extrapolated that we also might not be sure they were all integers (or, I should say, strings representing integers...), so there are two potential error types: IndexError and ValueError. I assumed that if either one occurred, we would want to leave that particular list member (if it exists) as-is (hence the pass). I see three ways around this: - test each list for length, and each member for integer-ness, before casting anything; - catch the exception, test to see whether it's an IndexError or a ValueError, and if not then do something; - print/log every exception. The first one violates "It's better to ask forgiveness than to ask permission" (and it's slow), the second one's a pain in the butt; the third one gets slow if LoL is large and has many non-standard members. Is there a fourth way? Actually, I'm asking because I've run into similar situations and been dissatisfied with my own solution. Generally, if there are two or more "acceptable" errors that you can foresee, but you still want to catch any others, what's an elegant, readable, and computationally-cheap way to do it? Maybe a dictionary of exceptions...? -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From wescpy at gmail.com Fri Jan 9 00:45:56 2009 From: wescpy at gmail.com (wesley chun) Date: Thu, 8 Jan 2009 15:45:56 -0800 Subject: [Tutor] casting string to integer in a list of lists In-Reply-To: <40af687b0901081511r5530db39kc03ce880ead73a22@mail.gmail.com> References: <21359600.post@talk.nabble.com> <40af687b0901081326l93a793mb9b0158ba7c71373@mail.gmail.com> <78b3a9580901081421q7086bakbdd2a9b54bcfd060@mail.gmail.com> <40af687b0901081511r5530db39kc03ce880ead73a22@mail.gmail.com> Message-ID: <78b3a9580901081545v6a5b89adi70afc930e53c1275@mail.gmail.com> >> except: >> pass >> >> try not to code these 2 lines in anything that you do because it will >> come back to haunt you when something is not working right but you >> can't find any errors. that's because this code masks and throws away >> everything!! > > there are two potential error types: IndexError and ValueError. I assumed that if > either one occurred, we would want to leave that particular list member (if > it exists) as-is (hence the pass). > : > - catch the exception, test to see whether it's an IndexError or a > ValueError, and if not then do something; > : as opposed to the above... except (IndexError, ValueError): pass ...is much more acceptable. there are 2 general conventions: - catch errors explicitly (as to not mask the others) and pass/ignore - catch 'em all (except Exception) and do *some*thing (not pass) both of those cases shows that you did your due diligence and that you're just not blindly throwing things away. > Generally, if there are two or more "acceptable" errors that you can foresee, > but you still want to catch any others, what's an elegant, readable, and > computationally-cheap way to do it? Maybe a dictionary of exceptions...? A tuple of exceptions works, just like what we did above, and more, i.e., (IndexError, ValueError, TypeError, KeyError... hope this helps! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 "Python Fundamentals", Prentice Hall, (c)2009 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From alan.gauld at btinternet.com Fri Jan 9 02:18:25 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 9 Jan 2009 01:18:25 -0000 Subject: [Tutor] casting string to integer in a list of lists References: <21359600.post@talk.nabble.com> Message-ID: "culpritNr1" wrote > Say I have this nice list of lists: > > LoL = [['chrX', '160944034', '160944035', 'gnfX.145.788', '63.60'], > ['chrX', '161109992', '161109993', 'rs13484104', > '63.60'], > Now I want to cast the second and third "columns" from string to > integer, > like this > > LoL = [['chrX', 160944034, 160944035, 'gnfX.145.788', '63.60'], > ['chrX', 161109992, 161109993, 'rs13484104', '63.60'], Being picky that's not really casting that's converting. Casting is where you take the same set of binary data and treat it as if it were a different type but without changing the binary. Conversion is where you actually change the data into a new representation. Conversion is relatively easy in Python, casting is a bit more tricky. Alan G. From marc.tompkins at gmail.com Fri Jan 9 02:29:11 2009 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Thu, 8 Jan 2009 17:29:11 -0800 Subject: [Tutor] casting string to integer in a list of lists In-Reply-To: <78b3a9580901081545v6a5b89adi70afc930e53c1275@mail.gmail.com> References: <21359600.post@talk.nabble.com> <40af687b0901081326l93a793mb9b0158ba7c71373@mail.gmail.com> <78b3a9580901081421q7086bakbdd2a9b54bcfd060@mail.gmail.com> <40af687b0901081511r5530db39kc03ce880ead73a22@mail.gmail.com> <78b3a9580901081545v6a5b89adi70afc930e53c1275@mail.gmail.com> Message-ID: <40af687b0901081729w12d8f635yc15ad30542049dc7@mail.gmail.com> On Thu, Jan 8, 2009 at 3:45 PM, wesley chun wrote: > A tuple of exceptions works, just like what we did above, and more, > i.e., (IndexError, ValueError, TypeError, KeyError... > > Thank you, thank you, thank you! I'm sure it's been staring me in the face, but I never realized I could use a tuple of exception types - that's why I said it was a pain in the butt, trapping the exception and doing "isinstance" checks against it. How did I miss this? Learn something new every day, no? -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From michael at arpsorensen.dk Fri Jan 9 09:27:19 2009 From: michael at arpsorensen.dk (=?UTF-8?Q?Michael_Bernhard_Arp_S=C3=B8rensen?=) Date: Fri, 9 Jan 2009 09:27:19 +0100 Subject: [Tutor] Python debugger Message-ID: <1618520901090027y5ac4e16fr9cafbba728748099@mail.gmail.com> Hi there. I've just started using the python debugger and I wonder how I could have lived without it earlier. I just wonder if there is a smarter way to show what all the variables contain in any given point in the debugger. I'm using this approach: import sys f = sys._getframe() p f.f_locals.items() It's not exacly pretty in its output, but it's better than nothing. Can this be done in a smarter way? -- Kind regards Michael B. Arp S?rensen Programmer / BOFH "Ride out and meet them." -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Fri Jan 9 12:38:08 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 9 Jan 2009 06:38:08 -0500 Subject: [Tutor] Python debugger In-Reply-To: <1618520901090027y5ac4e16fr9cafbba728748099@mail.gmail.com> References: <1618520901090027y5ac4e16fr9cafbba728748099@mail.gmail.com> Message-ID: <1c2a2c590901090338w2bd9da1fo4981c55f21ff0f42@mail.gmail.com> On Fri, Jan 9, 2009 at 3:27 AM, Michael Bernhard Arp S?rensen wrote: > Hi there. > > I've just started using the python debugger and I wonder how I could have > lived without it earlier. > > I just wonder if there is a smarter way to show what all the variables > contain in any given point in the debugger. I'm using this approach: > > import sys > f = sys._getframe() > p f.f_locals.items() > > It's not exacly pretty in its output, but it's better than nothing. Can this > be done in a smarter way? 'a' will show the arguments to the current function; not the same but shorter. p locals().items() is probably the same as what you are doing. You might want to look at a graphical debugger such as winpdb. Kent From michael at arpsorensen.dk Fri Jan 9 13:36:25 2009 From: michael at arpsorensen.dk (=?UTF-8?Q?Michael_Bernhard_Arp_S=C3=B8rensen?=) Date: Fri, 9 Jan 2009 13:36:25 +0100 Subject: [Tutor] Python debugger In-Reply-To: <1c2a2c590901090338w2bd9da1fo4981c55f21ff0f42@mail.gmail.com> References: <1618520901090027y5ac4e16fr9cafbba728748099@mail.gmail.com> <1c2a2c590901090338w2bd9da1fo4981c55f21ff0f42@mail.gmail.com> Message-ID: <1618520901090436n47d9e0a6ld1f2f1ca64a787d@mail.gmail.com> Hi. Thanks for the input. Your way of doing it is simpler and possible to use as an alias in pdb. I can't use a graphical debugger because i mostly code python over ssh on remote servers in my company. Thanks anyway. It was actually helpfull. :-) /Michael On Fri, Jan 9, 2009 at 12:38 PM, Kent Johnson wrote: > On Fri, Jan 9, 2009 at 3:27 AM, Michael Bernhard Arp S?rensen > wrote: > > Hi there. > > > > I've just started using the python debugger and I wonder how I could have > > lived without it earlier. > > > > I just wonder if there is a smarter way to show what all the variables > > contain in any given point in the debugger. I'm using this approach: > > > > import sys > > f = sys._getframe() > > p f.f_locals.items() > > > > It's not exacly pretty in its output, but it's better than nothing. Can > this > > be done in a smarter way? > > 'a' will show the arguments to the current function; not the same but > shorter. > p locals().items() is probably the same as what you are doing. > > You might want to look at a graphical debugger such as winpdb. > > Kent > -------------- next part -------------- An HTML attachment was scrubbed... URL: From T.Gkikopoulos at dundee.ac.uk Fri Jan 9 13:53:54 2009 From: T.Gkikopoulos at dundee.ac.uk (Triantafyllos Gkikopoulos) Date: Fri, 09 Jan 2009 12:53:54 +0000 Subject: [Tutor] casting string to integer in a list of lists Message-ID: <496748E2020000B30000179D@gw-out.dundee.ac.uk> Hi Your, I work with genomic datasets as well and have recently only started working with python (so my advice is a bit naive) I would say although there may be different ways you can cast an integer or float type into your list of lists you may actually no need to do so with your starting file/list... ie: if for example you want to do stuff with the location chrX with start 160944034 and end 160944035 you could: for x in LoL: startstring=LoL[1] #this would be '160944034' startint=int(startstring) #this would be 160944034 now if you also use a counter you can iterate and do all sort of calculations for different genomic locations. I use the csv module and then append into a numpy array that takes type float, so you could work with that as well, cheers Dr Triantafyllos Gkikopoulos >>> culpritNr1 01/08/09 8:42 PM >>> Hi All, Say I have this nice list of lists: LoL = [['chrX', '160944034', '160944035', 'gnfX.145.788', '63.60'], ['chrX', '161109992', '161109993', 'rs13484104', '63.60'], ['chrX', '161414112', '161414113', 'rs13484105', '63.60'], ['chrX', '161544071', '161544072', 'rs13484106', '63.60'], ['chrX', '162030736', '162030737', 'gnfX.146.867', '67.05'], ['chrX', '164171913', '164171914', 'gnfX.148.995', '70.45']] Now I want to cast the second and third "columns" from string to integer, like this LoL = [['chrX', 160944034, 160944035, 'gnfX.145.788', '63.60'], ['chrX', 161109992, 161109993, 'rs13484104', '63.60'], ['chrX', 161414112, 161414113, 'rs13484105', '63.60'], ['chrX', 161544071, 161544072, 'rs13484106', '63.60'], ['chrX', 162030736, 162030737, 'gnfX.146.867', '67.05'], ['chrX', 164171913, 164171914, 'gnfX.148.995', '70.45']] Is there any elegant way to do this? I can't assume that all lines will have the same number of elements. Thank you, Your Culprit -- View this message in context: http://www.nabble.com/casting-string-to-integer-in-a-list-of-lists-tp21359600p21359600.html Sent from the Python - tutor mailing list archive at Nabble.com. _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor The University of Dundee is a registered Scottish charity, No: SC015096 From kent37 at tds.net Fri Jan 9 15:14:18 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 9 Jan 2009 09:14:18 -0500 Subject: [Tutor] Python debugger In-Reply-To: <1618520901090436n47d9e0a6ld1f2f1ca64a787d@mail.gmail.com> References: <1618520901090027y5ac4e16fr9cafbba728748099@mail.gmail.com> <1c2a2c590901090338w2bd9da1fo4981c55f21ff0f42@mail.gmail.com> <1618520901090436n47d9e0a6ld1f2f1ca64a787d@mail.gmail.com> Message-ID: <1c2a2c590901090614m65e97814gc1b6554919f7044a@mail.gmail.com> On Fri, Jan 9, 2009 at 7:36 AM, Michael Bernhard Arp S?rensen wrote: > I can't use a graphical debugger because i mostly code python over ssh on > remote servers in my company. Winpdb opens a socket connection between the debugger and debuggee. Perhaps it would run over an ssh tunnel... Kent From ig2ar-saf1 at yahoo.co.uk Fri Jan 9 15:20:26 2009 From: ig2ar-saf1 at yahoo.co.uk (culpritNr1) Date: Fri, 9 Jan 2009 06:20:26 -0800 (PST) Subject: [Tutor] casting string to integer in a list of lists In-Reply-To: <496748E2020000B30000179D@gw-out.dundee.ac.uk> References: <21359600.post@talk.nabble.com> <496748E2020000B30000179D@gw-out.dundee.ac.uk> Message-ID: <21373193.post@talk.nabble.com> Hello Trias and all, Glad to see that somebody recognized the BED genomic annotation format. Your naive approach is probably the first thing that one could try. It is sure to work. The problem is that your code becomes unnecessarily long/cumbersome: every time I would have to use a particular element I would have to cast it first. So, an alternative idea is to modify the entire list of lists and get done with once and for all. This could be done manually with a couple of FOR loops. It would be easy and somebody already provided a solution early on (thank you!). Being a relative newcomer to python, my question was if there was an ELEGANT way to do this casting, perhaps as a list comprehension operation. I wondered if the beauty of python could reach that far. I thank you all for your comments, culpritNr1 trias wrote: > > Hi Your, > > I work with genomic datasets as well and have recently only started > working with python (so my advice is a bit naive) > > I would say although there may be different ways you can cast an integer > or float type into your list of lists you may actually no need to do so > with your starting file/list... ie: > > if for example you want to do stuff with the location chrX with start > 160944034 and end 160944035 > > you could: > for x in LoL: > startstring=LoL[1] #this would be '160944034' > startint=int(startstring) #this would be 160944034 > > now if you also use a counter you can iterate and do all sort of > calculations for different genomic locations. > > I use the csv module and then append into a numpy array that takes type > float, so you could work with that as well, > > cheers > > > Dr Triantafyllos Gkikopoulos >>>> culpritNr1 01/08/09 8:42 PM >>> > > Hi All, > > Say I have this nice list of lists: > > LoL = [['chrX', '160944034', '160944035', 'gnfX.145.788', '63.60'], > ['chrX', '161109992', '161109993', 'rs13484104', '63.60'], > ['chrX', '161414112', '161414113', 'rs13484105', '63.60'], > ['chrX', '161544071', '161544072', 'rs13484106', '63.60'], > ['chrX', '162030736', '162030737', 'gnfX.146.867', '67.05'], > ['chrX', '164171913', '164171914', 'gnfX.148.995', '70.45']] > > Now I want to cast the second and third "columns" from string to integer, > like this > > LoL = [['chrX', 160944034, 160944035, 'gnfX.145.788', '63.60'], > ['chrX', 161109992, 161109993, 'rs13484104', '63.60'], > ['chrX', 161414112, 161414113, 'rs13484105', '63.60'], > ['chrX', 161544071, 161544072, 'rs13484106', '63.60'], > ['chrX', 162030736, 162030737, 'gnfX.146.867', '67.05'], > ['chrX', 164171913, 164171914, 'gnfX.148.995', '70.45']] > > Is there any elegant way to do this? I can't assume that all lines will > have > the same number of elements. > > Thank you, > > Your Culprit > > > -- > View this message in context: > http://www.nabble.com/casting-string-to-integer-in-a-list-of-lists-tp21359600p21359600.html > Sent from the Python - tutor mailing list archive at Nabble.com. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > The University of Dundee is a registered Scottish charity, No: SC015096 > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- View this message in context: http://www.nabble.com/casting-string-to-integer-in-a-list-of-lists-tp21359600p21373193.html Sent from the Python - tutor mailing list archive at Nabble.com. From denis.spir at free.fr Fri Jan 9 16:38:37 2009 From: denis.spir at free.fr (spir) Date: Fri, 9 Jan 2009 16:38:37 +0100 Subject: [Tutor] casting string to integer in a list of lists In-Reply-To: <21373193.post@talk.nabble.com> References: <21359600.post@talk.nabble.com> <496748E2020000B30000179D@gw-out.dundee.ac.uk> <21373193.post@talk.nabble.com> Message-ID: <20090109163837.46e658c8@o> Le Fri, 9 Jan 2009 06:20:26 -0800 (PST), culpritNr1 a ?crit : > > Hello Trias and all, > > Glad to see that somebody recognized the BED genomic annotation format. > Being a relative newcomer to python, my question was if there was an ELEGANT > way to do this casting, perhaps as a list comprehension operation. I > wondered if the beauty of python could reach that far. already given such a solution -- denis > > I thank you all for your comments, > > culpritNr1 > ------ la vida e estranya From dsarmientos at gmail.com Fri Jan 9 16:50:47 2009 From: dsarmientos at gmail.com (Daniel Sarmiento) Date: Fri, 9 Jan 2009 10:50:47 -0500 Subject: [Tutor] casting string to integer in a list of lists Message-ID: I am not an expert and don't know if this is considered 'elegant', but this is what I would try conv = [[j[0], int(j[1]), int(j[2])] + j[3:] for j in LoL] > Hi Your, > > I work with genomic datasets as well and have recently only started > working with python (so my advice is a bit naive) > > I would say although there may be different ways you can cast an integer > or float type into your list of lists you may actually no need to do so with > your starting file/list... ie: > > if for example you want to do stuff with the location chrX with start > 160944034 and end 160944035 > > you could: > for x in LoL: > startstring=LoL[1] #this would be '160944034' > startint=int(startstring) #this would be 160944034 > > now if you also use a counter you can iterate and do all sort of > calculations for different genomic locations. > > I use the csv module and then append into a numpy array that takes type > float, so you could work with that as well, > > cheers > > > Dr Triantafyllos Gkikopoulos > >>> culpritNr1 01/08/09 8:42 PM >>> > > Hi All, > > Say I have this nice list of lists: > > LoL = [['chrX', '160944034', '160944035', 'gnfX.145.788', '63.60'], > ['chrX', '161109992', '161109993', 'rs13484104', '63.60'], > ['chrX', '161414112', '161414113', 'rs13484105', '63.60'], > ['chrX', '161544071', '161544072', 'rs13484106', '63.60'], > ['chrX', '162030736', '162030737', 'gnfX.146.867', '67.05'], > ['chrX', '164171913', '164171914', 'gnfX.148.995', '70.45']] > > Now I want to cast the second and third "columns" from string to integer, > like this > > LoL = [['chrX', 160944034, 160944035, 'gnfX.145.788', '63.60'], > ['chrX', 161109992, 161109993, 'rs13484104', '63.60'], > ['chrX', 161414112, 161414113, 'rs13484105', '63.60'], > ['chrX', 161544071, 161544072, 'rs13484106', '63.60'], > ['chrX', 162030736, 162030737, 'gnfX.146.867', '67.05'], > ['chrX', 164171913, 164171914, 'gnfX.148.995', '70.45']] > > Is there any elegant way to do this? I can't assume that all lines will > have > the same number of elements. > > Thank you, > > Your Culprit > > > -- > View this message in context: > http://www.nabble.com/casting-string-to-integer-in-a-list-of-lists-tp21359600p21359600.html > Sent from the Python - tutor mailing list archive at Nabble.com. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > The University of Dundee is a registered Scottish charity, No: SC015096 > -------------- next part -------------- An HTML attachment was scrubbed... URL: From eduardo.susan at gmail.com Fri Jan 9 17:18:53 2009 From: eduardo.susan at gmail.com (Eduardo Vieira) Date: Fri, 9 Jan 2009 09:18:53 -0700 Subject: [Tutor] What does OP stand for? Message-ID: <9356b9f30901090818u5e6a86ecud119df334db4883d@mail.gmail.com> Hello, I'm new to this list, and am enjoying it. I just wonder what "OP" stands for, as I have seen quite a few mentions in the python lists Thanks Edu From ig2ar-saf1 at yahoo.co.uk Fri Jan 9 17:10:27 2009 From: ig2ar-saf1 at yahoo.co.uk (culpritNr1) Date: Fri, 9 Jan 2009 08:10:27 -0800 (PST) Subject: [Tutor] casting string to integer in a list of lists In-Reply-To: <20090108225752.2977c752@o> References: <21359600.post@talk.nabble.com> <20090108225752.2977c752@o> Message-ID: <21375207.post@talk.nabble.com> Hello Denis and All, Your solution does show elegance. To remind people, it's this one: lol = [[1,2,3],[4,5,6],[7,8,9]] new_lol = [[a,b**3,c] for [a,b,c] in lol] print lol print new_lol ==> [[1, 2, 3], [4, 5, 6], [7, 8, 9]] [[1, 8, 3], [4, 125, 6], [7, 512, 9]] Now, as I said in my original post, I can't assume that all inner-lists will have the same number of elements. Common data looks like this LoL = [['chrX', '160944034', '160944035', 'gnfX.145.788', '63.60'], ['chrX', '161109992', '161109993', 'rs13484104', '63.60'], ['chrX', '161414112', '161414113', 'undetermined'], ['chrX', '161544071', '161544072', 'rs13484106', '63.60', 'RNA-BP', 'PLoS Biol 6(10): e255'], ['chrX', '162030736', '162030737', 'gnfX.146.867', '67.05'], ['chrX', '164171913', '164171914', 'gnfX.148.995', '70.45']] Do you still think that this problem can be elegantly tackled by list comprehensions? Thank you, culpritNr1 spir wrote: > > Le Thu, 8 Jan 2009 11:51:01 -0800 (PST), > culpritNr1 a ?crit : > >> >> Hi All, >> >> Say I have this nice list of lists: >> >> LoL = [['chrX', '160944034', '160944035', 'gnfX.145.788', '63.60'], >> ['chrX', '161109992', '161109993', 'rs13484104', '63.60'], >> ['chrX', '161414112', '161414113', 'rs13484105', '63.60'], >> ['chrX', '161544071', '161544072', 'rs13484106', '63.60'], >> ['chrX', '162030736', '162030737', 'gnfX.146.867', '67.05'], >> ['chrX', '164171913', '164171914', 'gnfX.148.995', '70.45']] >> >> Now I want to cast the second and third "columns" from string to integer, >> like this >> >> LoL = [['chrX', 160944034, 160944035, 'gnfX.145.788', '63.60'], >> ['chrX', 161109992, 161109993, 'rs13484104', '63.60'], >> ['chrX', 161414112, 161414113, 'rs13484105', '63.60'], >> ['chrX', 161544071, 161544072, 'rs13484106', '63.60'], >> ['chrX', 162030736, 162030737, 'gnfX.146.867', '67.05'], >> ['chrX', 164171913, 164171914, 'gnfX.148.995', '70.45']] >> >> Is there any elegant way to do this? I can't assume that all lines will >> have >> the same number of elements. > > In you do not need checking whether specific items are "castable" (i.e. > you really know what's in > the list) you may use such a pattern: > > lol = [[1,2,3],[4,5,6],[7,8,9]] > new_lol = [[a,b**3,c] for [a,b,c] in lol] > print lol > print new_lol > ==> > [[1, 2, 3], [4, 5, 6], [7, 8, 9]] > [[1, 8, 3], [4, 125, 6], [7, 512, 9]] > > denis >> Thank you, >> >> Your Culprit >> >> > > > ------ > la vida e estranya > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- View this message in context: http://www.nabble.com/casting-string-to-integer-in-a-list-of-lists-tp21359600p21375207.html Sent from the Python - tutor mailing list archive at Nabble.com. From ig2ar-saf1 at yahoo.co.uk Fri Jan 9 17:23:04 2009 From: ig2ar-saf1 at yahoo.co.uk (culpritNr1) Date: Fri, 9 Jan 2009 08:23:04 -0800 (PST) Subject: [Tutor] casting string to integer in a list of lists In-Reply-To: References: <21359600.post@talk.nabble.com> Message-ID: <21375430.post@talk.nabble.com> Thanks Daniel, That is EXACTLY what I was looking for. Actually, int() does not really work but this does: [ [line[0], eval(line[1]), eval(line[2])] + line[3:] for line in LoL] Again, thanks. culpritNr1 Daniel Sarmiento-2 wrote: > > I am not an expert and don't know if this is considered 'elegant', but > this > is what I would try > > conv = [[j[0], int(j[1]), int(j[2])] + j[3:] for j in LoL] > > >> Hi Your, >> >> I work with genomic datasets as well and have recently only started >> working with python (so my advice is a bit naive) >> >> I would say although there may be different ways you can cast an integer >> or float type into your list of lists you may actually no need to do so >> with >> your starting file/list... ie: >> >> if for example you want to do stuff with the location chrX with start >> 160944034 and end 160944035 >> >> you could: >> for x in LoL: >> startstring=LoL[1] #this would be '160944034' >> startint=int(startstring) #this would be 160944034 >> >> now if you also use a counter you can iterate and do all sort of >> calculations for different genomic locations. >> >> I use the csv module and then append into a numpy array that takes type >> float, so you could work with that as well, >> >> cheers >> >> >> Dr Triantafyllos Gkikopoulos >> >>> culpritNr1 01/08/09 8:42 PM >>> >> >> Hi All, >> >> Say I have this nice list of lists: >> >> LoL = [['chrX', '160944034', '160944035', 'gnfX.145.788', '63.60'], >> ['chrX', '161109992', '161109993', 'rs13484104', '63.60'], >> ['chrX', '161414112', '161414113', 'rs13484105', '63.60'], >> ['chrX', '161544071', '161544072', 'rs13484106', '63.60'], >> ['chrX', '162030736', '162030737', 'gnfX.146.867', '67.05'], >> ['chrX', '164171913', '164171914', 'gnfX.148.995', '70.45']] >> >> Now I want to cast the second and third "columns" from string to integer, >> like this >> >> LoL = [['chrX', 160944034, 160944035, 'gnfX.145.788', '63.60'], >> ['chrX', 161109992, 161109993, 'rs13484104', '63.60'], >> ['chrX', 161414112, 161414113, 'rs13484105', '63.60'], >> ['chrX', 161544071, 161544072, 'rs13484106', '63.60'], >> ['chrX', 162030736, 162030737, 'gnfX.146.867', '67.05'], >> ['chrX', 164171913, 164171914, 'gnfX.148.995', '70.45']] >> >> Is there any elegant way to do this? I can't assume that all lines will >> have >> the same number of elements. >> >> Thank you, >> >> Your Culprit >> >> >> -- >> View this message in context: >> http://www.nabble.com/casting-string-to-integer-in-a-list-of-lists-tp21359600p21359600.html >> Sent from the Python - tutor mailing list archive at Nabble.com. >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> >> The University of Dundee is a registered Scottish charity, No: SC015096 >> > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- View this message in context: http://www.nabble.com/casting-string-to-integer-in-a-list-of-lists-tp21359600p21375430.html Sent from the Python - tutor mailing list archive at Nabble.com. From mail at timgolden.me.uk Fri Jan 9 17:51:58 2009 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 09 Jan 2009 16:51:58 +0000 Subject: [Tutor] What does OP stand for? In-Reply-To: <9356b9f30901090818u5e6a86ecud119df334db4883d@mail.gmail.com> References: <9356b9f30901090818u5e6a86ecud119df334db4883d@mail.gmail.com> Message-ID: <496780AE.8030302@timgolden.me.uk> Eduardo Vieira wrote: > Hello, I'm new to this list, and am enjoying it. I just wonder what > "OP" stands for, as I have seen quite a few mentions in the python > lists Original Poster - ie whoever it was who first raised the question we're discussing now. In the case of this thread, you're the OP. TJG From mail at timgolden.me.uk Fri Jan 9 17:52:17 2009 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 09 Jan 2009 16:52:17 +0000 Subject: [Tutor] What does OP stand for? In-Reply-To: <9356b9f30901090818u5e6a86ecud119df334db4883d@mail.gmail.com> References: <9356b9f30901090818u5e6a86ecud119df334db4883d@mail.gmail.com> Message-ID: <496780C1.2060308@timgolden.me.uk> Eduardo Vieira wrote: > Hello, I'm new to this list, and am enjoying it. I just wonder what > "OP" stands for, as I have seen quite a few mentions in the python > lists Original Poster - ie whoever it was who first raised the question we're discussing now. In the case of this thread, you're the OP. TJG From kent37 at tds.net Fri Jan 9 17:57:19 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 9 Jan 2009 11:57:19 -0500 Subject: [Tutor] casting string to integer in a list of lists In-Reply-To: <21375430.post@talk.nabble.com> References: <21359600.post@talk.nabble.com> <21375430.post@talk.nabble.com> Message-ID: <1c2a2c590901090857q2214be78p11640f3fe84bf6bf@mail.gmail.com> On Fri, Jan 9, 2009 at 11:23 AM, culpritNr1 wrote: > That is EXACTLY what I was looking for. > > Actually, int() does not really work but this does: > > [ [line[0], eval(line[1]), eval(line[2])] + line[3:] for line in LoL] That's strange. What happened when you tried int() ? What version of Python are you using? Kent PS Please subscribe to the list From denis.spir at free.fr Fri Jan 9 18:30:21 2009 From: denis.spir at free.fr (spir) Date: Fri, 9 Jan 2009 18:30:21 +0100 Subject: [Tutor] casting string to integer in a list of lists In-Reply-To: <21375207.post@talk.nabble.com> References: <21359600.post@talk.nabble.com> <20090108225752.2977c752@o> <21375207.post@talk.nabble.com> Message-ID: <20090109183021.3c1c5470@o> Le Fri, 9 Jan 2009 08:10:27 -0800 (PST), culpritNr1 a ?crit : > > Hello Denis and All, > > Your solution does show elegance. To remind people, it's this one: > > lol = [[1,2,3],[4,5,6],[7,8,9]] > new_lol = [[a,b**3,c] for [a,b,c] in lol] > print lol > print new_lol > ==> > [[1, 2, 3], [4, 5, 6], [7, 8, 9]] > [[1, 8, 3], [4, 125, 6], [7, 512, 9]] > > Now, as I said in my original post, I can't assume that all inner-lists will > have the same number of elements. Common data looks like this > > LoL = [['chrX', '160944034', '160944035', 'gnfX.145.788', '63.60'], > ['chrX', '161109992', '161109993', 'rs13484104', '63.60'], > ['chrX', '161414112', '161414113', 'undetermined'], > ['chrX', '161544071', '161544072', 'rs13484106', '63.60', > 'RNA-BP', 'PLoS Biol 6(10): e255'], > ['chrX', '162030736', '162030737', 'gnfX.146.867', '67.05'], > ['chrX', '164171913', '164171914', 'gnfX.148.995', '70.45']] > > Do you still think that this problem can be elegantly tackled by list > comprehensions? The straightforward method is indeed to to loop with neccsary checks/trials embedded in loop. Now, there imo is more elegant method which is to define a custom int that integrates such tests. And then to call this custom conversion instead of built-in int. This lets open the possibility of a list comp expression. Below an example: def possible_cube(val): try: return val ** 3 except: return val lol = [[1,2,'x'],[4,'y',6],['z',8,9]] new_lol = [[possible_cube(val) for val in l] for l in lol] print lol print new_lol ==> [[1, 2, 'x'], [4, 'y', 6], ['z', 8, 9]] [[1, 8, 'x'], [64, 'y', 216], ['z', 512, 729]] This may be longer because there is a custom function call in each loop. Now, it's a question of taste and priority. denis ------ la vida e estranya From denis.spir at free.fr Fri Jan 9 18:33:22 2009 From: denis.spir at free.fr (spir) Date: Fri, 9 Jan 2009 18:33:22 +0100 Subject: [Tutor] casting string to integer in a list of lists In-Reply-To: <20090109183021.3c1c5470@o> References: <21359600.post@talk.nabble.com> <20090108225752.2977c752@o> <21375207.post@talk.nabble.com> <20090109183021.3c1c5470@o> Message-ID: <20090109183322.5bde099b@o> Forgot a "detail" > def possible_cube(val): > try: > return val ** 3 > except TypeError: > return val denis From wescpy at gmail.com Fri Jan 9 19:12:06 2009 From: wescpy at gmail.com (wesley chun) Date: Fri, 9 Jan 2009 10:12:06 -0800 Subject: [Tutor] casting string to integer in a list of lists In-Reply-To: <40af687b0901081729w12d8f635yc15ad30542049dc7@mail.gmail.com> References: <21359600.post@talk.nabble.com> <40af687b0901081326l93a793mb9b0158ba7c71373@mail.gmail.com> <78b3a9580901081421q7086bakbdd2a9b54bcfd060@mail.gmail.com> <40af687b0901081511r5530db39kc03ce880ead73a22@mail.gmail.com> <78b3a9580901081545v6a5b89adi70afc930e53c1275@mail.gmail.com> <40af687b0901081729w12d8f635yc15ad30542049dc7@mail.gmail.com> Message-ID: <78b3a9580901091012n4d150fb8o1cfe9ee00e7eb8fb@mail.gmail.com> >> A tuple of exceptions works, just like what we did above, and more, >> i.e., (IndexError, ValueError, TypeError, KeyError... >> > Thank you, thank you, thank you! I'm sure it's been staring me in the face, > but I never realized I could use a tuple of exception types - that's why I > said it was a pain in the butt, trapping the exception and doing > "isinstance" checks against it. How did I miss this? wow, you were really going out of your way. i believe the docs have some examples but cannot confirm this. > Learn something new every day, no? even i do. oh, here's something else for the OP... i forgot to mention there is a useful string method called isdigit() that you can use on the string in question. it returns True if all the chars in the string are digits, meaning that it's likely safe to call int() on it. cheers, -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 "Python Fundamentals", Prentice Hall, (c)2009 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From ig2ar-saf1 at yahoo.co.uk Fri Jan 9 19:24:20 2009 From: ig2ar-saf1 at yahoo.co.uk (culpritNr1) Date: Fri, 9 Jan 2009 10:24:20 -0800 (PST) Subject: [Tutor] casting string to integer in a list of lists In-Reply-To: <1c2a2c590901090857q2214be78p11640f3fe84bf6bf@mail.gmail.com> References: <21359600.post@talk.nabble.com> <21375430.post@talk.nabble.com> <1c2a2c590901090857q2214be78p11640f3fe84bf6bf@mail.gmail.com> Message-ID: <21377706.post@talk.nabble.com> Hello Kent and All, Errata: int() does work. I think that in my test code a number such as '4.5' might have slipped in and then int() protested. eval() worked in all my attempts. So, thanks Daniel Sarmiento, your solution is correct as is. By the way, when I said 'cast' I really meant 'convert'. Sorry, my badness. Thanks for pointing that out. culpritNr1 Kent Johnson wrote: > > On Fri, Jan 9, 2009 at 11:23 AM, culpritNr1 > wrote: >> That is EXACTLY what I was looking for. >> >> Actually, int() does not really work but this does: >> >> [ [line[0], eval(line[1]), eval(line[2])] + line[3:] for line in LoL] > > That's strange. What happened when you tried int() ? What version of > Python are you using? > > Kent > > PS Please subscribe to the list > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- View this message in context: http://www.nabble.com/casting-string-to-integer-in-a-list-of-lists-tp21359600p21377706.html Sent from the Python - tutor mailing list archive at Nabble.com. From vginer at gmail.com Fri Jan 9 19:41:37 2009 From: vginer at gmail.com (Vicent) Date: Fri, 9 Jan 2009 19:41:37 +0100 Subject: [Tutor] Where's Psyco now? Message-ID: <50ed08f40901091041v2602817ar6557fab2087212f1@mail.gmail.com> Hello. This is my first message to the list. In this article written in 2002 http://www.ibm.com/developerworks/library/l-psyco.html they talk about Psyco as a module that makes it possible to accelerate Python. Is it still a state-of-the-art module? I found it here also: http://pypi.python.org/pypi/psyco/1.6 Do you think it's useful, or it depends...? -- Vicent Giner-Bosch, Valencia, Spain -------------- next part -------------- An HTML attachment was scrubbed... URL: From clp2 at rebertia.com Fri Jan 9 20:21:28 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Fri, 9 Jan 2009 11:21:28 -0800 Subject: [Tutor] Where's Psyco now? In-Reply-To: <50ed08f40901091041v2602817ar6557fab2087212f1@mail.gmail.com> References: <50ed08f40901091041v2602817ar6557fab2087212f1@mail.gmail.com> Message-ID: <50697b2c0901091121u523a506ei40c62d4bce5be107@mail.gmail.com> On Fri, Jan 9, 2009 at 10:41 AM, Vicent wrote: > Hello. This is my first message to the list. > > In this article written in 2002 > > http://www.ibm.com/developerworks/library/l-psyco.html > > they talk about Psyco as a module that makes it possible to accelerate > Python. > > Is it still a state-of-the-art module? > > I found it here also: http://pypi.python.org/pypi/psyco/1.6 > > Do you think it's useful, or it depends...? Its present homepage is http://psyco.sourceforge.net/ , and yes, it is still useful and fairly current. However, it should be used judiciously; only bother with it if you're having a performance problem and would otherwise be tempted to rewrite the algorithm in C. Don't casually use it as an all-purpose accelerator, as that's not what it was built for. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com From phr34kc0der at gmx.co.uk Sat Jan 10 00:53:31 2009 From: phr34kc0der at gmx.co.uk (phr34kc0der) Date: Fri, 09 Jan 2009 23:53:31 +0000 Subject: [Tutor] website login Message-ID: <4967E37B.7060206@gmx.co.uk> Hi everyone, I have a python question i would like to ask. Im trying to write a script to login to a website and mirror it. I need to submit a post request to /login.php which is fine, but how can i access other pages on the site. For example data = urllib.urlencode({"username" : "myUser", "password" : "myPass"}) urllib.urlopen("http://www.example.com/login.php", data) page = urllib.urlopen("http://www.example.com/page_on_site.html") when look "page" it is just showing me login.php Thanks for any advice you can give. From jjcrump at myuw.net Sat Jan 10 00:47:38 2009 From: jjcrump at myuw.net (Jon Crump) Date: Fri, 9 Jan 2009 15:47:38 -0800 (PST) Subject: [Tutor] changing string in place Message-ID: Dear all, I've been around and around with this and can't seem to conceptualize it properly. I've got a javascript object in a text file that I'd like to treat as json so that I can import it into a python program via simplejson.loads(); however, it's not proper json because it has new Date() object declarations in it. So I thought to pre-process it by translating the dates into ISO format, but RE is making me cross-eyed. example string: s = """{"title" : "Hebertot, Normandie", "start" : new Date(1203,10,7), "description" : "Hardy's long name: Hebertot, Normandie. <br> <img src=\"document.png\" style=\"cursor: pointer\" onclick=\"SimileAjax.WindowManager.cancelPopups();show_next('tab3');pager('035'); return false\"/>pg.035: 1203-10-10 to 1203-11-18"},{"title" : "Newark-Upon-Trent, Nottinghamshire", "start" : new Date(1216,9,16), "end" : new Date(1216,9,18), "description" : "Hardy's long name: Newark-Upon-Trent, Nottinghamshire. <br> "}""" I can locate the dates with: jdate = re.compile('new Date\(\d{4},\d{1,2},\d{1,2}\)') and: jsdates = jdate.findall(s) I can get a regex pattern that groups the necessary elements: dateElems = re.compile('(\d{4}),(\d{1,2}),(\d{1,2})') But I can't seem to put the bits together with re.sub() (or str.replace() ?) in the right sort of loop. How can I return the string with _all_ the dates changed in place thus: """{"title" : "Hebertot, Normandie", "start" : "1203-11-07"... etc. instead of """{"title" : "Hebertot, Normandie", "start" : new Date(1203,10,7)... etc. (js dates are 0 indexed, so Date(1203,10,7) is Nov. 7, 1203) I'm sure this is a simple matter, but I'm just not looking at it right. Jon From mwalsh at mwalsh.org Sat Jan 10 02:15:41 2009 From: mwalsh at mwalsh.org (Martin Walsh) Date: Fri, 09 Jan 2009 19:15:41 -0600 Subject: [Tutor] changing string in place In-Reply-To: References: Message-ID: <4967F6BD.8090905@mwalsh.org> Jon Crump wrote: > Dear all, > > I've been around and around with this and can't seem to conceptualize it > properly. > > I've got a javascript object in a text file that I'd like to treat as > json so that I can import it into a python program via > simplejson.loads(); however, it's not proper json because it has new > Date() object declarations in it. So I thought to pre-process it by > translating the dates into ISO format, but RE is making me cross-eyed. > > example string: > > s = """{"title" : "Hebertot, Normandie", "start" : new Date(1203,10,7), > "description" : "Hardy's long name: Hebertot, Normandie. <br> > <img src=\"document.png\" style=\"cursor: pointer\" > onclick=\"SimileAjax.WindowManager.cancelPopups();show_next('tab3');pager('035'); > return false\"/>pg.035: 1203-10-10 to 1203-11-18"},{"title" : > "Newark-Upon-Trent, Nottinghamshire", "start" : new Date(1216,9,16), > "end" : new Date(1216,9,18), "description" : "Hardy's long name: > Newark-Upon-Trent, Nottinghamshire. <br> "}""" > > I can locate the dates with: > jdate = re.compile('new Date\(\d{4},\d{1,2},\d{1,2}\)') I think you're pretty close... # note the extra parens jdate = re.compile('new Date\((\d{4}),(\d{1,2}),(\d{1,2})\)') ... then ... print jdate.sub(r'"\1-\2-\3"', s) {"title" : "Hebertot, Normandie", "start" : "1203-10-7", "description" : "Hardy's long name: Hebertot, Normandie. <br> <img src="document.png" style="cursor: pointer" onclick="SimileAjax.WindowManager.cancelPopups();show_next('tab3');pager('035'); return false"/>pg.035: 1203-10-10 to 1203-11-18"},{"title" : "Newark-Upon-Trent, Nottinghamshire", "start" : "1216-9-16", "end" : "1216-9-18", "description" : "Hardy's long name: Newark-Upon-Trent, Nottinghamshire. <br> "} You can also use named groups which *might* help make clearer what's happening above, something like: jdate = re.compile('new Date\((?P\d{4}),(?P\d{1,2}),(?P\d{1,2})\)') print jdate.sub(r'"\g-\g-\g"', s) More info here: http://docs.python.org/library/re.html#re.sub HTH, Marty From kent37 at tds.net Sat Jan 10 03:10:36 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 9 Jan 2009 21:10:36 -0500 Subject: [Tutor] website login In-Reply-To: <4967E37B.7060206@gmx.co.uk> References: <4967E37B.7060206@gmx.co.uk> Message-ID: <1c2a2c590901091810o420dfccfl7b26b75aa59afe1a@mail.gmail.com> On Fri, Jan 9, 2009 at 6:53 PM, phr34kc0der wrote: > Hi everyone, > > I have a python question i would like to ask. > > Im trying to write a script to login to a website and mirror it. I need to > submit a post request to /login.php which is fine, but how can i access > other pages on the site. See the 'Authentication' section on this page: http://personalpages.tds.net/~kent37/kk/00010.html Kent From mwalsh at mwalsh.org Sat Jan 10 04:28:52 2009 From: mwalsh at mwalsh.org (Martin Walsh) Date: Fri, 09 Jan 2009 21:28:52 -0600 Subject: [Tutor] changing string in place In-Reply-To: <4968157F.6020108@mwalsh.org> References: <4967F6BD.8090905@mwalsh.org> <4968157F.6020108@mwalsh.org> Message-ID: <496815F4.6070405@mwalsh.org> Jon Crump wrote: > I'm still faced with the problem of the javascript months being 0 > indexed. I have to add 1 to group \2 in order to get my acurate > date-string. Obviously I can't do > > print jdate.sub(r'"\1-\2+1-\3"', s) > > because the first argument to sub() is a string. How can I act on \2 > before it's substituted for the matched string? > Ah, sorry I missed that part the first time through. The first argument to jdate.sub ('repl') can also be a function that accepts an re.match object and returns a string, so something like the following (*untested*) may be helpful: jdate = re.compile('new Date\((\d{4}),(\d{1,2}),(\d{1,2})\)') def repldate(match): y, m, d = map(int, match.groups()) return '%04d-%02d-%02d' % (y, m+1, d) print jdate.sub(repldate, s) HTH, Marty > Thanks again, > Jon From prasadaraon50 at gmail.com Sat Jan 10 12:01:49 2009 From: prasadaraon50 at gmail.com (prasad rao) Date: Sat, 10 Jan 2009 03:01:49 -0800 Subject: [Tutor] multiplication table Message-ID: <9e3fac840901100301h7c13727fwb77beda52bb86d78@mail.gmail.com> HiI tried to print multiplication table using (*args) to pass parameters.and tried to print tables side by side.But the code looks messy .Is there a better way to do it. def mtab(*arg): for x in range(1,11): print '%3d'%(x),'x','%3d'%(arg[0]),'=','%3d'%(x*arg[0]),(' '*5),\ '%3d'%(x),'x','%3d'%(arg[1]),'=','%3d'%(x*arg[1]),(' '*5),\ '%3d'%(x),'x','%3d'%(arg[2]),'=','%3d'%(x*arg[2]),(' '*5) print(('-')*10).center(78) for x in range (1,11): print '%3d'%(x),'x','%3d'%(arg[3]),'=','%3d'%(x*arg[3]),(' '*5),\ '%3d'%(x),'x','%3d'%(arg[4]),'=','%3d'%(x*arg[4]),(' '*5),\ '%3d'%(x),'x','%3d'%(arg[5]),'=','%3d'%(x*arg[5]),(' '*5) Prasad -------------- next part -------------- An HTML attachment was scrubbed... URL: From michael at arpsorensen.dk Sat Jan 10 12:56:39 2009 From: michael at arpsorensen.dk (=?UTF-8?Q?Michael_Bernhard_Arp_S=C3=B8rensen?=) Date: Sat, 10 Jan 2009 12:56:39 +0100 Subject: [Tutor] Python debugger In-Reply-To: <1c2a2c590901090614m65e97814gc1b6554919f7044a@mail.gmail.com> References: <1618520901090027y5ac4e16fr9cafbba728748099@mail.gmail.com> <1c2a2c590901090338w2bd9da1fo4981c55f21ff0f42@mail.gmail.com> <1618520901090436n47d9e0a6ld1f2f1ca64a787d@mail.gmail.com> <1c2a2c590901090614m65e97814gc1b6554919f7044a@mail.gmail.com> Message-ID: <1618520901100356i61404e5cp300425f9d86ae60f@mail.gmail.com> It might and I'll keep it in mind. However, I'm not going to ditch my linux just to get a gui debugger. After all, I do have WingIDE installed in Linux, but I wanted to be free of the GUI limitations I have when I code on a host that I connect to through a minicom on another ssh host. I do that from time to time. Thanks anyway. I got what I needed. :-) /Michael On Fri, Jan 9, 2009 at 3:14 PM, Kent Johnson wrote: > On Fri, Jan 9, 2009 at 7:36 AM, Michael Bernhard Arp S?rensen > wrote: > > > I can't use a graphical debugger because i mostly code python over ssh on > > remote servers in my company. > > Winpdb opens a socket connection between the debugger and debuggee. > Perhaps it would run over an ssh tunnel... > > Kent > -------------- next part -------------- An HTML attachment was scrubbed... URL: From jadrifter at gmail.com Sat Jan 10 13:37:11 2009 From: jadrifter at gmail.com (jadrifter) Date: Sat, 10 Jan 2009 04:37:11 -0800 Subject: [Tutor] Python debugger In-Reply-To: <1618520901100356i61404e5cp300425f9d86ae60f@mail.gmail.com> References: <1618520901090027y5ac4e16fr9cafbba728748099@mail.gmail.com> <1c2a2c590901090338w2bd9da1fo4981c55f21ff0f42@mail.gmail.com> <1618520901090436n47d9e0a6ld1f2f1ca64a787d@mail.gmail.com> <1c2a2c590901090614m65e97814gc1b6554919f7044a@mail.gmail.com> <1618520901100356i61404e5cp300425f9d86ae60f@mail.gmail.com> Message-ID: <1231591031.3077.2.camel@ltop> Despite the name I believe Winpdb is platform independent I haven't used it myself but I looked into it while following this thread. http://winpdb.org/ John Purser On Sat, 2009-01-10 at 12:56 +0100, Michael Bernhard Arp S?rensen wrote: > It might and I'll keep it in mind. > > However, I'm not going to ditch my linux just to get a gui debugger. > After all, I do have WingIDE installed in Linux, but I wanted to be > free of the GUI limitations I have when I code on a host that I > connect to through a minicom on another ssh host. I do that from time > to time. > > Thanks anyway. I got what I needed. :-) > > /Michael > > On Fri, Jan 9, 2009 at 3:14 PM, Kent Johnson wrote: > On Fri, Jan 9, 2009 at 7:36 AM, Michael Bernhard Arp S?rensen > wrote: > > > I can't use a graphical debugger because i mostly code > python over ssh on > > remote servers in my company. > > > Winpdb opens a socket connection between the debugger and > debuggee. > Perhaps it would run over an ssh tunnel... > > Kent > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From fatcat1111 at gmail.com Sat Jan 10 04:15:25 2009 From: fatcat1111 at gmail.com (Justin) Date: Fri, 9 Jan 2009 19:15:25 -0800 Subject: [Tutor] Yield and recursion Message-ID: <400c5d8e0901091915g5858047cic3ee942aa8d0fa4@mail.gmail.com> Hello, I am new to Python and I'm having trouble with generators. I have built a tree (and verified that it looks good, and my left() and right() functions are correct as well), and I am able to traverse it as I would expect: def preorder(tree, index, path=[]): if index >= len(tree): return path = path + [tree[index]] print path preorder(tree, left(index), path) preorder(tree, right(index), path) preorder(tree, 0) This prints out a series of lists, each containing a subtree, as expected. E.g., [0] [1, 2] [3, 4, 5, 6] ... However when I attempt to convert preorder() to a generator and iterate over the results things don't go as planned: def preorder(tree, index, path=[]): if index >= len(tree): return path = path + [tree[index]] yield path preorder(tree, left(index), path) preorder(tree, right(index), path) for subtree in preorder(tree, 0): print subtree This results in only the first list being returned: [0] I suspect it has something to do trying to, on the second pass, yield from a generator that hasn't been created. Does that sound right? If so, what can I do? Would somebody please enlighten this poor confused dev? Thank you in advance. From sofdow at yahoo.com Sat Jan 10 06:48:51 2009 From: sofdow at yahoo.com (john dow) Date: Fri, 9 Jan 2009 21:48:51 -0800 (PST) Subject: [Tutor] How do we upload multiple files simultaneously? Message-ID: <21385206.post@talk.nabble.com> Dear All, I a newbie to python... my problem is to upload more than one file on a single go. I have an option open is using some FTP client... Is there any other methods like what mega upload uses??? thanks in advace.. regards, john -- View this message in context: http://www.nabble.com/How-do-we-upload-multiple-files-simultaneously--tp21385206p21385206.html Sent from the Python - tutor mailing list archive at Nabble.com. From sofdow at yahoo.com Sat Jan 10 07:26:39 2009 From: sofdow at yahoo.com (john dow) Date: Fri, 9 Jan 2009 22:26:39 -0800 (PST) Subject: [Tutor] How do we upload multiple files simultaneously? Message-ID: <21385206.post@talk.nabble.com> Dear All, I a newbie to python... my problem is to upload more than one file on a single go. I have an option open is using some FTP client... Is there any other methods like what mega upload uses??? thanks in advace.. regards, john -- View this message in context: http://www.nabble.com/How-do-we-upload-multiple-files-simultaneously--tp21385206p21385206.html Sent from the Python - tutor mailing list archive at Nabble.com. From kent37 at tds.net Sat Jan 10 14:07:23 2009 From: kent37 at tds.net (Kent Johnson) Date: Sat, 10 Jan 2009 08:07:23 -0500 Subject: [Tutor] multiplication table In-Reply-To: <9e3fac840901100301h7c13727fwb77beda52bb86d78@mail.gmail.com> References: <9e3fac840901100301h7c13727fwb77beda52bb86d78@mail.gmail.com> Message-ID: <1c2a2c590901100507t2bf2e860v51b663bf19dd47b1@mail.gmail.com> On Sat, Jan 10, 2009 at 6:01 AM, prasad rao wrote: > Hi > I tried to print multiplication table using (*args) to pass parameters.and > tried > to print tables side by side.But the code looks messy .Is there a better way > to do it. > def mtab(*arg): > for x in range(1,11): > print '%3d'%(x),'x','%3d'%(arg[0]),'=','%3d'%(x*arg[0]),(' '*5),\ > '%3d'%(x),'x','%3d'%(arg[1]),'=','%3d'%(x*arg[1]),(' '*5),\ > '%3d'%(x),'x','%3d'%(arg[2]),'=','%3d'%(x*arg[2]),(' '*5) > print(('-')*10).center(78) > for x in range (1,11): > print '%3d'%(x),'x','%3d'%(arg[3]),'=','%3d'%(x*arg[3]),(' '*5),\ > '%3d'%(x),'x','%3d'%(arg[4]),'=','%3d'%(x*arg[4]),(' '*5),\ > '%3d'%(x),'x','%3d'%(arg[5]),'=','%3d'%(x*arg[5]),(' '*5) You have a lot of duplicated code. You can reduce the duplication by using functions and loops. The first step is to put all the print code into a function rather than repeating the same three formatting expressions over and over: def show(x, y): print '%3d'%(x),'x','%3d'%(y),'=','%3d'%(x*y),(' '*5), Then mtab() can be written like this: def mtab(*arg): for x in range(1,11): show(x, arg[0]) show(x, arg[1]) show(x, arg[2]) print print(('-')*10).center(78) for x in range (1,11): show(x, arg[3]) show(x, arg[4]) show(x, arg[5]) print Now you can see that the show() statements are still repetitive, they can be put into a loop: def mtab(*arg): for x in range(1,11): for i in range(0, 3): show(x, arg[i]) print print(('-')*10).center(78) for x in range (1,11): for i in range(3, 6): show(x, arg[i]) print This is OK except the interface is awkward; do you really want to tell it each number for the table, or would you rather give it a range of numbers? Also you can use another loop to eliminate the duplicated printing of the tables: def mtab(lower, upper): for start in range(lower, upper+1, 3): for x in range(1,11): for y in range(start, start+3): show(x, y) print print(('-')*10).center(78) mtab(1, 11) This does not give quite the same result as your original - it prints the divider after each table - and it always prints three tables per group, even if you didn't ask for it - but it is much simpler and more flexible than your original. Kent From kent37 at tds.net Sat Jan 10 14:49:10 2009 From: kent37 at tds.net (Kent Johnson) Date: Sat, 10 Jan 2009 08:49:10 -0500 Subject: [Tutor] Yield and recursion In-Reply-To: <400c5d8e0901091915g5858047cic3ee942aa8d0fa4@mail.gmail.com> References: <400c5d8e0901091915g5858047cic3ee942aa8d0fa4@mail.gmail.com> Message-ID: <1c2a2c590901100549v50be3071l952aa6613859e729@mail.gmail.com> On Fri, Jan 9, 2009 at 10:15 PM, Justin wrote: > However when I attempt to convert preorder() to a generator and > iterate over the results things don't go as planned: > > def preorder(tree, index, path=[]): > if index >= len(tree): return > path = path + [tree[index]] > yield path > preorder(tree, left(index), path) > preorder(tree, right(index), path) You have to explicitly loop over and yield the results of the recursive calls; there is no automatic machinery or shortcut for this: def preorder(tree, index, path=[]): if index >= len(tree): return path = path + [tree[index]] yield path for path in preorder(tree, left(index), path): yield path for path in preorder(tree, right(index), path): yield path You may want to yield just the individual path elements, not the full path, at each step. Kent From kent37 at tds.net Sat Jan 10 14:50:30 2009 From: kent37 at tds.net (Kent Johnson) Date: Sat, 10 Jan 2009 08:50:30 -0500 Subject: [Tutor] Python debugger In-Reply-To: <1231591031.3077.2.camel@ltop> References: <1618520901090027y5ac4e16fr9cafbba728748099@mail.gmail.com> <1c2a2c590901090338w2bd9da1fo4981c55f21ff0f42@mail.gmail.com> <1618520901090436n47d9e0a6ld1f2f1ca64a787d@mail.gmail.com> <1c2a2c590901090614m65e97814gc1b6554919f7044a@mail.gmail.com> <1618520901100356i61404e5cp300425f9d86ae60f@mail.gmail.com> <1231591031.3077.2.camel@ltop> Message-ID: <1c2a2c590901100550y26eac239j9871ae86ccb60769@mail.gmail.com> On Sat, Jan 10, 2009 at 7:37 AM, jadrifter wrote: > Despite the name I believe Winpdb is platform independent Yes, it is, it is windows as in GUI not windows as in Microsoft. Kent From prasadaraon50 at gmail.com Sat Jan 10 14:52:03 2009 From: prasadaraon50 at gmail.com (prasad rao) Date: Sat, 10 Jan 2009 05:52:03 -0800 Subject: [Tutor] Thanks Message-ID: <9e3fac840901100552x7c18d71al7ff70fb3f664374f@mail.gmail.com> Hello Your code is concise and neat.It will take some time for me to understand how it is doing the job. Thank you >You have a lot of duplicated code. You can reduce the duplication by >using functions and loops. >The first step is to put all the print code into a function rather >than repeating the same three formatting expressions over and over: >def show(x, y): > print '%3d'%(x),'x','%3d'%(y),'=','%3d'%(x*y),(' '*5), >Then mtab() can be written like this: >def mtab(*arg): > for x in range(1,11): show(x, arg[0]) show(x, arg[1]) show(x, arg[2]) print print(('-')*10).center(78) for x in range (1,11): show(x, arg[3]) show(x, arg[4]) show(x, arg[5]) print >Now you can see that the show() statements are still repetitive, they >can be put into a loop: >def mtab(*arg): > for x in range(1,11): for i in range(0, 3): show(x, arg[i]) print print(('-')*10).center(78) for x in range (1,11): for i in range(3, 6): show(x, arg[i]) print >This is OK except the interface is awkward; do you really want to tell >it each number for the table, or would you rather give it a range of >numbers? Also you can use another loop to eliminate the duplicated >printing of the tables: >def mtab(lower, upper): for start in range(lower, upper+1, 3): for x in range(1,11): for y in range(start, start+3): show(x, y) print print(('-')*10).center(78) >mtab(1, 11) >This does not give quite the same result as your original - it prints >the divider after each table - and it always prints three tables per >group, even if you didn't ask for it - but it is much simpler and more >flexible than your original. >Kent -------------- next part -------------- An HTML attachment was scrubbed... URL: From ptmcg at austin.rr.com Sat Jan 10 16:32:19 2009 From: ptmcg at austin.rr.com (Paul McGuire) Date: Sat, 10 Jan 2009 09:32:19 -0600 Subject: [Tutor] changing string in place In-Reply-To: References: Message-ID: <1AB0672DAE1C4D5BA98D524B3D466007@AWA2> Sometimes pyparsing is less stressful than struggling with RE's typoglyphics, especially for a one-off conversion (also note handling of quoted strings - if a 'new Date(y,m,d)' occurs inside a quoted string, this script *won't* convert it): from pyparsing import nums,Word,Literal,quotedString # parse a number, return it as an int num = Word(nums).setParseAction(lambda t:int(t[0])) # format of a json 'new Date' - assign names to date fields newdate = ( Literal("new") + "Date" + '(' + num("year") + ',' + num("month") + ',' + num("day") + ')' ) # parse action to convert dates def reformatDate(t): t["month"] += 1 return '"%(year)04d-%(month)02d-%(day)02d"' % t newdate.setParseAction( reformatDate ) # do conversions - explicit parsing of quoted strings # will skip over "new Date" strings if there are any # enclosed in quotes print (quotedString | newdate).transformString(s) -- Paul From lie.1296 at gmail.com Sat Jan 10 23:19:55 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Sat, 10 Jan 2009 22:19:55 +0000 (UTC) Subject: [Tutor] How do we upload multiple files simultaneously? References: <21385206.post@talk.nabble.com> Message-ID: On Fri, 09 Jan 2009 21:48:51 -0800, john dow wrote: > Dear All, > > I a newbie to python... > > my problem is to upload more than one file on a single go. I have an > option open is using some FTP client... > You might be interested with Twisted. Alternatively you might also be interested with threading or multiprocessing and also urllib. From srilyk at gmail.com Sun Jan 11 00:13:28 2009 From: srilyk at gmail.com (W W) Date: Sat, 10 Jan 2009 17:13:28 -0600 Subject: [Tutor] How do we upload multiple files simultaneously? In-Reply-To: References: <21385206.post@talk.nabble.com> Message-ID: <333efb450901101513w5af37b18vf7b5d43e014d6ab5@mail.gmail.com> On Sat, Jan 10, 2009 at 4:19 PM, Lie Ryan wrote: > On Fri, 09 Jan 2009 21:48:51 -0800, john dow wrote: > > > Dear All, > > > > I a newbie to python... > > > > my problem is to upload more than one file on a single go. I have an > > option open is using some FTP client... > > > > You might be interested with Twisted. > > Alternatively you might also be interested with threading or > multiprocessing and also urllib. Another option would be a list of files to upload, i.e. def upload(filename): #implementation here files = ['file1.txt', 'file2.txt', 'file3.txt'] for file in files: upload(file) Of course there are various different ways you could perform that type of action, but that should point you in the right direction. HTH, Wayne -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn't. - Primo Levi -------------- next part -------------- An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Sun Jan 11 02:57:11 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sat, 10 Jan 2009 17:57:11 -0800 Subject: [Tutor] Working with IDLE in XP, Set Up for A New Program In-Reply-To: <556845.95820.qm@web86704.mail.ukl.yahoo.com> References: <556845.95820.qm@web86704.mail.ukl.yahoo.com> Message-ID: <496951F7.5070204@sbcglobal.net> An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Sun Jan 11 03:08:05 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sat, 10 Jan 2009 18:08:05 -0800 Subject: [Tutor] Working with IDLE in XP, Set Up for A New Program In-Reply-To: <496951F7.5070204@sbcglobal.net> References: <556845.95820.qm@web86704.mail.ukl.yahoo.com> <496951F7.5070204@sbcglobal.net> Message-ID: <49695485.1010500@sbcglobal.net> An HTML attachment was scrubbed... URL: From srilyk at gmail.com Sun Jan 11 16:28:37 2009 From: srilyk at gmail.com (W W) Date: Sun, 11 Jan 2009 09:28:37 -0600 Subject: [Tutor] Working with IDLE in XP, Set Up for A New Program In-Reply-To: <49695485.1010500@sbcglobal.net> References: <556845.95820.qm@web86704.mail.ukl.yahoo.com> <496951F7.5070204@sbcglobal.net> <49695485.1010500@sbcglobal.net> Message-ID: <333efb450901110728h28b49775i4030a293d93c742d@mail.gmail.com> On Sat, Jan 10, 2009 at 8:08 PM, Wayne Watson wrote: > I immediately answered my own question by clicking on a link that took me > to a web site with the pdf; however, it looks like I installed Python 2.6. > It'll be easy to uninstall, but I don't see 2.5 -- yet. > http://www.activestate.com/store/download.aspx?prdGUID=b08b04e0-6872-4d9d-a722-7a0c2dea2758 They have python 2.5.2... something. On the right hand side, as of this message, anyway. HTH, The Other Wayne > Wayne Watson wrote: > > Hi, this is a continuation of my post from way back in August. I just > installed Pythonwin. It's showing me a window for "Dive into Python". > Apparently, it's an extensive document. How do I determine how many pages > there are, and do I print the whole thing section by section? Maybe there's > a PDF? > > ALAN GAULD wrote: > > > > Where do I get pythonwin? > > Either download the Windows extensions as linked from the > Python.org web site, or even better download and install the > Activestate.com version of Python. Its free but you must register. > It has lots of goodies and uses pythonwin as the default IDE. > I use that on all my Windows PCs. > > Alan g > > Alan Gauld wrote: > > > "Wayne Watson" wrote > > would like to know if there's an easier way to start it than what I use? I > pick on a py file, and then use the pull down menu, right-click, to select > IDLE. > > > Yes, it should be on the Start menu possibly listed as Python GUI. > > Or you can set up a shortcut to it by selecting idle.pyw in explorer and > creating a shortcut and dragging it to your desktop. > > Or you could do yourself a favour and get the Pythonwin extensions and use > Pythonwin instead. IDLE is fine for a cross platform IDE but it is ugly and > less feature rich than Pythonwin. And the pythonwin installer sets up the > menus etc for you. > > HTH > > > -- > > Wayne Watson (Watson Adventures, Prop., Nevada City, CA) > > (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) > Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet "We are in a race between education and catastrophe." > ? H.G. Wells > > Web Page: > > > -- > > Wayne Watson (Watson Adventures, Prop., Nevada City, CA) > > (121.01 Deg. W, 39.26 Deg. N) GMT-8 hr std. time) * "What killed the electric car? Expensive batteries did." > -- Physics for Future Presidents, Richard A. Muller*** Web Page: > > ------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.orghttp://mail.python.org/mailman/listinfo/tutor > > > -- > > Wayne Watson (Watson Adventures, Prop., Nevada City, CA) > > (121.01 Deg. W, 39.26 Deg. N) GMT-8 hr std. time) * "What killed the electric car? Expensive batteries did." > -- Physics for Future Presidents, Richard A. Muller*** Web Page: > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn't. - Primo Levi -------------- next part -------------- An HTML attachment was scrubbed... URL: From denis.spir at free.fr Sun Jan 11 19:11:53 2009 From: denis.spir at free.fr (spir) Date: Sun, 11 Jan 2009 19:11:53 +0100 Subject: [Tutor] indented grammar parsing Message-ID: <20090111191153.16a0b805@o> Hello, this is a rather specific question about parsing an indented grammar. I have a working implementation (presented below) that may be worth a critic review -- if you like it. First issue is: is there a way to express an indented formatfing using a common grammar language such as BNF (or regex)? If yes, how to do that? If not, what kind of formal grammar is actually such a format? Is there any standard way to express it? I have searched python's grammar for this: actually, for any compound statement, a block (= section content) is simply renamed 'suite' with no more format expression. The lexical analysis section on indentation reads: '' The indentation levels of consecutive lines are used to generate INDENT and DEDENT tokens, using a stack, as follows. Before the first line of the file is read, a single zero is pushed on the stack; this will never be popped off again. The numbers pushed on the stack will always be strictly increasing from bottom to top. At the beginning of each logical line, the line?s indentation level is compared to the top of the stack. If it is equal, nothing happens. If it is larger, it is pushed on the stack, and one INDENT token is generated. If it is smaller, it must be one of the numbers occurring on the stack; all numbers on the stack that are larger are popped off, and for each number popped off a DEDENT token is generated. At the end of the file, a DEDENT token is generated for each number remaining on the stack that is larger than zero. '' I guess from this text that python parsers have a pre-parse phase that generate the so-called INDENT and DEDENT tokens -- which are then used during actual parsing. So that a typical section looks like this for the parser: header INDENT line line line DEDENT Which is, in fact, recreating a common block start / stop format (e.g. C's {block}). Is it? Do you know whether python parsers actually do that during a kind of pre-parse phase, or whether their designers have found a way of matching indent/dedent together with the rest of the source text? Thank you, Denis ================== My trial: I have have implemented an overall parser to parse an indented grammar in the simplest (recursive) case I could specify: * no blank line, no comment * a single format of inline pattern * each indent level marked as a single (tab) char * only step 1 indentation increase To do this, I use a set of tricks. Below the grammar (using a pseudo BNF/regex format -- actually it is implemented using a custom parser generator): inline : [a..z0..9_]+ line : Indent inline NL bloc : (section | line)+ section : line IndentMore bloc IndentLess all : <= bloc> Oviously, I use 3 names starting with Indent, that are not defined. They are kinds of pseudo-patterns and all rely on an external variable that holds the current indent level and is hosted as an attribute of Indent: * Indent: matches if a proper indentation is found, meaning equal to current indent level -- advances pointer * IndentMore: matches if the actual indentation found is =level+1 -- does not advance pointer (=lookahead) -- increments current level * IndentLess: matches if the actual indentation found is Right() ''' # match indentation start_pos = pos (result,pos) = ZeroOrMore(TAB)._check(text,pos) # case proper indent decrement indent_level = pos - start_pos if indent_level < Indent.level: Indent.level -= 1 result = Result(self, None, text,start_pos,start_pos) return (result,start_pos) # (no pointer advance) # case no indent decrement (by step 1 or more) # (may also be end-of-text reached) if pos >= len(text): raise EndOfText(self, text, start_pos) message = "No proper indentation decrement:\nindent level %s --> %s"\ %(Indent.level, indent_level) raise NoMatch(self, text, start_pos, message) def _full_expr(self): return "INDENT--" Below a test text and the corresponding parse result shown in tree view: ======= 1 2 3 31 32 4 5 6 61 62 63 631 632 7 ======= ======= all line:1 line:2 section line:3 bloc line:31 line:32 line:4 line:5 section line:6 bloc line:61 line:62 section line:63 bloc line:631 line:632 line:7 ======= I first want to use this structure to parse config files written according to an recursive indented format. So that the result would be a (record) object holding properties which actually each are either a parameter or a nested sub-config, e.g.: config name : val name : val connexion name : val name : val transmission name : val name : val ------ la vida e estranya From julianpaceqb at yahoo.com Sun Jan 11 23:01:25 2009 From: julianpaceqb at yahoo.com (rev pacce) Date: Sun, 11 Jan 2009 14:01:25 -0800 (PST) Subject: [Tutor] help Message-ID: <410633.69344.qm@web62001.mail.re1.yahoo.com> I have no expierence using python. I was following a tutorial and i kept getting a syntax error. it was???>>> print "hello world!"? hello world was not coming up underneath it.. i tried to run the module but that didnt work either. -------------- next part -------------- An HTML attachment was scrubbed... URL: From jadrifter at gmail.com Sun Jan 11 23:53:30 2009 From: jadrifter at gmail.com (jadrifter) Date: Sun, 11 Jan 2009 14:53:30 -0800 Subject: [Tutor] help In-Reply-To: <410633.69344.qm@web62001.mail.re1.yahoo.com> References: <410633.69344.qm@web62001.mail.re1.yahoo.com> Message-ID: <1231714410.6041.4.camel@ltop> On Sun, 2009-01-11 at 14:01 -0800, rev pacce wrote: > I have no expierence using python. I was following a tutorial and i > kept getting a syntax error. it was >>> print "hello world!" hello > world was not coming up underneath it.. i tried to run the module but > that didnt work either. > > _______________________________________________ Hello, Don't type the >>> into python. Just type: print "hello world!" into the interactive prompt and I think it will work for you. John From alan.gauld at btinternet.com Mon Jan 12 00:14:13 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 11 Jan 2009 23:14:13 -0000 Subject: [Tutor] help References: <410633.69344.qm@web62001.mail.re1.yahoo.com> Message-ID: "rev pacce" wrote > I have no expierence using python. > I was following a tutorial and i kept getting a syntax error. > it was >>> print "hello world!" hello world was not coming up OK, I guess that you tried typing the >>> howerver that bit should be produced by the Python interpreter. You need to have an interpreter running before you start typing for most tutorials. You can get an interpreter from your command window or console or by using one of the GUI Python tools such as IDLE or Pythonwin. Can you tell us how you are starting python? Are you getting a >>> prompt anywhere? If you are using IDLE a good place to start is here: http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/index.html -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From sierra_mtnview at sbcglobal.net Mon Jan 12 02:55:36 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sun, 11 Jan 2009 17:55:36 -0800 Subject: [Tutor] Active State Python with IDLE Python 2.5 Message-ID: <496AA318.6020508@sbcglobal.net> An HTML attachment was scrubbed... URL: From brian.mathis at gmail.com Mon Jan 12 03:32:32 2009 From: brian.mathis at gmail.com (Brian Mathis) Date: Sun, 11 Jan 2009 21:32:32 -0500 Subject: [Tutor] help In-Reply-To: <183c528b0901111831t38d62342ia0386358f4fe1d2f@mail.gmail.com> References: <410633.69344.qm@web62001.mail.re1.yahoo.com> <183c528b0901111831t38d62342ia0386358f4fe1d2f@mail.gmail.com> Message-ID: <183c528b0901111832r33faba36u2523d92770a14078@mail.gmail.com> I'm also new to python, but I have another suggestion on what might be going on. If you downloaded the newly released python version 3.0, ' print "hello world" ' is a syntax error because in 3.0 the "print" command has changed into a function. The correct statement would now be: print("Hello World") including the ( ). There are other changes too, which might cause other problems in the tutorial you are using. This is might be more confusing than you want to deal with right now, so I'd recommend installing python 2.6 instead, since most tutorials will probably be written for that. Once you've got a handle on python, upgrade to 3.0. On Sun, Jan 11, 2009 at 5:01 PM, rev pacce wrote: > > I have no experience using python. I was following a tutorial and i kept getting a syntax error. it was >>> print "hello world!" hello world was not coming up underneath it.. i tried to run the module but that didn't work either. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From marco.m.petersen at gmail.com Mon Jan 12 07:31:02 2009 From: marco.m.petersen at gmail.com (Marco Petersen) Date: Mon, 12 Jan 2009 14:31:02 +0800 Subject: [Tutor] 2to3 Help? Message-ID: <496AE3A6.9050304@gmail.com> I have Python 3.0. I tried to use the 2to3 program included with the interpreter to convert some scripts for Python 2.5 to Python 3.0 ones. When I try to start it form the Python command line, it says it is a syntax error. This was the line of code: $ 2to3 testscript.py Any help would be appreciated. Thanks - Marco From alan.gauld at btinternet.com Mon Jan 12 09:51:18 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 12 Jan 2009 08:51:18 -0000 Subject: [Tutor] Active State Python with IDLE Python 2.5 References: <496AA318.6020508@sbcglobal.net> Message-ID: "Wayne Watson" wrote > I installed "Python" 2.5 a few months ago, and decided I'd like to > try > windowpy from ActiveState. Is having both of these installed going > to > cause me trouble? Multiple versions of Python should not be a problem provided you put them in different folders. C:\python25 and C:\ASpython25 for example You will have to remember which one is the default version (ie will be used when you double click a python file for example) but you can set things up to run both. But there is little point. If you are on Windows I'd personally uninstall the vanilla version and install the ActiveState version, it has a lot more features for Windows users. Alan G. From alan.gauld at btinternet.com Mon Jan 12 09:56:04 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 12 Jan 2009 08:56:04 -0000 Subject: [Tutor] 2to3 Help? References: <496AE3A6.9050304@gmail.com> Message-ID: "Marco Petersen" wrote >I have Python 3.0. I tried to use the 2to3 program included with the >interpreter to convert some scripts for Python 2.5 to Python 3.0 >ones. > When I try to start it form the Python command line, it says it is a > syntax error. > Its always best to send us an actual cut n paste of error messages. Its not clear where the error is coming from by your desription, it could be Python (most likely) or the shell. > This was the line of code: > > $ 2to3 testscript.py But I suspect... this will run your default python interpreter which is likely to still be your 2.5 version. THe convertion scrpt is almost certainly 3.0. So I think you will need to explicitly call the interpreter: $ some/path/to/python3 2to3 testscript.py Actually isn't 2to3 a .py file too? ie 2to3.py? Just some guesses... I haven't got around to installing Python 3 yet. Alan G. From sierra_mtnview at sbcglobal.net Mon Jan 12 11:24:38 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Mon, 12 Jan 2009 02:24:38 -0800 Subject: [Tutor] Active State Python with IDLE Python 2.5 In-Reply-To: References: <496AA318.6020508@sbcglobal.net> Message-ID: <496B1A66.5050306@sbcglobal.net> An HTML attachment was scrubbed... URL: From kent37 at tds.net Mon Jan 12 12:40:00 2009 From: kent37 at tds.net (Kent Johnson) Date: Mon, 12 Jan 2009 06:40:00 -0500 Subject: [Tutor] 2to3 Help? In-Reply-To: References: <496AE3A6.9050304@gmail.com> Message-ID: <1c2a2c590901120340n5349c27eh9fcce5e646d1aeb2@mail.gmail.com> On Mon, Jan 12, 2009 at 3:56 AM, Alan Gauld wrote: > "Marco Petersen" wrote >> This was the line of code: >> >> $ 2to3 testscript.py > > But I suspect... > this will run your default python interpreter which is likely to still > be your 2.5 version. THe convertion scrpt is almost certainly 3.0. > So I think you will need to explicitly call the interpreter: > > $ some/path/to/python3 2to3 testscript.py > > Actually isn't 2to3 a .py file too? ie 2to3.py? 2to3 is a python program supplied with both Python 2.6 and 3.0. It is a simple launcher that starts lib2to3.main(). It has a shebang line to invoke the interpreter that, on my Mac at least, includes the complete path. That said, I too guess that somehow the OP has a mismatch between the Python version running and the version of lib2to3 being used. I would check on what is in 2to3. Kent From vceder at canterburyschool.org Mon Jan 12 14:07:39 2009 From: vceder at canterburyschool.org (Vern Ceder) Date: Mon, 12 Jan 2009 08:07:39 -0500 Subject: [Tutor] 2to3 Help? In-Reply-To: References: Message-ID: <496B409B.5020205@canterburyschool.org> > "Marco Petersen" wrote > >> > This was the line of code: >> > >> > $ 2to3 testscript.py > > But I suspect... > this will run your default python interpreter which is likely to still > be your 2.5 version. THe convertion scrpt is almost certainly 3.0. > So I think you will need to explicitly call the interpreter: Right - 2to3 isn't part of Python 2.5, but it is a part of 2.6 and 3.0 > > $ some/path/to/python3 2to3 testscript.py > > Actually isn't 2to3 a .py file too? ie 2to3.py? It's a Python file, but it doesn't have the .py extension. On my system it explicitly references Python 3 as the interpreter on the she-bang line, though, so that may not be the problem. > > Just some guesses... I haven't got around to installing Python 3 yet. > > Alan G. Cheers, Vern Ceder -- This time for sure! -Bullwinkle J. Moose ----------------------------- Vern Ceder, Director of Technology Canterbury School, 3210 Smith Road, Ft Wayne, IN 46804 vceder at canterburyschool.org; 260-436-0746; FAX: 260-436-5137 From noufal at nibrahim.net.in Mon Jan 12 16:56:55 2009 From: noufal at nibrahim.net.in (Noufal Ibrahim) Date: Mon, 12 Jan 2009 21:26:55 +0530 Subject: [Tutor] Selecting first matching element from a list Message-ID: <496B6847.9080701@nibrahim.net.in> Hello everyone, What is the pythonic was of selecting the first element of a list matching some condition? I often end up using [x for x in lst if cond(x)][0] This looks bad and raises IndexError if nothing is found which is ugly too. Thanks. -- ~noufal http://nibrahim.net.in/ From bgailer at gmail.com Mon Jan 12 18:21:53 2009 From: bgailer at gmail.com (bob gailer) Date: Mon, 12 Jan 2009 12:21:53 -0500 Subject: [Tutor] Selecting first matching element from a list In-Reply-To: <496B6847.9080701@nibrahim.net.in> References: <496B6847.9080701@nibrahim.net.in> Message-ID: <496B7C31.9040104@gmail.com> Noufal Ibrahim wrote: > Hello everyone, > What is the pythonic way of selecting the first element of a > list matching some condition? > I often end up using > > [x for x in lst if cond(x)][0] > > This looks bad and raises IndexError if nothing is found which > is ugly too. 1) itertools.dropwhile(cond, lst) will return a list with the desired element first. 2) "looks bad" and "is ugly" are emotional responses. What are you feeling and wanting when you say those things? 3) You can avoid the index error: lst2 = [x for x in lst if cond(x)] if lst2: desired = lst2[0] else: deal with element not found. OR for x in lst: if cond(x): break else: deal with element not found. -- Bob Gailer Chapel Hill NC 919-636-4239 From wescpy at gmail.com Mon Jan 12 19:00:20 2009 From: wescpy at gmail.com (wesley chun) Date: Mon, 12 Jan 2009 10:00:20 -0800 Subject: [Tutor] Selecting first matching element from a list In-Reply-To: <496B7C31.9040104@gmail.com> References: <496B6847.9080701@nibrahim.net.in> <496B7C31.9040104@gmail.com> Message-ID: <78b3a9580901121000tf1eb67drc8361741429cdd59@mail.gmail.com> > 1) itertools.dropwhile(cond, lst) will return a list with the desired element first. i think in order to use this, the OP needs to invert his Boolean logic because it *drops* elements while the conditional is True. as soon as it hits False the 1st time, all remaining elements (including the one that breaks the "while) is yielded. once he flips it, a single call to next() with a try-except StopIteration will be similar to the code in your msg: results = itertools.dropwhile(invCond, lst) try: desired = results.next() except StopIteration: deal with element not found bob's 2) and 3) are spot on. hope this helps! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 "Python Fundamentals", Prentice Hall, (c)2009 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From kent37 at tds.net Mon Jan 12 19:09:08 2009 From: kent37 at tds.net (Kent Johnson) Date: Mon, 12 Jan 2009 13:09:08 -0500 Subject: [Tutor] Selecting first matching element from a list In-Reply-To: <496B7C31.9040104@gmail.com> References: <496B6847.9080701@nibrahim.net.in> <496B7C31.9040104@gmail.com> Message-ID: <1c2a2c590901121009v6a7d1a67l5a653e90c2db91a8@mail.gmail.com> On Mon, Jan 12, 2009 at 12:21 PM, bob gailer wrote: > Noufal Ibrahim wrote: >> >> Hello everyone, >> What is the pythonic way of selecting the first element of a list >> matching some condition? >> I often end up using >> >> [x for x in lst if cond(x)][0] >> >> This looks bad and raises IndexError if nothing is found which is >> ugly too. > > 1) itertools.dropwhile(cond, lst) will return a list with the desired > element first. I think you mean itertools.takewhile(). Note that it returns an iterable, not a list; use next() to get the first element. You can also use a generator expression to do pretty much the same thing: (x for x in lst if cond(x)).next() This will raise StopIteration if no element meets the condition. Compared to the list comp, it has the advantage of stopping when it finds the first matching element; the list comp finds all matches. Kent From alan.gauld at freenet.co.uk Mon Jan 12 20:07:23 2009 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon, 12 Jan 2009 19:07:23 -0000 Subject: [Tutor] Deleting recursive folder definition Message-ID: <50C11A8B9DB748FA9E6E892067CCE014@xp> I've managed to do something incredibly stupid on my XP box. I've created a folder that is a link to itself - at least I think that's what has happened, it was a CASE tool that I was using that actually did the damage. The symptoms are that I can "infinitely" navigate down to the next level. I can also delete as many folders as I like but the top level properties still report 232 folders... Also I get error messages on the defective folder saying the filename(ie path) is too long. I've tried using Cygwin rm, I've tried renaming the folder to a shorter name., I've tried using the DOS DEL command. My last resort is to try to write a program to do it, but how? Does anyone know enough about Windows filesystem (NTFS) to know which API calls etc I would need? Or is there a better solution? I'm not even sure this approach will work since it will just recurse to inifinity too I suspect! The MSDN and Knowledge Base don't seem to offer any advice either... Any ideas? Alan G. From lawrence.wickline at gmail.com Mon Jan 12 20:46:03 2009 From: lawrence.wickline at gmail.com (Lawrence Wickline) Date: Mon, 12 Jan 2009 11:46:03 -0800 Subject: [Tutor] Deleting recursive folder definition In-Reply-To: <50C11A8B9DB748FA9E6E892067CCE014@xp> References: <50C11A8B9DB748FA9E6E892067CCE014@xp> Message-ID: <6879FE0E-C2A9-4FB9-ABCA-5B72E77F3646@gmail.com> did you try "rd /s /q" from the root directory command prompt? -L On Jan 12, 2009, at 11:07 AM, Alan Gauld wrote: > I've managed to do something incredibly stupid on my XP box. > I've created a folder that is a link to itself - at least I think > that's what has > happened, it was a CASE tool that I was using that actually did the > damage. > > The symptoms are that I can "infinitely" navigate down to the next > level. > I can also delete as many folders as I like but the top level > properties > still report 232 folders... Also I get error messages on the defective > folder saying the filename(ie path) is too long. > > I've tried using Cygwin rm, I've tried renaming the folder to a > shorter > name., I've tried using the DOS DEL command. > > My last resort is to try to write a program to do it, but how? > Does anyone know enough about Windows filesystem (NTFS) to know > which API calls etc I would need? Or is there a better solution? > I'm not even sure this approach will work since it will just recurse > to inifinity too I suspect! > > The MSDN and Knowledge Base don't seem to offer any advice either... > > Any ideas? > > Alan G. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From d.conca at gmail.com Mon Jan 12 21:23:31 2009 From: d.conca at gmail.com (Daniele) Date: Mon, 12 Jan 2009 21:23:31 +0100 Subject: [Tutor] Deleting recursive folder definition Message-ID: <537341c70901121223m1346bf60t91d5fe813905b84c@mail.gmail.com> > From: "Alan Gauld" > Date: Mon, 12 Jan 2009 19:07:23 -0000 > Subject: [Tutor] Deleting recursive folder definition > I've managed to do something incredibly stupid on my XP box. > I've created a folder that is a link to itself - at least I think that's what has > happened, it was a CASE tool that I was using that actually did the damage. > Any ideas? Hi Alan, I would try to boot from a linux live cd and remove the folder that way, also try the unlink unix command. Daniele From malaclypse2 at gmail.com Mon Jan 12 22:32:12 2009 From: malaclypse2 at gmail.com (Jerry Hill) Date: Mon, 12 Jan 2009 16:32:12 -0500 Subject: [Tutor] Deleting recursive folder definition In-Reply-To: <50C11A8B9DB748FA9E6E892067CCE014@xp> References: <50C11A8B9DB748FA9E6E892067CCE014@xp> Message-ID: <16651e80901121332p622f0f10o2c2c3e51e4a922dc@mail.gmail.com> On Mon, Jan 12, 2009 at 2:07 PM, Alan Gauld wrote: > I've managed to do something incredibly stupid on my XP box. > I've created a folder that is a link to itself - at least I think that's > what has > happened, it was a CASE tool that I was using that actually did the damage. Try exploring the options in fsutil.exe. Some (untested!) suggestions: fsutil.exe reparsepoint query fsutil.exe reparsepoint delete If that doesn't do the job, you probably need to figure out *exactly* what type of NTFS object you're dealing with. Some search terms that might get you started: NTFS plus one of: hard link soft link reparse point junction point There are tools out there that make dealing with some of the more exotic NTFS file-like objects easier, but I'm not too familiar with them. You'll probably need to explore some, and probably learn more about NTFS than you ever wanted to know :) -- Jerry From metolone+gmane at gmail.com Mon Jan 12 22:38:05 2009 From: metolone+gmane at gmail.com (Mark Tolonen) Date: Mon, 12 Jan 2009 13:38:05 -0800 Subject: [Tutor] Deleting recursive folder definition References: <50C11A8B9DB748FA9E6E892067CCE014@xp> Message-ID: "Alan Gauld" wrote in message news:50C11A8B9DB748FA9E6E892067CCE014 at xp... > I've managed to do something incredibly stupid on my XP box. > I've created a folder that is a link to itself - at least I think that's > what has > happened, it was a CASE tool that I was using that actually did the > damage. > > The symptoms are that I can "infinitely" navigate down to the next level. > I can also delete as many folders as I like but the top level properties > still report 232 folders... Also I get error messages on the defective > folder saying the filename(ie path) is too long. > > I've tried using Cygwin rm, I've tried renaming the folder to a shorter > name., I've tried using the DOS DEL command. > > My last resort is to try to write a program to do it, but how? > Does anyone know enough about Windows filesystem (NTFS) to know > which API calls etc I would need? Or is there a better solution? > I'm not even sure this approach will work since it will just recurse > to inifinity too I suspect! > > The MSDN and Knowledge Base don't seem to offer any advice either... > > Any ideas? It sounds as if you've created an "NTFS junction point." The XP Help topic shows 3 utilities that may help: Microsoft offers three utilities for creating and manipulating NTFS junction points: Linkd.exe a.. Grafts any target folder onto a Windows 2000 version of NTFS folder b.. Displays the target of an NTFS junction point c.. Deletes NTFS junction points that are created with Linkd.exe d.. Location: Microsoft Windows 2000 Resource Kit Mountvol.exe a.. Grafts the root folder of a local volume onto a Windows 2000 version of NTFS folder (or "mounts" the volume) b.. Displays the target of an NTFS junction point that is used to mount a volume c.. Lists the local file system volumes that are available for use d.. Deletes the volume mount points that are created with mountvol.exe e.. Location: Windows 2000 CD-ROM in the I386 folder Delrp.exe a.. Deletes NTFS junction points b.. Also deletes other types of reparse points, which are the entities that underlie junction points c.. Aimed primarily at developers who create reparse points d.. Location: Microsoft Windows 2000 Resource Kit Linkd or Delrp sound like what you may need. If you want to fix the problem programmatically, try looking up: DeviceIoControl FSCTL_GET_REPARSE_POINT FSCTL_DELETE_REPARSE_POINT FSCTL_SET_REPARSE_POINT -Mark -Mark From wormwood_3 at yahoo.com Mon Jan 12 22:39:30 2009 From: wormwood_3 at yahoo.com (wormwood_3) Date: Mon, 12 Jan 2009 13:39:30 -0800 (PST) Subject: [Tutor] Optional parameter passing Message-ID: <355911.66899.qm@web110805.mail.gq1.yahoo.com> Hello all, I have used *args and **kwargs to have a function accept optional parameters, but is there a lazy way to optionally pass parameters? For example, say my script can accept a number of parameters for a database connection, such as user, password, and database name. The function that makes the MySQL call has a default for user, say "root". So if the user didn't pass in a value for the user option, I don't want to pass it to the function doing the MySQL call. I don't want to have to do: if options.user: do_mysql_query(user) else: do_mysql_query() and so on for each possible option. Is there a better way? Thanks, Sam _______________________ Samuel Huckins Homepage - http://samuelhuckins.com Tech blog - http://dancingpenguinsoflight.com/ Photos - http://www.flickr.com/photos/samuelhuckins/ AIM - samushack | Gtalk - samushack | Skype - shuckins -------------- next part -------------- An HTML attachment was scrubbed... URL: From wormwood_3 at yahoo.com Mon Jan 12 22:42:42 2009 From: wormwood_3 at yahoo.com (wormwood_3) Date: Mon, 12 Jan 2009 13:42:42 -0800 (PST) Subject: [Tutor] Optional parameter passing References: <355911.66899.qm@web110805.mail.gq1.yahoo.com> Message-ID: <928792.59520.qm@web110812.mail.gq1.yahoo.com> A small correction to my code, although the point was hopefully still clear: if options.user: do_mysql_query(options.user) else: do_mysql_query() ________________________________ From: wormwood_3 To: Python Tutorlist Sent: Monday, January 12, 2009 4:39:30 PM Subject: [Tutor] Optional parameter passing Hello all, I have used *args and **kwargs to have a function accept optional parameters, but is there a lazy way to optionally pass parameters? For example, say my script can accept a number of parameters for a database connection, such as user, password, and database name. The function that makes the MySQL call has a default for user, say "root". So if the user didn't pass in a value for the user option, I don't want to pass it to the function doing the MySQL call. I don't want to have to do: if options.user: do_mysql_query(user) else: do_mysql_query() and so on for each possible option. Is there a better way? Thanks, Sam _______________________ Samuel Huckins Homepage - http://samuelhuckins.com Tech blog - http://dancingpenguinsoflight.com/ Photos - http://www.flickr.com/photos/samuelhuckins/ AIM - samushack | Gtalk - samushack | Skype - shuckins -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Mon Jan 12 23:09:31 2009 From: kent37 at tds.net (Kent Johnson) Date: Mon, 12 Jan 2009 17:09:31 -0500 Subject: [Tutor] Optional parameter passing In-Reply-To: <355911.66899.qm@web110805.mail.gq1.yahoo.com> References: <355911.66899.qm@web110805.mail.gq1.yahoo.com> Message-ID: <1c2a2c590901121409o56825e5epc9cafaf73d74b6c4@mail.gmail.com> On Mon, Jan 12, 2009 at 4:39 PM, wormwood_3 wrote: > Hello all, > > I have used *args and **kwargs to have a function accept optional > parameters, but is there a lazy way to optionally pass parameters? For > example, say my script can accept a number of parameters for a database > connection, such as user, password, and database name. The function that > makes the MySQL call has a default for user, say "root". So if the user > didn't pass in a value for the user option, I don't want to pass it to the > function doing the MySQL call. I don't want to have to do: > > if options.user: > do_mysql_query(user) > else: > do_mysql_query() > > and so on for each possible option. Is there a better way? You would have to put the options into a collection, a list or dict or class. You can use *args and **kwargs at the point of call as well as in a function definition. What about having the defaults in the options object and just passing it to the function? do_mysql_query(options) or pass the options and have the function use code like user = options.user or 'root' Kent From wferguson1 at socal.rr.com Mon Jan 12 23:23:41 2009 From: wferguson1 at socal.rr.com (WM.) Date: Mon, 12 Jan 2009 14:23:41 -0800 Subject: [Tutor] HOW DO I PYTHONIZE A BASICALLY BASIC PROGRAM? Message-ID: <496BC2ED.9060007@socal.rr.com> # The natural numbers(natnum), under 1000, divisible by 3 or by 5 are to be added together. natnum = 0 num3 = 0 num5 = 0 cume = 0 # The 'and' is the 15 filter; the 'or' is the 3 or 5 filter. while natnum <= 999: num3 = natnum/3 num5 = natnum/5 if natnum - (num3 * 3) == 0 and natnum - (num5 * 5) == 0: cume = cume + natnum elif natnum - (num3 * 3) == 0 or natnum - (num5 * 5) == 0: if natnum - (num3 * 3) == 0: cume = cume + natnum elif natnum - (num5 * 5) == 0: cume = cume + natnum natnum = natnum + 1 print cume This problem was kicked around last month and I did not understand any of the scripts. So I tried to recall the BASIC ifs and loops. The project euler guys say it works, but how might it be made more Pythonic? From wormwood_3 at yahoo.com Mon Jan 12 23:34:27 2009 From: wormwood_3 at yahoo.com (wormwood_3) Date: Mon, 12 Jan 2009 14:34:27 -0800 (PST) Subject: [Tutor] Optional parameter passing References: <355911.66899.qm@web110805.mail.gq1.yahoo.com> <1c2a2c590901121409o56825e5epc9cafaf73d74b6c4@mail.gmail.com> Message-ID: <951885.2369.qm@web110814.mail.gq1.yahoo.com> You know, that's a great idea :-) Just using options I could keep my initial checks the same (e.g. making sure needed options were included by looking at options.foo) and pass it along without adding much to the query function. Thanks! _______________________ Samuel Huckins Homepage - http://samuelhuckins.com Tech blog - http://dancingpenguinsoflight.com/ Photos - http://www.flickr.com/photos/samuelhuckins/ AIM - samushack | Gtalk - samushack | Skype - shuckins ________________________________ From: Kent Johnson To: wormwood_3 Cc: Python Tutorlist Sent: Monday, January 12, 2009 5:09:31 PM Subject: Re: [Tutor] Optional parameter passing On Mon, Jan 12, 2009 at 4:39 PM, wormwood_3 wrote: > Hello all, > > I have used *args and **kwargs to have a function accept optional > parameters, but is there a lazy way to optionally pass parameters? For > example, say my script can accept a number of parameters for a database > connection, such as user, password, and database name. The function that > makes the MySQL call has a default for user, say "root". So if the user > didn't pass in a value for the user option, I don't want to pass it to the > function doing the MySQL call. I don't want to have to do: > > if options.user: > do_mysql_query(user) > else: > do_mysql_query() > > and so on for each possible option. Is there a better way? You would have to put the options into a collection, a list or dict or class. You can use *args and **kwargs at the point of call as well as in a function definition. What about having the defaults in the options object and just passing it to the function? do_mysql_query(options) or pass the options and have the function use code like user = options.user or 'root' Kent -------------- next part -------------- An HTML attachment was scrubbed... URL: From emadnawfal at gmail.com Tue Jan 13 00:35:58 2009 From: emadnawfal at gmail.com (=?WINDOWS-1256?Q?Emad_Nawfal_(=DA=E3=C7=CF_=E4=E6=DD=E1)?=) Date: Mon, 12 Jan 2009 18:35:58 -0500 Subject: [Tutor] HOW DO I PYTHONIZE A BASICALLY BASIC PROGRAM? In-Reply-To: <496BC2ED.9060007@socal.rr.com> References: <496BC2ED.9060007@socal.rr.com> Message-ID: <652641e90901121535m4d879de0n18f9c71ef457ce70@mail.gmail.com> On Mon, Jan 12, 2009 at 5:23 PM, WM. wrote: > # The natural numbers(natnum), under 1000, divisible by 3 or by 5 are to be > added together. > natnum = 0 > num3 = 0 > num5 = 0 > cume = 0 > # The 'and' is the 15 filter; the 'or' is the 3 or 5 filter. > while natnum <= 999: > num3 = natnum/3 > num5 = natnum/5 > if natnum - (num3 * 3) == 0 and natnum - (num5 * 5) == 0: > cume = cume + natnum > elif natnum - (num3 * 3) == 0 or natnum - (num5 * 5) == 0: > if natnum - (num3 * 3) == 0: > cume = cume + natnum > elif natnum - (num5 * 5) == 0: > cume = cume + natnum > natnum = natnum + 1 > print cume > > > This problem was kicked around last month and I did not understand any of > the scripts. So I tried to recall the BASIC ifs and loops. The project > euler guys say it works, but how might it be made more Pythonic? > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > I guess using a list comprehension will work >>>x = [number for number in range(1000) if number%3 ==0 or number%2 ==0] >>> sum(x) 333167 >>> -- ?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? ????????.....???? ??????? "No victim has ever been more repressed and alienated than the truth" Emad Soliman Nawfal Indiana University, Bloomington http://emnawfal.googlepages.com -------------------------------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: From juryef at yahoo.com Tue Jan 13 01:49:04 2009 From: juryef at yahoo.com (Judith Flores) Date: Mon, 12 Jan 2009 16:49:04 -0800 (PST) Subject: [Tutor] Modify a dictionary using csv.DictWriter Message-ID: <410140.63636.qm@web34704.mail.mud.yahoo.com> Hello, I have been struggling a while trying to figure out how to modify a csv file using the csv.DictWriter class. Let's suppose I have the following code: import csv outfile=open('template.csv','w') # This is a pre-existing file that contains 3 variables (3 columns). The variables will (or will not) have a value each. x='new_value' writing=csv.DictWriter(outfile, fieldnames=['variable1','variable2','variable2']) data={'variable1' : x} # What I intent to do here is to overwrite whatever value exists for variable 1. There will always exist only one value per variable. writing.writerow(data) I have several questions about how DictWriter works, and I am sorry if my questions have a very obvious answer, which I am 'obviously' missing. 1. When I run the code above for the first time, the contents of the pre-existing file disappear, if I run the script a second time, now I can see the value of x. 2. The fieldnames don't appear in the csv file, only the values. 3. Is there a way to let the DictWriter know that the header of the csv file corresponds to all the fieldnames? To avoid typing all the names. As usual, thank you very much for your help. Judith From alan.gauld at btinternet.com Tue Jan 13 02:10:51 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 13 Jan 2009 01:10:51 -0000 Subject: [Tutor] Modify a dictionary using csv.DictWriter References: <410140.63636.qm@web34704.mail.mud.yahoo.com> Message-ID: "Judith Flores" wrote > I have been struggling a while trying to figure out how to modify > a csv > file using the csv.DictWriter class. Let's suppose I have the > following code: I have never used DictWriter but... > outfile=open('template.csv','w') # This is a pre-existing file Opening a file to write will create a new empty file. It will effectively delete the pre existing file! > 1. When I run the code above for the first time, the contents of the > pre-existing > file disappear, if I run the script a second time, now I can see the > value of x. Not sure why you see it on the second run but you are deleting the file with the open call. You probably need to open one file for reading and another for writing thenm at the end delete the first file (or rename it to .bak) and overwrite with the written (modified) file. > 2. The fieldnames don't appear in the csv file, only the values. > 3. Is there a way to let the DictWriter know that the header of the > csv > file corresponds to all the fieldnames? To avoid typing all the > names. I can't help with that bit, sorry. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From john at fouhy.net Tue Jan 13 02:23:37 2009 From: john at fouhy.net (John Fouhy) Date: Tue, 13 Jan 2009 14:23:37 +1300 Subject: [Tutor] Modify a dictionary using csv.DictWriter In-Reply-To: <410140.63636.qm@web34704.mail.mud.yahoo.com> References: <410140.63636.qm@web34704.mail.mud.yahoo.com> Message-ID: <5e58f2e40901121723o34cd59e1v42497dd31ccaff@mail.gmail.com> 2009/1/13 Judith Flores : > Hello, Hi Judith, > 1. When I run the code above for the first time, the contents of the pre-existing file disappear, if I > run the script a second time, now I can see the value of x. This is a consequence of this line: > outfile=open('template.csv','w') # This is a pre-existing file that contains 3 variables (3 In python (and most programming languages), if you open a file for writing (mode 'w'), you automatically get a new, empty file. Any existing file with the same name is lost. If you want to add records to the end of the file, you can open in append mode ('a'). See the python library documentation for "Built-in Functions" for more. (the docs also mention mode 'a+', which is for "updating". I confess that I do not know the difference between 'a' and 'a+' (or 'w' and 'w+' for that matter)) If you want to modify rows in a csv file, your only option is: 1. Read the csv file into a python data structure. 2. Make the appropriate changes. 3. Write all the data out to a new csv file. CSV files aren't really intended as mutable data stores. If this is what you want, perhaps the shelve module would work better for you (it's like a dict, but on disk), or even a relational database such as sqlite3 (included with python 2.5 and up). > 2. The fieldnames don't appear in the csv file, only the values. I don't think the csv module will write a header row. However, it is easy enough to do yourself: just: fieldnames = ['variable1', 'variable2', 'variable3'] outfile.write(','.join(fieldnames) + '\n') > 3. Is there a way to let the DictWriter know that the header of the csv file corresponds to all the > fieldnames? To avoid typing all the names. If you read in the csv file using DictReader, you should have access to the field names as keys of the dictionaries (although possibly not in the same order). Alternatively, just type them out once and give them a name: fieldnames = ['variable1', 'variable2', 'variable3'] After all, your program should probably know what your data looks like :-) HTH. -- John. From bgailer at gmail.com Tue Jan 13 03:20:10 2009 From: bgailer at gmail.com (bob gailer) Date: Mon, 12 Jan 2009 21:20:10 -0500 Subject: [Tutor] HOW DO I PYTHONIZE A BASICALLY BASIC PROGRAM? In-Reply-To: <496BC2ED.9060007@socal.rr.com> References: <496BC2ED.9060007@socal.rr.com> Message-ID: <496BFA5A.7070101@gmail.com> WM. wrote: > # The natural numbers(natnum), under 1000, divisible by 3 or by 5 are > to be added together. > natnum = 0 > num3 = 0 > num5 = 0 > cume = 0 > # The 'and' is the 15 filter; the 'or' is the 3 or 5 filter. > while natnum <= 999: > num3 = natnum/3 > num5 = natnum/5 > if natnum - (num3 * 3) == 0 and natnum - (num5 * 5) == 0: > cume = cume + natnum > elif natnum - (num3 * 3) == 0 or natnum - (num5 * 5) == 0: > if natnum - (num3 * 3) == 0: > cume = cume + natnum > elif natnum - (num5 * 5) == 0: > cume = cume + natnum > natnum = natnum + 1 > print cume > My head hurts trying to follow all that logic and expressions. That is a sign of too much code. Let's simplify: 1) no need to initialize num3 or num5 2) replace while with for 3a) replace natnum - (num3 * 3) == 0 with natnum == (num3 * 3) 3b) replact that with not (natnum % 3) 4) use += and -= for natnum in range(1000): if not (natnum % 3 or natnum % 5): # adds 1 if divisible by 3 and/or 5 cume += 1 if not natnum % 15: # remove one of the ones if divisible by 15 cume -= 1 Since the result of not is True (1) or False (0) one can also write cume += not (natnum % 3 or natnum % 5) cume 1= not (natnum % 15) An alternative: for natnum in range(1000): if not natnum % 15: pass elif not (natnum % 3 or natnum % 5): # adds 1 if divisible by 3 or 5 cume += 1 > > This problem was kicked around last month and I did not understand any > of the scripts. That's really unfortunate. Would you for your learning take one of them, tell us what if any parts of it you understand and let us nudge you toward more understanding. -- Bob Gailer Chapel Hill NC 919-636-4239 From s4027340 at student.uq.edu.au Tue Jan 13 05:28:30 2009 From: s4027340 at student.uq.edu.au (Mr Gerard Kelly) Date: Tue, 13 Jan 2009 14:28:30 +1000 Subject: [Tutor] A list of input arguments Message-ID: I have a problem with understanding how lists, strings, tuples, number types and input arguments all interact with each other. I have this program, in which I can use the *a structure to input unlimited arguments. As an example, if I use three arguments, it looks like this: def main(): #Play a chord pygame.mixer.pre_init(sample_rate, -16, 1) # 44.1kHz, 16-bit signed, mono pygame.init() play_for(waves(440,550,660), 5000) In that final line, I would like to be able to define the input arguments on a different line (I'm hoping to eventually make a Tkinter entry box), but when I try to do this: def main(): #Play a chord pygame.mixer.pre_init(sample_rate, -16, 1) # 44.1kHz, 16-bit signed, mono pygame.init() chord=[440,550,660] play_for(waves(chord), 5000) it doesn't work. It doesn't work with a string or a tuple either. The problem is that another part of the code needs to take float(chord[0]), that is convert the first input value into the float class, and the error message says "TypeError: float() argument must be a string or a number." This is fine when the elements of *chord are listed inside the function's parentheses, but it doesn't work if they're listed outside. Is there any way to list the input arguments without listing them inside the function's parentheses? Thanks. From alan.gauld at btinternet.com Tue Jan 13 10:16:58 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 13 Jan 2009 09:16:58 -0000 Subject: [Tutor] A list of input arguments References: Message-ID: "Mr Gerard Kelly" wrote >I have a problem with understanding how lists, strings, tuples, >number > types and input arguments all interact with each other. OK, they are all different types. Some of them take a single value (sometimes known as a scalar type) and others take a collection of values (sometimes known as a sequence). Strings are unusual in that they can be considered as a scalar type or as a collection of characters! Input parameters are simply local variables for the function to which they are attached. Other than the fact that you can assign them values from outside the function whe you call it they act just like normal variables. def f(): print x x = 42 f() Is the same (almost)) as def f(x): print x > As an example, if I use three arguments, it looks like this: > > def main(): > play_for(waves(440,550,660), 5000) > def main(): > chord=[440,550,660] > play_for(waves(chord), 5000) > > it doesn't work. Because you are passing a single value (a list) into a function that expects 3 values. > It doesn't work with a string or a tuple either. Because strings and tuples are also single (container )entities You must unpack your collection when calling the function: play_for(waves(chord[0],chord[1],chord[2]),5000) > The problem is that another part of the code needs to take > float(chord[0]), that is convert the first input value into the > float > class, and the error message says "TypeError: float() argument must > be a > string or a number." Thats right, and as you did above you must extract the first element since the code can't tell that yopu have passed it a collection instead of a number! > Is there any way to list the input arguments without listing them > inside > the function's parentheses? No, because the function expects 3 arguments so you must pass it 3. That is the contract (or interface) that exists betweeen the writer of the function and you the consumer of it. Programming. particularly on larger projects with multiple teams, is all about defining interfaces and adhering to them! If you want thebenefit of the function you must respect its contract. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From s4027340 at student.uq.edu.au Tue Jan 13 12:32:52 2009 From: s4027340 at student.uq.edu.au (Mr Gerard Kelly) Date: Tue, 13 Jan 2009 21:32:52 +1000 Subject: [Tutor] A list of input arguments Message-ID: <9c0be977ab.977ab9c0be@uq.edu.au> Many thanks for your helpful answer Alan. My only other question is, does there exist a convenient way to unpack a collection of variable length? If you know that there are 3 elements in the collection, you can specify: play_for(waves(chord[0],chord[1],chord[2]),500) But then if you want to change the number of elements in the list "chord", say from 3 to 5, you have to change the code accordingly. Is there some sort of way to instruct the code to unpack its elements for any number of elements? Like i=len(chord) play_for(waves(chord[0],chord[1],...,chord[i-1]),500) If there is a way to do this it would be great! ----- Original Message ----- From: Alan Gauld Date: Tuesday, January 13, 2009 7:16 pm Subject: Re: [Tutor] A list of input arguments > "Mr Gerard Kelly" wrote > > >I have a problem with understanding how lists, strings, tuples, > >number > > types and input arguments all interact with each other. > > OK, they are all different types. Some of them take a single value > (sometimes known as a scalar type) and others take a collection > of values (sometimes known as a sequence). Strings are unusual > in that they can be considered as a scalar type or as a collection > of characters! > > Input parameters are simply local variables for the function to > which they are attached. Other than the fact that you can assign > them values from outside the function whe you call it they act just > like normal variables. > > def f(): > print x > > x = 42 > f() > > Is the same (almost)) as > > def f(x): > print x > > > As an example, if I use three arguments, it looks like this: > > > > def main(): > > play_for(waves(440,550,660), 5000) > > > > def main(): > > chord=[440,550,660] > > play_for(waves(chord), 5000) > > > > it doesn't work. > > Because you are passing a single value (a list) into a function that > expects 3 values. > > > It doesn't work with a string or a tuple either. > > Because strings and tuples are also single (container )entities > > You must unpack your collection when calling the function: > > play_for(waves(chord[0],chord[1],chord[2]),5000) > > > The problem is that another part of the code needs to take > > float(chord[0]), that is convert the first input value into the > > float > > class, and the error message says "TypeError: float() argument > must > > be a > > string or a number." > > Thats right, and as you did above you must extract the first element > since the code can't tell that yopu have passed it a collection > instead > of a number! > > > Is there any way to list the input arguments without listing them > > inside > > the function's parentheses? > > No, because the function expects 3 arguments so you must pass it 3. > That is the contract (or interface) that exists betweeen the writer > of > the > function and you the consumer of it. Programming. particularly on > larger projects with multiple teams, is all about defining interfaces > and adhering to them! If you want thebenefit of the function you must > respect its contract. > > HTH, > > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.freenetpages.co.uk/hp/alan.gauld > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Tue Jan 13 12:38:41 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 13 Jan 2009 06:38:41 -0500 Subject: [Tutor] HOW DO I PYTHONIZE A BASICALLY BASIC PROGRAM? In-Reply-To: <496BFA5A.7070101@gmail.com> References: <496BC2ED.9060007@socal.rr.com> <496BFA5A.7070101@gmail.com> Message-ID: <1c2a2c590901130338v6a9427dep72681213eae246a5@mail.gmail.com> On Mon, Jan 12, 2009 at 9:20 PM, bob gailer wrote: > for natnum in range(1000): > if not (natnum % 3 or natnum % 5): # adds 1 if divisible by 3 and/or 5 > cume += 1 > if not natnum % 15: # remove one of the ones if divisible by 15 > cume -= 1 This subtraction is not needed because the multiples of 15 are not double-counted. The 'or' condition counts multiples of 15 just once. Kent From kent37 at tds.net Tue Jan 13 12:42:40 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 13 Jan 2009 06:42:40 -0500 Subject: [Tutor] A list of input arguments In-Reply-To: References: Message-ID: <1c2a2c590901130342r195dbcfuf616d3f1cfd0936c@mail.gmail.com> On Tue, Jan 13, 2009 at 4:16 AM, Alan Gauld wrote: > "Mr Gerard Kelly" wrote >> Is there any way to list the input arguments without listing them inside >> the function's parentheses? > > No, because the function expects 3 arguments so you must pass it 3. > That is the contract (or interface) that exists betweeen the writer of the > function and you the consumer of it. Programming. particularly on > larger projects with multiple teams, is all about defining interfaces > and adhering to them! If you want thebenefit of the function you must > respect its contract. You can use *args to pass multiple arguments in a list. For example, In [1]: def show(a, b, c): ...: print a, b, c In [2]: values = [1, 2, 3] In [3]: show(*values) 1 2 3 Kent From kent37 at tds.net Tue Jan 13 13:42:11 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 13 Jan 2009 07:42:11 -0500 Subject: [Tutor] A list of input arguments In-Reply-To: <9c0be977ab.977ab9c0be@uq.edu.au> References: <9c0be977ab.977ab9c0be@uq.edu.au> Message-ID: <1c2a2c590901130442p28bd1565u7ca8a5c36eedf1ab@mail.gmail.com> On Tue, Jan 13, 2009 at 6:32 AM, Mr Gerard Kelly wrote: > My only other question is, does there exist a convenient way to unpack a > collection of variable length? > > If you know that there are 3 elements in the collection, you can specify: > > play_for(waves(chord[0],chord[1],chord[2]),500) > > But then if you want to change the number of elements in the list > "chord", say from 3 to 5, you have to change the code accordingly. Is > there some sort of way to instruct the code to unpack its elements for > any number of elements? > > Like > i=len(chord) > play_for(waves(chord[0],chord[1],...,chord[i-1]),500) Presuming that waves() is defined to take an arbitrary number of arguments, e.g. def waves(*args) you can use play_for(waves(*chord), 500) to call it with a variable number of arguments. Kent From denis.spir at free.fr Tue Jan 13 13:50:49 2009 From: denis.spir at free.fr (spir) Date: Tue, 13 Jan 2009 13:50:49 +0100 Subject: [Tutor] traceback Message-ID: <20090113135049.3e1c11e3@o> Hello, is there a way to read an exception's traceback? Cannot find it in object attributes. [dir() shows no traceback, __dict__ is empty.] t = "a" try: print t[1] except IndexError, e: print e print repr(e) print dir(e) print e. __dict__ print e.args print e.message raise ==> string index out of range IndexError('string index out of range',) ['__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__', '__getitem__', '__getslice__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setstate__', '__str__', 'args', 'message'] {} ('string index out of range',) string index out of range Traceback (most recent call last): File "___test__.py", line 10, in print t[1] IndexError: string index out of range Denis ------ la vida e estranya From a.t.hofkamp at tue.nl Tue Jan 13 13:55:03 2009 From: a.t.hofkamp at tue.nl (A.T.Hofkamp) Date: Tue, 13 Jan 2009 13:55:03 +0100 Subject: [Tutor] traceback In-Reply-To: <20090113135049.3e1c11e3@o> References: <20090113135049.3e1c11e3@o> Message-ID: <496C8F27.9010301@tue.nl> spir wrote: > Hello, > > is there a way to read an exception's traceback? Cannot find it in object attributes. [dir() > shows no traceback, __dict__ is empty.] You should be able to do that with the traceback module. Sincerely, Albert From ji_zhiqiang at 163.com Tue Jan 13 14:42:06 2009 From: ji_zhiqiang at 163.com (jzq) Date: Tue, 13 Jan 2009 21:42:06 +0800 Subject: [Tutor] Python and Abaqus In-Reply-To: <452123.29963.qm@web53903.mail.re2.yahoo.com> Message-ID: <1231854126.31108.3.camel@jzq-laptop> hi,I need your help. Could you give me some examples about the using of python in abaqus? Thanks a lot. From kent37 at tds.net Tue Jan 13 15:21:36 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 13 Jan 2009 09:21:36 -0500 Subject: [Tutor] Python and Abaqus In-Reply-To: <1231854126.31108.3.camel@jzq-laptop> References: <452123.29963.qm@web53903.mail.re2.yahoo.com> <1231854126.31108.3.camel@jzq-laptop> Message-ID: <1c2a2c590901130621y20f0617dq590749c02cbe5d3f@mail.gmail.com> On Tue, Jan 13, 2009 at 8:42 AM, jzq wrote: > hi,I need your help. > Could you give me some examples about the using of python in abaqus? > Thanks a lot. I'm not sure there is anyone on this list who knows abaqus, previous questions have come up pretty dry. We can help with the python part... Googling 'python abaqus' might give a little help. Kent From frenc1z at gmail.com Tue Jan 13 17:45:38 2009 From: frenc1z at gmail.com (frenc1z 1z) Date: Tue, 13 Jan 2009 17:45:38 +0100 Subject: [Tutor] Date comparison across time zones Message-ID: <7b60d8a80901130845s30842deeuba55afec99285a5c@mail.gmail.com> Hello, I'm a novice python (python 2.6.1) user with the following problem. Never though this was going to be so difficult :-). I would like to compare some dates (date+time really). The dates all have the following RFC2822 format: Eg. is d1 < d2? d1 = "Tue, 13 Jan 2009 03:27:29 -0800" d2 = "Tue, 13 Jan 2009 02:40:00 -0600" My thinking is that I first need to make these two dates comparable, and eliminate the impact of time zone and dst. Understand that I can acheive this using strptime. Been trying to parse these dates as follows: print datetime.strptime("Tue, 13 Jan 2009 02:40:00 -0800", "%a, %d %b %Y %H:%M:%S %z"). I get the following error on the conversion "ValueError: 'z' is a bad directive in format '%a, %d %b %Y %H:%M:%S %z'". >From what I have read, I understand that python 2.6 would support the %z directive, so I do not really understand the error. Apart from that, how can I best attach this problem? At first sight it would seem trivial, but unfortunately I can't build on sufficient experience in python to get to a solution. Many thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Tue Jan 13 19:01:02 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 13 Jan 2009 13:01:02 -0500 Subject: [Tutor] Date comparison across time zones In-Reply-To: <7b60d8a80901130845s30842deeuba55afec99285a5c@mail.gmail.com> References: <7b60d8a80901130845s30842deeuba55afec99285a5c@mail.gmail.com> Message-ID: <1c2a2c590901131001p90c778kb7d4c87d6d31d49@mail.gmail.com> On Tue, Jan 13, 2009 at 11:45 AM, frenc1z 1z wrote: > I would like to compare some dates (date+time really). The dates all have > the following RFC2822 format: > > Eg. is d1 < d2? > d1 = "Tue, 13 Jan 2009 03:27:29 -0800" > d2 = "Tue, 13 Jan 2009 02:40:00 -0600" > > Been trying to parse these dates as follows: print datetime.strptime("Tue, > 13 Jan 2009 02:40:00 -0800", "%a, %d %b %Y %H:%M:%S %z"). > > I get the following error on the conversion "ValueError: 'z' is a bad > directive in format '%a, %d %b %Y %H:%M:%S %z'". The correct format code is %Z (upper case). However that still doesn't work, I don't have a complete solution for you. In [8]: datetime.strptime("Tue, 13 Jan 2009 02:40:00 EST", "%a, %d %b %Y %H:%M:%S %Z") --------------------------------------------------------------------------- ValueError Traceback (most recent call last) C:\Project\Play\ in () C:\Python25\lib\_strptime.py in strptime(data_string, format) 328 if not found: 329 raise ValueError("time data did not match format: data=%s fmt=%s" % --> 330 (data_string, format)) 331 if len(data_string) != found.end(): 332 raise ValueError("unconverted data remains: %s" % ValueError: time data did not match format: data=Tue, 13 Jan 2009 02:40:00 EST fmt=%a, %d %b %Y %H:%M:%S %Z Kent From ig2ar-saf1 at yahoo.co.uk Tue Jan 13 19:19:03 2009 From: ig2ar-saf1 at yahoo.co.uk (culpritNr1) Date: Tue, 13 Jan 2009 10:19:03 -0800 (PST) Subject: [Tutor] power of 2.718282 Message-ID: <21441385.post@talk.nabble.com> Hello All, It such a simple question, but because of that, googling for an answer just pulls the wrong results. How do I compute a power of e in Python? Say I need 2.718282 to the 10th. In R for example, I just do exp(10). I would appreciate a low level solution because I have to iteratively call that computation millions of times. Anything more efficient than 2.718182**10 may be good. Thank you, culpritNr1 -- View this message in context: http://www.nabble.com/power-of-2.718282-tp21441385p21441385.html Sent from the Python - tutor mailing list archive at Nabble.com. From marc.tompkins at gmail.com Tue Jan 13 19:25:16 2009 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Tue, 13 Jan 2009 10:25:16 -0800 Subject: [Tutor] power of 2.718282 In-Reply-To: <21441385.post@talk.nabble.com> References: <21441385.post@talk.nabble.com> Message-ID: <40af687b0901131025k26fd0773g9b5a5f2917e5be6d@mail.gmail.com> On Tue, Jan 13, 2009 at 10:19 AM, culpritNr1 wrote: > > How do I compute a power of e in Python? > > Say I need 2.718282 to the 10th. In R for example, I just do exp(10). > > I would appreciate a low level solution because I have to iteratively call > that computation millions of times. Anything more efficient than > 2.718182**10 may be good. > Import the "math" module. From the 2.6 docs: Power and logarithmic functions > > math.exp(x) > Return e**x. > > math.log(x[, base]) > Return the logarithm of x to the given base. If the base is not specified, > return the natural logarithm of x (that is, the logarithm to base e). > Changed in version 2.3: base argument added. > > math.log1p(x) > Return the natural logarithm of 1+x (base e). The result is calculated in > a way which is accurate for x near zero. > New in version 2.6. > > math.log10(x) > Return the base-10 logarithm of x. > > math.pow(x, y) > Return x raised to the power y. Exceptional cases follow Annex 'F' of the > C99 standard as far as possible. In particular, pow(1.0, x) and pow(x, 0.0) > always return 1.0, even when x is a zero or a NaN. If both x and y are > finite, x is negative, and y is not an integer then pow(x, y) is undefined, > and raises ValueError. > Changed in version 2.6: The outcome of 1**nan and nan**0 was undefined. > > math.sqrt(x) > Return the square root of x. > -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Tue Jan 13 19:33:53 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 13 Jan 2009 13:33:53 -0500 Subject: [Tutor] power of 2.718282 In-Reply-To: <21441385.post@talk.nabble.com> References: <21441385.post@talk.nabble.com> Message-ID: <1c2a2c590901131033l594f5860ia76c060ed3c0b55@mail.gmail.com> On Tue, Jan 13, 2009 at 1:19 PM, culpritNr1 wrote: > > Hello All, > > It such a simple question, but because of that, googling for an answer just > pulls the wrong results. > > How do I compute a power of e in Python? > > Say I need 2.718282 to the 10th. In R for example, I just do exp(10). import math math.exp(10) http://docs.python.org/library/math.html#math.exp Kent From ig2ar-saf1 at yahoo.co.uk Tue Jan 13 19:38:36 2009 From: ig2ar-saf1 at yahoo.co.uk (culpritNr1) Date: Tue, 13 Jan 2009 10:38:36 -0800 (PST) Subject: [Tutor] power of 2.718282 In-Reply-To: <1c2a2c590901131033l594f5860ia76c060ed3c0b55@mail.gmail.com> References: <21441385.post@talk.nabble.com> <1c2a2c590901131033l594f5860ia76c060ed3c0b55@mail.gmail.com> Message-ID: <21441787.post@talk.nabble.com> Thanks Marc and Kent and all. math.exp() is what I was looking for. culpritNr1 -- View this message in context: http://www.nabble.com/power-of-2.718282-tp21441385p21441787.html Sent from the Python - tutor mailing list archive at Nabble.com. From adam.jtm30 at gmail.com Tue Jan 13 20:11:15 2009 From: adam.jtm30 at gmail.com (Adam Bark) Date: Tue, 13 Jan 2009 19:11:15 +0000 Subject: [Tutor] power of 2.718282 In-Reply-To: <21441787.post@talk.nabble.com> References: <21441385.post@talk.nabble.com> <1c2a2c590901131033l594f5860ia76c060ed3c0b55@mail.gmail.com> <21441787.post@talk.nabble.com> Message-ID: According to a quick interactive session and the timeit module it's quicker to do 2.71828**10 than using math.exp, I'm guessing cos of the function call. >>> t=timeit.Timer("2.718282**10") >>> t.repeat() [0.073765993118286133, 0.066617012023925781, 0.06807398796081543] >>> t=timeit.Timer("math.exp(10)", "import math") >>> t.repeat() [0.42525100708007812, 0.43169903755187988, 0.4239799976348877] >>> t=timeit.Timer("exp(10)", "from math import exp") >>> t.repeat() [0.36061406135559082, 0.36182284355163574, 0.35887718200683594] 2009/1/13 culpritNr1 > > Thanks Marc and Kent and all. math.exp() is what I was looking for. > > culpritNr1 > > > -- > View this message in context: > http://www.nabble.com/power-of-2.718282-tp21441385p21441787.html > Sent from the Python - tutor mailing list archive at Nabble.com. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From mwalsh at mwalsh.org Tue Jan 13 20:18:21 2009 From: mwalsh at mwalsh.org (Martin Walsh) Date: Tue, 13 Jan 2009 13:18:21 -0600 Subject: [Tutor] Date comparison across time zones In-Reply-To: <7b60d8a80901130845s30842deeuba55afec99285a5c@mail.gmail.com> References: <7b60d8a80901130845s30842deeuba55afec99285a5c@mail.gmail.com> Message-ID: <496CE8FD.1000908@mwalsh.org> frenc1z 1z wrote: > Hello, > I would like to compare some dates (date+time really). The dates all > have the following RFC2822 format: > > Eg. is d1 < d2? > d1 = "Tue, 13 Jan 2009 03:27:29 -0800" > d2 = "Tue, 13 Jan 2009 02:40:00 -0600" > > My thinking is that I first need to make these two dates comparable, and > eliminate the impact of time zone and dst. Understand that I can acheive > this using strptime. > > Been trying to parse these dates as follows: print > datetime.strptime("Tue, 13 Jan 2009 02:40:00 -0800", "%a, %d %b %Y > %H:%M:%S %z"). > > I get the following error on the conversion "ValueError: 'z' is a bad > directive in format '%a, %d %b %Y %H:%M:%S %z'". > I'm not sure how one would accomplish this with only the stdlib, but there are at least two 3rd party modules which you may find useful. dateutil: http://labix.org/python-dateutil mx.DateTime: http://www.egenix.com/products/python/mxBase/mxDateTime/ Each of these implement a timezone aware date-string parser, here is an (untested) example or two: d1 = "Tue, 13 Jan 2009 03:27:29 -0800" d2 = "Tue, 13 Jan 2009 02:40:00 -0600" from dateutil import parser dparser = parser.parser() p1 = dparser.parse(d1) p2 = dparser.parse(d2) print p1 < p2 from mx.DateTime import DateTimeFrom m1 = DateTimeFrom(d1) m2 = DateTimeFrom(d2) print m1 < m2 HTH, Marty From emadnawfal at gmail.com Tue Jan 13 21:14:09 2009 From: emadnawfal at gmail.com (=?WINDOWS-1256?Q?Emad_Nawfal_(=DA=E3=C7=CF_=E4=E6=DD=E1)?=) Date: Tue, 13 Jan 2009 15:14:09 -0500 Subject: [Tutor] python3.0 and tkinter on ubuntu 8.10 Message-ID: <652641e90901131214l3a1f8a2bkfc91217f15c0da0d@mail.gmail.com> Hi Tutors,I have downloaded Python3.0 and started playing with it. I like it because of the utf-8 default encoding, but I'm having trouble importing tkinter. I get the following: >>> import turtle Traceback (most recent call last): File "", line 1, in File "/usr/local/lib/python3.0/turtle.py", line 107, in import tkinter as TK File "/usr/local/lib/python3.0/tkinter/__init__.py", line 39, in import _tkinter # If this fails your Python may not be configured for Tk ImportError: No module named _tkinter >>> import tkinter Traceback (most recent call last): File "", line 1, in File "/usr/local/lib/python3.0/tkinter/__init__.py", line 39, in import _tkinter # If this fails your Python may not be configured for Tk ImportError: No module named _tkinter >>> Any idea how this can be solved on Ubuntu 8.10. I don't have this problem with the default Python installation (2.5.2) Thank you -- ?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? ????????.....???? ??????? "No victim has ever been more repressed and alienated than the truth" Emad Soliman Nawfal Indiana University, Bloomington -------------------------------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: From bermanrl at cfl.rr.com Tue Jan 13 21:30:06 2009 From: bermanrl at cfl.rr.com (Robert Berman) Date: Tue, 13 Jan 2009 15:30:06 -0500 Subject: [Tutor] python3.0 and tkinter on ubuntu 8.10 In-Reply-To: <652641e90901131214l3a1f8a2bkfc91217f15c0da0d@mail.gmail.com> References: <652641e90901131214l3a1f8a2bkfc91217f15c0da0d@mail.gmail.com> Message-ID: <496CF9CE.20506@cfl.rr.com> An HTML attachment was scrubbed... URL: From emadnawfal at gmail.com Tue Jan 13 21:39:18 2009 From: emadnawfal at gmail.com (=?WINDOWS-1256?Q?Emad_Nawfal_(=DA=E3=C7=CF_=E4=E6=DD=E1)?=) Date: Tue, 13 Jan 2009 15:39:18 -0500 Subject: [Tutor] python3.0 and tkinter on ubuntu 8.10 In-Reply-To: <496CF9CE.20506@cfl.rr.com> References: <652641e90901131214l3a1f8a2bkfc91217f15c0da0d@mail.gmail.com> <496CF9CE.20506@cfl.rr.com> Message-ID: <652641e90901131239k6640ef5ev8e48c6716a9d2882@mail.gmail.com> On Tue, Jan 13, 2009 at 3:30 PM, Robert Berman wrote: > Emad, > > A number of people in the Ubuntu community have attempted to work with > Python3.0 under Ubuntu 8.10 and almost all have found it to be a frustrating > and painful experience with some having disastrous consequences. I was > looking for the latest discussion thread on this issue in the Ubuntu forums, > but the forums are currently down. > > You might want to use Google to track this under Python 3.0 + Ubuntu 8.10. > > The overall consensus of opinion is to wait until Python 3.0 became the > default under Ubuntu before using it. > YMMV. > > Robert Berman > > Emad Nawfal (???? ????) wrote: > > Hi Tutors,I have downloaded Python3.0 and started playing with it. I like > it because of the utf-8 default encoding, but I'm having trouble importing > tkinter. I get the following: > >>> import turtle > Traceback (most recent call last): > File "", line 1, in > File "/usr/local/lib/python3.0/turtle.py", line 107, in > import tkinter as TK > File "/usr/local/lib/python3.0/tkinter/__init__.py", line 39, in > import _tkinter # If this fails your Python may not be configured for > Tk > ImportError: No module named _tkinter > >>> import tkinter > Traceback (most recent call last): > File "", line 1, in > File "/usr/local/lib/python3.0/tkinter/__init__.py", line 39, in > import _tkinter # If this fails your Python may not be configured for > Tk > ImportError: No module named _tkinter > >>> > > Any idea how this can be solved on Ubuntu 8.10. I don't have this problem > with the default Python installation (2.5.2) > Thank you > > > -- > ?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? ????????.....???? > ??????? > "No victim has ever been more repressed and alienated than the truth" > > Emad Soliman Nawfal > Indiana University, Bloomington > > -------------------------------------------------------- > > ------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.orghttp://mail.python.org/mailman/listinfo/tutor > > Thanks Robert for the advice about Ubuntu. I did a lot of Googling before I posted my question, but could not find an answer. I do basic things with Python that involve using lots of Arabic text, and this is why python3.0 was supposed to make my life easier, but I'm learning GUI building now, and it has given me the first frustration. -- ?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? ????????.....???? ??????? "No victim has ever been more repressed and alienated than the truth" Emad Soliman Nawfal Indiana University, Bloomington http://emnawfal.googlepages.com -------------------------------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: From vceder at canterburyschool.org Tue Jan 13 22:02:48 2009 From: vceder at canterburyschool.org (Vern Ceder) Date: Tue, 13 Jan 2009 16:02:48 -0500 Subject: [Tutor] python3.0 and tkinter on ubuntu 8.10 In-Reply-To: References: Message-ID: <496D0178.8000009@canterburyschool.org> Hi, I have Python 3.0/Tkinter/IDLE working fine on Ubuntu 8.10, but it takes a certain amount of fiddling. 1. Make sure the stock Ubuntu Python 3.0 package is not installed 2. download the Python 3.0 source from python.org 3. install the following packages: build-essential libsqlite3-dev libreadline5-dev libncurses5-dev zlib1g-dev libbz2-dev libssl-dev libgdbm-dev tk-dev 4. unpack the Python source and switch to that folder 5. build Python using the standard ./configure, make, make install sequence - if you want more detail/help on that process, just ask... I'd be happy to explain this process in more detail if anyone wants... Cheers, Vern > Hi Tutors,I have downloaded Python3.0 and started playing with it. I like it > because of the utf-8 default encoding, but I'm having trouble importing > tkinter. I get the following: >>>> >>> import turtle > Traceback (most recent call last): > File "", line 1, in > File "/usr/local/lib/python3.0/turtle.py", line 107, in > import tkinter as TK > File "/usr/local/lib/python3.0/tkinter/__init__.py", line 39, in > import _tkinter # If this fails your Python may not be configured for Tk > ImportError: No module named _tkinter >>>> >>> import tkinter > Traceback (most recent call last): > File "", line 1, in > File "/usr/local/lib/python3.0/tkinter/__init__.py", line 39, in > import _tkinter # If this fails your Python may not be configured for Tk > ImportError: No module named _tkinter >>>> >>> > > Any idea how this can be solved on Ubuntu 8.10. I don't have this problem > with the default Python installation (2.5.2) > Thank you -- This time for sure! -Bullwinkle J. Moose ----------------------------- Vern Ceder, Director of Technology Canterbury School, 3210 Smith Road, Ft Wayne, IN 46804 vceder at canterburyschool.org; 260-436-0746; FAX: 260-436-5137 From alan.gauld at btinternet.com Tue Jan 13 22:20:10 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 13 Jan 2009 21:20:10 -0000 Subject: [Tutor] A list of input arguments References: <1c2a2c590901130342r195dbcfuf616d3f1cfd0936c@mail.gmail.com> Message-ID: "Kent Johnson" wrote >>> Is there any way to list the input arguments without listing them >>> inside >>> the function's parentheses? >> >> No, because the function expects 3 arguments so you must pass it 3. > > You can use *args to pass multiple arguments in a list. For example, > > In [2]: values = [1, 2, 3] > > In [3]: show(*values) > 1 2 3 Thats true although I read the question as meaning can I pass in an arbitrary list of arguments even though the function takes 3... The follow-on question seemed to back up that understanding. But it could mean what you took it for in which case clearly the answer is yes and *chords would have worked. I cobfess I don;t like the *args style where the function takes a specified number of params because I find it too easy to hide bugs by inadvertantly passing the wrong number of args. Explicit is better etc... -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From ig2ar-saf1 at yahoo.co.uk Tue Jan 13 22:27:25 2009 From: ig2ar-saf1 at yahoo.co.uk (culpritNr1) Date: Tue, 13 Jan 2009 13:27:25 -0800 (PST) Subject: [Tutor] Gamma distribution function Message-ID: <21444899.post@talk.nabble.com> Hello All, OK. This time a less trivial question. Is there a function to enable us sample from a Poisson distribution? There is random.uniform, random.normalvariate(), random.expovariate()... Is there some kind of random.poisson()? Thank you, culpritNr1 -- View this message in context: http://www.nabble.com/Gamma-distribution-function-tp21444899p21444899.html Sent from the Python - tutor mailing list archive at Nabble.com. From alan.gauld at btinternet.com Tue Jan 13 22:32:11 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 13 Jan 2009 21:32:11 -0000 Subject: [Tutor] Date comparison across time zones References: <7b60d8a80901130845s30842deeuba55afec99285a5c@mail.gmail.com> Message-ID: "frenc1z 1z" wrote > I'm a novice python (python 2.6.1) user with the following problem. > > Never though this was going to be so difficult :-). Timezones are devilishly difficult to do if you need to be complete. If you are only dealing with the Western world then its not so bad and most libraries will work. > I would like to compare some dates (date+time really). The dates all > have > the following RFC2822 format: > > Eg. is d1 < d2? > d1 = "Tue, 13 Jan 2009 03:27:29 -0800" > d2 = "Tue, 13 Jan 2009 02:40:00 -0600" > > My thinking is that I first need to make these two dates comparable, > and > eliminate the impact of time zone and dst. Understand that I can > acheive > this using strptime. You can convert to UTC time and compare that way. That avoids issues of having two different timezones in the conversion functions and conflicts within the TZ. environment variables. tzset() should work. Be sure to turn the timezone back to wjatever it was before (store tzname) when you are done. HTH, Alan G. From emadnawfal at gmail.com Tue Jan 13 22:32:38 2009 From: emadnawfal at gmail.com (=?WINDOWS-1256?Q?Emad_Nawfal_(=DA=E3=C7=CF_=E4=E6=DD=E1)?=) Date: Tue, 13 Jan 2009 16:32:38 -0500 Subject: [Tutor] python3.0 and tkinter on ubuntu 8.10 In-Reply-To: <496D0178.8000009@canterburyschool.org> References: <496D0178.8000009@canterburyschool.org> Message-ID: <652641e90901131332g60caaa70l5490a85cb49972f2@mail.gmail.com> On Tue, Jan 13, 2009 at 4:02 PM, Vern Ceder wrote: > Hi, > > I have Python 3.0/Tkinter/IDLE working fine on Ubuntu 8.10, but it takes a > certain amount of fiddling. > > 1. Make sure the stock Ubuntu Python 3.0 package is not installed > > 2. download the Python 3.0 source from python.org > > 3. install the following packages: build-essential libsqlite3-dev > libreadline5-dev libncurses5-dev zlib1g-dev libbz2-dev libssl-dev > libgdbm-dev tk-dev > > 4. unpack the Python source and switch to that folder > > 5. build Python using the standard ./configure, make, make install sequence > - if you want more detail/help on that process, just ask... > > I'd be happy to explain this process in more detail if anyone wants... > > Cheers, > Vern > Yes Vern, it works. Thank you so much. I installed the missing packages and downloaded and installed the Python3.0 source and it's now perfect. Thanks again > > Hi Tutors,I have downloaded Python3.0 and started playing with it. I like >> it >> because of the utf-8 default encoding, but I'm having trouble importing >> tkinter. I get the following: >> >>> >>> import turtle >>>>> >>>> Traceback (most recent call last): >> File "", line 1, in >> File "/usr/local/lib/python3.0/turtle.py", line 107, in >> import tkinter as TK >> File "/usr/local/lib/python3.0/tkinter/__init__.py", line 39, in >> import _tkinter # If this fails your Python may not be configured for >> Tk >> ImportError: No module named _tkinter >> >>> >>> import tkinter >>>>> >>>> Traceback (most recent call last): >> File "", line 1, in >> File "/usr/local/lib/python3.0/tkinter/__init__.py", line 39, in >> import _tkinter # If this fails your Python may not be configured for >> Tk >> ImportError: No module named _tkinter >> >>> >>> >>>>> >>>> >> Any idea how this can be solved on Ubuntu 8.10. I don't have this problem >> with the default Python installation (2.5.2) >> Thank you >> > > > -- > This time for sure! > -Bullwinkle J. Moose > ----------------------------- > Vern Ceder, Director of Technology > Canterbury School, 3210 Smith Road, Ft Wayne, IN 46804 > vceder at canterburyschool.org; 260-436-0746; FAX: 260-436-5137 > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- ?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? ????????.....???? ??????? "No victim has ever been more repressed and alienated than the truth" Emad Soliman Nawfal Indiana University, Bloomington http://emnawfal.googlepages.com -------------------------------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Jan 13 22:39:51 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 13 Jan 2009 21:39:51 -0000 Subject: [Tutor] power of 2.718282 References: <21441385.post@talk.nabble.com> Message-ID: "culpritNr1" wrote > I would appreciate a low level solution because I have to > iteratively call > that computation millions of times. Anything more efficient than > 2.718182**10 may be good. Umm, what's wrong with from math import e # more precision than 2.718182 print e**10 e**10 is shorter to type and probably just as fast as a function call (if not faster!). I see others have pointed out that the math module has this covered but I'm curious about your definition of efficiency? Alan G. From denis.spir at free.fr Tue Jan 13 22:45:01 2009 From: denis.spir at free.fr (spir) Date: Tue, 13 Jan 2009 22:45:01 +0100 Subject: [Tutor] python3.0 and tkinter on ubuntu 8.10 In-Reply-To: <496D0178.8000009@canterburyschool.org> References: <496D0178.8000009@canterburyschool.org> Message-ID: <20090113224501.26112f02@o> Le Tue, 13 Jan 2009 16:02:48 -0500, Vern Ceder a ?crit : > Hi, > > I have Python 3.0/Tkinter/IDLE working fine on Ubuntu 8.10, but it takes > a certain amount of fiddling. > > 1. Make sure the stock Ubuntu Python 3.0 package is not installed > > 2. download the Python 3.0 source from python.org > > 3. install the following packages: build-essential libsqlite3-dev > libreadline5-dev libncurses5-dev zlib1g-dev libbz2-dev libssl-dev > libgdbm-dev tk-dev > > 4. unpack the Python source and switch to that folder > > 5. build Python using the standard ./configure, make, make install > sequence - if you want more detail/help on that process, just ask... > > I'd be happy to explain this process in more detail if anyone wants... > > Cheers, > Vern Yes, I would like it, as I'm under ubuntu too and plan to switch to py3.0 soon. Do you know whether there are issues under ubuntu 8.04 with py3.0? (I have both ubuntu 8.04 & 8.10) Thanks, Denis ------ la vida e estranya From bermanrl at cfl.rr.com Tue Jan 13 22:46:22 2009 From: bermanrl at cfl.rr.com (Robert Berman) Date: Tue, 13 Jan 2009 16:46:22 -0500 Subject: [Tutor] python3.0 and tkinter on ubuntu 8.10 Message-ID: <496D0BAE.3000807@cfl.rr.com> An HTML attachment was scrubbed... URL: From jervisau at gmail.com Tue Jan 13 22:54:15 2009 From: jervisau at gmail.com (Jervis Whitley) Date: Wed, 14 Jan 2009 08:54:15 +1100 Subject: [Tutor] Gamma distribution function In-Reply-To: <21444899.post@talk.nabble.com> References: <21444899.post@talk.nabble.com> Message-ID: <8e63a5ce0901131354p53ea1d0focc0a93f9af5d47f0@mail.gmail.com> On Wed, Jan 14, 2009 at 8:27 AM, culpritNr1 wrote: > > > there some kind of random.poisson()? > > Thank you, > > culpritNr1 > > Hello try the scipy library: >>> from scipy import stats >>> lamb = 10 >>> stats.distributions.poisson.rvs(lamb, loc=0) array([5]) >>> stats.distributions.poisson.rvs(lamb, loc=0) array([14]) http://www.scipy.org/ cheers, -------------- next part -------------- An HTML attachment was scrubbed... URL: From marc.tompkins at gmail.com Tue Jan 13 23:09:18 2009 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Tue, 13 Jan 2009 14:09:18 -0800 Subject: [Tutor] power of 2.718282 In-Reply-To: References: <21441385.post@talk.nabble.com> Message-ID: <40af687b0901131409p7007e485r11f796f8f4210e6b@mail.gmail.com> On Tue, Jan 13, 2009 at 1:39 PM, Alan Gauld wrote: > I would appreciate a low level solution because I have to iteratively call >> that computation millions of times. Anything more efficient than >> 2.718182**10 may be good. >> > > Umm, what's wrong with > > from math import e # more precision than 2.718182 > print e**10 > Apparently nothing at all is wrong with it: C:\Python25\Lib>python timeit.py -s "import math" "x=math.exp(10)" 1000000 loops, best of 3: 0.678 usec per loop C:\Python25\Lib>python timeit.py -s "from math import e" "x=e**10" 1000000 loops, best of 3: 0.411 usec per loop -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From ig2ar-saf1 at yahoo.co.uk Tue Jan 13 23:11:05 2009 From: ig2ar-saf1 at yahoo.co.uk (culpritNr1) Date: Tue, 13 Jan 2009 14:11:05 -0800 (PST) Subject: [Tutor] Gamma distribution function In-Reply-To: <8e63a5ce0901131354p53ea1d0focc0a93f9af5d47f0@mail.gmail.com> References: <21444899.post@talk.nabble.com> <8e63a5ce0901131354p53ea1d0focc0a93f9af5d47f0@mail.gmail.com> Message-ID: <21445597.post@talk.nabble.com> Hi Jarvis, I tried the scipy function. I don't understand it. Look, if you go to http://en.wikipedia.org/wiki/Poisson_Distribution wiki's Poisson distribution documentation you'll find that this is the naive way to compute a Poisson probability mass function >>> lam = 1 >>> k = 2 >>> math.exp(-lam) * lam**k / factorial(k) 0.18393972058572117 Notice that it matches the figure in the wiki page (the red curve). Now, the scipy module does this: >>> stats.distributions.poisson.rvs(1, 2) array([3]) >>> stats.distributions.poisson.rvs(1, 2) array([2]) >>> stats.distributions.poisson.rvs(1, 2) array([2]) >>> stats.distributions.poisson.rvs(1, 2) array([4]) >>> stats.distributions.poisson.rvs(1, 2) array([3]) >>> stats.distributions.poisson.rvs(1, 2) array([2]) The python documentation on this functionality is extremely poor. Look >>> help("scipy.stats.distributions.poisson.rvs") Help on method rvs in scipy.stats.distributions.poisson: scipy.stats.distributions.poisson.rvs = rvs(self, *args, **kwds) method of scipy.stats.distributions.poisson_gen instance Do you understand what's going on? Thanks, culpritNr1 -- View this message in context: http://www.nabble.com/Gamma-distribution-function-tp21444899p21445597.html Sent from the Python - tutor mailing list archive at Nabble.com. From kent37 at tds.net Tue Jan 13 23:42:26 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 13 Jan 2009 17:42:26 -0500 Subject: [Tutor] power of 2.718282 In-Reply-To: <40af687b0901131409p7007e485r11f796f8f4210e6b@mail.gmail.com> References: <21441385.post@talk.nabble.com> <40af687b0901131409p7007e485r11f796f8f4210e6b@mail.gmail.com> Message-ID: <1c2a2c590901131442m26032c1dj84e37e7afa638e01@mail.gmail.com> On Tue, Jan 13, 2009 at 5:09 PM, Marc Tompkins wrote: > Apparently nothing at all is wrong with it: > C:\Python25\Lib>python timeit.py -s "import math" "x=math.exp(10)" > 1000000 loops, best of 3: 0.678 usec per loop > > C:\Python25\Lib>python timeit.py -s "from math import e" "x=e**10" > 1000000 loops, best of 3: 0.411 usec per loop Using ** beats exp() because there is an explicit bytecode for exponentiation so no function call is needed. Careful, though; on my computer about 1/2 of the difference between these two is due to the different style of import: C:\Project\Mango> python -m timeit -s "import math" "x=math.exp(10)" 1000000 loops, best of 3: 0.467 usec per loop C:\Project\Mango> python -m timeit -s "from math import exp" "x=exp(10)" 1000000 loops, best of 3: 0.352 usec per loop C:\Project\Mango> python -m timeit -s "from math import e" "x=e**10" 1000000 loops, best of 3: 0.259 usec per loop Name lookup and function call are both expensive in Python. Using a constant instead of the variable e is substantially faster: C:\Project\Mango> python -m timeit "x=2.718182**10" 10000000 loops, best of 3: 0.0399 usec per loop Kent From kent37 at tds.net Tue Jan 13 23:53:36 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 13 Jan 2009 17:53:36 -0500 Subject: [Tutor] Gamma distribution function In-Reply-To: <21445597.post@talk.nabble.com> References: <21444899.post@talk.nabble.com> <8e63a5ce0901131354p53ea1d0focc0a93f9af5d47f0@mail.gmail.com> <21445597.post@talk.nabble.com> Message-ID: <1c2a2c590901131453m28065cddu877c50a37f38cef5@mail.gmail.com> On Tue, Jan 13, 2009 at 5:11 PM, culpritNr1 wrote: > > Hi Jarvis, > > I tried the scipy function. I don't understand it. Look, if you go to > http://en.wikipedia.org/wiki/Poisson_Distribution wiki's Poisson > distribution documentation you'll find that this is the naive way to > compute a Poisson probability mass function > >>>> lam = 1 >>>> k = 2 >>>> math.exp(-lam) * lam**k / factorial(k) > 0.18393972058572117 > > Notice that it matches the figure in the wiki page (the red curve). > > Now, the scipy module does this: >>>> stats.distributions.poisson.rvs(1, 2) > array([3]) > > The python documentation on this functionality is extremely poor. See http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.poisson.html I think you want poisson.pmf(), not poisson.rvs(). See the note at the bottom of the referenced page. I think rvs() is picking random values distributed according to the given poisson distribution, that is why you get different numbers each time. Kent From ig2ar-saf1 at yahoo.co.uk Tue Jan 13 23:40:36 2009 From: ig2ar-saf1 at yahoo.co.uk (culpritNr1) Date: Tue, 13 Jan 2009 14:40:36 -0800 (PST) Subject: [Tutor] Gamma distribution function In-Reply-To: <8e63a5ce0901131354p53ea1d0focc0a93f9af5d47f0@mail.gmail.com> References: <21444899.post@talk.nabble.com> <8e63a5ce0901131354p53ea1d0focc0a93f9af5d47f0@mail.gmail.com> Message-ID: <21446064.post@talk.nabble.com> I just figured it out myself. This is how to do it both the naive and the efficient way, respectively: >>> import math >>> from scipy import factorial >>> lam = 1 >>> k = 2 >>> math.exp(-lam) * lam**k / factorial(k) 0.18393972058572117 >>> from scipy import stats >>> stats.poisson.pmf(2,1) array(0.18393972058572114) thanks all anyway, culpritNr1 Jervis Whitley wrote: > > On Wed, Jan 14, 2009 at 8:27 AM, culpritNr1 > wrote: > >> >> >> there some kind of random.poisson()? >> >> Thank you, >> >> culpritNr1 >> >> Hello try the scipy library: >>>> from scipy import stats >>>> lamb = 10 >>>> stats.distributions.poisson.rvs(lamb, loc=0) > array([5]) >>>> stats.distributions.poisson.rvs(lamb, loc=0) > array([14]) > > http://www.scipy.org/ > > cheers, > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- View this message in context: http://www.nabble.com/Gamma-distribution-function-tp21444899p21446064.html Sent from the Python - tutor mailing list archive at Nabble.com. From jervisau at gmail.com Tue Jan 13 23:59:21 2009 From: jervisau at gmail.com (Jervis Whitley) Date: Wed, 14 Jan 2009 09:59:21 +1100 Subject: [Tutor] Fwd: Gamma distribution function In-Reply-To: <8e63a5ce0901131426y1b7f7b2fne6369b1891213b5e@mail.gmail.com> References: <21444899.post@talk.nabble.com> <8e63a5ce0901131354p53ea1d0focc0a93f9af5d47f0@mail.gmail.com> <21445597.post@talk.nabble.com> <8e63a5ce0901131426y1b7f7b2fne6369b1891213b5e@mail.gmail.com> Message-ID: <8e63a5ce0901131459x3bec3bdes68c36ad3dba8d2db@mail.gmail.com> ---------- Forwarded message ---------- From: Jervis Whitley Date: Wed, Jan 14, 2009 at 9:26 AM Subject: Re: [Tutor] Gamma distribution function To: culpritNr1 On Wed, Jan 14, 2009 at 9:11 AM, culpritNr1 wrote: > > The python documentation on this functionality is extremely poor. Look > >>> help("scipy.stats.distributions.poisson.rvs") > Help on method rvs in scipy.stats.distributions.poisson: > scipy.stats.distributions.poisson.rvs = rvs(self, *args, **kwds) method of > scipy.stats.distributions.poisson_gen instance > > Do you understand what's going on? > > Thanks, > > culpritNr1 > > > -- > View this message in context: > http://www.nabble.com/Gamma-distribution-function-tp21444899p21445597.html > Sent from the Python - tutor mailing list archive at Nabble.com. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > Your previous email said you wanted to sample from the poisson function, which is what that rvs method is doing, taking random samples from a poisson distribution of lambda = 1 in your case. They also provide a means to shift the function from a nominal x crossing of 0 using the second argument, in your case you have used 2. So you were sampling from a function of mean 1 shifted right by 2. The below has been taken from the poisson documentation itself: print stats.distributions.poisson.__doc__ A poisson discrete random variable. Discrete random variables are defined from a standard form. The standard form may require some other parameters to complete its specification. The distribution methods also take an optional location parameter using loc= keyword. The default is loc=0. The calling form of the methods follow: poisson.rvs(mu,loc=0) - random variates poisson.pmf(x,mu,loc=0) - probability mass function poisson.cdf(x,mu,loc=0) - cumulative density function poisson.sf(x,mu,loc=0) - survival function (1-cdf --- sometimes more accurate) poisson.ppf(q,mu,loc=0) - percent point function (inverse of cdf --- percentiles) poisson.isf(q,mu,loc=0) - inverse survival function (inverse of sf) poisson.stats(mu,loc=0,moments='mv') - mean('m',axis=0), variance('v'), skew('s'), and/or kurtosis('k') poisson.entropy(mu,loc=0) - entropy of the RV Alternatively, the object may be called (as a function) to fix the shape and location parameters returning a "frozen" discrete RV object: myrv = poisson(mu,loc=0) - frozen RV object with the same methods but holding the given shape and location fixed. You can construct an aribtrary discrete rv where P{X=xk} = pk by passing to the rv_discrete initialization method (through the values= keyword) a tuple of sequences (xk,pk) which describes only those values of X (xk) that occur with nonzero probability (pk). Poisson distribution poisson.pmf(k, mu) = exp(-mu) * mu**k / k! for k >= 0 If you are after a probability at a given k (which it now sounds like you may be after) you might be interested in the pmf method. (Sorry I did a reply instead of reply-all) Cheers, Jervis -------------- next part -------------- An HTML attachment was scrubbed... URL: From jjcrump at myuw.net Wed Jan 14 00:09:26 2009 From: jjcrump at myuw.net (Jon Crump) Date: Tue, 13 Jan 2009 15:09:26 -0800 (PST) Subject: [Tutor] quoting and escaping Message-ID: All, Something I don't understand (so what else is new?) about quoting and escaping: >>> s = """ "some" \"thing\" """ >>> s ' "some" "thing" ' I've got strings like this: s = """[{"title" : "Egton, Yorkshire", "start" : new Date(1201,1,4), "description" : "Hardy's long name: Egton, Yorkshire. <br> "}, {"title" : "Guilsborough, Yorkshire", "start" : new Date(1201,1,5), "description" : "Hardy's long name: Guilsborough, Yorkshire. <br> <img src=\"document.png\" style=\"cursor: pointer\" onclick=\"SimileAjax.WindowManager.cancelPopups();show_next('tab3');pager('006'); return false\"/>pg.006: 1201-02-05 to 1202-03-07"}]""" Thanks to your good help, I can re.sub() to translate the new Date() objects into "datetime.date()" instances, thus: [{"title" : "Egton, Yorkshire", "start" : "date(1201, 02, 04)", "description" : "Hardy's long name: Egton, Yorkshire. <br> "}, {"title" : "Guilsborough, Yorkshire", "start" : "date(1201, 02, 05)", "description" : "Hardy's long name: Guilsborough, Yorkshire. <br> <img src="document.png" style="cursor: pointer" onclick="SimileAjax.WindowManager.cancelPopups();show_next('tab3');pager('006'); return false"/>pg.006: 1201-02-05 to 1202-03-07"}] with the quotation marks, eval() evaluates these date() instances correctly; however, python treats " and \" as if they were identical so I wind up with bad syntax: multiple doublequoted strings in a dictionary value. How can I identify \" in a regex so that I can replace it with something that eval() won't choke on? This is pretty confusing to me, so I've tried to provide clarification below: >>> a = """{"aKey" : "aValue"}""" >>> eval(a) {'aKey': 'aValue'} ## so far so good, but then: >>> b = """{"aKey" : "a value with \"literal quotes\" in it"}""" >>> eval(b) Traceback (most recent call last): File "", line 1, in File "", line 1 {"aKey" : "a value with "literal quotes" in it"} ^ SyntaxError: invalid syntax From steve at alchemy.com Wed Jan 14 01:07:23 2009 From: steve at alchemy.com (Steve Willoughby) Date: Tue, 13 Jan 2009 16:07:23 -0800 (PST) Subject: [Tutor] quoting and escaping In-Reply-To: References: Message-ID: <58113.134.134.136.14.1231891643.squirrel@webmail.alchemy.com> On Tue, January 13, 2009 15:09, Jon Crump wrote: > All, > > Something I don't understand (so what else is new?) about quoting and > escaping: > >>>> s = """ "some" \"thing\" """ >>>> s > ' "some" "thing" ' Correct. Note that """ ... """ is just a string constant the same as "..." is, with the exception that it can easily span multiple physical lines. What happens between the quotes, though, is the same. This includes the fact that \ is used to escape special characters, so \" is how you can type a literal " character without it being interpreted as the end-of-string delimiter. Of course, since this is a triple-double-quoted string, a plain old " won't be confused as such anyway, so yes, in this particular instance they evaluate to the same character when the string object is created. To avoid this, you could either escape the backslashes, so you'd have: s = """ "some" \\"thing\\" """ (now s == ' "some" \"thing\" ') or, I think better, would be to use raw string constants: s = r""" "some" \"thing\" """ (now s == ' "some" \"thing\" ') (note that if you're looking at the representation of s in your interpreter, it'll actually print as ' "some" \\"thing\\" ', since it's showing you that the \s are literal. The actual string value is as intended, though) From john at fouhy.net Wed Jan 14 01:12:10 2009 From: john at fouhy.net (John Fouhy) Date: Wed, 14 Jan 2009 13:12:10 +1300 Subject: [Tutor] quoting and escaping In-Reply-To: References: Message-ID: <5e58f2e40901131612mee8c482hada628206b0234ef@mail.gmail.com> 2009/1/14 Jon Crump : >>>> b = """{"aKey" : "a value with \"literal quotes\" in it"}""" >>>> eval(b) > > Traceback (most recent call last): > File "", line 1, in > File "", line 1 > {"aKey" : "a value with "literal quotes" in it"} > ^ > SyntaxError: invalid syntax Is it an option to just do: >>> b = """{'aKey':'a value with "literal quotes" in it'}""" >>> eval(b) {'aKey': 'a value with "literal quotes" in it'} ? (or, heck, get rid of eval.. do you really need it?) -- John. From steve at alchemy.com Wed Jan 14 01:18:33 2009 From: steve at alchemy.com (Steve Willoughby) Date: Tue, 13 Jan 2009 16:18:33 -0800 (PST) Subject: [Tutor] quoting and escaping In-Reply-To: <5e58f2e40901131612mee8c482hada628206b0234ef@mail.gmail.com> References: <5e58f2e40901131612mee8c482hada628206b0234ef@mail.gmail.com> Message-ID: <59276.134.134.136.14.1231892313.squirrel@webmail.alchemy.com> On Tue, January 13, 2009 16:12, John Fouhy wrote: > (or, heck, get rid of eval.. do you really need it?) As a general comment, especially for beginning to intermediate programmers, the answer to "do you need eval()" is usually "not really." There's almost always a better, easier and more straightforward way to do what eval() is usually naively used for. From damontimm at gmail.com Wed Jan 14 01:34:09 2009 From: damontimm at gmail.com (Damon Timm) Date: Tue, 13 Jan 2009 19:34:09 -0500 Subject: [Tutor] Sys.stdin Question Message-ID: <262679b50901131634h6d252f78t4f2942d8b45f569e@mail.gmail.com> Hi - am writing a script to send myself email messages from the command line ... I want to have the option be able to input the message body via a pipe so I can easily shoot emails to myself (like from: ls, cat, df, du, mount, etc) ... what i want to be able to do is: $ ls -la | myscript.py and in the script use something like this (just an example to keep it short): cli_input = sys.stdin.read() if cli_input: print "I piped this in:", cli_input else: print "nothing got piped in, moving on." This works when I do have something coming via stdin ... but if I run the script without piping something first ... it just sits there (I assume, waiting for some stdin) ... How do I tell it: if there is no stdin, just move on? Thanks, Damon From alan.gauld at btinternet.com Wed Jan 14 02:15:36 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 14 Jan 2009 01:15:36 -0000 Subject: [Tutor] Gamma distribution function References: <21444899.post@talk.nabble.com><8e63a5ce0901131354p53ea1d0focc0a93f9af5d47f0@mail.gmail.com> <21445597.post@talk.nabble.com> Message-ID: "culpritNr1" wrote > I tried the scipy function. I don't understand it. Try reading about it here: http://numpy.sourceforge.net/numdoc/HTML/numdoc.htm It explains the output format. I believe it applies to the scipy version as well as the numpy. > The python documentation on this functionality is extremely poor. >>>> help("scipy.stats.distributions.poisson.rvs") That will only find the basic help in the doc strings. You need to look at the documented help too. The web page is the best I've found. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Wed Jan 14 02:28:42 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 14 Jan 2009 01:28:42 -0000 Subject: [Tutor] Sys.stdin Question References: <262679b50901131634h6d252f78t4f2942d8b45f569e@mail.gmail.com> Message-ID: "Damon Timm" wrote > $ ls -la | myscript.py > > cli_input = sys.stdin.read() > > if cli_input: > print "I piped this in:", cli_input > This works when I do have something coming via stdin ... but if I > run > the script without piping something first ... it just sits there (I > assume, waiting for some stdin) ... Yep, if you hit Ctr-D (ie. EOF) it should continue as normal. The way other Unix style programs deal with this is to write the code to read from a general file and if you want to use stdin provide an argument of '-': $ ls -la | myscript.py - Or sometimes use a if argument to specify a file which can then be '-' for stdin: $ ls -la | myscript.py -f- Either of these will enable your script to email a file if asked, read from nowhere if no file is specified or from stdin if specifically told to. Of course the standard utility approach is to read from stdin as default in which case no flags are needed but you have to provide the EOF manually. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From john at fouhy.net Wed Jan 14 02:45:53 2009 From: john at fouhy.net (John Fouhy) Date: Wed, 14 Jan 2009 14:45:53 +1300 Subject: [Tutor] Sys.stdin Question In-Reply-To: <262679b50901131634h6d252f78t4f2942d8b45f569e@mail.gmail.com> References: <262679b50901131634h6d252f78t4f2942d8b45f569e@mail.gmail.com> Message-ID: <5e58f2e40901131745v55471568pcf2d879c9d2ad09c@mail.gmail.com> 2009/1/14 Damon Timm : > This works when I do have something coming via stdin ... but if I run > the script without piping something first ... it just sits there (I > assume, waiting for some stdin) ... > > How do I tell it: if there is no stdin, just move on? This might work: import select, sys def isData(): return select.select([sys.stdin], [], [], 0) == ([sys.stdin], [], []) if isData(): print 'You typed:', sys.stdin.read() else: print 'Nothing to see here.' I say "might" because it is OS-dependent, but I guess you are using unix/linux. Source: http://www.darkcoding.net/software/non-blocking-console-io-is-not-possible/ I found that by searching for "python stdin non-blocking". This is because "blocking" is jargon for "waiting until something happens". In this case, stdin.read() is blocking until it sees some data with an EOF. HTH! -- John. From steve at alchemy.com Wed Jan 14 02:55:47 2009 From: steve at alchemy.com (Steve Willoughby) Date: Tue, 13 Jan 2009 17:55:47 -0800 (PST) Subject: [Tutor] Sys.stdin Question In-Reply-To: <5e58f2e40901131745v55471568pcf2d879c9d2ad09c@mail.gmail.com> References: <262679b50901131634h6d252f78t4f2942d8b45f569e@mail.gmail.com> <5e58f2e40901131745v55471568pcf2d879c9d2ad09c@mail.gmail.com> Message-ID: <39283.134.134.136.14.1231898147.squirrel@webmail.alchemy.com> On Tue, January 13, 2009 17:45, John Fouhy wrote: > 2009/1/14 Damon Timm : >> This works when I do have something coming via stdin ... but if I run >> the script without piping something first ... it just sits there (I >> assume, waiting for some stdin) ... This is playing a dangerous game, though, of introducing a race condition. Is there nothing on the standard input RIGHT NOW because the source on the other end of the pipe hasn't managed to generate anything yet, or because there's nothing piped? A better approach is either to explicitly specify whether to read from stdin or a file, as Alan demonstrated (and the fileinput module implements this for you, by the way), or to see if stdin is connected to a terminal or not. So instead of seeing if anything's showing up (and introducing timing dependencies and uncertainty), see if it's attached to a real terminal at all. On Unix, os.isatty(sys.stdin) will tell you this. steve From damontimm at gmail.com Wed Jan 14 02:59:19 2009 From: damontimm at gmail.com (Damon Timm) Date: Tue, 13 Jan 2009 20:59:19 -0500 Subject: [Tutor] Sys.stdin Question In-Reply-To: References: <262679b50901131634h6d252f78t4f2942d8b45f569e@mail.gmail.com> Message-ID: <262679b50901131759uf2589eem349266cca7b2ecbf@mail.gmail.com> On Tue, Jan 13, 2009 at 8:28 PM, Alan Gauld wrote: > The way other Unix style programs deal with this is to write the code > to read from a general file and if you want to use stdin provide an > argument of '-': That's a good idea, actually -- I hadn't thought of that. Although I use that "-" a lot in command line programs ... It would force someone to be specific about what it was they wanted the script to do ... then, I guess, I can just have it do an if statement that asks: if args[0] == "-" then ... blah. I may do that ... the script, itself, actually handles attachments, too ... so I could use that flag, also, to say: attach the standard out to an email. On Tue, Jan 13, 2009 at 8:45 PM, John Fouhy wrote: > This might work: > > import select, sys > def isData(): > return select.select([sys.stdin], [], [], 0) == > ([sys.stdin], [], []) > > if isData(): > print 'You typed:', sys.stdin.read() > else: > print 'Nothing to see here.' Oh ho ho! Very neat! I will have to head over to the python docs to see what that is but it seems to work! > I say "might" because it is OS-dependent, but I guess you are using unix/linux. Yea - you guessed right. > Source: http://www.darkcoding.net/software/non-blocking-console-io-is-not-possible/ > > I found that by searching for "python stdin non-blocking". This is > because "blocking" is jargon for "waiting until something happens". > In this case, stdin.read() is blocking until it sees some data with an > EOF. Thanks for that tip -- as you probably guessed, google wasn't turning up too many results for me. But this is working now. However ... reading the next comment has me thinking again: On Tue, Jan 13, 2009 at 8:55 PM, Steve Willoughby wrote: > This is playing a dangerous game, though, of introducing a race condition. > Is there nothing on the standard input RIGHT NOW because the source on > the other end of the pipe hasn't managed to generate anything yet, or > because there's nothing piped? > > A better approach is either to explicitly specify whether to read from > stdin or a file, as Alan demonstrated (and the fileinput module implements > this for you, by the way), or to see if stdin is connected to a terminal > or not. So instead of seeing if anything's showing up (and introducing > timing dependencies and uncertainty), see if it's attached to a real > terminal at all. On Unix, os.isatty(sys.stdin) will tell you this. Does this concern still apply with John's suggestion? I just tested it in my little application and didn't have an issue ... of course, I only ran a couple different command line items before throwing up my hands in celebration. I can go to using the "-" option ... although, to be honest, I like the idea of the script thinking for itself ... that is: if there is stdin, use it -- if not, not ... and, I was thinking of attaching the stdin as a text file, if present. And not attaching anything, if not. Thanks everyone! From steve at alchemy.com Wed Jan 14 03:10:38 2009 From: steve at alchemy.com (Steve Willoughby) Date: Tue, 13 Jan 2009 18:10:38 -0800 (PST) Subject: [Tutor] Sys.stdin Question In-Reply-To: <262679b50901131759uf2589eem349266cca7b2ecbf@mail.gmail.com> References: <262679b50901131634h6d252f78t4f2942d8b45f569e@mail.gmail.com> <262679b50901131759uf2589eem349266cca7b2ecbf@mail.gmail.com> Message-ID: <39742.134.134.136.14.1231899038.squirrel@webmail.alchemy.com> On Tue, January 13, 2009 17:59, Damon Timm wrote: > ... then, I guess, I can just have it do an if statement that asks: if > args[0] == "-" then ... blah. I may do that ... the script, itself, Look at the fileinput module. If you're looking at the command line for a list of filenames, which may include "-" to mean (read stdin at this point in the list of files), your script's logic is reduced to simply: while line in fileinput.input(): # process the line and your script focuses on its specific task. >> or not. So instead of seeing if anything's showing up (and introducing >> timing dependencies and uncertainty), see if it's attached to a real >> terminal at all. On Unix, os.isatty(sys.stdin) will tell you this. > > Does this concern still apply with John's suggestion? I just tested > it in my little application and didn't have an issue ... of course, I Yes, it does. And in a trivial case, it will usually work. But don't base your solutions on something that looks like it sorta works most of the time but isn't really the recommended practice, because it will break later and you'll spend a lot of time figuring out why it's not being reliable. > I can go to using the "-" option ... although, to be honest, I like > the idea of the script thinking for itself ... that is: if there is > stdin, use it -- if not, not ... and, I was thinking of attaching the > stdin as a text file, if present. And not attaching anything, if not. As the Zen of Python states, "explicit is better than implicit." Scripts which just magically "do the right thing" can be cool to play with, but they have a nasty tendency to guess wrong about what the right thing might be. In this case, you're making assumptions about how to *guess* whether there's standard input piped at your script, and running with those assumptions... but there are easily identified cases where those assumptions don't hold true. Also, think of anyone other than you (or you at a later date) using this script. The number of things the script does for no apparent reason can lead to frustration and doubt that you really know, as a user, what the script is really going to try to do in a given situation, and what you'll have to do on your end to "trick" it into doing what you really wanted in the first place. It's cute, but ultimately implicit behavior doesn't make for good, long-lasting solid applications. From john at fouhy.net Wed Jan 14 03:05:27 2009 From: john at fouhy.net (John Fouhy) Date: Wed, 14 Jan 2009 15:05:27 +1300 Subject: [Tutor] Sys.stdin Question In-Reply-To: <262679b50901131759uf2589eem349266cca7b2ecbf@mail.gmail.com> References: <262679b50901131634h6d252f78t4f2942d8b45f569e@mail.gmail.com> <262679b50901131759uf2589eem349266cca7b2ecbf@mail.gmail.com> Message-ID: <5e58f2e40901131805r50628b65ue8290b95e128ef13@mail.gmail.com> 2009/1/14 Damon Timm : > On Tue, Jan 13, 2009 at 8:55 PM, Steve Willoughby wrote: >> This is playing a dangerous game, though, of introducing a race condition. >> Is there nothing on the standard input RIGHT NOW because the source on >> the other end of the pipe hasn't managed to generate anything yet, or >> because there's nothing piped? > Does this concern still apply with John's suggestion? I just tested > it in my little application and didn't have an issue ... of course, I > only ran a couple different command line items before throwing up my > hands in celebration. It's easy to test: ### test.py ### import time time.sleep(1) print 'foo' ### $ python test.py | python stdintest.py Nothing to see here. close failed: [Errno 32] Broken pipe [not shown: the 1 second pause after "Nothing to see here." showed up] You could "fix" it by adding a delay to your consumer script.. as long as none of your input scripts take longer than the delay to generate output. Or do things differently, which might be smarter :-) -- John. From metolone+gmane at gmail.com Wed Jan 14 03:48:39 2009 From: metolone+gmane at gmail.com (Mark Tolonen) Date: Tue, 13 Jan 2009 18:48:39 -0800 Subject: [Tutor] Date comparison across time zones References: <7b60d8a80901130845s30842deeuba55afec99285a5c@mail.gmail.com> Message-ID: "frenc1z 1z" wrote in message news:7b60d8a80901130845s30842deeuba55afec99285a5c at mail.gmail.com... > Hello, > > I'm a novice python (python 2.6.1) user with the following problem. > > Never though this was going to be so difficult :-). > > I would like to compare some dates (date+time really). The dates all have > the following RFC2822 format: > > Eg. is d1 < d2? > d1 = "Tue, 13 Jan 2009 03:27:29 -0800" > d2 = "Tue, 13 Jan 2009 02:40:00 -0600" Check out the email.utils module, specifically the parsedate_tz and mktime_tz functions. -Mark From kent37 at tds.net Wed Jan 14 04:13:10 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 13 Jan 2009 22:13:10 -0500 Subject: [Tutor] quoting and escaping In-Reply-To: References: Message-ID: <1c2a2c590901131913i3cba55f6k642fafc557a6d8a0@mail.gmail.com> On Tue, Jan 13, 2009 at 6:09 PM, Jon Crump wrote: > I've got strings like this: > > s = """[{"title" : "Egton, Yorkshire", "start" : new Date(1201,1,4), > "description" : "Hardy's long name: Egton, Yorkshire. <br> "}, > {"title" : "Guilsborough, Yorkshire", "start" : new Date(1201,1,5), > "description" : "Hardy's long name: Guilsborough, Yorkshire. <br> > <img src=\"document.png\" style=\"cursor: pointer\" > onclick=\"SimileAjax.WindowManager.cancelPopups();show_next('tab3');pager('006'); > return false\"/>pg.006: 1201-02-05 to 1202-03-07"}]""" Where does this come from? It looks like the string representation of a dict. Can you get the actual dict? Perhaps there is a better way to do whatever you are doing? Kent From noufal at nibrahim.net.in Wed Jan 14 11:36:54 2009 From: noufal at nibrahim.net.in (Noufal Ibrahim) Date: Wed, 14 Jan 2009 16:06:54 +0530 Subject: [Tutor] Selecting first matching element from a list In-Reply-To: <496B7C31.9040104@gmail.com> References: <496B6847.9080701@nibrahim.net.in> <496B7C31.9040104@gmail.com> Message-ID: <496DC046.5060604@nibrahim.net.in> bob gailer wrote: > > 2) "looks bad" and "is ugly" are emotional responses. What are you > feeling and wanting when you say those things? It's hard for me to qualify really but my general idea of list comprehensions is that they transform and filter lists creating other lists. For instance, I'd call this if key in foo: return foo[key] else: return 'unknown' 'ugly' when compared to return foo.get(key,'unknown') I guess I'm looking for the idiomatic way of performing such an operation. My gut feel tells me that the zeroth element of a list comprehension is not the right way to go but I wanted confirmation/rebuttal. Peace. -- ~noufal http://nibrahim.net.in/ From s4027340 at student.uq.edu.au Wed Jan 14 11:52:21 2009 From: s4027340 at student.uq.edu.au (Mr Gerard Kelly) Date: Wed, 14 Jan 2009 20:52:21 +1000 Subject: [Tutor] lists and Entry Message-ID: There is a little Tkinter program. It lets you type something in a box, and will display it at the command line. from Tkinter import * master = Tk() e = Entry(master) e.pack() e.focus_set() def callback(): s=e.get() print s b = Button(master, text="get", width=10, command=callback) b.pack() mainloop() The get() method returns a string, how do I make it return a list? I want to be able to type in 1,2,3 into the box and get [1,2,3] to appear on the command line. If I change the callback() method so that it says s=[e.get()] I just get a list with one element, the string: ['1,2,3'] If I make it s=list(e.get()) I get a list with every character as an element: ['1', ',', '2', ',', '3'] How to just get plain [1,2,3]? many thanks From roadierich at googlemail.com Wed Jan 14 12:17:28 2009 From: roadierich at googlemail.com (Richard Lovely) Date: Wed, 14 Jan 2009 11:17:28 +0000 Subject: [Tutor] Active State Python with IDLE Python 2.5 In-Reply-To: <496B1A66.5050306@sbcglobal.net> References: <496AA318.6020508@sbcglobal.net> <496B1A66.5050306@sbcglobal.net> Message-ID: The Activestate package IS vanilla python. It just comes packaged with a few addon modules for things such as ActiveX and with windows GUI libraries. If it works with Vanilla Python, there's virtually no reason it won't work with the activestate distribution, and vice versa, as long as you don't use any of the activestate modules in applications you want to work on other operating systems. It's like the TK modules, if you don't import them, you don't need to worry about whether your users have them or not. On 12/01/2009, Wayne Watson wrote: > Thanks. Is it possible to just disable the vanilla version? I may want to > switch between the two. Most users of the program I'm about to modify use > the vanilla version. At some point, I may want to go back to it to verify > that in their world all is OK. > > > Alan Gauld wrote: > > "Wayne Watson" wrote > > I installed "Python" 2.5 a few months ago, and decided I'd like to try > windowpy from ActiveState. Is having both of these installed going to > cause me trouble? > > Multiple versions of Python should not be a problem provided you put > them in different folders. > > C:\python25 > > and > > C:\ASpython25 > > for example > > You will have to remember which one is the default version (ie will > be used when you double click a python file for example) but you > can set things up to run both. But there is little point. If you are > on Windows I'd personally uninstall the vanilla version and install > the ActiveState version, it has a lot more features for Windows users. > > Alan G. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > -- > Wayne Watson (Watson Adventures, Prop., Nevada City, CA) (121.01 Deg. W, > 39.26 Deg. N) GMT-8 hr std. time) "What killed the electric car? > Expensive batteries did." -- Physics for Future Presidents, Richard A. > Muller Web Page: > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Richard "Roadie Rich" Lovely, part of the JNP|UK Famile www.theJNP.com From andreengels at gmail.com Wed Jan 14 12:39:54 2009 From: andreengels at gmail.com (Andre Engels) Date: Wed, 14 Jan 2009 12:39:54 +0100 Subject: [Tutor] lists and Entry In-Reply-To: References: Message-ID: <6faf39c90901140339n127e747cgaf5712c99784cd3e@mail.gmail.com> On Wed, Jan 14, 2009 at 11:52 AM, Mr Gerard Kelly wrote: > There is a little Tkinter program. It lets you type something in a box, > and will display it at the command line. > > > from Tkinter import * > > master = Tk() > > e = Entry(master) > e.pack() > > e.focus_set() > > def callback(): > s=e.get() > print s > > b = Button(master, text="get", width=10, command=callback) > b.pack() > > mainloop() > > > > The get() method returns a string, how do I make it return a list? > I want to be able to type in 1,2,3 into the box and get [1,2,3] to > appear on the command line. > > If I change the callback() method so that it says > s=[e.get()] > I just get a list with one element, the string: ['1,2,3'] > > If I make it > s=list(e.get()) > I get a list with every character as an element: ['1', ',', '2', ',', '3'] > > How to just get plain [1,2,3]? You'll have to work with the string. Assuming that the string will always be a couple of integers, separated by commas (if getting input from the keyboard, create a loop so that data are being called again and again until it parses correctly), you can get what you want with: s=[int(n) for n in e.get().split(',')] Explaining this Python: e.get(), as you have noticed, is a string consisting of whatever has been put in, in this case '1,2,3'. e.get.split(',') means "split e.get() into pieces at each comma, and make a list out of it'. This gives: ['1','2','3']. And finally [int(n) for n in A] with A being a list (or more generally, anything enumerable) gives a list consisting of the int value of the items in A. -- Andr? Engels, andreengels at gmail.com From emadnawfal at gmail.com Wed Jan 14 12:43:38 2009 From: emadnawfal at gmail.com (=?WINDOWS-1256?Q?Emad_Nawfal_(=DA=E3=C7=CF_=E4=E6=DD=E1)?=) Date: Wed, 14 Jan 2009 06:43:38 -0500 Subject: [Tutor] lists and Entry In-Reply-To: References: Message-ID: <652641e90901140343s4c1b209ai28ba90d715268cb5@mail.gmail.com> On Wed, Jan 14, 2009 at 5:52 AM, Mr Gerard Kelly wrote: > There is a little Tkinter program. It lets you type something in a box, > and will display it at the command line. > > > from Tkinter import * > > master = Tk() > > e = Entry(master) > e.pack() > > e.focus_set() > > def callback(): > s=e.get() > print s > > b = Button(master, text="get", width=10, command=callback) > b.pack() > > mainloop() > > > > The get() method returns a string, how do I make it return a list? > I want to be able to type in 1,2,3 into the box and get [1,2,3] to > appear on the command line. > > If I change the callback() method so that it says > s=[e.get()] > I just get a list with one element, the string: ['1,2,3'] > > If I make it > s=list(e.get()) > I get a list with every character as an element: ['1', ',', '2', ',', '3'] > > How to just get plain [1,2,3]? > > many thanks One possibility is to split the string on the comma. If you have a string like : s = '1,2,3' then s.split(',') = [1,2,3] If you later want to change this into a list of integers for example, you might use something like a list comprehension. Look at the following interactive session: >>> s = "1,2,3" >>> m = s.split(',') >>> m ['1', '2', '3'] >>> f = [int(i) for i in m] >>> f [1, 2, 3] >>> This is a reply from a programming amateur, so I think you might consider it until you get a better solution. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- ?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? ????????.....???? ??????? "No victim has ever been more repressed and alienated than the truth" Emad Soliman Nawfal Indiana University, Bloomington http://emnawfal.googlepages.com -------------------------------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: From wesbrooks at gmail.com Wed Jan 14 16:37:36 2009 From: wesbrooks at gmail.com (Wesley Brooks) Date: Wed, 14 Jan 2009 15:37:36 +0000 Subject: [Tutor] Small python web server suitable for web cam streams? Message-ID: Dear Users, I'm aware that there is a large array of web toolkits available in python and I would like to hear some opinions on which may be best suited to my specification so I can research them further. I have a machine which runs for extended periods of time, and often into days rather than just hours. I would like to set up the computer so that it hosts a simple web page displaying current status information, and a feed from a web camera which is viewing the business end of the machine. This web site will not be opened to the wider internet, just kept as open access to all machines on the local network. There is currently no requirement for any control from the user end, just to view the page or pages. This will be running on a windows machine. Yours Faithfully, Wesley Brooks -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Wed Jan 14 17:21:56 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 14 Jan 2009 11:21:56 -0500 Subject: [Tutor] Small python web server suitable for web cam streams? In-Reply-To: References: Message-ID: <1c2a2c590901140821q75841c08m4a09965688774013@mail.gmail.com> On Wed, Jan 14, 2009 at 10:37 AM, Wesley Brooks wrote: > I have a machine which runs for extended periods of time, and often into > days rather than just hours. I would like to set up the computer so that it > hosts a simple web page displaying current status information, and a feed > from a web camera which is viewing the business end of the machine. This web > site will not be opened to the wider internet, just kept as open access to > all machines on the local network. There is currently no requirement for any > control from the user end, just to view the page or pages. Will the web server generate the status page and talk to the camera, or is it just showing static data that comes from somewhere else? If the data is generated outside the server you can use IIS or Apache to display them. If you are generating pages in the server then something simple like CherryPy might be a good choice, rather than one of the full-featured web frameworks. Kent From bgailer at gmail.com Wed Jan 14 17:25:51 2009 From: bgailer at gmail.com (bob gailer) Date: Wed, 14 Jan 2009 11:25:51 -0500 Subject: [Tutor] Selecting first matching element from a list In-Reply-To: <496DC046.5060604@nibrahim.net.in> References: <496B6847.9080701@nibrahim.net.in> <496B7C31.9040104@gmail.com> <496DC046.5060604@nibrahim.net.in> Message-ID: <496E120F.2020201@gmail.com> Noufal Ibrahim wrote: > bob gailer wrote: > >> >> 2) "looks bad" and "is ugly" are emotional responses. What are you >> feeling and wanting when you say those things? > > It's hard for me to qualify really but my general idea of list > comprehensions is that they transform and filter lists creating other > lists. > > For instance, I'd call this > if key in foo: > return foo[key] > else: > return 'unknown' > > 'ugly' when compared to > > return foo.get(key,'unknown') > > I guess I'm looking for the idiomatic way of performing such an > operation. My gut feel tells me that the zeroth element of a list > comprehension is not the right way to go but I wanted > confirmation/rebuttal. I suggest writing the algorithm in step-by-step pseudocode then asking "how can I write this in Python"? High level goal: Given a list of numbers, return the first that meets a condition. If none meet the condition, return 'unknown'. Step-by-step process in pseudocode: for each element in list see if it meets the condition if it does stop and return the element if we have not stopped return 'unknown' How many ways are there in Python to go thru a list (and apply a function to each element)? The ones I know are: while for list comprehension map() I discard while as for takes less code and is easier to understand. I discard map() as it is the "old way" to do a comprehension. That leaves for and comprehension. The advantage of for is that you can stop the process once you find the desired element. The advantage of comprehension is compactness and readability. You must work with the tools available (or write your own). But the heart of anything you write will be the original pseudocode. Then you must live with any emotional reactions. -- Bob Gailer Chapel Hill NC 919-636-4239 From denis.spir at free.fr Wed Jan 14 18:09:51 2009 From: denis.spir at free.fr (spir) Date: Wed, 14 Jan 2009 18:09:51 +0100 Subject: [Tutor] traceback Message-ID: <20090114180951.6095bbb3@o> Hello, I rather often use exceptions as information providers at design or debug time. A typical use of mine is to have a test version of methods that wrap standard version: def run(): do stuff that may raise exc def testRun(): try: run() except Error,error: sys.error.write(str(error)) So that I can run a bunch of (possibly failing) tests and still get all worthful info. Now, the drawback is that I then lose python provided traceback, as for any reason str(exc) does not return tracback, only the "message". To have the traceback I planned to catch the traceback manually. The aims whare: * be able to output the tracback prepended to the message, when useful * try to find a more readable (for me) format * filter it: e.g. print only last trace mark of each module If you have ideas on the best way to do this, thanks. I tried to use sys.exc_info() that returns a (type,value,traceback) tuple and the format_tb() function of the traceback module. *Sometimes* I get the traceback as expected and all is fine. But in most cases sys.exc_info() returns (None,None,None) like if there was absolutely no active exception. I cannot consistently reproduce the issue to make a clear diagnosis. Thank you, Denis ------ la vida e estranya From kent37 at tds.net Wed Jan 14 18:31:55 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 14 Jan 2009 12:31:55 -0500 Subject: [Tutor] Selecting first matching element from a list In-Reply-To: <496E120F.2020201@gmail.com> References: <496B6847.9080701@nibrahim.net.in> <496B7C31.9040104@gmail.com> <496DC046.5060604@nibrahim.net.in> <496E120F.2020201@gmail.com> Message-ID: <1c2a2c590901140931i5ec3b7a3o15509b9448c4b4d6@mail.gmail.com> On Wed, Jan 14, 2009 at 11:25 AM, bob gailer wrote: > How many ways are there in Python to go thru a list (and apply a function to > each element)? The ones I know are: > while > for > list comprehension > map() filter() is more appropriate than map() for this problem generator expression itertools functions Kent From kent37 at tds.net Wed Jan 14 18:34:54 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 14 Jan 2009 12:34:54 -0500 Subject: [Tutor] traceback In-Reply-To: <20090114180951.6095bbb3@o> References: <20090114180951.6095bbb3@o> Message-ID: <1c2a2c590901140934pa3bc2c4k622e462ea5754b3b@mail.gmail.com> On Wed, Jan 14, 2009 at 12:09 PM, spir wrote: > Hello, > > I rather often use exceptions as information providers at design or debug time. A typical use > of mine is to have a test version of methods that wrap standard version: > > def run(): > do stuff > that may > raise exc > def testRun(): > try: > run() > except Error,error: > sys.error.write(str(error)) I use traceback.print_exc() for this. Kent From wesbrooks at gmail.com Wed Jan 14 18:53:55 2009 From: wesbrooks at gmail.com (Wesley Brooks) Date: Wed, 14 Jan 2009 17:53:55 +0000 Subject: [Tutor] Small python web server suitable for web cam streams? In-Reply-To: <1c2a2c590901140821q75841c08m4a09965688774013@mail.gmail.com> References: <1c2a2c590901140821q75841c08m4a09965688774013@mail.gmail.com> Message-ID: At the minimum the page would need to display progress through a job, any error messages, and a picture from the web camera. I've used something that grabbed images from a USB camera using python a while back so at the simplest I could be just after something to display a html page with an image and just update the page on the server end once every second or so and rely on the user to hit the refresh to get a new image. For the next level it would be great to have something as above but with a video stream from the camera, and various pages displaying temperatures etc. The very best would have time plots for various temperatures (these of course could be images generated by seperate scripts as before) and email alerts out to users when a job is complete or an error occurs. Is this best solved using two different toolkits? One to make the page and another to host it? Thanks for your help. I'll have a look at CherryPy. Wesley. 2009/1/14 Kent Johnson > On Wed, Jan 14, 2009 at 10:37 AM, Wesley Brooks > wrote: > > I have a machine which runs for extended periods of time, and often into > > days rather than just hours. I would like to set up the computer so that > it > > hosts a simple web page displaying current status information, and a feed > > from a web camera which is viewing the business end of the machine. This > web > > site will not be opened to the wider internet, just kept as open access > to > > all machines on the local network. There is currently no requirement for > any > > control from the user end, just to view the page or pages. > > Will the web server generate the status page and talk to the camera, > or is it just showing static data that comes from somewhere else? > > If the data is generated outside the server you can use IIS or Apache > to display them. If you are generating pages in the server then > something simple like CherryPy might be a good choice, rather than one > of the full-featured web frameworks. > > Kent > -------------- next part -------------- An HTML attachment was scrubbed... URL: From damontimm at gmail.com Wed Jan 14 19:27:03 2009 From: damontimm at gmail.com (Damon Timm) Date: Wed, 14 Jan 2009 13:27:03 -0500 Subject: [Tutor] Sys.stdin Question In-Reply-To: <39742.134.134.136.14.1231899038.squirrel@webmail.alchemy.com> References: <262679b50901131634h6d252f78t4f2942d8b45f569e@mail.gmail.com> <262679b50901131759uf2589eem349266cca7b2ecbf@mail.gmail.com> <39742.134.134.136.14.1231899038.squirrel@webmail.alchemy.com> Message-ID: <262679b50901141027p3f44f9c4q52f2cab3dd2310b1@mail.gmail.com> On Tue, Jan 13, 2009 at 9:05 PM, John Fouhy wrote: > It's easy to test: > > ### test.py ### > import time > time.sleep(1) > print 'foo' > ### > > $ python test.py | python stdintest.py > Nothing to see here. > close failed: [Errno 32] Broken pipe > > [not shown: the 1 second pause after "Nothing to see here." showed up] > > You could "fix" it by adding a delay to your consumer script.. as long > as none of your input scripts take longer than the delay to generate > output. Or do things differently, which might be smarter :-) Yea - I can see where that would become a problem ... hmm ... I think I am going to look into what Steve is suggesting with the fileinput module ... On Tue, Jan 13, 2009 at 9:10 PM, Steve Willoughby wrote: > As the Zen of Python states, "explicit is better than implicit." > > Scripts which just magically "do the right thing" can be cool to play > with, but they have a nasty tendency to guess wrong about what the right > thing might be. In this case, you're making assumptions about how to > *guess* whether there's standard input piped at your script, and running > with those assumptions... but there are easily identified cases where > those assumptions don't hold true. That's a good point ... here is more of what I am trying to do ... minus exceptions and the actual functions that sends the mail ... I could use the "-" stdin bit to either signify the body message of the email, or an attachment ... or, I guess, both ... (I left out the details of actually emailing stuff and all the imports): def sendMail(recipient, subject, text, *attachmentFilePaths): #here is the function used to send the mail and attachments... def main(): parser = OptionParser(usage="%prog [options: -s -t -m ] [attachemnts, if any...]") parser.add_option("-q", "--quiet", action="store_true", dest="quiet") parser.add_option("-s", "--subject", action="store", type="string", dest="subject", default=default_subject) parser.add_option("-t", "--to", action="store", type="string", dest="recipient", default=default_recipient) parser.add_option("-m", "--message", action="store", type="string", dest="message") (options, args) = parser.parse_args() sendMail(options.recipient, options.subject, options.text, args) $ sendmail.py -t me at me.com -s "my subject" -m - attament.jpg or maybe $ dmesg | sendmail.py -t me at me.com -s "my subject" -m "here is output from dmesg" - someotherattachmenttoo.doc Thanks for all this help. On Tue, Jan 13, 2009 at 9:10 PM, Steve Willoughby wrote: > On Tue, January 13, 2009 17:59, Damon Timm wrote: >> ... then, I guess, I can just have it do an if statement that asks: if >> args[0] == "-" then ... blah. I may do that ... the script, itself, > > Look at the fileinput module. If you're looking at the command line for a > list of filenames, which may include "-" to mean (read stdin at this point > in the list of files), your script's logic is reduced to simply: > > while line in fileinput.input(): > # process the line > > and your script focuses on its specific task. > >>> or not. So instead of seeing if anything's showing up (and introducing >>> timing dependencies and uncertainty), see if it's attached to a real >>> terminal at all. On Unix, os.isatty(sys.stdin) will tell you this. >> >> Does this concern still apply with John's suggestion? I just tested >> it in my little application and didn't have an issue ... of course, I > > Yes, it does. And in a trivial case, it will usually work. But don't > base your solutions on something that looks like it sorta works most of > the time but isn't really the recommended practice, because it will break > later and you'll spend a lot of time figuring out why it's not being > reliable. > >> I can go to using the "-" option ... although, to be honest, I like >> the idea of the script thinking for itself ... that is: if there is >> stdin, use it -- if not, not ... and, I was thinking of attaching the >> stdin as a text file, if present. And not attaching anything, if not. > > As the Zen of Python states, "explicit is better than implicit." > > Scripts which just magically "do the right thing" can be cool to play > with, but they have a nasty tendency to guess wrong about what the right > thing might be. In this case, you're making assumptions about how to > *guess* whether there's standard input piped at your script, and running > with those assumptions... but there are easily identified cases where > those assumptions don't hold true. > > Also, think of anyone other than you (or you at a later date) using this > script. The number of things the script does for no apparent reason can > lead to frustration and doubt that you really know, as a user, what the > script is really going to try to do in a given situation, and what you'll > have to do on your end to "trick" it into doing what you really wanted in > the first place. It's cute, but ultimately implicit behavior doesn't make > for good, long-lasting solid applications. > > From kent37 at tds.net Wed Jan 14 20:05:24 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 14 Jan 2009 14:05:24 -0500 Subject: [Tutor] Small python web server suitable for web cam streams? In-Reply-To: References: <1c2a2c590901140821q75841c08m4a09965688774013@mail.gmail.com> Message-ID: <1c2a2c590901141105w5dd74c92m1bdf19f1a8ced6be@mail.gmail.com> On Wed, Jan 14, 2009 at 12:53 PM, Wesley Brooks wrote: > The very best would have time plots for various temperatures (these of > course could be images generated by seperate scripts as before) and email > alerts out to users when a job is complete or an error occurs. I've used matplotlib to dynamically create and display charts on a web page. There are also some interesting JavaScript chart packages. smtplib (in the Python lib) can send your emails. > Is this best solved using two different toolkits? One to make the page and > another to host it? I would start out putting it in the server and change it if there are performance problems. Depending on how complex your HTML is, you might want to use one of the template libraries - Mako, Genshi, Jinja, Kid, Cheetah, ... I can't recommend a specific one. Kent From vanden at gmail.com Wed Jan 14 20:20:28 2009 From: vanden at gmail.com (Brian van den Broek) Date: Wed, 14 Jan 2009 14:20:28 -0500 Subject: [Tutor] help with getting python to run from command prompt on Windows XP Message-ID: <496E3AFC.7030909@gmail.com> Hi all, I'm trying, via email, to help a friend set up python on his Windows XP computer. I've been strictly linux for some time now, and don't have a Windows machine on which to investigate. We've hit a problem, and I'd appreciate a push. He's got python 2.6.1 installed as evidenced by the Startbar program icon for Idle launching as expected. When run from IDLE, `print sys.executable' yields `C:\\Python26\\pythonw.exe'. He reports that C:\Python26 contains both python.exe and pythonw.exe. I've had him add the text `;C:\Python26' (without quotes) to the end of his Path environment variable via the Control Panel|System Properties way of editing Environment variables. I've had him reboot afterwards. After all of that, he reports that an attempt to run python from the command prompt produces a complaint that `` `python' is not recognized as an internal or external command, operable program or batch file.'' Can someone with Windows knowledge please tell me what I am missing? Am I wrong in recalling that from the command prompt on Windows, one wants python, rather than pythonw? (I seem to recollect that pythonw.exe is what you associate with .py files to prevent a double-click on a .py icon from producing the `DOS box flash' and *not* what one wants to use from the prompt itself.) Thanks and best, Brian vdB From broek at cc.umanitoba.ca Wed Jan 14 20:36:20 2009 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Wed, 14 Jan 2009 14:36:20 -0500 Subject: [Tutor] help with getting python to run from command prompt on Windows XP Message-ID: <496E3EB4.20207@cc.umanitoba.ca> Hi all, I'm trying, via email, to help a friend set up python on his Windows XP computer. I've been strictly linux for some time now, and don't have a Windows machine on which to investigate. We've hit a problem, and I'd appreciate a push. He's got python 2.6.1 installed as evidenced by the Startbar program icon for Idle launching as expected. When run from IDLE, `print sys.executable' yields `C:\\Python26\\pythonw.exe'. He reports that C:\Python26 contains both python.exe and pythonw.exe. I've had him add the text `;C:\Python26' (without quotes) to the end of his Path environment variable via the Control Panel|System Properties way of editing Environment variables. I've had him reboot afterwards. After all of that, he reports that an attempt to run python from the command prompt produces a complaint that `` `python' is not recognized as an internal or external command, operable program or batch file.'' Can someone with Windows knowledge please tell me what I am missing? Am I wrong in recalling that from the command prompt on Windows, one wants python, rather than pythonw? (I seem to recollect that pythonw.exe is what you associate with .py files to prevent a double-click on a .py icon from producing the `DOS box flash' and *not* what one wants to use from the prompt itself.) Thanks and best, Brian vdB From kent37 at tds.net Wed Jan 14 21:01:50 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 14 Jan 2009 15:01:50 -0500 Subject: [Tutor] help with getting python to run from command prompt on Windows XP In-Reply-To: <496E3EB4.20207@cc.umanitoba.ca> References: <496E3EB4.20207@cc.umanitoba.ca> Message-ID: <1c2a2c590901141201q3a771d15o48336f61a44cc82d@mail.gmail.com> On Wed, Jan 14, 2009 at 2:36 PM, Brian van den Broek wrote: > Hi all, > > I'm trying, via email, to help a friend set up python on his Windows > XP computer. I've been strictly linux for some time now, and don't > have a Windows machine on which to investigate. We've hit a problem, > and I'd appreciate a push. > > He's got python 2.6.1 installed as evidenced by the Startbar program > icon for Idle launching as expected. When run from IDLE, `print > sys.executable' yields `C:\\Python26\\pythonw.exe'. > He reports that C:\Python26 contains both python.exe and pythonw.exe. > > I've had him add the text `;C:\Python26' (without quotes) to the end > of his Path environment variable via the Control Panel|System > Properties way of editing Environment variables. I've had him reboot > afterwards. > > After all of that, he reports that an attempt to run python from the > command prompt produces a complaint that `` `python' is not recognized > as an internal or external command, operable program or batch file.'' > > Can someone with Windows knowledge please tell me what I am missing? > Am I wrong in recalling that from the command prompt on Windows, one > wants python, rather than pythonw? (I seem to recollect that > pythonw.exe is what you associate with .py files to prevent a > double-click on a .py icon from producing the `DOS box flash' and > *not* what one wants to use from the prompt itself.) It sounds to me like you have asked him to do the right thing. I would try - check the Path setting by typing 'set path' at a command prompt and verify that C:\Python26 is in the displayed path - try running Python with a full path, i.e. at the command prompt try 'C:\Python26\python.exe' Kent From wescpy at gmail.com Wed Jan 14 21:09:27 2009 From: wescpy at gmail.com (wesley chun) Date: Wed, 14 Jan 2009 12:09:27 -0800 Subject: [Tutor] help with getting python to run from command prompt on Windows XP In-Reply-To: <1c2a2c590901141201q3a771d15o48336f61a44cc82d@mail.gmail.com> References: <496E3EB4.20207@cc.umanitoba.ca> <1c2a2c590901141201q3a771d15o48336f61a44cc82d@mail.gmail.com> Message-ID: <78b3a9580901141209r5c8b4d42pab71a3ce07b8f6d4@mail.gmail.com> On Wed, Jan 14, 2009 at 12:01 PM, Kent Johnson wrote: > On Wed, Jan 14, 2009 at 2:36 PM, Brian van den Broek > wrote: >> >> He's got python 2.6.1 installed as evidenced by the Startbar program >> icon for Idle launching as expected. When run from IDLE, `print >> sys.executable' yields `C:\\Python26\\pythonw.exe'. >> He reports that C:\Python26 contains both python.exe and pythonw.exe. >> >> I've had him add the text `;C:\Python26' (without quotes) to the end >> of his Path environment variable via the Control Panel|System >> Properties way of editing Environment variables. I've had him reboot >> afterwards. >> >> After all of that, he reports that an attempt to run python from the >> command prompt produces a complaint that `` `python' is not recognized >> as an internal or external command, operable program or batch file.'' > > It sounds to me like you have asked him to do the right thing. I would try > - check the Path setting by typing 'set path' at a command prompt and > verify that C:\Python26 is in the displayed path > - try running Python with a full path, i.e. at the command prompt try > 'C:\Python26\python.exe' i fully agree with kent's comments/suggestions. you appeared to have them do the right thing. fwiw, the only time i run into that error after doing the same thing as you is that i'm trying that command in an already-opened command window -- i need to close that and open another that takes in the changes to the environment variables. but you did tell them to reboot, so this shouldn't be your problem. also, i think (but cannot confirm as i'm on a mac now that) there are two PATH env vars... one for the current user and one for all users (if you have administrative privileges. good luck! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 "Python Fundamentals", Prentice Hall, (c)2009 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From w.richert at gmx.net Wed Jan 14 21:19:11 2009 From: w.richert at gmx.net (Willi Richert) Date: Wed, 14 Jan 2009 21:19:11 +0100 Subject: [Tutor] traceback In-Reply-To: <20090114180951.6095bbb3@o> References: <20090114180951.6095bbb3@o> Message-ID: <200901142119.11994.w.richert@gmx.net> Hi, do you observe the same behavior with traceback.format_exc()? I've used that always in such situations which worked all the time. Regards, wr Am Mittwoch, 14. Januar 2009 18:09:51 schrieb spir: > Hello, > > I rather often use exceptions as information providers at design or debug > time. A typical use of mine is to have a test version of methods that wrap > standard version: > > def run(): > do stuff > that may > raise exc > def testRun(): > try: > run() > except Error,error: > sys.error.write(str(error)) > > So that I can run a bunch of (possibly failing) tests and still get all > worthful info. Now, the drawback is that I then lose python provided > traceback, as for any reason str(exc) does not return tracback, only the > "message". To have the traceback I planned to catch the traceback manually. > The aims whare: > * be able to output the tracback prepended to the message, when useful > * try to find a more readable (for me) format > * filter it: e.g. print only last trace mark of each module > If you have ideas on the best way to do this, thanks. > > I tried to use sys.exc_info() that returns a (type,value,traceback) tuple > and the format_tb() function of the traceback module. *Sometimes* I get the > traceback as expected and all is fine. But in most cases sys.exc_info() > returns (None,None,None) like if there was absolutely no active exception. > I cannot consistently reproduce the issue to make a clear diagnosis. > > Thank you, > Denis > > ------ > la vida e estranya > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From vceder at canterburyschool.org Wed Jan 14 21:38:20 2009 From: vceder at canterburyschool.org (Vern Ceder) Date: Wed, 14 Jan 2009 15:38:20 -0500 Subject: [Tutor] Python3.0 and Tkinter on ubuntu 8.10 HOWTO In-Reply-To: <652641e90901131332g60caaa70l5490a85cb49972f2@mail.gmail.com> References: <496D0178.8000009@canterburyschool.org> <652641e90901131332g60caaa70l5490a85cb49972f2@mail.gmail.com> Message-ID: <496E4D3C.1000301@canterburyschool.org> Since there was some interest in the question of how to get a full Python 3.0, including Tkinter and IDLE, compiled on Ubuntu Intrepid 8.10, I've written up what I've done and posted it at http://learnpython.wordpress.com/2009/01/14/installing-python-30-on-ubuntu/ Cheers, Vern Ceder -- This time for sure! -Bullwinkle J. Moose ----------------------------- Vern Ceder, Director of Technology Canterbury School, 3210 Smith Road, Ft Wayne, IN 46804 vceder at canterburyschool.org; 260-436-0746; FAX: 260-436-5137 From bermanrl at cfl.rr.com Wed Jan 14 21:53:15 2009 From: bermanrl at cfl.rr.com (Robert Berman) Date: Wed, 14 Jan 2009 15:53:15 -0500 Subject: [Tutor] Python3.0 and Tkinter on ubuntu 8.10 HOWTO In-Reply-To: <496E4D3C.1000301@canterburyschool.org> References: <496D0178.8000009@canterburyschool.org> <652641e90901131332g60caaa70l5490a85cb49972f2@mail.gmail.com> <496E4D3C.1000301@canterburyschool.org> Message-ID: <496E50BB.6040601@cfl.rr.com> Very good and most welcome. Robert Berman Vern Ceder wrote: > Since there was some interest in the question of how to get a full > Python 3.0, including Tkinter and IDLE, compiled on Ubuntu Intrepid > 8.10, I've written up what I've done and posted it at > http://learnpython.wordpress.com/2009/01/14/installing-python-30-on-ubuntu/ > > > Cheers, > Vern Ceder > From marc.tompkins at gmail.com Wed Jan 14 22:06:18 2009 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Wed, 14 Jan 2009 13:06:18 -0800 Subject: [Tutor] help with getting python to run from command prompt on Windows XP In-Reply-To: <78b3a9580901141209r5c8b4d42pab71a3ce07b8f6d4@mail.gmail.com> References: <496E3EB4.20207@cc.umanitoba.ca> <1c2a2c590901141201q3a771d15o48336f61a44cc82d@mail.gmail.com> <78b3a9580901141209r5c8b4d42pab71a3ce07b8f6d4@mail.gmail.com> Message-ID: <40af687b0901141306n66fa4787ma3a6844dae5938ac@mail.gmail.com> On Wed, Jan 14, 2009 at 12:09 PM, wesley chun wrote: > > i fully agree with kent's comments/suggestions. you appeared to have > them do the right thing. fwiw, the only time i run into that error > after doing the same thing as you is that i'm trying that command in > an already-opened command window -- i need to close that and open > another that takes in the changes to the environment variables. but > you did tell them to reboot, so this shouldn't be your problem. > > also, i think (but cannot confirm as i'm on a mac now that) there are > two PATH env vars... one for the current user and one for all users > (if you have administrative privileges. > > - As wesley said, you don't have to reboot anymore (as you did in the old days when you set environment variables through AUTOEXEC.BAT). Changes to environment variables take effect as soon as you click Apply or OK, but they only affect subsequently-opened command prompts - so if you have a prompt open, just close it and open a new one. Rebooting will certainly do the trick, but if you need to try more than once, this will save a LOT of time. - Also as wesley said, there MAY BE two separate PATHs - in my experience, the user-level one is usually empty and can be deleted to avoid confusion. If it's _not_ empty, it's usually by mistake... (there may be exceptions, but every single time I've seen a program that added something to the user-level path, it's turned out to have been unintentional.) - There's also a PATHEXT variable that holds a list of extensions that Windows should consider executable - its contents should look like this: ".COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH" If something has edited this variable and removed .EXE from the list... - The #1 problem I run into in providing telephone support is misunderstandings over the names of punctuation characters. I hate to ask, but is there a possibility of confusion between the colon and semicolon? (e.g. ":C;\Python26" instead of ";C:\Python26") That would do it... -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From jjcrump at myuw.net Wed Jan 14 23:14:15 2009 From: jjcrump at myuw.net (Jon Crump) Date: Wed, 14 Jan 2009 14:14:15 -0800 (PST) Subject: [Tutor] quoting and escaping In-Reply-To: <1c2a2c590901131913i3cba55f6k642fafc557a6d8a0@mail.gmail.com> References: <1c2a2c590901131913i3cba55f6k642fafc557a6d8a0@mail.gmail.com> Message-ID: Kent, Steve, Marty, et alia, On Tue, 13 Jan 2009, Kent Johnson wrote: > Where does this come from? It looks like the string representation of > a dict. Can you get the actual dict? Perhaps there is a better way to > do whatever you are doing? It does look like that doesn't it, but it's actually a javascript object in a file Itinerary.js This file is in the format expected by the Simile Timeline software (if you're interested, you can see the working web application at ). The data for this application was prepared by means of a python script that you all have been helping me with from time to time. The script isn't pretty and bears everywhere the marks of inexperience, but I've learned a lot doing it and it works. Having created the js file, I found that I might wish to edit the data in a variety of ways, so I thought, well, it looks like a python dictionary, maybe I can make it act like one. simplejson.loads() was the obvious thing to try, but since the data format isn't really json that didn't work. The new Date() object declarations needed to be modified to look like datetime.date() instances. Marty Walsh very helpfully reminded me that re.sub() can take a function as its first argument, so once I got the regex string right, it was easy to turn new Date(1216,9,18) into "datetime.date(12,10,18)". In experimenting at the interpreter command line I was confused by the fact that the interpreter was interpreting the escaped quotation marks in my string fragment rather than rendering the escape character. Steve Willoughby's kind message explained the business of 'raw' strings which put me on the right track to understanding what was happening. In the event, however, the escapes were not a problem because file.read() returns a raw string. So now I can put the pieces together and do this: >>> itin = file('/PathToFile/Itinerary.js', 'r') >>> >>> jdate = re.compile('new Date\((\d{4}),(\d{1,2}),(\d{1,2})\)') >>> >>> def repldate(match): ... y, m, d = map(int, match.groups()) ... return '\"date(%04d, %02d, %02d)\"' % (y, m+1, d) ... >>> print type(eval(jdate.sub(repldate, itin.read()))) And that's what I wanted all along. I'm mindful of the security implications of eval() and understand that it's bad form, but since this processing is entirely internal I don't think that'll be a problem. I agree that there's probably a better way of doing things, especially in the generation of Itinerary.js in the first place. Creating in python a data structure for another language by means of string formatting seemed like a kluge to me even at the time, but being the tyro that I am, I didn't know how else to proceed. The data file in question is at and the python used for the original text processing is in the same directory at itin-processing.py. It's a big ugly mess full of naive notes to myself, if anyone cares to look at it and offer any comments or advice I could not be anything but grateful. I've learned so much from you guys, and thank you Kent for following up, but, given my long-windedness, aren't you sorry you asked? ;-) Thanks again, Jon From emadnawfal at gmail.com Wed Jan 14 23:39:43 2009 From: emadnawfal at gmail.com (=?WINDOWS-1256?Q?Emad_Nawfal_(=DA=E3=C7=CF_=E4=E6=DD=E1)?=) Date: Wed, 14 Jan 2009 17:39:43 -0500 Subject: [Tutor] Python3.0 and Tkinter on ubuntu 8.10 HOWTO In-Reply-To: <496E50BB.6040601@cfl.rr.com> References: <496D0178.8000009@canterburyschool.org> <652641e90901131332g60caaa70l5490a85cb49972f2@mail.gmail.com> <496E4D3C.1000301@canterburyschool.org> <496E50BB.6040601@cfl.rr.com> Message-ID: <652641e90901141439q1acbf00o4f6e1d1f287b0aa2@mail.gmail.com> Great source for Unicode lovers On Wed, Jan 14, 2009 at 3:53 PM, Robert Berman wrote: > Very good and most welcome. > > Robert Berman > > Vern Ceder wrote: > >> Since there was some interest in the question of how to get a full Python >> 3.0, including Tkinter and IDLE, compiled on Ubuntu Intrepid 8.10, I've >> written up what I've done and posted it at >> http://learnpython.wordpress.com/2009/01/14/installing-python-30-on-ubuntu/ >> >> Cheers, >> Vern Ceder >> >> _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- ?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? ????????.....???? ??????? "No victim has ever been more repressed and alienated than the truth" Emad Soliman Nawfal Indiana University, Bloomington http://emnawfal.googlepages.com -------------------------------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: From s4027340 at student.uq.edu.au Thu Jan 15 01:14:28 2009 From: s4027340 at student.uq.edu.au (Mr Gerard Kelly) Date: Thu, 15 Jan 2009 10:14:28 +1000 Subject: [Tutor] strings and int() Message-ID: If you have a string "6", and you do int("6"), you get the number 6. But if you have a string "2*3" and you do int("2*3") you get a name error. How do you take an expression in a string, and evaluate the expression to get a number? I want to be able to turn the string "2*3" into the number 6. thanks From alan.gauld at btinternet.com Thu Jan 15 01:27:00 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 15 Jan 2009 00:27:00 -0000 Subject: [Tutor] lists and Entry References: Message-ID: "Mr Gerard Kelly" wrote > There is a little Tkinter program. It lets you type something in a > box, > and will display it at the command line. > > e = Entry(master) > e.pack() > def callback(): > s=e.get() > print s > > b = Button(master, text="get", width=10, command=callback) > The get() method returns a string, how do I make it return a list? You don't. The Entry widget returns a list just like you get when you use raw_input() in a console program. Its up to you to parse and convert that string into whatever you require. You can use other widget types of course and they return slightly different types of data but they will all generally be string oriented. An editable list entry can return a list of strings for example... This is not really a fault of Tkinter BTW, its how nearly all GUIs work. They just capture what the user types and display strings that you provide. The processing of those input and output strings is the "business logic" of your program - in other words its up to you! HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Thu Jan 15 01:34:14 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 15 Jan 2009 00:34:14 -0000 Subject: [Tutor] help with getting python to run from command prompt onWindows XP References: <496E3AFC.7030909@gmail.com> Message-ID: "Brian van den Broek" wrote > icon for Idle launching as expected. When run from IDLE, `print > sys.executable' yields `C:\\Python26\\pythonw.exe'. > He reports that C:\Python26 contains both python.exe and > pythonw.exe. > > I've had him add the text `;C:\Python26' (without quotes) to the end > of his Path environment variable via the Control Panel|System > Properties way of editing Environment variables. I've had him reboot > afterwards. Get him to type SET > env.txt at the DOS prompt that should list all environment variables into env.txt Get him to email that file to you and check what it says about PATH. > After all of that, he reports that an attempt to run python from the > command prompt produces a complaint that `` `python' is not > recognized as an internal or external command, operable program or > batch file.'' What happens if he types C:PROMPT> C:\Python26\python.exe In other words uses the full path? > Can someone with Windows knowledge please tell me what I am missing? Nothing so far as I can tell, but from experience you need to double check the settings at every stage, its very easy to make a mistake - like using a colon instead of semi colon etc. > pythonw.exe is what you associate with .py files to prevent a > double-click on a .py icon from producing the `DOS box flash' and > *not* what one wants to use from the prompt itself.) pythonw is used for running GUI apps without a console appearing in the background. You definitely don;t want to runpythonw from the command line! -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk From jadrifter at gmail.com Thu Jan 15 01:37:39 2009 From: jadrifter at gmail.com (jadrifter) Date: Wed, 14 Jan 2009 16:37:39 -0800 Subject: [Tutor] strings and int() In-Reply-To: References: Message-ID: <1231979859.6496.6.camel@ltop> Try eval("2*3") On Thu, 2009-01-15 at 10:14 +1000, Mr Gerard Kelly wrote: > If you have a string "6", and you do int("6"), you get the number 6. > > But if you have a string "2*3" and you do int("2*3") you get a name error. > > How do you take an expression in a string, and evaluate the expression > to get a number? > > I want to be able to turn the string "2*3" into the number 6. > > thanks > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From alan.gauld at btinternet.com Thu Jan 15 01:42:40 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 15 Jan 2009 00:42:40 -0000 Subject: [Tutor] help with getting python to run from command prompt onWindows XP References: <496E3EB4.20207@cc.umanitoba.ca><1c2a2c590901141201q3a771d15o48336f61a44cc82d@mail.gmail.com><78b3a9580901141209r5c8b4d42pab71a3ce07b8f6d4@mail.gmail.com> <40af687b0901141306n66fa4787ma3a6844dae5938ac@mail.gmail.com> Message-ID: "Marc Tompkins" wrote > - Also as wesley said, there MAY BE two separate PATHs - in my > experience, > the user-level one is usually empty and can be deleted to avoid > confusion. > If it's _not_ empty, it's usually by mistake... It should be used where multiple users use a single machine and they each install their own programs for their own exclusive use. Then the programs will set the local path not the all-user one. Unfortunately XP tends to spoil the usefulness of this by making users administrators by default instead of regular users or power users! Administrators install things for all users by default... It has always frustrated me that Microsoft took a decision that effectively bypassed one of the most powerful security devices on a multi user computer by making Admin rights the default! And then compounded it by making the only other option so brain dead nobody would use it! How many ordinary PC owners are going to go to the hassle of starting up the policy editor etc to access the other levels of access that XP provides?? And thats assuming you have XP Pro.... XP Home users dont even get the policy editor. Alan G. From artie.ziff at gmail.com Thu Jan 15 01:44:11 2009 From: artie.ziff at gmail.com (Artie Ziff) Date: Wed, 14 Jan 2009 16:44:11 -0800 Subject: [Tutor] running & debugging in python interactive shell Message-ID: <496E86DB.20202@gmail.com> Greetings. I am attempting to search archives, however I thought it would be OK to ask while I search... thank you to those who responded to my previous inquiry. Your response was very helpful to me. My environment is embedded so I have only a python interactive shell for running python scripts. Does anyone know of an article that describes best practices for running and debugging scripts inside the python shell? Of course, I use import directive to run my script for first run. I am seeking techniques for invoking parts of script after initial import. I hope this makes sense to those persons reading. :) Cheers, AZ From s4027340 at student.uq.edu.au Thu Jan 15 03:19:04 2009 From: s4027340 at student.uq.edu.au (Mr Gerard Kelly) Date: Thu, 15 Jan 2009 12:19:04 +1000 Subject: [Tutor] eval and floating point Message-ID: Thanks very much I've noticed that the eval() function gives an integer, so eval("3/2") gives back 1. float(eval("3/2")) doesn't seem to work, any way to get a floating point number back with eval()? I know you can just do ("3./2."), but is there any way to do it with just ("3/2")? From pine508 at hotmail.com Thu Jan 15 03:18:30 2009 From: pine508 at hotmail.com (Che M) Date: Wed, 14 Jan 2009 21:18:30 -0500 Subject: [Tutor] running & debugging in python interactive shell In-Reply-To: <496E86DB.20202@gmail.com> References: <496E86DB.20202@gmail.com> Message-ID: > Date: Wed, 14 Jan 2009 16:44:11 -0800 > From: artie.ziff at gmail.com > To: tutor at python.org > Subject: [Tutor] running & debugging in python interactive shell > > Greetings. > > I am attempting to search archives, however I thought it would be OK to > ask while I search... thank you to those who responded to my previous > inquiry. Your response was very helpful to me. > > My environment is embedded so I have only a python interactive shell for > running python scripts. Does anyone know of an article that describes > best practices for running and debugging scripts inside the python > shell? Of course, I use import directive to run my script for first run. > I am seeking techniques for invoking parts of script after initial > import. I hope this makes sense to those persons reading. :) > > Cheers, > AZ I'd like to add to this question and expand it: can anyone point me to a good resource on debugging *generally*? Particularly using a debugger. I have never learned any "right" way to debug my code, just sort of read off the errors generated and do what I can. I use Boa Constructor, which has a built-in debugger, but I don't quite grok how best to use it (some of that is lack of practice, some is lack of understanding), though I get the sense that they are more-or-less the same across IDEs. I thought maybe there is an existing tutorial somewhere on how best to make use of a debugger. Thanks, Che _________________________________________________________________ Windows Live?: Keep your life in sync. http://windowslive.com/howitworks?ocid=TXT_TAGLM_WL_t1_allup_howitworks_012009 -------------- next part -------------- An HTML attachment was scrubbed... URL: From jervisau at gmail.com Thu Jan 15 03:26:29 2009 From: jervisau at gmail.com (Jervis Whitley) Date: Thu, 15 Jan 2009 13:26:29 +1100 Subject: [Tutor] eval and floating point In-Reply-To: References: Message-ID: <8e63a5ce0901141826w73ee61efs8c71853763d5aab5@mail.gmail.com> On Thu, Jan 15, 2009 at 1:19 PM, Mr Gerard Kelly wrote: > Thanks very much > > I've noticed that the eval() function gives an integer, so eval("3/2") > gives back 1. float(eval("3/2")) doesn't seem to work, any way to get a > floating point number back with eval()? > > I know you can just do ("3./2."), but is there any way to do it with > just ("3/2")? > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > Hi, at the top of your script you can write: from __future__ import division now >>> eval("4/3") 1.33333 You can read up on it here if you are interested.. http://www.python.org/dev/peps/pep-0238/ Cheers -------------- next part -------------- An HTML attachment was scrubbed... URL: From vceder at canterburyschool.org Thu Jan 15 03:31:13 2009 From: vceder at canterburyschool.org (Vern Ceder) Date: Wed, 14 Jan 2009 21:31:13 -0500 Subject: [Tutor] eval and floating point In-Reply-To: References: Message-ID: <496E9FF1.6070805@canterburyschool.org> Mr Gerard Kelly wrote: > Thanks very much > > I've noticed that the eval() function gives an integer, so eval("3/2") > gives back 1. float(eval("3/2")) doesn't seem to work, any way to get a > floating point number back with eval()? > > I know you can just do ("3./2."), but is there any way to do it with > just ("3/2")? If you are using a current version of Python, the line: from __future__ import division will make division with the "/" return a float; you then use "//" for integer division.... >>> from __future__ import division >>> eval("3/2") 1.5 >>> eval("3//2") 1 >>> Cheers, Vern -- This time for sure! -Bullwinkle J. Moose ----------------------------- Vern Ceder, Director of Technology Canterbury School, 3210 Smith Road, Ft Wayne, IN 46804 vceder at canterburyschool.org; 260-436-0746; FAX: 260-436-5137 From jadrifter at gmail.com Thu Jan 15 03:33:06 2009 From: jadrifter at gmail.com (jadrifter) Date: Wed, 14 Jan 2009 18:33:06 -0800 Subject: [Tutor] eval and floating point In-Reply-To: References: Message-ID: <1231986786.6496.12.camel@ltop> On Thu, 2009-01-15 at 12:19 +1000, Mr Gerard Kelly wrote: > Thanks very much > > I've noticed that the eval() function gives an integer, so eval("3/2") > gives back 1. float(eval("3/2")) doesn't seem to work, any way to get a > floating point number back with eval()? > > I know you can just do ("3./2."), but is there any way to do it with > just ("3/2")? That's not the eval function returning that integer so much as it is Python itself. You might try: eval ("1.0 * 3/2") From bill at celestial.net Thu Jan 15 05:12:31 2009 From: bill at celestial.net (Bill Campbell) Date: Wed, 14 Jan 2009 20:12:31 -0800 Subject: [Tutor] eval and floating point In-Reply-To: <1231986786.6496.12.camel@ltop> References: <1231986786.6496.12.camel@ltop> Message-ID: <20090115041231.GA8730@ayn.mi.celestial.com> On Wed, Jan 14, 2009, jadrifter wrote: >On Thu, 2009-01-15 at 12:19 +1000, Mr Gerard Kelly wrote: >> Thanks very much >> >> I've noticed that the eval() function gives an integer, so eval("3/2") >> gives back 1. float(eval("3/2")) doesn't seem to work, any way to get a >> floating point number back with eval()? >> >> I know you can just do ("3./2."), but is there any way to do it with >> just ("3/2")? > >That's not the eval function returning that integer so much as it is >Python itself. You might try: >eval ("1.0 * 3/2") Make either the numerator or denominator floating point. eval ('3.0/2') Python does the Right Thing(tm) when dividing two integers, returning an integer result. Bill -- INTERNET: bill at celestial.com Bill Campbell; Celestial Software LLC URL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way Voice: (206) 236-1676 Mercer Island, WA 98040-0820 Fax: (206) 232-9186 The essence of all slavery consists in taking the produce of another's labor by force. It is immaterial whether this force be founded on ownership of the slave or ownership of the money that he must get to live on. Leo Tolstoy 1891 From s4027340 at student.uq.edu.au Thu Jan 15 06:41:32 2009 From: s4027340 at student.uq.edu.au (Mr Gerard Kelly) Date: Thu, 15 Jan 2009 15:41:32 +1000 Subject: [Tutor] tkinter canvas Message-ID: I am trying to make a simple Tkinter program using the canvas widget. All it does take a number (6 in this case) and draw that number of blue boxes on a canvas. from Tkinter import * master = Tk() numboxes=6 width=40*(numboxes+2) height=200 w = Canvas(master, width=width, height=height) w.pack() size=width/(numboxes+2) box=[0]*numboxes for i in range(numboxes): box[i]=w.create_rectangle((1+i)*40, 40, (2+i)*40, height-40, fill="blue") mainloop() I want to be able to bind these boxes to an event - so that I can either click on them, or hold the mouse cursor over them, and have them change color. However I haven't been able to find any examples of related tkinter code on google, and the tutorials and documentation about binding and events with canvas items is very confusing without being able to see it used in examples. From andorphin at gmail.com Thu Jan 15 07:00:58 2009 From: andorphin at gmail.com (David Williams) Date: Wed, 14 Jan 2009 22:00:58 -0800 Subject: [Tutor] Non-blocking non-interactive graphics display Message-ID: <4a289b480901142200k3e376eaeg39de1ed8de1e239c@mail.gmail.com> Hi All, I am still getting my python legs (similar to sea legs but more scale-y) and ran across a decision that I'd like some advice on. I am looking for the simplest way of displaying a little positional data as a line graphic in a window as a script runs. Something like: #Set up some points pt1 = (0,0) pt2 = (2,1) pt3 = (3,2) #Create a window that displays the points as two lines connected at pt2 import somethingsomething #maybe something like import enthought.enable window = somethingsomething.graph_points_as_line(pt1,pt2,pt3) #Iterate for i in range(0,100): #Change the points slightly, this takes a bit of time [pt1, pt2, pt3] = update_points_with_derived_values(pt1,pt2,pt3) #Update the display window.graph_points(pt1,pt2,pt3) My problem is that using tkinter, it looks to be a bit difficult to get this to work since showing the window blocks the rest of the script from running. I am not terribly familiar with threads and keen to avoid them if they are unnecessary. The display is non-interactive and so communication with it can be one-way. Ideally I would just be able to get some interaction with a library that is similar to processing (the graphics environment) which just lets me throw some graphics primitives at it and gives me a nice window or saved file. Bonus points if it is part of the Enthought Python Distribution and pleasingly anti-aliased. Does anyone have any recommendations for a package to use for this and a pointer to a particularly good tutorial or snippet of sample code? Thanks much, Dave From agent.krycek at gmail.com Thu Jan 15 07:29:14 2009 From: agent.krycek at gmail.com (Alex Krycek) Date: Wed, 14 Jan 2009 23:29:14 -0700 Subject: [Tutor] Creating simple windows in XP Message-ID: Hello, I'd like to create very simple GUI's in XP. For the sake of simplicity, I'm trying to avoid downloading and installing anything (although I am considering EasyGui). To see how well it works, I've tried having my program run a Visual Basic script ( i.e. subprocess.call(someScript.vbs, shell = True) ). It seemed to work ok. I was just wondering if there was a better and/or easier way of doing this. Thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: From wescpy at gmail.com Thu Jan 15 08:08:53 2009 From: wescpy at gmail.com (wesley chun) Date: Wed, 14 Jan 2009 23:08:53 -0800 Subject: [Tutor] strings and int() In-Reply-To: References: Message-ID: <78b3a9580901142308ve703477ob12aa94e373a3550@mail.gmail.com> > If you have a string "6", and you do int("6"), you get the number 6. > But if you have a string "2*3" and you do int("2*3") you get a name error. the reason you get this error is because "2*3" is not a string representation of an integer whereas "6" is. in other words 2*3 is not a number. > How do you take an expression in a string, and evaluate the expression to get a number? you just said the answer yourself... *evaluate the expression*. to do just that, use the eval() built-in function. eval("2*3") takes that string, turns it into Python executable code and returns the expression that results from the evaluation of that code. hope this helps! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 "Python Fundamentals", Prentice Hall, (c)2009 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From ballerz4ishi at sbcglobal.net Thu Jan 15 08:14:16 2009 From: ballerz4ishi at sbcglobal.net (Ishan Puri) Date: Wed, 14 Jan 2009 23:14:16 -0800 (PST) Subject: [Tutor] NLTK Message-ID: <37301.92756.qm@web83304.mail.sp1.yahoo.com> Hi, I have download NLTK for Python 2.5. It download automatically to C:\Program Files\Python25\libs\site-packages\nltk. When I try to open a module in python, it says that no such module exists. What do I need to do? -------------- next part -------------- An HTML attachment was scrubbed... URL: From andreengels at gmail.com Thu Jan 15 09:05:28 2009 From: andreengels at gmail.com (Andre Engels) Date: Thu, 15 Jan 2009 09:05:28 +0100 Subject: [Tutor] strings and int() In-Reply-To: References: Message-ID: <6faf39c90901150005o7dc91624h45ff04ca36bf8088@mail.gmail.com> On Thu, Jan 15, 2009 at 1:14 AM, Mr Gerard Kelly wrote: > If you have a string "6", and you do int("6"), you get the number 6. > > But if you have a string "2*3" and you do int("2*3") you get a name error. > > How do you take an expression in a string, and evaluate the expression > to get a number? > > I want to be able to turn the string "2*3" into the number 6. There is a method for that, namely eval. eval("2*3") evaluates 2*3 as a Python expression and thus gives the integer 6. However, usage of eval is very much discouraged, because it is a very unsafe function. The problem is that a Python expression can be formed to do whatever Python can, and that's a lot. If you use it on something coming from outside the program, you open up your program to an attack by providing malevolent data. If you use it on something from inside your program, it is usually is better to look more precisely on what you are creating. Still, I guess it could be used provided that you _first_ check whether the string is of a form that does not have anything dangerous coming from it. In your case, you might execute eval only if the string that it is to be executed on consists only of numbers and the characters -+/*%(). I _think_ there is nothing bad that can happen then. -- Andr? Engels, andreengels at gmail.com From orsenthil at gmail.com Thu Jan 15 11:04:25 2009 From: orsenthil at gmail.com (Senthil Kumaran) Date: Thu, 15 Jan 2009 15:34:25 +0530 Subject: [Tutor] NLTK In-Reply-To: <37301.92756.qm@web83304.mail.sp1.yahoo.com> References: <37301.92756.qm@web83304.mail.sp1.yahoo.com> Message-ID: <7c42eba10901150204t3e7379eeqf9f78509136367fb@mail.gmail.com> > Ishan Puri wrote: > Hi, > I have download NLTK for Python 2.5. It download automatically to > C:\Program Files\Python25\libs\site-packages\nltk. When I try to open a > module in python, it says that no such module exists. What do I need to do? There are ways to install the module in the site-packages. Just downloading and copying to site-packages may not be enough. After you have downloaded the NLTK page, extract it to a separate directory, and find a file called setup.py If it is present, do python setup.py install That sould do. If setup.py is not present, locate README.txt and follow the instructions. Even after following the instructions, if you get any error message, copy/paste the error message here so that we would be able to assist you better. -- Senthil From orsenthil at gmail.com Thu Jan 15 11:13:09 2009 From: orsenthil at gmail.com (Senthil Kumaran) Date: Thu, 15 Jan 2009 15:43:09 +0530 Subject: [Tutor] eval and floating point In-Reply-To: <20090115041231.GA8730@ayn.mi.celestial.com> References: <1231986786.6496.12.camel@ltop> <20090115041231.GA8730@ayn.mi.celestial.com> Message-ID: <7c42eba10901150213k6824820ehc067cd15e1098c44@mail.gmail.com> On Thu, Jan 15, 2009 at 9:42 AM, Bill Campbell wrote: > Python does the Right Thing(tm) when dividing two integers, > returning an integer result. > Unless it is python 3k, in which integer division (single /) can result in float. Because int is a long by default. :-) -- Senthil From denis.spir at free.fr Thu Jan 15 11:54:50 2009 From: denis.spir at free.fr (spir) Date: Thu, 15 Jan 2009 11:54:50 +0100 Subject: [Tutor] traceback In-Reply-To: <200901142119.11994.w.richert@gmx.net> References: <20090114180951.6095bbb3@o> <200901142119.11994.w.richert@gmx.net> Message-ID: <20090115115450.4fcab2c6@o> Le Wed, 14 Jan 2009 21:19:11 +0100, Willi Richert a ?crit : > Hi, > > do you observe the same behavior with traceback.format_exc()? I've used that > always in such situations which worked all the time. > > Regards, > wr Actually yes, for the traceback object returned by sys.exc_info() is None. (sys.exc_info() --> (None,None,None)). Like if there was no exception raised, or like if it had been clear()ed. But when I don't catch the exception launched by a test program, I get the standard python error message and the prog stops -- which proves that there *is* an active exception. Simply, I cannot have it returned by sys.exc_info(). I will try more today to understand why/when/how this happens. As I said, in some circomstances all works well (sys.exc_info() returns a filled (type,value,traceback) tuple) but as of now I cannot understand why. Denis > Am Mittwoch, 14. Januar 2009 18:09:51 schrieb spir: > > Hello, > > > > I rather often use exceptions as information providers at design or debug > > time. A typical use of mine is to have a test version of methods that wrap > > standard version: > > > > def run(): > > do stuff > > that may > > raise exc > > def testRun(): > > try: > > run() > > except Error,error: > > sys.error.write(str(error)) > > > > So that I can run a bunch of (possibly failing) tests and still get all > > worthful info. Now, the drawback is that I then lose python provided > > traceback, as for any reason str(exc) does not return tracback, only the > > "message". To have the traceback I planned to catch the traceback manually. > > The aims whare: > > * be able to output the tracback prepended to the message, when useful > > * try to find a more readable (for me) format > > * filter it: e.g. print only last trace mark of each module > > If you have ideas on the best way to do this, thanks. > > > > I tried to use sys.exc_info() that returns a (type,value,traceback) tuple > > and the format_tb() function of the traceback module. *Sometimes* I get the > > traceback as expected and all is fine. But in most cases sys.exc_info() > > returns (None,None,None) like if there was absolutely no active exception. > > I cannot consistently reproduce the issue to make a clear diagnosis. > > > > Thank you, > > Denis > > > > ------ > > la vida e estranya > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > ------ la vida e estranya From denis.spir at free.fr Thu Jan 15 12:48:00 2009 From: denis.spir at free.fr (spir) Date: Thu, 15 Jan 2009 12:48:00 +0100 Subject: [Tutor] single key ordered sequence Message-ID: <20090115124800.6637f730@o> Hello, a little algorithmic question. I have a list of tuples element, in which the first item is a kind of key. I need a target list with only one tuple per key. But the order must be kept -- so that I cannot use a temp dictionary. Additionally, in this case the chosen element for a repeted key is the last one occurring in source list. How would you do that? I used the following method that walks through the list with indexes in top-down order, and "marks" items to delete by "None-ing" them. But this a ugly trick imo, and I find the overall method to complicated for such a simple task. There shold be a clear one-liner for that, I guess. Also, how to practically walk in reverse order in a list without copying it (e.g. items[::-1]), especially if i need both indexes and items (couldn't find with enumerate()). items = [(1,'a'),(1,'b'),(2,'a'),(3,'a'),(3,'b'),(4,'a'),(5,'a'),(5,'b'),(5,'c')] keys = [] for index in range(len(items)-1,-1,-1): key = items[index][0] if key in keys: items[index] = None else: keys.append(key) items = [item for item in items if item is not None] denis ------ la vida e estranya From richert at c-lab.de Thu Jan 15 12:02:28 2009 From: richert at c-lab.de (Willi Richert) Date: Thu, 15 Jan 2009 12:02:28 +0100 Subject: [Tutor] traceback In-Reply-To: <20090115115450.4fcab2c6@o> References: <20090114180951.6095bbb3@o> <200901142119.11994.w.richert@gmx.net> <20090115115450.4fcab2c6@o> Message-ID: <200901151202.28733.richert@c-lab.de> Hi, from http://effbot.org/pyref/sys.exc_info.htm: "The information returned is specific both to the current thread and to the current stack frame. If the current stack frame is not handling an exception, the information is taken from the calling stack frame, or its caller, and so on until a stack frame is found that is handling an exception." Maybe you are actually in two different threads? Take also a look at http://pbe.lightbird.net/traceback-module.html Regards, wr Am Donnerstag, 15. Januar 2009 11:54:50 schrieb spir: > Le Wed, 14 Jan 2009 21:19:11 +0100, > > Willi Richert a ?crit : > > Hi, > > > > do you observe the same behavior with traceback.format_exc()? I've used > > that always in such situations which worked all the time. > > > > Regards, > > wr > > Actually yes, for the traceback object returned by sys.exc_info() is None. > (sys.exc_info() --> (None,None,None)). Like if there was no exception > raised, or like if it had been clear()ed. But when I don't catch the > exception launched by a test program, I get the standard python error > message and the prog stops -- which proves that there *is* an active > exception. Simply, I cannot have it returned by sys.exc_info(). > I will try more today to understand why/when/how this happens. As I said, > in some circomstances all works well (sys.exc_info() returns a filled > (type,value,traceback) tuple) but as of now I cannot understand why. > > Denis > > > Am Mittwoch, 14. Januar 2009 18:09:51 schrieb spir: > > > Hello, > > > > > > I rather often use exceptions as information providers at design or > > > debug time. A typical use of mine is to have a test version of methods > > > that wrap standard version: > > > > > > def run(): > > > do stuff > > > that may > > > raise exc > > > def testRun(): > > > try: > > > run() > > > except Error,error: > > > sys.error.write(str(error)) > > > > > > So that I can run a bunch of (possibly failing) tests and still get all > > > worthful info. Now, the drawback is that I then lose python provided > > > traceback, as for any reason str(exc) does not return tracback, only > > > the "message". To have the traceback I planned to catch the traceback > > > manually. The aims whare: > > > * be able to output the tracback prepended to the message, when useful > > > * try to find a more readable (for me) format > > > * filter it: e.g. print only last trace mark of each module > > > If you have ideas on the best way to do this, thanks. > > > > > > I tried to use sys.exc_info() that returns a (type,value,traceback) > > > tuple and the format_tb() function of the traceback module. *Sometimes* > > > I get the traceback as expected and all is fine. But in most cases > > > sys.exc_info() returns (None,None,None) like if there was absolutely no > > > active exception. I cannot consistently reproduce the issue to make a > > > clear diagnosis. > > > > > > Thank you, > > > Denis > > > > > > ------ > > > la vida e estranya > > > _______________________________________________ > > > Tutor maillist - Tutor at python.org > > > http://mail.python.org/mailman/listinfo/tutor > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > ------ > la vida e estranya > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Dipl.-Inform. Willi Richert C-LAB - Cooperative Computing & Communication Laboratory der Universit?t Paderborn und Siemens FU.323 F?rstenallee 11 D-33102 Paderborn Tel: +49 5251 60 6120 Fax: +49 5251 60 6065 http://www.c-lab.de From alan.gauld at btinternet.com Thu Jan 15 13:00:39 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 15 Jan 2009 12:00:39 -0000 Subject: [Tutor] tkinter canvas References: Message-ID: "Mr Gerard Kelly" wrote > All it does take a number (6 in this case) and draw that number of > blue > boxes on a canvas. > > I want to be able to bind these boxes to an event - so that I can > either > click on them, or hold the mouse cursor over them, and have them > change > color. I don;t think you can bind events to an object on a canvas, the events can only be bound to the canvas. So you would need to determine which object was being highlighted using the x,y coordinates of the event at the canvas level and then manipulate the shapes accordingly. This might be easier if you create a series of shape objects and hold a list of those. You can then iterate over the list to lovcate which object contains the point and that object can update itself. This also makes handling the case of overlapping objects easier. There might be a more Tkinter'ish way of doing this but I've not come across it. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Thu Jan 15 13:08:39 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 15 Jan 2009 12:08:39 -0000 Subject: [Tutor] eval and floating point References: Message-ID: "Mr Gerard Kelly" wrote > I've noticed that the eval() function gives an integer, so > eval("3/2") > gives back 1. float(eval("3/2")) doesn't seem to work, any way to > get a > floating point number back with eval()? Move the float inside the eval: eval("float(3/2)") It's nothing to do with eval but with Python. eval just asks the interpreter to evaluate the string. Which is why you hardly ever need to use eval, you can usually work with the string in your own code and execute it that way. Alan G From alan.gauld at btinternet.com Thu Jan 15 13:04:50 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 15 Jan 2009 12:04:50 -0000 Subject: [Tutor] Non-blocking non-interactive graphics display References: <4a289b480901142200k3e376eaeg39de1ed8de1e239c@mail.gmail.com> Message-ID: "David Williams" wrote > I am looking for the simplest way of displaying a little positional > data as a line graphic in a window as a script runs. I got a bit lost in the description which followed but a couple of things stood out: > My problem is that using tkinter, it looks to be a bit difficult to > get this to work since showing the window blocks the rest of the > script from running. That shouldn't happen if your code is event driven. You manipulate the data, update the screen then stop and wait for the next evernt (which could be a timer) > I am not terribly familiar with threads and keen > to avoid them if they are unnecessary. It doesn't sound like you need threads for this. > The display is non-interactive and so communication with it > can be one-way. You still want to use events but probabnly driven by timers > Bonus points if it is part of the Enthought Python Distribution and > pleasingly anti-aliased. Sorry, I've never come across Envision before. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Thu Jan 15 13:14:16 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 15 Jan 2009 12:14:16 -0000 Subject: [Tutor] running & debugging in python interactive shell References: <496E86DB.20202@gmail.com> Message-ID: "Artie Ziff" wrote > running python scripts. Does anyone know of an article that > describes > best practices for running and debugging scripts inside the python > shell? Of course, I use import directive to run my script for first > run. > I am seeking techniques for invoking parts of script after initial > import. I hope this makes sense to those persons reading. :) Provided you have built the module as a set of functions/classes then after import you can just call those functions from the shell. You cannot invoke arbitrary lines of code (as you can in the Smalltalk workspace for example). Accessing functions etc is normal practice in the shell so I'm not sure what you are really asking here? -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk From alan.gauld at btinternet.com Thu Jan 15 13:18:46 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 15 Jan 2009 12:18:46 -0000 Subject: [Tutor] Creating simple windows in XP References: Message-ID: "Alex Krycek" wrote > I'd like to create very simple GUI's in XP. For the sake of > simplicity, I'm > trying to avoid downloading and installing anything (although I am > considering EasyGui). The basic GUI framework in Python is Tkinter and that works fine on XP. See my tutorial topic on GUI programming for a very simople intro before trying any of themore fully featured Tkinter tutorials... > To see how well it works, I've tried having my > program run a Visual Basic script ( i.e. > subprocess.call(someScript.vbs, > shell = True) ). It seemed to work ok. I was just wondering if > there was a > better and/or easier way of doing this. That does of course work but is not really you creating a GUI its just running another program. You could start Word or Excel just as easily! There are many other Python GUI frameworks, some have GUI builders somewhat like VB. But they are all downloadable add-ons. Tkinter is the only one that comes as sandard. Its primitive, but easy to learn and use for basic form style applications. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From andreengels at gmail.com Thu Jan 15 13:21:47 2009 From: andreengels at gmail.com (Andre Engels) Date: Thu, 15 Jan 2009 13:21:47 +0100 Subject: [Tutor] eval and floating point In-Reply-To: References: Message-ID: <6faf39c90901150421n6374587dl4b237dc3f9bf1803@mail.gmail.com> On Thu, Jan 15, 2009 at 1:08 PM, Alan Gauld wrote: > > "Mr Gerard Kelly" wrote > >> I've noticed that the eval() function gives an integer, so eval("3/2") >> gives back 1. float(eval("3/2")) doesn't seem to work, any way to get a >> floating point number back with eval()? > > Move the float inside the eval: > > eval("float(3/2)") That still does not work, because the 'float' comes after the division. 3/2 equals 1, so float(3/2) equals 1.0. To make it work, you'll have to put the float inside the division: eval("float(3)/2") or eval("3/float(2)") Which, as said before, is written less complicatedly as: eval("3.0/2") -- Andr? Engels, andreengels at gmail.com From kent37 at tds.net Thu Jan 15 13:24:29 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 15 Jan 2009 07:24:29 -0500 Subject: [Tutor] tkinter canvas In-Reply-To: References: Message-ID: <1c2a2c590901150424k4181b8fs94b79270d1f941c2@mail.gmail.com> On Thu, Jan 15, 2009 at 12:41 AM, Mr Gerard Kelly wrote: > I want to be able to bind these boxes to an event - so that I can either > click on them, or hold the mouse cursor over them, and have them change > color. Here is a version of your program that binds the Enter and Leave events to each box and changes the box color when the mouse is over it: ######################### from Tkinter import * master = Tk() numboxes=6 width=40*(numboxes+2) height=200 w = Canvas(master, width=width, height=height) w.pack() size=width/(numboxes+2) box=[0]*numboxes def enter(e, i): e.widget.itemconfigure(box[i], fill='red') def leave(e, i): e.widget.itemconfigure(box[i], fill='blue') for i in range(numboxes): box[i]=w.create_rectangle((1+i)*40, 40, (2+i)*40, height-40, fill="blue") w.tag_bind(box[i], '', lambda e, i=i: enter(e, i)) w.tag_bind(box[i], '', lambda e, i=i: leave(e, i)) mainloop() ####################### The 'i=i' in the lambda is needed due to the (surprising) way that variables are bound to closures; without it, every event would be bound to the same value of i. Some explanation here: http://code.activestate.com/recipes/502271/ Kent From kent37 at tds.net Thu Jan 15 13:32:05 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 15 Jan 2009 07:32:05 -0500 Subject: [Tutor] Non-blocking non-interactive graphics display In-Reply-To: <4a289b480901142200k3e376eaeg39de1ed8de1e239c@mail.gmail.com> References: <4a289b480901142200k3e376eaeg39de1ed8de1e239c@mail.gmail.com> Message-ID: <1c2a2c590901150432x57bb750m5653b9565201e9ef@mail.gmail.com> On Thu, Jan 15, 2009 at 1:00 AM, David Williams wrote: > I am looking for the simplest way of displaying a little positional > data as a line graphic in a window as a script runs. > > Something like: > > #Set up some points > pt1 = (0,0) > pt2 = (2,1) > pt3 = (3,2) > #Create a window that displays the points as two lines connected at pt2 > import somethingsomething #maybe something like import enthought.enable > window = somethingsomething.graph_points_as_line(pt1,pt2,pt3) > #Iterate > for i in range(0,100): > #Change the points slightly, this takes a bit of time > [pt1, pt2, pt3] = update_points_with_derived_values(pt1,pt2,pt3) > #Update the display > window.graph_points(pt1,pt2,pt3) > > My problem is that using tkinter, it looks to be a bit difficult to > get this to work since showing the window blocks the rest of the > script from running. A little more context might help. What is the rest of the script doing? Is it the update points that is being blocked? tkinter supports animation. Here is an example of animation in tkinter that might help: http://effbot.org/zone/tkinter-animation.htm Kent From kent37 at tds.net Thu Jan 15 13:33:47 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 15 Jan 2009 07:33:47 -0500 Subject: [Tutor] Creating simple windows in XP In-Reply-To: References: Message-ID: <1c2a2c590901150433t4f02b82fkab416c105669d97c@mail.gmail.com> On Thu, Jan 15, 2009 at 1:29 AM, Alex Krycek wrote: > Hello, > > I'd like to create very simple GUI's in XP. For the sake of simplicity, I'm > trying to avoid downloading and installing anything (although I am > considering EasyGui). To see how well it works, I've tried having my > program run a Visual Basic script ( i.e. subprocess.call(someScript.vbs, > shell = True) ). It seemed to work ok. I was just wondering if there was a > better and/or easier way of doing this. Tkinter is the only GUI framework that comes with Python. If EasyGUI meets your needs, why not use it? Kent From denis.spir at free.fr Thu Jan 15 14:19:22 2009 From: denis.spir at free.fr (spir) Date: Thu, 15 Jan 2009 14:19:22 +0100 Subject: [Tutor] traceback -- how it works? In-Reply-To: <200901142119.11994.w.richert@gmx.net> References: <20090114180951.6095bbb3@o> <200901142119.11994.w.richert@gmx.net> Message-ID: <20090115141922.17e0fdf4@o> Le Wed, 14 Jan 2009 21:19:11 +0100, Willi Richert a ?crit : > Hi, > > do you observe the same behavior with traceback.format_exc()? I've used that > always in such situations which worked all the time. > > Regards, > wr Hello again, Willi & all, I guess I got the point. I thought that tracebacks where generated when an exception occurs, and then the exception itself was in a way linked to the matching traceback. Actually I thought that because the trace path exists before the exception. But I was wrong. It seems instead that the exception is first generated and only a traceback object. Maybe python generates the traceback only when it needs to print out the exception report, a part of which beeing the traceback. As a consequence, when an exception is created, no traceback exists at all, so that it may not be possible to have custom exceptions know about their own tracbacks. I wanted for a trial to have an "Error" type print out traceback in a different form. With rather complicated tests using a project of mine, I got what seemed unpredictable results where sometimes only a traceback existed. But simply launching an Error gives this: raise Error("TEST") ==> Traceback (most recent call last): File "tools.py", line 324, in testError() File "tools.py", line 287, in testError raise Error("TEST") __main__.Error: TEST Now, if I catch the first exception by nesting it inside a try...except, I will get the traceback of the first exception inside the second one: try: print 1/0 except ZeroDivisionError,error: raise Error(str(error) + " -- CAUGHT") ==> Traceback (most recent call last): File "tools.py", line 324, in testError() File "tools.py", line 291, in testError raise Error(str(error) + " -- CAUGHT") __main__.Error: module 'tools.py'-- in testError(): line 00289: print 1/0 integer division or modulo by zero -- CAUGHT Another more complex test involving an exception generated from within en external module gives: ### module tools.py ### from throw_error import throw_error def raise_uncaught_error(): try: throw_error() except TypeError: raise Error("A set cannot hold a mutable item.") ### module throw_error.py ### from sets import Set def build_set(l): s = Set(l) def throw_error(): build_set([[1,2,3]]) ==> Traceback (most recent call last): File "tools.py", line 318, in testError() File "tools.py", line 310, in testError raise_uncaught_error() File "tools.py", line 294, in raise_uncaught_error raise Error("A set cannot hold a mutable item.") __main__.Error: module 'tools.py'-- in raise_uncaught_error(): line 00291: throw_error() module '/home/spir/prog/ospyp/throw_error.py'-- in throw_error(): line 00009: build_set([[1,2,3]]) module '/home/spir/prog/ospyp/throw_error.py'-- in build_set(): line 00006: s = Set(l) module '/usr/lib/python2.5/sets.py'-- in __init__(): line 00429: self._update(iterable) module '/usr/lib/python2.5/sets.py'-- in _update(): line 00374: data[element] = value A set cannot hold a mutable item. The python traceback is the one of the second exception (mine), while the traceback read and reformatted by my custom exception is the one of the original exception (lauched by the module sets). Which is rather interesting -- even if not what I intended to do. Now, I can catch my own exception to avoid stopping a test unit run, for instance, and only print out the exception message: def raise_caught_error(): try: raise_uncaught_error() except Error,error: print error ==> module 'tools.py'-- in raise_uncaught_error(): line 00291: throw_error() module '/home/spir/prog/ospyp/throw_error.py'-- in throw_error(): line 00009: build_set([[1,2,3]]) module '/home/spir/prog/ospyp/throw_error.py'-- in build_set(): line 00006: s = Set(l) module '/usr/lib/python2.5/sets.py'-- in __init__(): line 00429: self._update(iterable) module '/usr/lib/python2.5/sets.py'-- in _update(): line 00374: data[element] = value A set cannot hold a mutable item. thank you for your help, Denis > Am Mittwoch, 14. Januar 2009 18:09:51 schrieb spir: > > Hello, > > > > I rather often use exceptions as information providers at design or debug > > time. A typical use of mine is to have a test version of methods that wrap > > standard version: > > > > def run(): > > do stuff > > that may > > raise exc > > def testRun(): > > try: > > run() > > except Error,error: > > sys.error.write(str(error)) > > > > So that I can run a bunch of (possibly failing) tests and still get all > > worthful info. Now, the drawback is that I then lose python provided > > traceback, as for any reason str(exc) does not return tracback, only the > > "message". To have the traceback I planned to catch the traceback manually. > > The aims whare: > > * be able to output the tracback prepended to the message, when useful > > * try to find a more readable (for me) format > > * filter it: e.g. print only last trace mark of each module > > If you have ideas on the best way to do this, thanks. > > > > I tried to use sys.exc_info() that returns a (type,value,traceback) tuple > > and the format_tb() function of the traceback module. *Sometimes* I get the > > traceback as expected and all is fine. But in most cases sys.exc_info() > > returns (None,None,None) like if there was absolutely no active exception. > > I cannot consistently reproduce the issue to make a clear diagnosis. > > > > Thank you, > > Denis > > ------ la vida e estranya From kent37 at tds.net Thu Jan 15 16:24:13 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 15 Jan 2009 10:24:13 -0500 Subject: [Tutor] traceback In-Reply-To: <20090114180951.6095bbb3@o> References: <20090114180951.6095bbb3@o> Message-ID: <1c2a2c590901150724k5777eee9of35b041f1fdfb795@mail.gmail.com> On Wed, Jan 14, 2009 at 12:09 PM, spir wrote: > Hello, > > I rather often use exceptions as information providers at design or debug time. A typical use > of mine is to have a test version of methods that wrap standard version: > > def run(): > do stuff > that may > raise exc > def testRun(): > try: > run() > except Error,error: > sys.error.write(str(error)) > > So that I can run a bunch of (possibly failing) tests and still get all worthful info. You might be interested in the unittest module. It lets you create and run a series of tests, some of which may fail, while reporting errors in a useful way. My introduction is here: http://personalpages.tds.net/~kent37/kk/00014.html Kent From kent37 at tds.net Thu Jan 15 16:32:27 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 15 Jan 2009 10:32:27 -0500 Subject: [Tutor] single key ordered sequence In-Reply-To: <20090115124800.6637f730@o> References: <20090115124800.6637f730@o> Message-ID: <1c2a2c590901150732x38f6b681x6a26e0f8f0014385@mail.gmail.com> On Thu, Jan 15, 2009 at 6:48 AM, spir wrote: > I have a list of tuples element, in which the first item is a kind of key. I need a target list > with only one tuple per key. But the order must be kept -- so that I cannot use a temp dictionary. > Additionally, in this case the chosen element for a repeted key is the last one occurring in > source list. > > How would you do that? In [1]: items = [(1,'a'),(1,'b'),(2,'a'),(3,'a'),(3,'b'),(4,'a'),(5,'a'),(5,'b'),(5,'c')] In [2]: seen = set() In [3]: newItems = [] In [5]: for item in reversed(items): ...: if item[0] not in seen: ...: seen.add(item[0]) ...: newItems.append(item) In [6]: newItems Out[6]: [(5, 'c'), (4, 'a'), (3, 'b'), (2, 'a'), (1, 'b')] In [7]: newItems.reverse() In [8]: newItems Out[8]: [(1, 'b'), (2, 'a'), (3, 'b'), (4, 'a'), (5, 'c')] Or, with a somewhat hacky list comp: In [9]: seen = set() In [10]: [ item for item in reversed(items) if item[0] not in seen and not seen.add(item[0]) ] > Also, how to practically walk in reverse order in a list without copying it (e.g. items[::-1]), > especially if i need both indexes and items (couldn't find with enumerate()). See use of reversed() above. You can combine it with enumerate(): In [13]: list(enumerate(reversed(items))) Out[13]: [(0, (5, 'c')), (1, (5, 'b')), (2, (5, 'a')), (3, (4, 'a')), (4, (3, 'b')), (5, (3, 'a')), (6, (2, 'a')), (7, (1, 'b')), (8, (1, 'a'))] In [16]: list(reversed(list(enumerate(items)))) Out[16]: [(8, (5, 'c')), (7, (5, 'b')), (6, (5, 'a')), (5, (4, 'a')), (4, (3, 'b')), (3, (3, 'a')), (2, (2, 'a')), (1, (1, 'b')), (0, (1, 'a'))] Kent From broek at cc.umanitoba.ca Thu Jan 15 17:27:19 2009 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Thu, 15 Jan 2009 11:27:19 -0500 Subject: [Tutor] help with getting python to run from command prompt onWindows XP In-Reply-To: References: <496E3AFC.7030909@gmail.com> Message-ID: <496F63E7.4020401@cc.umanitoba.ca> Alan Gauld said unto the world at 14/01/09 07:34 PM: > > "Brian van den Broek" wrote > >> icon for Idle launching as expected. When run from IDLE, `print >> sys.executable' yields `C:\\Python26\\pythonw.exe'. >> He reports that C:\Python26 contains both python.exe and pythonw.exe. >> >> I've had him add the text `;C:\Python26' (without quotes) to the end >> of his Path environment variable via the Control Panel|System >> Properties way of editing Environment variables. I've had him reboot >> afterwards. > > Get him to type > > SET > env.txt > > at the DOS prompt that should list all environment variables into env.txt > > Get him to email that file to you and check what it says about PATH. > >> After all of that, he reports that an attempt to run python from the >> command prompt produces a complaint that `` `python' is not recognized >> as an internal or external command, operable program or batch file.'' > > What happens if he types > > C:PROMPT> C:\Python26\python.exe > > In other words uses the full path? Hi all, Thanks to all respondents for the input. Apologies for the delay in reply; there's a bit of a lag as I'm communicating with my friend by email, too. With the full path, python loads as expected. I'm awaiting the results of SET > env.txt as per Alan's suggestion above. If that doesn't clear it up for me, I shall report back. Thanks again, Brian vdB From broek at cc.umanitoba.ca Thu Jan 15 17:48:30 2009 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Thu, 15 Jan 2009 11:48:30 -0500 Subject: [Tutor] help with getting python to run from command prompt onWindows XP In-Reply-To: <496F63E7.4020401@cc.umanitoba.ca> References: <496E3AFC.7030909@gmail.com> <496F63E7.4020401@cc.umanitoba.ca> Message-ID: <496F68DE.8090403@cc.umanitoba.ca> Brian van den Broek said unto the world at 15/01/09 11:27 AM: > Alan Gauld said unto the world at 14/01/09 07:34 PM: >> >> "Brian van den Broek" wrote > With the full path, python loads as expected. I'm awaiting the results of > SET > env.txt > as per Alan's suggestion above. Never fails. Shortly after posting, I got an answer back from the friend I'm trying to help. The (recognized by me as) relevant bits of output are: Path=C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\Program Files\texlive\2008\bin\win32;C:\Python26 PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH There is no subsequent Path line that might be stomping on the line shown above. I'm surprised that it is `Path' rather than `PATH'. Does that matter? I'm pretty sure that my friend didn't change that, as once he got into the `Edit System Variable' dialog, he felt uncertain and sent me a screen shot before he effected any modifications; the screen shot shows `Path'. Last, the texlive entry is from an installation of latex that I guided him through right before we installed python. Invoking latex from the command line works as expected, so I conclude that the Path is not broken. > If that doesn't clear it up for me, I shall report back. Didn't and did. Thanks and best, Brian From kent37 at tds.net Thu Jan 15 18:33:26 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 15 Jan 2009 12:33:26 -0500 Subject: [Tutor] help with getting python to run from command prompt onWindows XP In-Reply-To: <496F68DE.8090403@cc.umanitoba.ca> References: <496E3AFC.7030909@gmail.com> <496F63E7.4020401@cc.umanitoba.ca> <496F68DE.8090403@cc.umanitoba.ca> Message-ID: <1c2a2c590901150933r5e3b69acsb3864460d990513c@mail.gmail.com> On Thu, Jan 15, 2009 at 11:48 AM, Brian van den Broek wrote: > The (recognized by me as) relevant bits of output are: > Path=C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\Program > Files\texlive\2008\bin\win32;C:\Python26 > PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH > > There is no subsequent Path line that might be stomping on the line shown > above. > > I'm surprised that it is `Path' rather than `PATH'. Does that matter? I don't think so, my PC has 'Path' also. I'm stumped... Kent From digitalxero at gmail.com Thu Jan 15 18:35:03 2009 From: digitalxero at gmail.com (Dj Gilcrease) Date: Thu, 15 Jan 2009 10:35:03 -0700 Subject: [Tutor] help with getting python to run from command prompt onWindows XP In-Reply-To: <496F68DE.8090403@cc.umanitoba.ca> References: <496E3AFC.7030909@gmail.com> <496F63E7.4020401@cc.umanitoba.ca> <496F68DE.8090403@cc.umanitoba.ca> Message-ID: if he just needs to run python scripts you just need to type the script name (preferably from the directory it is in) eg: C:\Path\To\App>app_name.py and it will run Also if you have changed the enviromental variables, you need to close the command prompt and re-open it on windows since it does not propagate to existing instances Dj Gilcrease OpenRPG Developer ~~http://www.openrpg.com On Thu, Jan 15, 2009 at 9:48 AM, Brian van den Broek wrote: > Brian van den Broek said unto the world at 15/01/09 11:27 AM: >> >> Alan Gauld said unto the world at 14/01/09 07:34 PM: >>> >>> "Brian van den Broek" wrote > > prompt and replies including Alan's suggestion to get a text file dump of > environment variables.> > >> With the full path, python loads as expected. I'm awaiting the results of >> SET > env.txt >> as per Alan's suggestion above. > > Never fails. Shortly after posting, I got an answer back from the friend I'm > trying to help. > > The (recognized by me as) relevant bits of output are: > Path=C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\Program > Files\texlive\2008\bin\win32;C:\Python26 > PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH > > There is no subsequent Path line that might be stomping on the line shown > above. > > I'm surprised that it is `Path' rather than `PATH'. Does that matter? I'm > pretty sure that my friend didn't change that, as once he got into the `Edit > System Variable' dialog, he felt uncertain and sent me a screen shot before > he effected any modifications; the screen shot shows `Path'. > > Last, the texlive entry is from an installation of latex that I guided him > through right before we installed python. Invoking latex from the command > line works as expected, so I conclude that the Path is not broken. > >> If that doesn't clear it up for me, I shall report back. > > Didn't and did. > > Thanks and best, > > Brian > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From orsenthil at gmail.com Thu Jan 15 18:38:45 2009 From: orsenthil at gmail.com (Senthil Kumaran) Date: Thu, 15 Jan 2009 23:08:45 +0530 Subject: [Tutor] Python3.0 and Tkinter on ubuntu 8.10 HOWTO Message-ID: <20090115173845.GA7200@goofy> On Wed, Jan 14, 2009 at 03:38:20PM -0500, Vern Ceder wrote: > Since there was some interest in the question of how to get a full > Python 3.0, including Tkinter and IDLE, compiled on Ubuntu Intrepid > 8.10, I've written up what I've done and posted it at > http://learnpython.wordpress.com/2009/01/14/installing-python-30-on-ubuntu/ > Good explaination! You can also make a note about make fullinstall, which will make Python 3.0 as the default And also mention about python binary being present as python2.5,python2.6 and python3.0 when more than one version is installed. Thanks, Senthil -- Senthil Kumaran O.R. http://uthcode.sarovar.org From marc.tompkins at gmail.com Thu Jan 15 18:54:29 2009 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Thu, 15 Jan 2009 09:54:29 -0800 Subject: [Tutor] help with getting python to run from command prompt onWindows XP In-Reply-To: References: <496E3AFC.7030909@gmail.com> <496F63E7.4020401@cc.umanitoba.ca> <496F68DE.8090403@cc.umanitoba.ca> Message-ID: <40af687b0901150954l39647ac0x6f78965e2aebcc3d@mail.gmail.com> On Thu, Jan 15, 2009 at 9:35 AM, Dj Gilcrease wrote: > if he just needs to run python scripts you just need to type the > script name (preferably from the directory it is in) > > eg: C:\Path\To\App>app_name.py > > and it will run > By default, and on most people's machines, not true. You can double-click on a .py script from the GUI, and if your file associations are set correctly then Python (or PythonW) will be invoked - but from the command line, not so much. HOWEVER: if you add ";.PY;.PYW" to the end of your PATHEXT string, then this will work. (Just tried it out on my machine and wonder why I never did before.) Unfortunately, this still requires that Windows be able to find "python.exe" or "pythonw.exe" in the system path... so it's nifty, but doesn't solve the OP's problem. -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From orsenthil at gmail.com Thu Jan 15 18:56:39 2009 From: orsenthil at gmail.com (Senthil Kumaran) Date: Thu, 15 Jan 2009 23:26:39 +0530 Subject: [Tutor] single key ordered sequence Message-ID: <20090115175639.GB7200@goofy> > Also, how to practically walk in reverse order in a list without > copying it (e.g. items[::-1]), > especially if i need both indexes and items (couldn't find with > enumerate()). > Are you looking for reversed()? The way you are doing it is probably OK. But it can be simplified thus: keys = [] target = [] for item in reversed(items): if not item[0] in keys: keys.append(item[0]) target.append(item) print target If this is not what you wanted,then I have misunderstood your requirement and just based it on your code. Thanks, Senthil From marc.tompkins at gmail.com Thu Jan 15 19:07:23 2009 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Thu, 15 Jan 2009 10:07:23 -0800 Subject: [Tutor] help with getting python to run from command prompt onWindows XP In-Reply-To: <496F68DE.8090403@cc.umanitoba.ca> References: <496E3AFC.7030909@gmail.com> <496F63E7.4020401@cc.umanitoba.ca> <496F68DE.8090403@cc.umanitoba.ca> Message-ID: <40af687b0901151007jb8349d4u5bf4d1aa84ff5527@mail.gmail.com> On Thu, Jan 15, 2009 at 8:48 AM, Brian van den Broek wrote: > > The (recognized by me as) relevant bits of output are: > Path=C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\Program > Files\texlive\2008\bin\win32;C:\Python26 > PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH > > There is no subsequent Path line that might be stomping on the line shown > above. > New thought: could this be some sort of long-filename/short-filename weirdness? What happens if you have your friend do the following: > C:\>dir /x py* > Volume in drive C has no label. > Volume Serial Number is E400-17CA > > Directory of C:\ > > 2008-09-22 10:24 PM Python26 > 0 File(s) 0 bytes > 1 Dir(s) 9,809,756,160 bytes free > See that long empty space between "" and "Python26"? That means that there's no fake short filename associated with "Python26", which is what we expect - "Python26" is less than eight characters and has no spaces. However, funky things can happen during installation, and I have seen cases where filenames that _look_ normal STILL get fake short filenames associated with them. If you see anything between "" and "Python26" on your friend's machine (it would probably look like PYTHON~1.0, or something similar), then try putting (whatever it is) into the Path instead... -- www.fsrtechnologies.com p.s. - Full disclosure - I actually still have Python 2.5.1, so my directory is actually "Python25". Shouldn't matter, but wanted to disclose that. -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Jan 15 19:20:24 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 15 Jan 2009 18:20:24 -0000 Subject: [Tutor] eval and floating point References: <6faf39c90901150421n6374587dl4b237dc3f9bf1803@mail.gmail.com> Message-ID: "Andre Engels" wrote >> eval("float(3/2)") > > That still does not work, because the 'float' comes after the > division. 3/2 equals 1, so float(3/2) equals 1.0. To make it work, > you'll have to put the float inside the division: > > eval("float(3)/2") Ahem! Quite. That was what I actually intended to post! But having seen the other posts suggesting using future I had a rethink. I don't think either float() or the "3.0" approach will help the OP because I suspect he is trying to eval a string stored in a variable. In that case the "import future" trick is probably the only solution that will work, short of parsing the string and doing the division without using eval... HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From srilyk at gmail.com Thu Jan 15 19:20:45 2009 From: srilyk at gmail.com (W W) Date: Thu, 15 Jan 2009 12:20:45 -0600 Subject: [Tutor] running & debugging in python interactive shel In-Reply-To: References: <496E86DB.20202@gmail.com> Message-ID: <333efb450901151020i2f86dc6v2a7eb4f6da050711@mail.gmail.com> On Wed, Jan 14, 2009 at 8:18 PM, Che M wrote: > > I'd like to add to this question and expand it: can anyone point me to > a good resource on debugging *generally*? > The first result on "Debugger tutorial" on google sent me to this: http://www.cs.princeton.edu/~benjasik/gdb/gdbtut.html Though it's for a specific program, it seems to have some good general purpose advice. Personally, I've never had the need for a debugger (maybe because I'm not writing complicated enough programs) - a simple "print" statement (in the right spot) tends to take care of all of my debugging needs. -Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From wescpy at gmail.com Thu Jan 15 19:28:27 2009 From: wescpy at gmail.com (wesley chun) Date: Thu, 15 Jan 2009 10:28:27 -0800 Subject: [Tutor] eval and floating point In-Reply-To: References: <6faf39c90901150421n6374587dl4b237dc3f9bf1803@mail.gmail.com> Message-ID: <78b3a9580901151028meff495arbc201db004b91d15@mail.gmail.com> >>> eval("float(3/2)") >> >> That still does not work, because the 'float' comes after the >> division. 3/2 equals 1, so float(3/2) equals 1.0. To make it work, >> you'll have to put the float inside the division: >> eval("float(3)/2") correct. as long as one of the operands is a float, the division will be (or rather, the division *won't* be integer), i.e., "3./2" or "3/2.". > the "import future" trick is probably the only solution that will work, > short of parsing the string and doing the division without using eval... in addition to the import of division from __future__, which adds one extra line of code to all your source files which need this functionality, you can also use -Qnew to launch the interpreter, which defaults to the 3.x true division semantics: $ python -Qnew Python 2.4.5 (#1, May 9 2008, 12:23:22) [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> 3/2 1.5 hope this helps! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 "Python Fundamentals", Prentice Hall, (c)2009 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From alan.gauld at btinternet.com Thu Jan 15 19:28:37 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 15 Jan 2009 18:28:37 -0000 Subject: [Tutor] tkinter canvas References: <1c2a2c590901150424k4181b8fs94b79270d1f941c2@mail.gmail.com> Message-ID: "Kent Johnson" wrote > for i in range(numboxes): > box[i]=w.create_rectangle((1+i)*40, 40, (2+i)*40, height-40, > fill="blue") > w.tag_bind(box[i], '', lambda e, i=i: enter(e, i)) > w.tag_bind(box[i], '', lambda e, i=i: leave(e, i)) I'm wrong again. I've never noticed tag_bind() before. Although on investigation it is used by Grayson in his Tkinter book... I notice it can also be used in the Text widget to catch events on specific items of text or embedded images etc. Nice. Alan G From alan.gauld at btinternet.com Thu Jan 15 19:36:29 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 15 Jan 2009 18:36:29 -0000 Subject: [Tutor] help with getting python to run from command prompt onWindows XP References: <496E3AFC.7030909@gmail.com> <496F63E7.4020401@cc.umanitoba.ca> <496F68DE.8090403@cc.umanitoba.ca> Message-ID: "Brian van den Broek" wrote > The (recognized by me as) relevant bits of output are: > Path=C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\Program > Files\texlive\2008\bin\win32;C:\Python26 > PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH That looks OK. Puzzling! Scraping the barrel here but he is definitely using a command prompt to type the command? ie He is not using Start->Run? The latter has a different registry based, way of determining the path. Otherwise I'm baffled! Alan G From agent.krycek at gmail.com Thu Jan 15 19:47:32 2009 From: agent.krycek at gmail.com (Alex Krycek) Date: Thu, 15 Jan 2009 11:47:32 -0700 Subject: [Tutor] Creating simple windows in XP In-Reply-To: <1c2a2c590901150433t4f02b82fkab416c105669d97c@mail.gmail.com> References: <1c2a2c590901150433t4f02b82fkab416c105669d97c@mail.gmail.com> Message-ID: Thanks for the suggestions guys. I had looked at Tkinter before and liked that it comes w/ Python. It's just that it's so complex writing anything. EasyGui is pretty simple, but I relying on standard tools. I liked how in VB, for example, to open a dialog box you could write: MsgBox("Text", vbOKOnly, "Title"). I'll probably go with EasyGui. Thanks again. On Thu, Jan 15, 2009 at 5:33 AM, Kent Johnson wrote: > On Thu, Jan 15, 2009 at 1:29 AM, Alex Krycek > wrote: > > Hello, > > > > I'd like to create very simple GUI's in XP. For the sake of simplicity, > I'm > > trying to avoid downloading and installing anything (although I am > > considering EasyGui). To see how well it works, I've tried having my > > program run a Visual Basic script ( i.e. subprocess.call(someScript.vbs, > > shell = True) ). It seemed to work ok. I was just wondering if there was > a > > better and/or easier way of doing this. > > Tkinter is the only GUI framework that comes with Python. If EasyGUI > meets your needs, why not use it? > > Kent > -------------- next part -------------- An HTML attachment was scrubbed... URL: From jervisau at gmail.com Thu Jan 15 21:44:52 2009 From: jervisau at gmail.com (Jervis Whitley) Date: Fri, 16 Jan 2009 07:44:52 +1100 Subject: [Tutor] single key ordered sequence In-Reply-To: <20090115175639.GB7200@goofy> References: <20090115175639.GB7200@goofy> Message-ID: <8e63a5ce0901151244n5689fd4amd710888721aef287@mail.gmail.com> On Fri, Jan 16, 2009 at 4:56 AM, Senthil Kumaran wrote: > > Also, how to practically walk in reverse order in a list without > > copying it (e.g. items[::-1]), > > especially if i need both indexes and items (couldn't find with > > enumerate()). > > > Are you looking for reversed()? > The way you are doing it is probably OK. > But it can be simplified thus: > > keys = [] > target = [] > > for item in reversed(items): > if not item[0] in keys: > keys.append(item[0]) > target.append(item) > > print target > > If this is not what you wanted,then I have misunderstood your > requirement and just based it on your code. > > Thanks, > Senthil > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > how about this: items = [(1,'a'),(1,'b'),(2,'a'),(3,'a'), (3,'b'),(4,'a'),(5,'a'),(5,'b'),(5,'c')] mydict = dict(items) items = [item for item in mydict.iteritems()] testing shows: C:\WINDOWS\system32\cmd.exe /c python test_time.py **ORIGINAL** s = """ items = [(1,'a'),(1,'b'),(2,'a'),(3,'a'), (3,'b'),(4,'a'),(5,'a'),(5,'b'),(5,'c')] keys = [] for index in range(len(items)-1,-1,-1): key = items[index][0] if key in keys: items[index] = None else: keys.append(key) items = [item for item in items if item is not None] """ timeit.Timer(stmt=s).timit() 5.40928835422 **Test1** s = """ items = [(1,'a'),(1,'b'),(2,'a'),(3,'a'), (3,'b'),(4,'a'),(5,'a'),(5,'b'),(5,'c')] keys = [] for item in reversed(items): key = item[0] if key in keys: items.remove(item) else: keys.append(key) #items = [item for item in items if item is not None] """ timeit.Timer(stmt=s).timit() 5.02896436267 **Test2** s= """ items = [(1,'a'),(1,'b'),(2,'a'),(3,'a'), (3,'b'),(4,'a'),(5,'a'),(5,'b'),(5,'c')] keys = dict(items) items = [item for item in keys.iteritems()] """ timeit.Timer(stmt=s).timit() 3.38715506199 Hit any key to close this window... -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Thu Jan 15 23:15:12 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 15 Jan 2009 17:15:12 -0500 Subject: [Tutor] single key ordered sequence In-Reply-To: <8e63a5ce0901151244n5689fd4amd710888721aef287@mail.gmail.com> References: <20090115175639.GB7200@goofy> <8e63a5ce0901151244n5689fd4amd710888721aef287@mail.gmail.com> Message-ID: <1c2a2c590901151415l15b59885ud45b1d69df349f2d@mail.gmail.com> On Thu, Jan 15, 2009 at 3:44 PM, Jervis Whitley wrote: > how about this: > items = [(1,'a'),(1,'b'),(2,'a'),(3,'a'), > (3,'b'),(4,'a'),(5,'a'),(5,'b'),(5,'c')] > mydict = dict(items) > items = [item for item in mydict.iteritems()] That only coincidentally preserves order; the order of items in a dictionary is, for practical purposes, unpredictable. BTW [item for item in mydict.iteritems()] can be written as just mydict.items(). Kent From denis.spir at free.fr Thu Jan 15 23:29:48 2009 From: denis.spir at free.fr (spir) Date: Thu, 15 Jan 2009 23:29:48 +0100 Subject: [Tutor] traceback again: __traceback__ arg for exceptions in py3.0 Message-ID: <20090115232948.67b3ebfd@o> I just discovered the following: PEP 3134: Exception objects now store their traceback as the __traceback__ attribute. This means that an exception object now contains all the information pertaining to an exception, and there are fewer reasons to use sys.exc_info() (though the latter is not removed). in http://docs.python.org/dev/3.0/whatsnew/3.0.html denis ------ la vida e estranya From kent37 at tds.net Thu Jan 15 23:33:41 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 15 Jan 2009 17:33:41 -0500 Subject: [Tutor] indented grammar parsing In-Reply-To: <20090111191153.16a0b805@o> References: <20090111191153.16a0b805@o> Message-ID: <1c2a2c590901151433w6936d236v79826d636048a850@mail.gmail.com> On Sun, Jan 11, 2009 at 1:11 PM, spir wrote: > Hello, > > this is a rather specific question about parsing an indented grammar. > I have a working implementation (presented below) that may be worth a critic review -- if you like > it. > > First issue is: is there a way to express an indented formatfing using a common grammar > language such as BNF (or regex)? If yes, how to do that? If not, what kind of formal grammar is > actually such a format? Is there any standard way to express it? > > I guess from this text that python parsers have a pre-parse phase that generate the so-called > INDENT and DEDENT tokens -- which are then used during actual parsing. It's pretty common for parsers to be implemented in two phases, lexical scanning and actual parsing. The lexical scanner recognizes patterns in the source file and outputs a sequence of tokens. The parser analyzes the tokens, not the actual source text. So for the Python lexical scanner to emit INDENT and DEDENT tokens doesn't seem that strange to me. Kent From ksarikhani at gmail.com Thu Jan 15 23:38:21 2009 From: ksarikhani at gmail.com (Kayvan Sarikhani) Date: Thu, 15 Jan 2009 17:38:21 -0500 Subject: [Tutor] Opsware Global Shell Scripting In-Reply-To: References: Message-ID: Hello...thanks to several individuals, I've been able to get a little farther in this Opsware global shell script: #!/usr/bin/python import os outfile = open('test.txt','w') for servername in os.listdir('/opsw/Server/@'): print '---', servername print >> outfile, '---', servername rosh = 'rosh -n %s -l $LOGNAME \ date' % (servername) os.system(rosh) outfile.close() This does most of what I need, but I've run into two issues. 1) After it uses the rosh command to remotely access a managed system, it executes the "date" command...but I need to be able to direct the date output to the outfile. I imagine it's probably going to be similar to how it directs output of the servernames, but still not quite sure how this fits in the scheme of this command. 2) Some connection attempts to systems just hang...not really sure why (yet), but I'd like to be able to specify some kind of timeout so that it executes the rosh command, and if it doesn't connect in 10 seconds, breaks the connection, and moves on to the next server in the list. I've read that there is some kind of a built-in timeout function, but I'm quite stumped on this one. If anyone has any suggestions or pointers, I'd really appreciate it. Thanks very much! K -------------- next part -------------- An HTML attachment was scrubbed... URL: From jervisau at gmail.com Thu Jan 15 23:36:05 2009 From: jervisau at gmail.com (Jervis Whitley) Date: Fri, 16 Jan 2009 09:36:05 +1100 Subject: [Tutor] single key ordered sequence In-Reply-To: <1c2a2c590901151415l15b59885ud45b1d69df349f2d@mail.gmail.com> References: <20090115175639.GB7200@goofy> <8e63a5ce0901151244n5689fd4amd710888721aef287@mail.gmail.com> <1c2a2c590901151415l15b59885ud45b1d69df349f2d@mail.gmail.com> Message-ID: <8e63a5ce0901151436y1ed97353s4c8511de03b8a02a@mail.gmail.com> On Fri, Jan 16, 2009 at 9:15 AM, Kent Johnson wrote: > On Thu, Jan 15, 2009 at 3:44 PM, Jervis Whitley > wrote: > > how about this: > > items = [(1,'a'),(1,'b'),(2,'a'),(3,'a'), > > (3,'b'),(4,'a'),(5,'a'),(5,'b'),(5,'c')] > > mydict = dict(items) > > items = [item for item in mydict.iteritems()] > > That only coincidentally preserves order; the order of items in a > dictionary is, for practical purposes, unpredictable. > > BTW [item for item in mydict.iteritems()] can be written as just > mydict.items(). > > Kent I realise that what you have said is true, however can you show me a case where > items = dict(items).items() will not preserve order? Thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: From pine508 at hotmail.com Thu Jan 15 23:56:50 2009 From: pine508 at hotmail.com (Che M) Date: Thu, 15 Jan 2009 17:56:50 -0500 Subject: [Tutor] running & debugging in python interactive shel In-Reply-To: <333efb450901151020i2f86dc6v2a7eb4f6da050711@mail.gmail.com> References: <496E86DB.20202@gmail.com> <333efb450901151020i2f86dc6v2a7eb4f6da050711@mail.gmail.com> Message-ID: Date: Thu, 15 Jan 2009 12:20:45 -0600 From: srilyk at gmail.com To: pine508 at hotmail.com Subject: Re: [Tutor] running & debugging in python interactive shel CC: tutor at python.org On Wed, Jan 14, 2009 at 8:18 PM, Che M wrote: >> I'd like to add to this question and expand it: can anyone point me to >> a good resource on debugging *generally*? > The first result on "Debugger tutorial" on google sent me to this: > http://www.cs.princeton.edu/~benjasik/gdb/gdbtut.html > Though it's for a specific program, it seems to have some good general purpose advice. > Personally, I've never had the need for a debugger (maybe because I'm not writing complicated > enough programs) - a simple "print" statement (in the right spot) tends to take care of all of my > debugging needs. That page didn't strike me as very helpful for my case, but thanks anyway. I'll Google for it, too, but just wondered if any of the tutors here had any recommendations. I just checked Alan Gauld's tutorial and I see it doesn't have a debugger section (completely understandably, as this is sort of advanced). I also use print statements a fair bit. I've just heard that using a debugger is a very useful thing and I thought maybe someone would have some tips here or knew of a good Python-relevant tutorial about it. Thanks, Che -Wayne _________________________________________________________________ Windows Live?: Keep your life in sync. http://windowslive.com/explore?ocid=TXT_TAGLM_WL_t1_allup_explore_012009 From broek at cc.umanitoba.ca Fri Jan 16 00:05:53 2009 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Thu, 15 Jan 2009 18:05:53 -0500 Subject: [Tutor] help with getting python to run from command prompt onWindows XP In-Reply-To: <1c2a2c590901150933r5e3b69acsb3864460d990513c@mail.gmail.com> References: <496E3AFC.7030909@gmail.com> <496F63E7.4020401@cc.umanitoba.ca> <496F68DE.8090403@cc.umanitoba.ca> <1c2a2c590901150933r5e3b69acsb3864460d990513c@mail.gmail.com> Message-ID: <496FC151.3030005@cc.umanitoba.ca> Kent Johnson said unto the world at 15/01/09 12:33 PM: > On Thu, Jan 15, 2009 at 11:48 AM, Brian van den Broek > wrote: >> The (recognized by me as) relevant bits of output are: >> Path=C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\Program >> Files\texlive\2008\bin\win32;C:\Python26 >> PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH >> >> There is no subsequent Path line that might be stomping on the line shown >> above. >> >> I'm surprised that it is `Path' rather than `PATH'. Does that matter? > > I don't think so, my PC has 'Path' also. I'm stumped... > > Kent Hi all, Thanks for the further replies. As consensus seems to be there's nothing obvious to explain the problem, it's either going to be that my (relatively unsophisticated about computers) friend and I had a miscommunication over email or there is something at play that I won't be able to discern remotely. I'll have him verify all steps again and then call `gremlins'. Thanks for the help, Brian vdB From bgailer at gmail.com Fri Jan 16 00:39:07 2009 From: bgailer at gmail.com (bob gailer) Date: Thu, 15 Jan 2009 18:39:07 -0500 Subject: [Tutor] single key ordered sequence In-Reply-To: <8e63a5ce0901151436y1ed97353s4c8511de03b8a02a@mail.gmail.com> References: <20090115175639.GB7200@goofy> <8e63a5ce0901151244n5689fd4amd710888721aef287@mail.gmail.com> <1c2a2c590901151415l15b59885ud45b1d69df349f2d@mail.gmail.com> <8e63a5ce0901151436y1ed97353s4c8511de03b8a02a@mail.gmail.com> Message-ID: <496FC91B.9040400@gmail.com> Jervis Whitley wrote: > > > On Fri, Jan 16, 2009 at 9:15 AM, Kent Johnson > wrote: > > On Thu, Jan 15, 2009 at 3:44 PM, Jervis Whitley > > wrote: > > how about this: > > items = [(1,'a'),(1,'b'),(2,'a'),(3,'a'), > > (3,'b'),(4,'a'),(5,'a'),(5,'b'),(5,'c')] > > mydict = dict(items) > > items = [item for item in mydict.iteritems()] > > That only coincidentally preserves order; the order of items in a > dictionary is, for practical purposes, unpredictable. > > BTW [item for item in mydict.iteritems()] can be written as just > mydict.items(). > > Kent > > I realise that what you have said is true, however > can you show me a case where > > > items = dict(items).items() > > will not preserve order? Thanks. > On my computer: >>> dict((('z', 1), ('y', 2))).items() [('y', 2), ('z', 1)] -- Bob Gailer Chapel Hill NC 919-636-4239 From alan.gauld at btinternet.com Fri Jan 16 00:45:01 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 15 Jan 2009 23:45:01 -0000 Subject: [Tutor] Creating simple windows in XP References: <1c2a2c590901150433t4f02b82fkab416c105669d97c@mail.gmail.com> Message-ID: "Alex Krycek" wrote > EasyGui is pretty simple, but I relying on standard tools. I liked > how in > VB, for example, to open a dialog box you could write: > > MsgBox("Text", vbOKOnly, "Title"). > You mean like doing import tkMessageBox tkMessageBox.showinfo("Window Text", "A short message") in Tkinter? :-) OR res = tkMessageBox.askokcancel("Which?", "Ready to stop?") print res At that level Tkinter is pretty easy too. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Fri Jan 16 00:50:56 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 15 Jan 2009 23:50:56 -0000 Subject: [Tutor] running & debugging in python interactive shel References: <496E86DB.20202@gmail.com> <333efb450901151020i2f86dc6v2a7eb4f6da050711@mail.gmail.com> Message-ID: "Che M" wrote > tutors here had any recommendations. I just checked Alan Gauld's > tutorial and I see it doesn't have a debugger section (completely You need to get a copy of the paper book, it has a chapter on debugging, starting with print statements and going through to the Python debugger and finally the IDLE debugger - but that is only available in the book... Alan G From jervisau at gmail.com Fri Jan 16 00:52:52 2009 From: jervisau at gmail.com (Jervis Whitley) Date: Fri, 16 Jan 2009 10:52:52 +1100 Subject: [Tutor] single key ordered sequence In-Reply-To: <496FC91B.9040400@gmail.com> References: <20090115175639.GB7200@goofy> <8e63a5ce0901151244n5689fd4amd710888721aef287@mail.gmail.com> <1c2a2c590901151415l15b59885ud45b1d69df349f2d@mail.gmail.com> <8e63a5ce0901151436y1ed97353s4c8511de03b8a02a@mail.gmail.com> <496FC91B.9040400@gmail.com> Message-ID: <8e63a5ce0901151552ne20cb3djf6080c6a2c0aeb6@mail.gmail.com> On Fri, Jan 16, 2009 at 10:39 AM, bob gailer wrote: > Jervis Whitley wrote: > >> >> >> On Fri, Jan 16, 2009 at 9:15 AM, Kent Johnson > kent37 at tds.net>> wrote: >> >> On Thu, Jan 15, 2009 at 3:44 PM, Jervis Whitley >> > wrote: >> > how about this: >> > items = [(1,'a'),(1,'b'),(2,'a'),(3,'a'), >> > (3,'b'),(4,'a'),(5,'a'),(5,'b'),(5,'c')] >> > mydict = dict(items) >> > items = [item for item in mydict.iteritems()] >> >> That only coincidentally preserves order; the order of items in a >> dictionary is, for practical purposes, unpredictable. >> >> BTW [item for item in mydict.iteritems()] can be written as just >> mydict.items(). >> >> Kent >> >> I realise that what you have said is true, however can you show me a case >> where >> > items = dict(items).items() >> >> will not preserve order? Thanks. >> >> > On my computer: > > >>> dict((('z', 1), ('y', 2))).items() > [('y', 2), ('z', 1)] > > -- > Bob Gailer > Chapel Hill NC > 919-636-4239 > Same on mine, thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Fri Jan 16 00:53:00 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 15 Jan 2009 23:53:00 -0000 Subject: [Tutor] help with getting python to run from command prompt onWindows XP References: <496E3AFC.7030909@gmail.com> <496F63E7.4020401@cc.umanitoba.ca><496F68DE.8090403@cc.umanitoba.ca><1c2a2c590901150933r5e3b69acsb3864460d990513c@mail.gmail.com> <496FC151.3030005@cc.umanitoba.ca> Message-ID: "Brian van den Broek" wrote > I'll have him verify all steps again and then call `gremlins'. One last thing to try is to get him to send a screen shot with the error message showing. That will prove that he is using the right type of console, typing the right command and reporting the right error! Beyond that I think we are beaten... Alan G From s4027340 at student.uq.edu.au Fri Jan 16 02:00:30 2009 From: s4027340 at student.uq.edu.au (Mr Gerard Kelly) Date: Fri, 16 Jan 2009 11:00:30 +1000 Subject: [Tutor] tkinter canvas Message-ID: <505129e3.29e35051@uq.edu.au> wow, that's excellent, thanks so much. I haven't got a clue how lambda functions work, but they seem pretty useful, so I'll try to figure them out. ----- Original Message ----- From: Kent Johnson Date: Thursday, January 15, 2009 10:24 pm Subject: Re: [Tutor] tkinter canvas > On Thu, Jan 15, 2009 at 12:41 AM, Mr Gerard Kelly > wrote: > > > I want to be able to bind these boxes to an event - so that I can > either> click on them, or hold the mouse cursor over them, and have > them change > > color. > > Here is a version of your program that binds the Enter and Leave > events to each box and changes the box color when the mouse is over > it: > > ######################### > > from Tkinter import * > > master = Tk() > > numboxes=6 > > width=40*(numboxes+2) > height=200 > w = Canvas(master, width=width, height=height) > w.pack() > > size=width/(numboxes+2) > > box=[0]*numboxes > > def enter(e, i): > e.widget.itemconfigure(box[i], fill='red') > > def leave(e, i): > e.widget.itemconfigure(box[i], fill='blue') > > for i in range(numboxes): > box[i]=w.create_rectangle((1+i)*40, 40, (2+i)*40, height-40, > fill="blue") w.tag_bind(box[i], '', lambda e, i=i: > enter(e, i)) > w.tag_bind(box[i], '', lambda e, i=i: leave(e, i)) > > mainloop() > > ####################### > > The 'i=i' in the lambda is needed due to the (surprising) way that > variables are bound to closures; without it, every event would be > bound to the same value of i. Some explanation here: > http://code.activestate.com/recipes/502271/ > > Kent > From jervisau at gmail.com Fri Jan 16 02:09:43 2009 From: jervisau at gmail.com (Jervis Whitley) Date: Fri, 16 Jan 2009 12:09:43 +1100 Subject: [Tutor] running & debugging in python interactive she In-Reply-To: References: <496E86DB.20202@gmail.com> <333efb450901151020i2f86dc6v2a7eb4f6da050711@mail.gmail.com> Message-ID: <8e63a5ce0901151709y36391e36gb02a1cb89b9ec835@mail.gmail.com> On Fri, Jan 16, 2009 at 9:56 AM, Che M wrote: > > > > >> I'd like to add to this question and expand it: can anyone point me to > >> a good resource on debugging *generally*? > > The first result on "Debugger tutorial" on google sent me to this: > > > http://www.cs.princeton.edu/~benjasik/gdb/gdbtut.html > > > Though it's for a specific program, it seems to have some good general > purpose advice. > > Personally, I've never had the need for a debugger (maybe because I'm not > writing complicated > > enough programs) - a simple "print" statement (in the right spot) tends > to take care of all of my > > debugging needs. > > That page didn't strike me as very helpful for my case, but thanks > anyway. I'll Google for it, too, but just wondered if any of the > tutors here had any recommendations. I just checked Alan Gauld's > tutorial and I see it doesn't have a debugger section (completely > understandably, as this is sort of advanced). > > I also use print statements a fair bit. I've just heard that using > a debugger is a very useful thing and I thought maybe someone would > have some tips here or knew of a good Python-relevant tutorial about it. > > Thanks, > Che > > > -Wayne > > I did a search for 'python pdb tutorial' and found this resource: http://www.ferg.org/papers/debugging_in_python.html pdb is the python debugger, this tutorial will give you more than enough to get started. Cheers, -------------- next part -------------- An HTML attachment was scrubbed... URL: From dorseye at gmail.com Fri Jan 16 02:57:09 2009 From: dorseye at gmail.com (Eric Dorsey) Date: Thu, 15 Jan 2009 18:57:09 -0700 Subject: [Tutor] 2 & 4 or more spaces per indentation level.. Message-ID: Dear Pythonistas: Working in IDLE on Windows Vista, I have one program that I set to have 2 character spacing (due to the levels of if's and while's going on -- later my brother called this a bit of a code smell, ie. logic shouldn't go that deep, it should be broken out into separate functions instead. Thoughts on that are welcome to, do any of you feel logic should only go so many layers deep?), and my editor defaults to 4 (Which I believe is the standard according to PEP 8) I copied some code from the 2 spacing program to another I'm writing currently which has the default 4, and it got things kind of screwy with spacing. I believe I've got it fixed now by manually tabbing/spacing, etc., but I was wondering, if this happened on a much bigger scale, or you were say, pasting code in from some example where they used a different spacing than you, is there a simple/good/smart way to get it all back to the 4 spacing default? Or if for example I wanted to convert my 2 spacing program to the conventional 4? - Eric -------------- next part -------------- An HTML attachment was scrubbed... URL: From ballerz4ishi at sbcglobal.net Fri Jan 16 04:41:04 2009 From: ballerz4ishi at sbcglobal.net (Ishan Puri) Date: Thu, 15 Jan 2009 19:41:04 -0800 (PST) Subject: [Tutor] Corpora Message-ID: <892765.78280.qm@web83301.mail.sp1.yahoo.com> Hi, I was wondering if anyone could tell me where I can get corpora containing IMs, or blogs or any internet communication? This is kind of urgent. Thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: From orsenthil at gmail.com Fri Jan 16 04:41:06 2009 From: orsenthil at gmail.com (Senthil Kumaran) Date: Fri, 16 Jan 2009 09:11:06 +0530 Subject: [Tutor] 2 & 4 or more spaces per indentation level.. In-Reply-To: References: Message-ID: <20090116034106.GA9987@goofy> On Thu, Jan 15, 2009 at 06:57:09PM -0700, Eric Dorsey wrote: > Working in IDLE on Windows Vista, I have one program that I set to have > 2 character spacing (due to the levels of if's and while's going on -- > later my brother called this a bit of a code smell, ie. logic shouldn't > go that deep, it should be broken out into separate functions instead. Your brother is right. Logic should not go deep and moreover the screen width not enough even with 2 space indentation gives a not-so-good picture too. > Thoughts on that are welcome to, do any of you feel logic should only > go so many layers deep?), and my editor defaults to 4 (Which I believe > is the standard according to PEP 8) Thats the way to approach. Follow PEP8. > they used a different spacing than you, is there a simple/good/smart > way to get it all back to the 4 spacing default? Or if for example I Rule #0 is Never mix tabs and spaces. Rule #1 is use a standard spacing through out the code. And when copying from a certain space-setting indentation to another, the modular script will still work fine. You can use some global find/replace mechanism to do suit your setting. For eg. I remember doing :%s/\ \ /\ \ \ \ /g OR you can also run your code through pyindent or python code beautifier (Google for it, you might find one). But after using the beautifier under these situations, just rely on your eyes to do a quick check if the logic has not gone awry ( which rarely does, but still I would believe myself more than the tool). -- Senthil http://uthocode.sarovar.org From john at fouhy.net Fri Jan 16 04:56:33 2009 From: john at fouhy.net (John Fouhy) Date: Fri, 16 Jan 2009 16:56:33 +1300 Subject: [Tutor] Corpora In-Reply-To: <892765.78280.qm@web83301.mail.sp1.yahoo.com> References: <892765.78280.qm@web83301.mail.sp1.yahoo.com> Message-ID: <5e58f2e40901151956y352945c1u94242ab4c89838b9@mail.gmail.com> 2009/1/16 Ishan Puri : > Hi, > I was wondering if anyone could tell me where I can get corpora > containing IMs, or blogs or any internet communication? This is kind of > urgent. Have you tried the enron email dataset? http://www.cs.cmu.edu/~enron/ (google may turn up other links) -- John. From orsenthil at gmail.com Fri Jan 16 04:57:10 2009 From: orsenthil at gmail.com (Senthil Kumaran) Date: Fri, 16 Jan 2009 09:27:10 +0530 Subject: [Tutor] Corpora In-Reply-To: <892765.78280.qm@web83301.mail.sp1.yahoo.com> References: <892765.78280.qm@web83301.mail.sp1.yahoo.com> Message-ID: <7c42eba10901151957o42865912ld7823cbb479a5a59@mail.gmail.com> On Fri, Jan 16, 2009 at 9:11 AM, Ishan Puri wrote: > Hi, > I was wondering if anyone could tell me where I can get corpora > containing IMs, or blogs or any internet communication? This is kind of www.google.com And for IM's specifically, you can look at "Alice Bot" Project, the corpus will be in structured format and you might end up using python to parse it ( and your question becomes relevant to this list :) ) -- Senthil From alan.gauld at btinternet.com Fri Jan 16 10:05:09 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 16 Jan 2009 09:05:09 -0000 Subject: [Tutor] 2 & 4 or more spaces per indentation level.. References: Message-ID: "Eric Dorsey" wrote > Working in IDLE on Windows Vista, I have one program that I set to > have 2 > character spacing (due to the levels of if's and while's going on -- > later > my brother called this a bit of a code smell, ie. logic shouldn't go > that > deep, it should be broken out into separate functions instead. > Thoughts on > that are welcome to, do any of you feel logic should only go so many > layers > deep?), Deeply nested logic tends to be hard to debug and hard to terst thoroughly so yes, this is considered a bad smell. Refactoring the inner parts of a loop into a function is often a good way to deal with this but it may have a performamnce impact if its a critical bit of code so its not a cure all. Usually its possioble to reduce nesting by using a different logic flow (De Morgans rules often help here) or by using higher level structures like list comprehensions instead of loops. In fact functional programming techniques in general can help minimise nesting of code - this is one of the claimed advantages of functional languages, that they lead to less deeply nested programs... > I copied some code from the 2 spacing program to another I'm writing > currently which has the default 4, and it got things kind of screwy > with > spacing. This can happen if you don't have the code in functions. Its easy to copy a function but copying arbitrary lines out of a function is much more risky. > but I was wondering, if this happened on a much bigger scale, or you > were > say, pasting code in from some example where they used a different > spacing > than you, is there a simple/good/smart way to get it all back to the > 4 > spacing default? There are many tools around that can do this kind of thing - indent, tab nanny, untabify, format etc... Pick your own favourite. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From denis.spir at free.fr Fri Jan 16 12:54:28 2009 From: denis.spir at free.fr (spir) Date: Fri, 16 Jan 2009 12:54:28 +0100 Subject: [Tutor] 2 & 4 or more spaces per indentation level.. In-Reply-To: <20090116034106.GA9987@goofy> References: <20090116034106.GA9987@goofy> Message-ID: <20090116125428.45225420@o> Le Fri, 16 Jan 2009 09:11:06 +0530, Senthil Kumaran a ?crit : > > > they used a different spacing than you, is there a simple/good/smart > > way to get it all back to the 4 spacing default? Or if for example I > > Rule #0 is Never mix tabs and spaces. > Rule #1 is use a standard spacing through out the code. > > And when copying from a certain space-setting indentation to another, > the modular script will still work fine. You can use some global > find/replace mechanism to do suit your setting. > For eg. I remember doing :%s/\ \ /\ \ \ \ /g > The simplest method I guess is to first copy the code into a new file/doc/editor tab. Change there to your personal indent width using whatever tool your editor provides, or by global search/replace. Then only paste into your code. denis ------ la vida e estranya From vginer at gmail.com Fri Jan 16 13:51:03 2009 From: vginer at gmail.com (Vicent) Date: Fri, 16 Jan 2009 13:51:03 +0100 Subject: [Tutor] "Pointer" to a function? Storing a function as an object property? Passing arguments by value/by reference? Message-ID: <50ed08f40901160451h17222bbbhed6338213a41daf7@mail.gmail.com> I am posting this question to two Python forums: Tutor and Python(x,y). In the case of Tutor [1], I think it's the right place to ask questions for a newbie like me. In the case of Python(x,y) Discussion Group [2], I am posting also because I think I am addressing a specific group of Python users that probably previously dealed with the same problems I do now. Anyway, let me know if it's a good idea to keep on doing this in the future. This question is about how to define classes or objects (or data structures) I need to use, and how to do it in an efficient way. I want to define an object or data structure called "Problem". That "problem" has to contain, somehow, a property or element called "function" which, in fact, I would like it to be a function, or a "pointer" to a function. For example, if "prob" is a "Problem" object, I would like to be able to do something like this: # call the function in prob, and store the result in "x" : x = prob.function( arguments/variables required by the function ) Does it makes any sense? Which would it be the right (meaning efficient but still object-oriented-programming-compliant) way to do it? I mean, if I store "a whole function" within each "Problem" object (assuming it can be done in Python), each Problem object would be consuming lot of memory (wouldn't it?). Maybe it would be better just to store a kind of "pointer" to the function within the "problem" object, so the object would be "lighter". The function would be then defined outside the object, as usual. Can you give me some hint about this? By the way, I have another related question. In C you can pass arguments to a function by value or by reference. Is there any equivalence in Python to that approach? How is the usual way to pass function arguments in Python? I guess I'll discover many of this things by my own when "playing arround" with Python, but some orientation will be welcomed. [1] http://mail.python.org/mailman/listinfo/tutor [2] http://groups.google.es/group/pythonxy Thank you very much in advance. -- Vicent -------------- next part -------------- An HTML attachment was scrubbed... URL: From andreengels at gmail.com Fri Jan 16 14:05:15 2009 From: andreengels at gmail.com (Andre Engels) Date: Fri, 16 Jan 2009 14:05:15 +0100 Subject: [Tutor] "Pointer" to a function? Storing a function as an object property? Passing arguments by value/by reference? In-Reply-To: <50ed08f40901160451h17222bbbhed6338213a41daf7@mail.gmail.com> References: <50ed08f40901160451h17222bbbhed6338213a41daf7@mail.gmail.com> Message-ID: <6faf39c90901160505w10664117o582526c50b95fd2d@mail.gmail.com> On Fri, Jan 16, 2009 at 1:51 PM, Vicent wrote: > I am posting this question to two Python forums: Tutor and Python(x,y). > > In the case of Tutor [1], I think it's the right place to ask questions for > a newbie like me. > > In the case of Python(x,y) Discussion Group [2], I am posting also because I > think I am addressing a specific group of Python users that probably > previously dealed with the same problems I do now. Anyway, let me know if > it's a good idea to keep on doing this in the future. > > This question is about how to define classes or objects (or data structures) > I need to use, and how to do it in an efficient way. > > I want to define an object or data structure called "Problem". > > That "problem" has to contain, somehow, a property or element called > "function" which, in fact, I would like it to be a function, or a "pointer" > to a function. > > For example, if "prob" is a "Problem" object, I would like to be able to > do something like this: > > > # call the function in prob, and store the result in "x" : > > x = prob.function( arguments/variables required by the function ) > > > Does it makes any sense? Which would it be the right (meaning efficient but > still object-oriented-programming-compliant) way to do it? > > I mean, if I store "a whole function" within each "Problem" object (assuming > it can be done in Python), each Problem object would be consuming lot of > memory (wouldn't it?). Maybe it would be better just to store a kind of > "pointer" to the function within the "problem" object, so the object would > be "lighter". The function would be then defined outside the object, as > usual. > > Can you give me some hint about this? In fact, this can be done in Python very easily, see the following interactive session: >>> class test(object): pass >>> test1 = test() >>> test2 = test() >>> def double(x): return x+x >>> def square(x): return x*x >>> test1.f = double >>> test2.f = square >>> test1.f(5) 10 >>> test2.f(5) 25 >>> -- Andr? Engels, andreengels at gmail.com From kent37 at tds.net Fri Jan 16 14:57:38 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 16 Jan 2009 08:57:38 -0500 Subject: [Tutor] "Pointer" to a function? Storing a function as an object property? Passing arguments by value/by reference? In-Reply-To: <50ed08f40901160451h17222bbbhed6338213a41daf7@mail.gmail.com> References: <50ed08f40901160451h17222bbbhed6338213a41daf7@mail.gmail.com> Message-ID: <1c2a2c590901160557k1f02416ew35705dbe531295b9@mail.gmail.com> On Fri, Jan 16, 2009 at 7:51 AM, Vicent wrote: > I want to define an object or data structure called "Problem". > > That "problem" has to contain, somehow, a property or element called > "function" which, in fact, I would like it to be a function, or a "pointer" > to a function. > > For example, if "prob" is a "Problem" object, I would like to be able to > do something like this: > > > # call the function in prob, and store the result in "x" : > > x = prob.function( arguments/variables required by the function ) As Andr? showed, this is trivially easy in Python. To expand on his exampl...functions are "first-class objects" in Python. That means that a function is an object that can be used in the same way as other values, i.e. assigned to variables or attributes, passed as function parameters, etc. The introduction of this essay has a bit more about this: http://personalpages.tds.net/~kent37/kk/00001.html > Does it makes any sense? Sure. > I mean, if I store "a whole function" within each "Problem" object (assuming > it can be done in Python), each Problem object would be consuming lot of > memory (wouldn't it?). Maybe it would be better just to store a kind of > "pointer" to the function within the "problem" object, so the object would > be "lighter". The function would be then defined outside the object, as > usual. All Python values are references, so you are essentially storing a pointer to the function object within the problem. Python assignment does not copy. This is a fundamental concept of Python that often confuses newbies, it is worth taking some time to understand it correctly. My explanation is here: http://personalpages.tds.net/~kent37/kk/00012.html > By the way, I have another related question. In C you can pass arguments to > a function by value or by reference. Is there any equivalence in Python to > that approach? How is the usual way to pass function arguments in Python? This question is the source of endless heat and little light on comp.lang.python, for (IMO) two reasons: - the word 'reference' means two things in this context - 'pass by reference' as a way of parameter passing and 'reference' as a name for a pointer. - the (IMO) correct answer is 'neither'. Python passes object references by value. If you think of it as passing a pointer by value you will pretty much have the right idea. See the second link above for more. Kent From greg at thewhittiers.com Fri Jan 16 14:56:37 2009 From: greg at thewhittiers.com (greg whittier) Date: Fri, 16 Jan 2009 08:56:37 -0500 Subject: [Tutor] "Pointer" to a function? Storing a function as an object property? Passing arguments by value/by reference? In-Reply-To: <50ed08f40901160451h17222bbbhed6338213a41daf7@mail.gmail.com> References: <50ed08f40901160451h17222bbbhed6338213a41daf7@mail.gmail.com> Message-ID: On Fri, Jan 16, 2009 at 7:51 AM, Vicent wrote: > > That "problem" has to contain, somehow, a property or element called "function" which, in fact, I would like it to be a function, or a "pointer" to a function. In python, the name of a function is just a pointer to it. Try this >>> def foo(): print "Hi!" >>> class Problem: def __init__(self,fun): self.fun = fun >>> p1 = Problem(foo) >>> p2 = Problem(foo) >>> foo >>> p1.fun >>> p2.fun >>> p1.fun == p2.fun True >>> From vginer at gmail.com Fri Jan 16 16:28:34 2009 From: vginer at gmail.com (Vicent) Date: Fri, 16 Jan 2009 16:28:34 +0100 Subject: [Tutor] "Pointer" to a function? Storing a function as an object property? Passing arguments by value/by reference? In-Reply-To: References: <50ed08f40901160451h17222bbbhed6338213a41daf7@mail.gmail.com> Message-ID: <50ed08f40901160728x125e3927gf00203fd4332e4fd@mail.gmail.com> On Fri, Jan 16, 2009 at 14:56, greg whittier wrote: > > In python, the name of a function is just a pointer to it. Try this > > >>> def foo(): > print "Hi!" > > > >>> class Problem: > def __init__(self,fun): > self.fun = fun > > > >>> p1 = Problem(foo) > >>> p2 = Problem(foo) > >>> foo > > >>> p1.fun > > >>> p2.fun > > >>> p1.fun == p2.fun > True > >>> > Wow!!! I thought that the question was simple but I was afraid that the answer was going to be too complex. But I see that it actually works like I thought it should!!! It's extremely simple and intuitive, IMHO. Thank you to all for your precise and clear answers. I've learned a lot, and specially appreciate the links that Kent provided. I hope I can contribute to this forum in the future. -- Vicent -------------- next part -------------- An HTML attachment was scrubbed... URL: From david at abbottdavid.com Fri Jan 16 17:35:13 2009 From: david at abbottdavid.com (David) Date: Fri, 16 Jan 2009 11:35:13 -0500 Subject: [Tutor] Simple program with menu to view videos Message-ID: <4970B741.6010704@abbottdavid.com> Hi, I just received the dvd Python Fundamentals by Wesley J. Chun and it was packaged by the distributor for use on Window and Mac but I use Linux so I pulled the videos of of the dvd. There are 10 lessons with a total of 58 individual videos. Most lessons are 6-8 videos long. So I did as Alan has suggested and came up with a plan of attack. What my basic program does is plays the first video and then the next in that lesson and when finished them all goes back to the menu. I am asking for some tips on how I can make this program with less code and using some classes, if that is the best way to proceed. I have a lot of code that is just copied from one function to the next. I am new to python and enjoy these little projects because I can see them in action. Here is my starting point; http://dwabbott.com/code/index6.html thanks -david -- Powered by Gentoo GNU/LINUX http://www.linuxcrazy.com pgp.mit.edu From sierra_mtnview at sbcglobal.net Fri Jan 16 17:40:26 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Fri, 16 Jan 2009 08:40:26 -0800 Subject: [Tutor] Translating FORTRAN (77?) to Python? Message-ID: <4970B87A.7000005@sbcglobal.net> An HTML attachment was scrubbed... URL: From denis.spir at free.fr Fri Jan 16 18:32:19 2009 From: denis.spir at free.fr (spir) Date: Fri, 16 Jan 2009 18:32:19 +0100 Subject: [Tutor] @property? Message-ID: <20090116183219.57329501@o> Hello, would someone point me to some clear doc about properties: purpose, use, underlying model... [Could not find myself, probably because the word "property itself has far too wide meaning.] Thank you. denis ------ la vida e estranya From cfuller084 at thinkingplanet.net Fri Jan 16 18:19:09 2009 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Fri, 16 Jan 2009 11:19:09 -0600 Subject: [Tutor] Translating FORTRAN (77?) to Python? In-Reply-To: <4970B87A.7000005@sbcglobal.net> References: <4970B87A.7000005@sbcglobal.net> Message-ID: <200901161119.09724.cfuller084@thinkingplanet.net> On Friday 16 January 2009 10:40, Wayne Watson wrote: > I may have a need down the line to convert a large number of lines of > FORTRAN code to Python. Is there a good translator available to do this? In > the past, I've found some for translating Pascal to C, and possibly others. There is a Fotran to C converter, and you might have some luck interfacing that with SWIG or just following the tutorials in the Python docs. http://www.netlib.org/f2c/ http://docs.python.org/extending/ Cheers From greg at thewhittiers.com Fri Jan 16 19:10:27 2009 From: greg at thewhittiers.com (greg whittier) Date: Fri, 16 Jan 2009 13:10:27 -0500 Subject: [Tutor] Translating FORTRAN (77?) to Python? In-Reply-To: <4970B87A.7000005@sbcglobal.net> References: <4970B87A.7000005@sbcglobal.net> Message-ID: There's an absolutely incredible project call f2py http://cens.ioc.ee/projects/f2py2e/ that I've used before. It doesn't translate the code, but wraps it (which is actually better) and lets you import your library as a module. It even generates docstrings so you can see how to call the functions. On Fri, Jan 16, 2009 at 11:40 AM, Wayne Watson wrote: > I may have a need down the line to convert a large number of lines of > FORTRAN code to Python. Is there a good translator available to do this? In > the past, I've found some for translating Pascal to C, and possibly others. > -- > > Wayne Watson (Watson Adventures, Prop., Nevada City, CA) > > (121.01 Deg. W, 39.26 Deg. N) GMT-8 hr std. time) > > "The creation of the world did not occur at the > beginning of time; it occurs every day." -- M. Proust > > Web Page: > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From srilyk at gmail.com Fri Jan 16 19:10:40 2009 From: srilyk at gmail.com (W W) Date: Fri, 16 Jan 2009 12:10:40 -0600 Subject: [Tutor] Creating simple windows in XP In-Reply-To: References: <1c2a2c590901150433t4f02b82fkab416c105669d97c@mail.gmail.com> Message-ID: <333efb450901161010k2931d493j673399d949d6d557@mail.gmail.com> On Thu, Jan 15, 2009 at 5:45 PM, Alan Gauld wrote: > You mean like doing > > import tkMessageBox > tkMessageBox.showinfo("Window Text", "A short message") > > in Tkinter? :-) > > OR > > res = tkMessageBox.askokcancel("Which?", "Ready to stop?") > print res > > At that level Tkinter is pretty easy too. After trying that and getting the mildly annoying root window to pop up I did a quick search and found how to hide that window. from Tkinter import Tk root = Tk() root.withdraw() tkMessageBox.showinfo("Window", "Root window is gone!") If you need it back, root.deiconfiy() will show the window again. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at alchemy.com Fri Jan 16 19:13:21 2009 From: steve at alchemy.com (Steve Willoughby) Date: Fri, 16 Jan 2009 10:13:21 -0800 Subject: [Tutor] @property? In-Reply-To: <20090116183219.57329501@o> References: <20090116183219.57329501@o> Message-ID: <20090116181321.GA65871@dragon.alchemy.com> On Fri, Jan 16, 2009 at 06:32:19PM +0100, spir wrote: > Hello, > > would someone point me to some clear doc about properties: purpose, use, underlying model... > [Could not find myself, probably because the word "property itself has far too wide meaning.] I'm a little confused here because of the "@" in the subject. Do you mean Python syntax using the "@" in front of a name like: @protected def spam(eggs): ... Those are called "decorators". Try searching for those, or we can help if that's what you're looking for. -- Steve Willoughby | Using billion-dollar satellites steve at alchemy.com | to hunt for Tupperware. From denis.spir at free.fr Fri Jan 16 19:23:22 2009 From: denis.spir at free.fr (spir) Date: Fri, 16 Jan 2009 19:23:22 +0100 Subject: [Tutor] Simple program with menu to view videos In-Reply-To: <4970B741.6010704@abbottdavid.com> References: <4970B741.6010704@abbottdavid.com> Message-ID: <20090116192322.6df025ee@o> Le Fri, 16 Jan 2009 11:35:13 -0500, David a ?crit : > Hi, > I just received the dvd Python Fundamentals by Wesley J. Chun and it was > packaged by the distributor for use on Window and Mac but I use Linux so > I pulled the videos of of the dvd. There are 10 lessons with a total of > 58 individual videos. Most lessons are 6-8 videos long. So I did as Alan > has suggested and came up with a plan of attack. What my basic program > does is plays the first video and then the next in that lesson and when > finished them all goes back to the menu. I am asking for some tips on > how I can make this program with less code and using some classes, if > that is the best way to proceed. I have a lot of code that is just > copied from one function to the next. I am new to python and enjoy these > little projects because I can see them in action. Here is my starting point; > http://dwabbott.com/code/index6.html > thanks > -david Just had a look at your code. As you say: "a lot of code that is just copied from one function to the next". The only reason for that is your functions have no argument (parameter): def lesson3b(): player = "/usr/bin/mplayer" fname = "/home/david/Desktop/core_video/data/python_0302.flv" subprocess.call([player, fname]) lesson3c() From this instance of a specific lesson player function, you can simply define a generic one: def play_lesson(lesson_id): # does not belong here: player = "/usr/bin/mplayer" fname = lesson_file_name(lesson_id) # how to get the file name? subprocess.call([player, fname]) # does not belong here: lesson3c() Note that "player" is a constant, so that it does not belong to the function. At best, it may be an optional argument which could later be overriden (by e.g. a command line argument -- if ever you chage the player). Also, the lesson3c() call is part of an overall scheduling logic that should be controled from an external loop or menu -- this depends on how you intend to use the application. Finally, note that the lesson file names are pretty regular: There are built out a single prefix, a "series" number, then a lesson letter. Provided you do not change this logic, you can build the filenames easily. The prefix can be written as an optional arg, like the player. Also, I would distinguish "series" from "lesson" (this may be helpful at the schedular level). An alternative may be a lesson file lookup in a dictionary of (lesson_id:lesson_file_name) pairs, but there is no need for that here. So that the core lesson playing function may look like that: def play_lesson(series_id, lesson_id, player = "/usr/bin/mplayer", prefix="/home/david/Desktop/core_video/data/python_"): # convert lesson lowercass letter id to a ordinal: # (a,b,...z <--> 97,98,...122) lesson_id = ord(lesson_id) - 96 # I use below a string formatting expression # but the file name may be constructed "manually" fname = "%s%02d%02d" %(prefix, series_id, lesson_id) subprocess.call([player, fname]) Now, you need a master control function, from which the user can possibly choose which lesson to watch, that will accordingly call the lesson player func. As said, this mainly depends on how you expect it as a user. Note that the logic you first coded is a kind of "masked" recursivity: play1a play1b play1c .... playnx playny This would be implemented in the above version by an additional explicit recursive call: def play_lesson(series_id, lesson_id, player = "/usr/bin/mplayer", prefix="/home/david/Desktop/core_video/data/python_"): ....... subprocess.call([player, fname]) play_lesson(next_lesson(series_id, lesson_id)) (provided the next_lesson func exists) This is very probably *not* the user model of an adaptative lesson player tool ;-) For a question of taste or programming style, I would personly rather create a "lesson" type (class) that holds and handles all that stuff: identification, file_name, play(), next()... But it would probably be neither clearer, nore simpler. You could do it afterwards as an introduction to objects (the list will help you). Denis ------ la vida e estranya From wescpy at gmail.com Fri Jan 16 19:30:28 2009 From: wescpy at gmail.com (wesley chun) Date: Fri, 16 Jan 2009 10:30:28 -0800 Subject: [Tutor] "Pointer" to a function? Storing a function as an object property? Passing arguments by value/by reference? In-Reply-To: <1c2a2c590901160557k1f02416ew35705dbe531295b9@mail.gmail.com> References: <50ed08f40901160451h17222bbbhed6338213a41daf7@mail.gmail.com> <1c2a2c590901160557k1f02416ew35705dbe531295b9@mail.gmail.com> Message-ID: <78b3a9580901161030y53d0ef2apc95962f96b7d3623@mail.gmail.com> > All Python values are references, so you are essentially storing a > pointer to the function object within the problem. Python assignment > does not copy. This is a fundamental concept of Python that often > confuses newbies, it is worth taking some time to understand it > correctly. My explanation is here: > http://personalpages.tds.net/~kent37/kk/00012.html inside kent's post is an(other) article by fredrik lundh that may be difficult to see during reading so i want to post it so you don't miss it: http://effbot.org/zone/call-by-object.htm in my training courses, when people ask if Python is "call-by-reference" or "call-by-value," i tell them it's neither... *and* both, then proceed to show them what i mean. this topic is definitely a place where beginners trip up, and it is also where you begin your long road to maturity as a Python programmer. remember, Python places an strong emphasis on objects, and in this particular case, what happens depends on whether an object allows for modification (mutability). hope this helps! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 "Python Fundamentals", Prentice Hall, (c)2009 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From kent37 at tds.net Fri Jan 16 19:31:48 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 16 Jan 2009 13:31:48 -0500 Subject: [Tutor] @property? In-Reply-To: <20090116183219.57329501@o> References: <20090116183219.57329501@o> Message-ID: <1c2a2c590901161031v75f4ae45webd54968dd0b48@mail.gmail.com> On Fri, Jan 16, 2009 at 12:32 PM, spir wrote: > Hello, > > would someone point me to some clear doc about properties: purpose, use, underlying model... Properties: http://personalpages.tds.net/~kent37/kk/00008.html Decorators (the @ syntax): http://personalpages.tds.net/~kent37/kk/00001.html Kent From sierra_mtnview at sbcglobal.net Fri Jan 16 20:02:59 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Fri, 16 Jan 2009 11:02:59 -0800 Subject: [Tutor] Translating FORTRAN (77?) to Python? In-Reply-To: References: <4970B87A.7000005@sbcglobal.net> Message-ID: <4970D9E3.2030709@sbcglobal.net> An HTML attachment was scrubbed... URL: From sander.sweers at gmail.com Fri Jan 16 20:19:58 2009 From: sander.sweers at gmail.com (Sander Sweers) Date: Fri, 16 Jan 2009 20:19:58 +0100 Subject: [Tutor] Translating FORTRAN (77?) to Python? In-Reply-To: <4970D9E3.2030709@sbcglobal.net> References: <4970B87A.7000005@sbcglobal.net> <4970D9E3.2030709@sbcglobal.net> Message-ID: On Fri, Jan 16, 2009 at 20:02, Wayne Watson wrote: > That is interesting. I'll pursue it. Thanks. Of course, at the moment, I > have no F77 compiler, so I can't even execute or use the code. Is there a > freebie F77 compiler out there? GCC supportd it http://gcc.gnu.org/. Greets Sander From jsmith at medplus.com Fri Jan 16 20:10:48 2009 From: jsmith at medplus.com (Smith, Jeff) Date: Fri, 16 Jan 2009 14:10:48 -0500 Subject: [Tutor] Translating FORTRAN (77?) to Python? In-Reply-To: <4970D9E3.2030709@sbcglobal.net> References: <4970B87A.7000005@sbcglobal.net> <4970D9E3.2030709@sbcglobal.net> Message-ID: There was an add-on to the GNU C compiler for FORTRAN77 at one time (g77). I don't know if it is still available to how well it works though. Jeff ________________________________ From: tutor-bounces+jsmith=medplus.com at python.org [mailto:tutor-bounces+jsmith=medplus.com at python.org] On Behalf Of Wayne Watson Sent: Friday, January 16, 2009 2:03 PM To: greg whittier Cc: tutor at python.org Subject: Re: [Tutor] Translating FORTRAN (77?) to Python? That is interesting. I'll pursue it. Thanks. Of course, at the moment, I have no F77 compiler, so I can't even execute or use the code. Is there a freebie F77 compiler out there? greg whittier wrote: There's an absolutely incredible project call f2py http://cens.ioc.ee/projects/f2py2e/ that I've used before. It doesn't translate the code, but wraps it (which is actually better) and lets you import your library as a module. It even generates docstrings so you can see how to call the functions. On Fri, Jan 16, 2009 at 11:40 AM, Wayne Watson wrote: I may have a need down the line to convert a large number of lines of FORTRAN code to Python. Is there a good translator available to do this? In the past, I've found some for translating Pascal to C, and possibly others. -- Wayne Watson (Watson Adventures, Prop., Nevada City, CA) (121.01 Deg. W, 39.26 Deg. N) GMT-8 hr std. time) "The creation of the world did not occur at the beginning of time; it occurs every day." -- M. Proust Web Page: _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor -- Wayne Watson (Watson Adventures, Prop., Nevada City, CA) (121.01 Deg. W, 39.26 Deg. N) GMT-8 hr std. time) "The creation of the world did not occur at the beginning of time; it occurs every day." -- M. Proust Web Page: Confidentiality Notice: The information contained in this electronic transmission is confidential and may be legally privileged. It is intended only for the addressee(s) named above. If you are not an intended recipient, be aware that any disclosure, copying, distribution or use of the information contained in this transmission is prohibited and may be unlawful. If you have received this transmission in error, please notify us by telephone (513) 229-5500 or by email (postmaster at MedPlus.com). After replying, please erase it from your computer system. -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Fri Jan 16 19:29:09 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 16 Jan 2009 13:29:09 -0500 Subject: [Tutor] Simple program with menu to view videos In-Reply-To: <4970B741.6010704@abbottdavid.com> References: <4970B741.6010704@abbottdavid.com> Message-ID: <1c2a2c590901161029k698ecb79j502cc91c2324c36c@mail.gmail.com> On Fri, Jan 16, 2009 at 11:35 AM, David wrote: > I am asking for some tips on how I can make > this program with less code and using some classes, if that is the best way > to proceed. I have a lot of code that is just copied from one function to > the next. When you are copy/pasting code, think about how you can make a function that abstracts the copied bits. For example you could have this function: def play(filename): player = "/usr/bin/mplayer" fname = "/home/david/Desktop/core_video/data/" + filename subprocess.call([player, fname]) Then for example you would have def lesson10f(): play("python_1006.flv") menu() So that is a start. Now look at what you are doing with the individual sub-lessons. You really just want a way to play a series of lessons. This can be done with a loop: def lesson8(): files = ['python_0800a.flv', 'python_0801.flv', , 'python_0806.flv'] playall(files) def playall(files): for name in files: play(name) Since the lesson names follow a regular pattern you might even be able to generate the names automatically from the lesson number. Finally, put a loop in your menu function rather than having the lessons call back to the menu. Kent From sierra_mtnview at sbcglobal.net Fri Jan 16 21:06:45 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Fri, 16 Jan 2009 12:06:45 -0800 Subject: [Tutor] Translating FORTRAN (77?) to Python? In-Reply-To: References: <4970B87A.7000005@sbcglobal.net> <4970D9E3.2030709@sbcglobal.net> Message-ID: <4970E8D5.2070301@sbcglobal.net> An HTML attachment was scrubbed... URL: From sander.sweers at gmail.com Fri Jan 16 21:41:39 2009 From: sander.sweers at gmail.com (Sander Sweers) Date: Fri, 16 Jan 2009 21:41:39 +0100 Subject: [Tutor] Translating FORTRAN (77?) to Python? In-Reply-To: <4970E8D5.2070301@sbcglobal.net> References: <4970B87A.7000005@sbcglobal.net> <4970D9E3.2030709@sbcglobal.net> <4970E8D5.2070301@sbcglobal.net> Message-ID: On Fri, Jan 16, 2009 at 21:06, Wayne Watson wrote: > Anything under Win? Yes, minigw http://www.mingw.org/. Greets Sander From sierra_mtnview at sbcglobal.net Fri Jan 16 22:20:10 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Fri, 16 Jan 2009 13:20:10 -0800 Subject: [Tutor] Translating FORTRAN (77?) to Python? In-Reply-To: References: <4970B87A.7000005@sbcglobal.net> <4970D9E3.2030709@sbcglobal.net> <4970E8D5.2070301@sbcglobal.net> Message-ID: <4970FA0A.2030100@sbcglobal.net> An HTML attachment was scrubbed... URL: From sander.sweers at gmail.com Sat Jan 17 00:01:26 2009 From: sander.sweers at gmail.com (Sander Sweers) Date: Sat, 17 Jan 2009 00:01:26 +0100 Subject: [Tutor] Translating FORTRAN (77?) to Python? In-Reply-To: <4970FA0A.2030100@sbcglobal.net> References: <4970B87A.7000005@sbcglobal.net> <4970D9E3.2030709@sbcglobal.net> <4970E8D5.2070301@sbcglobal.net> <4970FA0A.2030100@sbcglobal.net> Message-ID: On Fri, Jan 16, 2009 at 22:20, Wayne Watson wrote: > Will that do me any good if I implement my application under Win Python? Your question was for a fotran compiler to compile the source code. The fotran program is your reference point to compare the results to. Greets Sander From jeremiah.jester at panasonic.aero Fri Jan 16 23:56:42 2009 From: jeremiah.jester at panasonic.aero (Jeremiah Jester) Date: Fri, 16 Jan 2009 14:56:42 -0800 Subject: [Tutor] curl and python Message-ID: <1232146602.10436.8.camel@M13425> I'm trying to get curl to traverse a remote http directory get all page names and do some processing on these file with python. For starters, i need to get the directory listing in an array from the domain. Any ideas on how to do this? Thanks, JJ Disclaimer: The information contained in this transmission, including any attachments, may contain confidential information of Panasonic Avionics Corporation. This transmission is intended only for the use of the addressee(s) listed above. Unauthorized review, dissemination or other use of the information contained in this transmission is strictly prohibited. If you have received this transmission in error or have reason to believe you are not authorized to receive it, please notify the sender by return email and promptly delete the transmission. From alan.gauld at btinternet.com Sat Jan 17 02:40:02 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 17 Jan 2009 01:40:02 -0000 Subject: [Tutor] [python(x, y)] "Pointer" to a function? Storing a function as an object property? Passing arguments by value/by reference? References: <50ed08f40901160451h17222bbbhed6338213a41daf7@mail.gmail.com> Message-ID: "Vicent" wrote > That "problem" has to contain, somehow, a property or element called > "function" which, in fact, I would like it to be a function, or a > "pointer" > to a function. I won't repeat what others have said about passing function objects into an object and storing them as attributes. However I will point out an even more fundamental approach to your problem and pick up on one of your comments... > # call the function in prob, and store the result in "x" : > > x = prob.function( arguments/variables required by the function ) This is normal syntax for accessing the methods of an object. Thus: class Problem: def function(self, args): # your function code here return result p = Problem() x = p.function() So if you know what function will be used for each problem then you can define it as part of the class definition as a normal method. Or you can pass a reference to a predefined function into the class constructor: class Problem: def __init__(self, aFunc): self.function = aFunc def f(): return 42 def g(): return 66 p1 = Problem(f) p2 = Problem(g) x = p1.function() # call f() y = p2.function() # call g() This is IMHO slightly more elegant than assigning the function to an attribute of the object after construction. The down side of this style is that these functions will not have any access to attributes inside your class via self, as methods would. > Does it makes any sense? Which would it be the right (meaning > efficient but > still object-oriented-programming-compliant) way to do it? Its all potentially object oriented, depending upon what you want to do. > I mean, if I store "a whole function" within each "Problem" object > (assuming > it can be done in Python), each Problem object would be consuming > lot of > memory (wouldn't it?). Methods are defined in classes (which are also objects in their own right in Python) and objects hold references to the class. So each instance only has a reference to the class which is used to access the predefined methods. The functions that you pass as parameters as just direct references to those function objects. > Maybe it would be better just to store a kind of > "pointer" to the function within the "problem" object, Thats what happens. > By the way, I have another related question. In C you can pass > arguments to > a function by value or by reference. Is there any equivalence in > Python to > that approach? How is the usual way to pass function arguments in > Python? Basically by reference but as Wes said there are some wrinkles whoch mean it can be less than intuitive for a beginner! -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Sat Jan 17 02:46:30 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 17 Jan 2009 01:46:30 -0000 Subject: [Tutor] Translating FORTRAN (77?) to Python? References: <4970B87A.7000005@sbcglobal.net><4970D9E3.2030709@sbcglobal.net> Message-ID: "Smith, Jeff" wrote > There was an add-on to the GNU C compiler for FORTRAN77 at one time > (g77). I don't know if it is still available to how well it works > though. Caveat: Fortran is one of the few mainstream languages that I have never read or written so I have no personal experience. But... At work we had a Fortran project which used the g77 GNU compiler and the FORTRAN team seemed to think it was OK. They were porting code from a VAX to a Sun Unix box. I believe the GNU g77 translator is available for Windows too. Alan G. From pine508 at hotmail.com Sat Jan 17 06:20:34 2009 From: pine508 at hotmail.com (Che M) Date: Sat, 17 Jan 2009 00:20:34 -0500 Subject: [Tutor] referring to subfolders Message-ID: I have been using absolute paths in my programs, but want to get out of the habit as I try to run them on other computers. I was surprised to find that this type of reference didn't work: path = '/subfolder/myfile.py' But instead I did it this way and it works: import os.path self.currentdir = os.curdir self.mysubfolder = os.path.join(self.currentdir, "subfolder") path = self.mysubfolder + '/myfile.py' Is this really the only way to do it,and so I have to import os.path each time I have a case where I refer to a subdirectory? It seems like something quick/built-in like the first way should work, or maybe I am misunderstanding something? Thanks. _________________________________________________________________ Windows Live?: Keep your life in sync. http://windowslive.com/explore?ocid=TXT_TAGLM_WL_t1_allup_explore_012009 From steve at alchemy.com Sat Jan 17 06:26:52 2009 From: steve at alchemy.com (Steve Willoughby) Date: Fri, 16 Jan 2009 21:26:52 -0800 Subject: [Tutor] referring to subfolders In-Reply-To: References: Message-ID: <49716C1C.6030503@alchemy.com> Che M wrote: > I have been using absolute paths in my programs, but > want to get out of the habit as I try to run them on > other computers. I was surprised to find that this > type of reference didn't work: > > path = '/subfolder/myfile.py' Pathnames are relative by default. So: 'myfile.py' would be the file myfile.py in the current directory. 'subfolder/myfile.py' would be myfile.py inside subfolder, which is below the current directory. It's the initial / character which makes it absolute, and start from the root directory. From pine508 at hotmail.com Sat Jan 17 06:36:01 2009 From: pine508 at hotmail.com (Che M) Date: Sat, 17 Jan 2009 00:36:01 -0500 Subject: [Tutor] referring to subfolders In-Reply-To: <49716C1C.6030503@alchemy.com> References: <49716C1C.6030503@alchemy.com> Message-ID: ---------------------------------------- > Date: Fri, 16 Jan 2009 21:26:52 -0800 > From: steve at alchemy.com > To: pine508 at hotmail.com > CC: tutor at python.org > Subject: Re: [Tutor] referring to subfolders > > Che M wrote: >> I have been using absolute paths in my programs, but >> want to get out of the habit as I try to run them on >> other computers. I was surprised to find that this >> type of reference didn't work: >> >> path = '/subfolder/myfile.py' > > Pathnames are relative by default. So: > 'myfile.py' > would be the file myfile.py in the current directory. > 'subfolder/myfile.py' > would be myfile.py inside subfolder, which is below the current directory. > > It's the initial / character which makes it absolute, and start from the > root directory. Thanks--much simpler! _________________________________________________________________ Windows Live?: Keep your life in sync. http://windowslive.com/howitworks?ocid=TXT_TAGLM_WL_t1_allup_howitworks_012009 From kent37 at tds.net Sat Jan 17 06:11:01 2009 From: kent37 at tds.net (Kent Johnson) Date: Sat, 17 Jan 2009 00:11:01 -0500 Subject: [Tutor] curl and python In-Reply-To: <1232146602.10436.8.camel@M13425> References: <1232146602.10436.8.camel@M13425> Message-ID: <1c2a2c590901162111q55a248f4vccd0b4b34591cb4e@mail.gmail.com> On Fri, Jan 16, 2009 at 5:56 PM, Jeremiah Jester wrote: > I'm trying to get curl to traverse a remote http directory get all page > names and do some processing on these file with python. > > For starters, i need to get the directory listing in an array from the > domain. Any ideas on how to do this? urllib2 and BeautifulSoup: http://personalpages.tds.net/~kent37/kk/00010.html http://personalpages.tds.net/~kent37/kk/00009.html Kent From kent37 at tds.net Sat Jan 17 14:03:46 2009 From: kent37 at tds.net (Kent Johnson) Date: Sat, 17 Jan 2009 08:03:46 -0500 Subject: [Tutor] referring to subfolders In-Reply-To: References: Message-ID: <1c2a2c590901170503r7446c70brce0d59cad9cae847@mail.gmail.com> On Sat, Jan 17, 2009 at 12:20 AM, Che M wrote: > import os.path > self.currentdir = os.curdir > self.mysubfolder = os.path.join(self.currentdir, "subfolder") > path = self.mysubfolder + '/myfile.py' > > Is this really the only way to do it,and so I have to import > os.path each time I have a case where I refer to a subdirectory? The advantage of os.path.join() (if you use it for all joins) is that it is portable, it will use the appropriate path separator for the platform it is running on. These days that is not such a big deal, perhaps, as Mac OSX, Windows and Linux all accept / as a path separator. Kent From bgailer at gmail.com Sat Jan 17 17:35:47 2009 From: bgailer at gmail.com (bob gailer) Date: Sat, 17 Jan 2009 11:35:47 -0500 Subject: [Tutor] Translating FORTRAN (77?) to Python? In-Reply-To: <4970B87A.7000005@sbcglobal.net> References: <4970B87A.7000005@sbcglobal.net> Message-ID: <497208E3.8040003@gmail.com> Wayne Watson wrote: > I may have a need down the line to convert a large number of lines of > FORTRAN code to Python. Is there a good translator available to do this? I guess from the responses and Google Search that no such translator exists. It is possible but not trivial to write one. I probably could do that but would need some motivation. From sierra_mtnview at sbcglobal.net Sat Jan 17 23:06:57 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sat, 17 Jan 2009 14:06:57 -0800 Subject: [Tutor] Translating FORTRAN (77?) to Python? In-Reply-To: References: <4970B87A.7000005@sbcglobal.net> <4970D9E3.2030709@sbcglobal.net> <4970E8D5.2070301@sbcglobal.net> <4970FA0A.2030100@sbcglobal.net> Message-ID: <49725681.7080602@sbcglobal.net> An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Sun Jan 18 03:28:34 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sat, 17 Jan 2009 18:28:34 -0800 Subject: [Tutor] Translating FORTRAN (77?) to Python? In-Reply-To: <497208E3.8040003@gmail.com> References: <4970B87A.7000005@sbcglobal.net> <497208E3.8040003@gmail.com> Message-ID: <497293D2.40801@sbcglobal.net> An HTML attachment was scrubbed... URL: From echolynx at gmail.com Sun Jan 18 04:04:38 2009 From: echolynx at gmail.com (Ian Egland) Date: Sat, 17 Jan 2009 22:04:38 -0500 Subject: [Tutor] Best Python3000 Tutorial for Beginner Message-ID: Hello all, I just joined this mailing list. I am a beginner to programming in general and would really appreciate a tutorial for Python3000 that at least covers the basics. I have tried reading the manual, but I think it was written for more experienced programmers wishing to switch to python rather than a beginner looking for where to start. Most of the other tutorials I have found were for earlier versions of Python, and because Python 3.0 was released on my birthday, I decided I was meant to learn that release. ;-) Anyway, any help would be appreciated. I will do my best to return the favor. -Ian -------------- next part -------------- An HTML attachment was scrubbed... URL: From orsenthil at gmail.com Sun Jan 18 04:14:40 2009 From: orsenthil at gmail.com (Senthil Kumaran) Date: Sun, 18 Jan 2009 08:44:40 +0530 Subject: [Tutor] Best Python3000 Tutorial for Beginner In-Reply-To: References: Message-ID: <7c42eba10901171914o6e85e360ka9b0b5d79fd22a77@mail.gmail.com> On Sun, Jan 18, 2009 at 8:34 AM, Ian Egland wrote: > Hello all, I just joined this mailing list. > > I am a beginner to programming in general and would really appreciate a > tutorial for Python3000 that at least covers the basics. I have tried Hello Ian, That is a nice reason to get started with a language. However, you have to remember that Python 3.0 is not a new language at all. It is just a backwards impatible release of the original almighty pyhon, which just tends to increase its strength and clean its design further. I am not at all surprised that you did not find any beginner Python 3.0 tutorial. It might be coming out soon, but the curretly people migrating to Python 3.0 are ones who already know python 2k well. So, for your purposes I would suggest the following. 1) Get Beginner Python tutorial. (See Alan's tutorial in this mailing list and also google for A Byte of Python) 2) Read and understand the language well. Get comfortable upto a point where you can differentiate between string, unicode and bytes. I should warn you that it might take months' time. and now you can read this very beginner friendly introduction to Python 3k. http://www.comp.leeds.ac.uk/nde/papers/teachpy3.html Thanks, Senthil From echolynx at gmail.com Sun Jan 18 04:21:34 2009 From: echolynx at gmail.com (Ian Egland) Date: Sat, 17 Jan 2009 22:21:34 -0500 Subject: [Tutor] Help with elif Message-ID: Wow, that was a quick response! Thanks all! I have looked at a couple tutorials and whipped this up. However, attempting to run it in IDLE results in a syntax error leaving my elif highlighted in red. What's wrong? I've looked at the code and can't find any syntax errors- though I've just started. print("[Temperature Converter, First Edition]") print("Created on January 17th, 2009 by Ian Egland") temp1 = int(input("Please enter a temperature: ")) scale = input("Convert to (F)ahrenheit or (C)elcius?") if scale == "F": temp2 = (9/5)*temp1+32 print(temp1, "C =", temp2, "F" elif scale == "C": # Error appears here. temp2 = (5/9)*(temp1-32) print(temp1, "F =", temp2, "C" else: print("Sorry, you must enter either an F or a C. Case-sensitive. Please try again." In regards to learning python, I've found that after I get somewhat-familiar with a language, I want a programming problem to solve with what I've learned. While learning Java, http://www.javabat.com has been my best friend. (That is, as close to a best friend as programming website can be.) Is there something like this for Java? Is one in the works? -Ian -------------- next part -------------- An HTML attachment was scrubbed... URL: From echolynx at gmail.com Sun Jan 18 04:22:58 2009 From: echolynx at gmail.com (Ian Egland) Date: Sat, 17 Jan 2009 22:22:58 -0500 Subject: [Tutor] Fixed Message-ID: Found it- wasn't closing the ()'s in the print()'s. Thanks anyway, sorry for filling your inbox. -Ian -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Sun Jan 18 04:44:25 2009 From: kent37 at tds.net (Kent Johnson) Date: Sat, 17 Jan 2009 22:44:25 -0500 Subject: [Tutor] Help with elif In-Reply-To: References: Message-ID: <1c2a2c590901171944j31949717t943ce3656c8cfea7@mail.gmail.com> On Sat, Jan 17, 2009 at 10:21 PM, Ian Egland wrote: > I have looked at a couple tutorials and whipped this up. However, attempting > to run it in IDLE results in a syntax error leaving my elif highlighted in > red. What's wrong? I've looked at the code and can't find any syntax errors- > though I've just started. > > print("[Temperature Converter, First Edition]") > print("Created on January 17th, 2009 by Ian Egland") > temp1 = int(input("Please enter a temperature: ")) > scale = input("Convert to (F)ahrenheit or (C)elcius?") > if scale == "F": > temp2 = (9/5)*temp1+32 > print(temp1, "C =", temp2, "F" Missing parenthesis in the above line. > elif scale == "C": # Error appears here. Syntax errors often appear on the line *following* the line with the actual error. Kent From brian.mathis at gmail.com Sun Jan 18 06:24:05 2009 From: brian.mathis at gmail.com (Brian Mathis) Date: Sun, 18 Jan 2009 00:24:05 -0500 Subject: [Tutor] Best Python3000 Tutorial for Beginner In-Reply-To: References: Message-ID: <183c528b0901172124g16552494q1df8fa99bf91ca53@mail.gmail.com> In addition to what was already mentioned, I found "Think Python" useful. It is aimed at both learning programming in general, and it teaches in python specifically. However, it's written for python 2. http://www.greenteapress.com/thinkpython/thinkpython.html On Sat, Jan 17, 2009 at 10:04 PM, Ian Egland wrote: > Hello all, I just joined this mailing list. > > I am a beginner to programming in general and would really appreciate a > tutorial for Python3000 that at least covers the basics. I have tried > reading the manual, but I think it was written for more experienced > programmers wishing to switch to python rather than a beginner looking for > where to start. Most of the other tutorials I have found were for earlier > versions of Python, and because Python 3.0 was released on my birthday, I > decided I was meant to learn that release. ;-) > > Anyway, any help would be appreciated. I will do my best to return the > favor. > > -Ian > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From alan.gauld at btinternet.com Sun Jan 18 10:04:52 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 18 Jan 2009 09:04:52 -0000 Subject: [Tutor] Best Python3000 Tutorial for Beginner References: Message-ID: "Ian Egland" wrote > I am a beginner to programming in general and would really > appreciate a > tutorial for Python3000 that at least covers the basics..... > where to start. Most of the other tutorials I have found were for > earlier > versions of Python, and because Python 3.0 was released on my > birthday, I > decided I was meant to learn that release. ;-) I have finally managed to get a new site for my tutorial and am intending to upgrade it to Python 3 over the next few months. (I have to learn Python 3 myself as I'm doing it!!) >From previous experience it will take me about 1 week per topic so 6 months in total to upgrade the whole tutor. If you are interested in being a guinea pig for the topics I can let you have early visibility. But it will take me much longer to write than you will want to spend reading! HTH -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk From alan.gauld at btinternet.com Sun Jan 18 10:09:06 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 18 Jan 2009 09:09:06 -0000 Subject: [Tutor] Help with elif References: Message-ID: "Ian Egland" wrote > learned. While learning Java, http://www.javabat.com has been my > best > friend. (That is, as close to a best friend as programming website > can be.) > Is there something like this for Java? Is one in the works? If you already know Java, even a little bit then my tutorial will be too basic for you. I'd try the Byte of Python website/book. Although the official tutorial should be understandable too... -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From jammy007_pp at yahoo.com Sun Jan 18 11:18:33 2009 From: jammy007_pp at yahoo.com (jammy007 pp) Date: Sun, 18 Jan 2009 02:18:33 -0800 (PST) Subject: [Tutor] Tutor Digest, Vol 59, Issue 90 In-Reply-To: Message-ID: <73001.44088.qm@web63301.mail.re1.yahoo.com> hi everyone? , i was trying to make a simple tic tac toe game using ascii characters . i read the source code from micheal dawson's book but didnt understand it much . if some one could? explain it to me with examples it would be great . thanks jammy -------------- next part -------------- An HTML attachment was scrubbed... URL: From vceder at canterburyschool.org Sun Jan 18 13:30:39 2009 From: vceder at canterburyschool.org (Vern Ceder) Date: Sun, 18 Jan 2009 07:30:39 -0500 Subject: [Tutor] Best Python3000 Tutorial for Beginner In-Reply-To: References: Message-ID: <497320EF.9030703@canterburyschool.org> Swaroop's Byte of Python has both 2.x and 3.x versions: http://www.swaroopch.com/notes/Python_en:Table_of_Contents Cheers, Vern Ceder Ian Egland wrote: > Hello all, I just joined this mailing list. > > I am a beginner to programming in general and would really appreciate a > tutorial for Python3000 that at least covers the basics. I have tried > reading the manual, but I think it was written for more experienced > programmers wishing to switch to python rather than a beginner looking > for where to start. Most of the other tutorials I have found were for > earlier versions of Python, and because Python 3.0 was released on my > birthday, I decided I was meant to learn that release. ;-) > > Anyway, any help would be appreciated. I will do my best to return the > favor. > > -Ian > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From kent37 at tds.net Sun Jan 18 13:56:57 2009 From: kent37 at tds.net (Kent Johnson) Date: Sun, 18 Jan 2009 07:56:57 -0500 Subject: [Tutor] Help with elif In-Reply-To: References: Message-ID: <1c2a2c590901180456x2babb1d4i7c40a1c3ddb7b1c2@mail.gmail.com> On Sat, Jan 17, 2009 at 10:21 PM, Ian Egland wrote: > In regards to learning python, I've found that after I get somewhat-familiar > with a language, I want a programming problem to solve with what I've > learned. While learning Java, http://www.javabat.com has been my best > friend. (That is, as close to a best friend as programming website can be.) > Is there something like this for Java? Is one in the works? I don't know of anything quite like JavaBat. I think you will find that experimenting with Python is much easier than with Java. It is very simple to try out Python in the interactive interpreter, in IDLE or in an editor. Many programmers' editors can be configured to run Python programs directly from the editor. You might possibly like to try Crunchy, which puts an interactive session right into a tutorial in your web browser: http://showmedo.com/videos/video?name=1430020&fromSeriesID=143#TB_inline?&width=776&height=618&inlineId=videoPlayer Some puzzle and problem sites are listed here: http://personalpages.tds.net/~kent37/stories/00021.html#e21puzzles-and-problems Kent From kent37 at tds.net Sun Jan 18 14:08:20 2009 From: kent37 at tds.net (Kent Johnson) Date: Sun, 18 Jan 2009 08:08:20 -0500 Subject: [Tutor] Tutor Digest, Vol 59, Issue 90 In-Reply-To: <73001.44088.qm@web63301.mail.re1.yahoo.com> References: <73001.44088.qm@web63301.mail.re1.yahoo.com> Message-ID: <1c2a2c590901180508w24f72b45vcc50b81c2d7e9a97@mail.gmail.com> On Sun, Jan 18, 2009 at 5:18 AM, jammy007 pp wrote: > hi everyone , > i was trying to make a simple tic tac toe game using ascii characters . > i read the source code from micheal dawson's book but didnt understand it > much . > > if some one could explain it to me with examples it would be great . Not everyone here has Dawson's book. A more specific question would help us help you. What is the first thing in the program that you don't understand? Kent From kent37 at tds.net Sun Jan 18 14:13:26 2009 From: kent37 at tds.net (Kent Johnson) Date: Sun, 18 Jan 2009 08:13:26 -0500 Subject: [Tutor] Best Python3000 Tutorial for Beginner In-Reply-To: <497320EF.9030703@canterburyschool.org> References: <497320EF.9030703@canterburyschool.org> Message-ID: <1c2a2c590901180513n654657f5kcf724bf5b6cc6ad2@mail.gmail.com> On Sun, Jan 18, 2009 at 7:30 AM, Vern Ceder wrote: > > Swaroop's Byte of Python has both 2.x and 3.x versions: > > http://www.swaroopch.com/notes/Python_en:Table_of_Contents This page gives direct access to both versions: http://www.swaroopch.com/notes/Python Kent From alan.gauld at btinternet.com Sun Jan 18 15:40:24 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 18 Jan 2009 14:40:24 -0000 Subject: [Tutor] Help with elif References: Message-ID: "Alan Gauld" wrote > If you already know Java, even a little bit then my tutorial will be > too basic for you. > > I'd try the Byte of Python website/book. Actually I meant the dive into python website/book. Not that there's anything wrong with "Byte of" either, but "Dive In" seems more appropriate if you already program in Java... -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From david at abbottdavid.com Sun Jan 18 16:37:50 2009 From: david at abbottdavid.com (David) Date: Sun, 18 Jan 2009 10:37:50 -0500 Subject: [Tutor] calculator will not multiply Message-ID: <49734CCE.3030808@abbottdavid.com> Everything else works + - / but not * why? thanks -david #!/usr/bin/python from __future__ import division import sys def add(x, y): return x + y def sub(x, y): return x - y def dev(x, y): return x / y def mul(x, y): return x * y def compute(arg1, arg2, arg3): if sys.argv[2] == "+": total = add(int(sys.argv[1]), int(sys.argv[3])) print total elif sys.argv[2] == "-": total = sub(int(sys.argv[1]), int(sys.argv[3])) print total elif sys.argv[2] == "/": total = dev(int(sys.argv[1]), int(sys.argv[3])) print total elif sys.argv[2] == "*": total = mul(int(sys.argv[1]), int(sys.argv[3])) print total else: print "oops" compute(sys.argv[1], sys.argv[2], sys.argv[3]) -- Powered by Gentoo GNU/LINUX http://www.linuxcrazy.com pgp.mit.edu From andreengels at gmail.com Sun Jan 18 16:49:09 2009 From: andreengels at gmail.com (Andre Engels) Date: Sun, 18 Jan 2009 16:49:09 +0100 Subject: [Tutor] calculator will not multiply In-Reply-To: <49734CCE.3030808@abbottdavid.com> References: <49734CCE.3030808@abbottdavid.com> Message-ID: <6faf39c90901180749x5aa114ddh3968c669a5300911@mail.gmail.com> On Sun, Jan 18, 2009 at 4:37 PM, David wrote: > Everything else works + - / but not * > why? > thanks > -david It works for me. However, I do have another issue with your code: > def compute(arg1, arg2, arg3): > if sys.argv[2] == "+": > total = add(int(sys.argv[1]), int(sys.argv[3])) > print total > elif sys.argv[2] == "-": > total = sub(int(sys.argv[1]), int(sys.argv[3])) > print total > elif sys.argv[2] == "/": > total = dev(int(sys.argv[1]), int(sys.argv[3])) > print total > elif sys.argv[2] == "*": > total = mul(int(sys.argv[1]), int(sys.argv[3])) > print total > else: > print "oops" You define this as a function of arg1, arg2 and arg3, but inside the function you use the 'outer value' of sys.argv[1], sys.argv[2] and sys.argv[3]. It is very much advisable to use local rather than global variables inside functions. That way: * you can re-use the function elsewhere in the program, or even in a different program * you can develop the function and the main program semi-independently. For example, suppose you want to make this part of a larger program, and change the call "myprogram.py 2 + 3" to "myprogram.py calculate 2 + 3". In your case, you would have to change all the sys.argv inside the function. If instead you define the function as: def compute(arg1, arg2, arg3): if sys.arg2 == "+": total = add(int(sys.arg1), int(sys.arg3)) print total elif sys.arg2 == "-": total = sub(int(sys.arg1), int(sys.arg3)) print total elif sys.arg2 == "/": total = dev(int(sys.arg1), int(sys.arg3)) print total elif sys.arg2 == "*": total = mul(int(sys.arg1), int(sys.arg3)) print total else: print "oops" this can be implemented without changing the function at all, you just need to change compute(sys.argv[1], sys.argv[2], sys.argv[3]) to if sys.argv[1].equals("compute"): compute(sys.argv[2], sys.argv[3], sys.argv[4]) -- Andr? Engels, andreengels at gmail.com From andreengels at gmail.com Sun Jan 18 16:51:04 2009 From: andreengels at gmail.com (Andre Engels) Date: Sun, 18 Jan 2009 16:51:04 +0100 Subject: [Tutor] calculator will not multiply In-Reply-To: <6faf39c90901180749x5aa114ddh3968c669a5300911@mail.gmail.com> References: <49734CCE.3030808@abbottdavid.com> <6faf39c90901180749x5aa114ddh3968c669a5300911@mail.gmail.com> Message-ID: <6faf39c90901180751p3818f65k7a977077da24fc86@mail.gmail.com> There's an editing error in my previous message. The corrected function should not be: def compute(arg1, arg2, arg3): if sys.arg2 == "+": total = add(int(sys.arg1), int(sys.arg3)) print total elif sys.arg2 == "-": total = sub(int(sys.arg1), int(sys.arg3)) print total elif sys.arg2 == "/": total = dev(int(sys.arg1), int(sys.arg3)) print total elif sys.arg2 == "*": total = mul(int(sys.arg1), int(sys.arg3)) print total else: print "oops" but: def compute(arg1, arg2, arg3): if arg2 == "+": total = add(int(sys.arg1), int(sys.arg3)) print total elif arg2 == "-": total = sub(int(sys.arg1), int(sys.arg3)) print total elif arg2 == "/": total = dev(int(sys.arg1), int(sys.arg3)) print total elif arg2 == "*": total = mul(int(sys.arg1), int(sys.arg3)) print total else: print "oops" -- Andr? Engels, andreengels at gmail.com From jadrifter at gmail.com Sun Jan 18 16:55:30 2009 From: jadrifter at gmail.com (jadrifter) Date: Sun, 18 Jan 2009 07:55:30 -0800 Subject: [Tutor] calculator will not multiply In-Reply-To: <49734CCE.3030808@abbottdavid.com> References: <49734CCE.3030808@abbottdavid.com> Message-ID: <1232294130.6118.4.camel@ltop> On Sun, 2009-01-18 at 10:37 -0500, David wrote: > Everything else works + - / but not * > why? > thanks > -david > > > #!/usr/bin/python > from __future__ import division > import sys > > > def add(x, y): > return x + y > def sub(x, y): > return x - y > def dev(x, y): > return x / y > def mul(x, y): > return x * y > def compute(arg1, arg2, arg3): > if sys.argv[2] == "+": > total = add(int(sys.argv[1]), int(sys.argv[3])) > print total > elif sys.argv[2] == "-": > total = sub(int(sys.argv[1]), int(sys.argv[3])) > print total > elif sys.argv[2] == "/": > total = dev(int(sys.argv[1]), int(sys.argv[3])) > print total > elif sys.argv[2] == "*": > total = mul(int(sys.argv[1]), int(sys.argv[3])) > print total > else: > print "oops" > > compute(sys.argv[1], sys.argv[2], sys.argv[3]) > > It worked fine for me. Don't forget to put quotes around the * sign or the shell will substitute. so: ./calc.py 2 '*' 9 or: ./calc.py 2 "*" 9 or: ./calc.py 2 \* 9 but not: ./calc.py 2 * 9 John Purser From david at abbottdavid.com Sun Jan 18 17:10:50 2009 From: david at abbottdavid.com (David) Date: Sun, 18 Jan 2009 11:10:50 -0500 Subject: [Tutor] calculator will not multiply In-Reply-To: <1232294130.6118.4.camel@ltop> References: <49734CCE.3030808@abbottdavid.com> <1232294130.6118.4.camel@ltop> Message-ID: <4973548A.3090607@abbottdavid.com> jadrifter wrote: > It worked fine for me. Don't forget to put quotes around the * sign or > the shell will substitute. > > so: > ./calc.py 2 '*' 9 > or: > ./calc.py 2 "*" 9 > or: > ./calc.py 2 \* 9 > but not: > ./calc.py 2 * 9 > > John Purser > > > Thanks Kent and jadrifter, that explains that! Also thanks for the tips Angre :) -- Powered by Gentoo GNU/LINUX http://www.linuxcrazy.com pgp.mit.edu From kent37 at tds.net Sun Jan 18 16:58:33 2009 From: kent37 at tds.net (Kent Johnson) Date: Sun, 18 Jan 2009 10:58:33 -0500 Subject: [Tutor] calculator will not multiply In-Reply-To: <49734CCE.3030808@abbottdavid.com> References: <49734CCE.3030808@abbottdavid.com> Message-ID: <1c2a2c590901180758m212c3a31wfded74e9f3e30e64@mail.gmail.com> On Sun, Jan 18, 2009 at 10:37 AM, David wrote: > Everything else works + - / but not * > why? > compute(sys.argv[1], sys.argv[2], sys.argv[3]) Because * is a special character to your shell. Probably your shell is expanding the * to a list of files. Try printing sys.argv from within your program, or quoting the * on the command line. Kent From marc.tompkins at gmail.com Sun Jan 18 19:45:13 2009 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Sun, 18 Jan 2009 10:45:13 -0800 Subject: [Tutor] calculator will not multiply In-Reply-To: <49734CCE.3030808@abbottdavid.com> References: <49734CCE.3030808@abbottdavid.com> Message-ID: <40af687b0901181045h64e8d799qbe4529000b811854@mail.gmail.com> On Sun, Jan 18, 2009 at 7:37 AM, David wrote: > Everything else works + - / but not * > why? > thanks > -david > > > #!/usr/bin/python > from __future__ import division > import sys > > > def add(x, y): > return x + y > def sub(x, y): > return x - y > def dev(x, y): > return x / y > def mul(x, y): > return x * y > def compute(arg1, arg2, arg3): > if sys.argv[2] == "+": > total = add(int(sys.argv[1]), int(sys.argv[3])) > print total > elif sys.argv[2] == "-": > total = sub(int(sys.argv[1]), int(sys.argv[3])) > print total > elif sys.argv[2] == "/": > total = dev(int(sys.argv[1]), int(sys.argv[3])) > print total > elif sys.argv[2] == "*": > total = mul(int(sys.argv[1]), int(sys.argv[3])) > print total > else: > print "oops" > > compute(sys.argv[1], sys.argv[2], sys.argv[3]) > > It works for me under Windows XP, so I suspect that the hints you've received about * being expanded by your shell are correct. However, I had an idea - rather than requiring your user to put quotes around the "*", why not do this: elif sys.argv[2] in ["*","x","X"]: total = mul(int(sys.argv[1]), int(sys.argv[3])) print total This could be a problem if you wanted to develop your calculator into a full-fledged scientific calculator, but otherwise... -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From david at abbottdavid.com Sun Jan 18 22:26:27 2009 From: david at abbottdavid.com (David) Date: Sun, 18 Jan 2009 16:26:27 -0500 Subject: [Tutor] calculator will not multiply In-Reply-To: <40af687b0901181045h64e8d799qbe4529000b811854@mail.gmail.com> References: <49734CCE.3030808@abbottdavid.com> <40af687b0901181045h64e8d799qbe4529000b811854@mail.gmail.com> Message-ID: <49739E83.5050608@abbottdavid.com> Marc Tompkins wrote: > It works for me under Windows XP, so I suspect that the hints you've > received about * being expanded by your shell are correct. However, I > had an idea - rather than requiring your user to put quotes around the > "*", why not do this: > > elif sys.argv[2] in ["*","x","X"]: > total = mul(int(sys.argv[1]), int(sys.argv[3])) > print total Thank you :) > > This could be a problem if you wanted to develop your calculator into a > full-fledged scientific calculator, but otherwise... I may need just a little more practice, not because of a lack of effort, but there seems to be a small problem with retention :( > > > -- > www.fsrtechnologies.com 500 server error > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Powered by Gentoo GNU/LINUX http://www.linuxcrazy.com pgp.mit.edu From echolynx at gmail.com Mon Jan 19 02:15:50 2009 From: echolynx at gmail.com (Ian Egland) Date: Sun, 18 Jan 2009 20:15:50 -0500 Subject: [Tutor] Convert String to Int Message-ID: 'Allo All. I know that, should you want to get an int from the user, you use int(input("Question!")). However, what if the user wasn't that savvy and didn't realize he/she HAD to enter a number? Program crash. Is there a way that I can get the input as a string, check and see if it's convertible to an integer, convert it if it is and ask them to try again if it's not? Thanks in advance. Ian -------------- next part -------------- An HTML attachment was scrubbed... URL: From sridhar.ratna at gmail.com Mon Jan 19 02:32:33 2009 From: sridhar.ratna at gmail.com (Sridhar Ratnakumar) Date: Sun, 18 Jan 2009 17:32:33 -0800 Subject: [Tutor] Convert String to Int In-Reply-To: References: Message-ID: <7c73a13a0901181732n4e143052wc5cb6ffbe791cfec@mail.gmail.com> On Sun, Jan 18, 2009 at 5:15 PM, Ian Egland wrote: > I know that, should you want to get an int from the user, you use > int(input("Question!")). However, what if the user wasn't that savvy and > didn't realize he/she HAD to enter a number? Program crash. Is there a way > that I can get the input as a string, check and see if it's convertible to > an integer, convert it if it is and ask them to try again if it's not? while True: try: a = int(raw_input()) break except ValueError: print "Try again" print 'You entered:', a From marc.tompkins at gmail.com Mon Jan 19 02:35:52 2009 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Sun, 18 Jan 2009 17:35:52 -0800 Subject: [Tutor] Convert String to Int In-Reply-To: References: Message-ID: <40af687b0901181735j58d1c1adq5c654efeed9b6ab1@mail.gmail.com> On Sun, Jan 18, 2009 at 5:15 PM, Ian Egland wrote: > I know that, should you want to get an int from the user, you use > int(input("Question!")). However, what if the user wasn't that savvy and > didn't realize he/she HAD to enter a number? Program crash. Is there a way > that I can get the input as a string, check and see if it's convertible to > an integer, convert it if it is and ask them to try again if it's not? > > You have two options: to test the input ahead of time, or to catch the crash. Believe it or not, number two is usually the preferred method (there's a programming axiom "It's better to ask forgiveness than permission") In Python, you put the operations that have a potential for disaster inside a try/except block, like so: try: > int(input("Question!")) > do whatever... > except: > ask again... > do the next thing > When Python "crashes", an Exception is generated, which carries all sorts of useful information about just what went wrong. It's good form to try to guess what the error might be before catching it (how many times have you been frustrated by some commercial program that says "Out of memory" {or some other catch-all} any time ANYTHING bad happens? It's because the programmer assumed that the only errors that would ever come up would be memory-related. Don't be that guy.) For example, do a test run like so: > >>> int('hello') > Traceback (most recent call last): > File "", line 1, in > ValueError: invalid literal for int() with base 10: 'hello' > Now you know that invalid input would result in a ValueError, so change my above code to: > try: > int(input("Question!")) > do whatever... > except ValueError: > ask again... > do the next thing > Someone else will no doubt already have posted how to test your input ahead of time - I thought I'd chime in with the other method... -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From echolynx at gmail.com Mon Jan 19 02:43:54 2009 From: echolynx at gmail.com (Ian Egland) Date: Sun, 18 Jan 2009 20:43:54 -0500 Subject: [Tutor] Convert String to Int In-Reply-To: <40af687b0901181735j58d1c1adq5c654efeed9b6ab1@mail.gmail.com> References: <40af687b0901181735j58d1c1adq5c654efeed9b6ab1@mail.gmail.com> Message-ID: Actually, nobody told me how to catch it before it occurs, though this "after error" stuff is new to me. Could you send an example of how to catch it beforehand? Just for the record? Thanks. Ian On Sun, Jan 18, 2009 at 8:35 PM, Marc Tompkins wrote: > On Sun, Jan 18, 2009 at 5:15 PM, Ian Egland wrote: > >> I know that, should you want to get an int from the user, you use >> int(input("Question!")). However, what if the user wasn't that savvy and >> didn't realize he/she HAD to enter a number? Program crash. Is there a way >> that I can get the input as a string, check and see if it's convertible to >> an integer, convert it if it is and ask them to try again if it's not? >> >> > You have two options: to test the input ahead of time, or to catch the > crash. Believe it or not, number two is usually the preferred method > (there's a programming axiom "It's better to ask forgiveness than > permission") In Python, you put the operations that have a potential for > disaster inside a try/except block, like so: > > try: >> int(input("Question!")) >> do whatever... >> except: >> ask again... >> do the next thing >> > > When Python "crashes", an Exception is generated, which carries all sorts > of useful information about just what went wrong. It's good form to try to > guess what the error might be before catching it (how many times have you > been frustrated by some commercial program that says "Out of memory" {or > some other catch-all} any time ANYTHING bad happens? It's because the > programmer assumed that the only errors that would ever come up would be > memory-related. Don't be that guy.) For example, do a test run like so: > >> >>> int('hello') >> Traceback (most recent call last): >> File "", line 1, in >> ValueError: invalid literal for int() with base 10: 'hello' >> > > Now you know that invalid input would result in a ValueError, so change my > above code to: > >> try: >> int(input("Question!")) >> do whatever... >> except ValueError: >> ask again... >> do the next thing >> > > Someone else will no doubt already have posted how to test your input ahead > of time - I thought I'd chime in with the other method... > > > -- > www.fsrtechnologies.com > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Mon Jan 19 03:59:04 2009 From: bgailer at gmail.com (bob gailer) Date: Sun, 18 Jan 2009 21:59:04 -0500 Subject: [Tutor] Convert String to Int In-Reply-To: References: Message-ID: <4973EC78.3080408@gmail.com> Ian Egland wrote: > 'Allo All. > > I know that, should you want to get an int from the user, you use > int(input("Question!")). However, what if the user wasn't that savvy > and didn't realize he/she HAD to enter a number? Program crash. Is > there a way that I can get the input as a string, check and see if > it's convertible to an integer, convert it if it is and ask them to > try again if it's not? a = raw_input("Enter an integer:") if a.isdigit(): # process input else: # complain -- Bob Gailer Chapel Hill NC 919-636-4239 From ajarncolin at gmail.com Mon Jan 19 07:28:44 2009 From: ajarncolin at gmail.com (col speed) Date: Mon, 19 Jan 2009 13:28:44 +0700 Subject: [Tutor] cube root Message-ID: <6a1b26420901182228v760bdaddweccbfed9b2495b12@mail.gmail.com> Hi there, just a quick one. Is there a way to obtain cube roots in python? I have been trying: math.pow(n,1.0/3) This works with some, but with 64, for example I get: >>> pow(64,1.0/3) 3.9999999999999996 However: >>> 4**3 64 Any ideas? Thanks Colin -------------- next part -------------- An HTML attachment was scrubbed... URL: From lupin at orcon.net.nz Mon Jan 19 07:41:34 2009 From: lupin at orcon.net.nz (Brett Wilkins) Date: Mon, 19 Jan 2009 19:41:34 +1300 Subject: [Tutor] cube root In-Reply-To: <6a1b26420901182228v760bdaddweccbfed9b2495b12@mail.gmail.com> References: <6a1b26420901182228v760bdaddweccbfed9b2495b12@mail.gmail.com> Message-ID: <4974209E.104@orcon.net.nz> Hey Colin, What you're running into here is the limited accuracy of floating point values... You'll likely find this happens a lot in python.. CPython, at least. (I know, as I do) I'm not sure, as I've never used it... but perhaps Numeric/Numpy handle this kinda stuff better (for accuracy's sake) Cheers, --Brett col speed wrote: > Hi there, just a quick one. > Is there a way to obtain cube roots in python? > I have been trying: > math.pow(n,1.0/3) > This works with some, but with 64, for example I get: > >>> pow(64,1.0/3) > 3.9999999999999996 > However: > >>> 4**3 > 64 > Any ideas? > Thanks > Colin > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From orsenthil at gmail.com Mon Jan 19 08:43:19 2009 From: orsenthil at gmail.com (Senthil Kumaran) Date: Mon, 19 Jan 2009 13:13:19 +0530 Subject: [Tutor] cube root In-Reply-To: <4974209E.104@orcon.net.nz> References: <6a1b26420901182228v760bdaddweccbfed9b2495b12@mail.gmail.com> <4974209E.104@orcon.net.nz> Message-ID: <7c42eba10901182343s3f7ac759tcc4c09a118f7f7aa@mail.gmail.com> On Mon, Jan 19, 2009 at 12:11 PM, Brett Wilkins wrote: > Hey Colin, > What you're running into here is the limited accuracy of floating point > values... Here the Python Documentation mentioning about the inherent limitations in dealing with floating point numbers: http://docs.python.org/tutorial/floatingpoint.html -- Senthil From denis.spir at free.fr Mon Jan 19 09:43:50 2009 From: denis.spir at free.fr (spir) Date: Mon, 19 Jan 2009 09:43:50 +0100 Subject: [Tutor] Convert String to Int In-Reply-To: <4973EC78.3080408@gmail.com> References: <4973EC78.3080408@gmail.com> Message-ID: <20090119094350.048af1b7@o> Le Sun, 18 Jan 2009 21:59:04 -0500, bob gailer a ?crit : > Ian Egland wrote: > > 'Allo All. > > > > I know that, should you want to get an int from the user, you use > > int(input("Question!")). However, what if the user wasn't that savvy > > and didn't realize he/she HAD to enter a number? Program crash. Is > > there a way that I can get the input as a string, check and see if > > it's convertible to an integer, convert it if it is and ask them to > > try again if it's not? > > a = raw_input("Enter an integer:") > if a.isdigit(): > # process input > else: > # complain > Actually, you probably run python 3.0, as you first wrote: int(input("Question!")) Before py3.0, input() would have processed & converted automatically the user input text (type string) into a number, if possible. So that int() would be useless. Try: >>> type(input()) 1 If you get this output, you have py<3.0 installed. But this behaviour was not the best (both for stability and security reasons) so that it was recommanded to use raw_input() instead, that keeps the input as raw string and lets the programmer process it carefully according to actual needs. With python 3, only raw_input() remains, but it has been renamed to "input()", so that only the correct feature is available. denis ------ la vida e estranya From alan.gauld at btinternet.com Mon Jan 19 10:00:13 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 19 Jan 2009 09:00:13 -0000 Subject: [Tutor] cube root References: <6a1b26420901182228v760bdaddweccbfed9b2495b12@mail.gmail.com> <4974209E.104@orcon.net.nz> Message-ID: "Brett Wilkins" wrote > What you're running into here is the limited accuracy of floating > point > values... You'll likely find this happens a lot in python.. CPython, > at least. In fact it happens with virtually every programming language available. The problem traces back to the way that computers represent floating point numbers in hardware. The integrated circuits cannot hold infinitely long numbers so they need to use a condensed representation and that inherently introduces small inaccuracies. (Think of 1/3 in decimal - an infinite series of 1.3333..., the same is true in binary, some numbers just cannot be represented accurately) In the specific case being discussed you can disguise the problem quite easily by displaying the result with a smaller number of decimal places using round() or string formatting: >>> 64**(1.0/3) 3.9999999999999996 >>> print 64**(1.0/3) 4.0 >>> round(64**(1.0/3)) 4.0 >>> "%5.3f" % 64**(1.0/3) '4.000' >>> When you need to compare floating point numbers you also need to be careful since: >>> 4.0 == 64**(1.0/3) ## is false! You need to introduce an error range, typically: >>> e = 0.00000001 >>> 4.0-e < 64**(1.0/3) < 4.0+e # is true You can also use the decimal module for exact decimal arithmetic but it introduces some other complications. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Mon Jan 19 10:05:49 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 19 Jan 2009 09:05:49 -0000 Subject: [Tutor] Convert String to Int References: Message-ID: "Ian Egland" wrote > I know that, should you want to get an int from the user, you use > int(input("Question!")). However, what if the user wasn't that savvy > and > didn't realize he/she HAD to enter a number? It's considered good UI design to phrase the prompt in such a way as to help the user know what to input: Thus: >>> x = int(input("Date(1-31): ")) or >>> s = int(input("Sex(m=1,f=2): ")) And then you have trhe responsibility to catch the error just in case... This is all part of "industrial standard" programming. You have to make your programs foolproof, while bearing in mind that nature keeps buiding bigger and better fools! -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Mon Jan 19 10:12:43 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 19 Jan 2009 09:12:43 -0000 Subject: [Tutor] Convert String to Int References: <40af687b0901181735j58d1c1adq5c654efeed9b6ab1@mail.gmail.com> Message-ID: "Ian Egland" wrote > Actually, nobody told me how to catch it before it occurs x = input('x = ') if type(x) == int: # check its an integer x = int(x) # ok, so convert to a number else: print ("Please enter a number") But that leads to much more complex and inefficient code so we prefer try: x = int(input(...)) except: print ('Please enter a number') PS. Assuming you are using Python v3. If you are using an earlier version its better(safer) to use raw_input() rather than input() which is potentially dangerous. In v3 old style input has been removed and raw_input replaced with a new safe input() HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Mon Jan 19 10:14:39 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 19 Jan 2009 09:14:39 -0000 Subject: [Tutor] Convert String to Int References: <4973EC78.3080408@gmail.com> Message-ID: "bob gailer" wrote > a = raw_input("Enter an integer:") > if a.isdigit(): > # process input Oops, yes. My posting on this is wrong because you can't compare to int untl after you convert the value. isdigit() is the correct check. Apologies - too early in the morning... Alan G From jammy007_pp at yahoo.com Mon Jan 19 10:18:41 2009 From: jammy007_pp at yahoo.com (jammy007 pp) Date: Mon, 19 Jan 2009 01:18:41 -0800 (PST) Subject: [Tutor] help on making python tictactoe Message-ID: <502624.34781.qm@web63305.mail.re1.yahoo.com> guys , i need immediate help on creating a simple tictactoe game . i read micheal dawson's book but didnt quiet get it . please help . thanks . jammy -------------- next part -------------- An HTML attachment was scrubbed... URL: From vginer at gmail.com Mon Jan 19 11:28:54 2009 From: vginer at gmail.com (Vicent) Date: Mon, 19 Jan 2009 11:28:54 +0100 Subject: [Tutor] cube root In-Reply-To: <4974209E.104@orcon.net.nz> References: <6a1b26420901182228v760bdaddweccbfed9b2495b12@mail.gmail.com> <4974209E.104@orcon.net.nz> Message-ID: <50ed08f40901190228h1a2858c1g1061068d16515560@mail.gmail.com> On Mon, Jan 19, 2009 at 07:41, Brett Wilkins wrote: > > What you're running into here is the limited accuracy of floating point > values... > You'll likely find this happens a lot in python.. CPython, at least. (I > know, as I do) > I'm not sure, as I've never used it... but perhaps Numeric/Numpy handle > this kinda stuff better (for accuracy's sake) > > Maybe this issue can be overcome by using symbolic notation when possible (maybe by using SymPy)? Has anyone any experience with this? -- Vicent -------------- next part -------------- An HTML attachment was scrubbed... URL: From ptmcg at austin.rr.com Mon Jan 19 11:29:03 2009 From: ptmcg at austin.rr.com (Paul McGuire) Date: Mon, 19 Jan 2009 04:29:03 -0600 Subject: [Tutor] cube root In-Reply-To: References: Message-ID: Wow! Everybody jumped on the "floating point inaccuracy" topic, I'm surprised no one tried to find out what the OP was trying to do with his cube root solver in the first place. Of course, the first-cut approach to solving the cube root is to raise to the 1/3 power, but this is not the only possible approach. Assuming that the OP wanted to try to find cube roots for integers, or raise an exception if the given number is not a perfect cube, I came up with this: def cube_root(n): "A modified Newton's Method solver for integral cube roots." if int(n) != n: raise ValueError("must provide an integer") if n in (-1,0,1): return n offset = (1,-1)[n > 0] x = n/2 seen = set() steps = 0 while 1: y = x**3 if y == n: #~ print "Found %d ^ 1/3 = %d in %d steps" % (n,x,steps) return x dydx = 3.0*x*x x += int((n-y)/dydx)+offset x = x or 1 if x in seen: raise ValueError("%d is not a perfect cube" % n) seen.add(x) steps += 1 This will correctly give 4 for 64, 5 for 125, etc., not 3.99999999999. Then I went googling for "python cube root", and found this curious solution: def root3rd(x): y, y1 = None, 2 while y!=y1: y = y1 y3 = y**3 d = (2*y3+x) y1 = (y*(y3+2*x)+d//2)//d return y This only works for perfect cubes, but could be made more robust with this test just before returning y: if y*y*y != x: raise ValueError("%d is not a perfect cube" % x) I was intrigued at this solution - timing it versus mine showed it to be 5x faster. I tried to see some sort of Newton's method implementation, but instead its more of a binary search. This was confirmed by adding this line inside the while loop: print y,y1 And to solve for the cube root of 1860867 (123**3), I get this output: None 2 2 4 4 8 8 16 16 32 32 62 62 105 105 123 with the value 123 returned as the answer. Note that the guess (variable y1) is initially doubled and redoubled, until the solution is neared. I tried initializing y1 to a different guess, the original number, and got this: None 1860867 1860867 930434 930434 465217 465217 232609 232609 116305 116305 58153 58153 29077 29077 14539 14539 7270 7270 3635 3635 1818 1818 909 909 456 456 235 235 141 141 123 Now the guess is halved each time until nearing the solution, then again converging to the solution 123. This algorithm is also robust in that it can do more than just cube roots. By changing this line: y3 = y**3 to: y3 = y**4 We get a 4th root solver! Unfortunately, this breaks down at the 5th root, as I found solutions would not converge. At this point, I lost interest in the general applicability of this algorithm, but it is still an interesting approach - does anyone know the theoretical basis for it? I guess I was just disappointed that taking cube roots of so small a number as 64 quickly got us into floating-point roundoff errors, and if the OP is doing something like looking for perfect cubes, then there are alternatives to the one-size-fits-almost-all logarithmic implementation of the '**' operator. -- Paul From lupin at orcon.net.nz Mon Jan 19 12:11:22 2009 From: lupin at orcon.net.nz (Brett Wilkins) Date: Tue, 20 Jan 2009 00:11:22 +1300 (NZDT) Subject: [Tutor] cube root Message-ID: <16251.131.203.105.1.1232363482.squirrel@mail.orcon.net.nz> The only language I've run into so far (I haven't used many, mind) that doesn't have this issue is Scheme :) (Just learning it at the moment.) Cheers, --Brett P.S. Forgive me if this email doesn't sort properly, sending through webmail, as I don't have a relaying SMTP available to me currently. Alan Gauld wrote: > > "Brett Wilkins" wrote > >> What you're running into here is the limited accuracy of floating point >> values... You'll likely find this happens a lot in python.. CPython, >> at least. > > In fact it happens with virtually every programming language available. > The problem traces back to the way that computers represent floating > point numbers in hardware. The integrated circuits cannot hold infinitely > long numbers so they need to use a condensed representation and > that inherently introduces small inaccuracies. (Think of 1/3 in > decimal - an infinite series of 1.3333..., the same is true in binary, > some numbers just cannot be represented accurately) > > In the specific case being discussed you can disguise the problem > quite easily by displaying the result with a smaller number of decimal > places using round() or string formatting: > >>>> 64**(1.0/3) > 3.9999999999999996 >>>> print 64**(1.0/3) > 4.0 >>>> round(64**(1.0/3)) > 4.0 >>>> "%5.3f" % 64**(1.0/3) > '4.000' >>>> > > When you need to compare floating point numbers you also > need to be careful since: > >>>> 4.0 == 64**(1.0/3) ## is false! > > You need to introduce an error range, typically: > >>>> e = 0.00000001 >>>> 4.0-e < 64**(1.0/3) < 4.0+e # is true > > You can also use the decimal module for exact decimal > arithmetic but it introduces some other complications. > > HTH, > > From kent37 at tds.net Mon Jan 19 12:58:11 2009 From: kent37 at tds.net (Kent Johnson) Date: Mon, 19 Jan 2009 06:58:11 -0500 Subject: [Tutor] cube root In-Reply-To: <16251.131.203.105.1.1232363482.squirrel@mail.orcon.net.nz> References: <16251.131.203.105.1.1232363482.squirrel@mail.orcon.net.nz> Message-ID: <1c2a2c590901190358v5f20a2f2k70606162c301b9e4@mail.gmail.com> On Mon, Jan 19, 2009 at 6:11 AM, Brett Wilkins wrote: > The only language I've run into so far (I haven't used many, mind) that > doesn't have this issue is Scheme :) It doesn't have an issue with cube roots or with floating point inaccuracies in general? If the latter, I would like to know how they do that... Kent From denis.spir at free.fr Mon Jan 19 13:13:53 2009 From: denis.spir at free.fr (spir) Date: Mon, 19 Jan 2009 13:13:53 +0100 Subject: [Tutor] cube root In-Reply-To: References: <6a1b26420901182228v760bdaddweccbfed9b2495b12@mail.gmail.com> <4974209E.104@orcon.net.nz> Message-ID: <20090119131353.4c5d6b2a@o> Do you know any common algorithm to convert decimal (in the sense of fractional) decimals (in the sense of base 10 numbers) into binaries? 123.456 --> 1111011.bbb... and/or 123456 * 10**(-3) --> bbb... * 2**(-bbb...) How do python/C achieve that? denis ------ la vida e estranya From andreengels at gmail.com Mon Jan 19 13:15:25 2009 From: andreengels at gmail.com (Andre Engels) Date: Mon, 19 Jan 2009 13:15:25 +0100 Subject: [Tutor] cube root In-Reply-To: <16251.131.203.105.1.1232363482.squirrel@mail.orcon.net.nz> References: <16251.131.203.105.1.1232363482.squirrel@mail.orcon.net.nz> Message-ID: <6faf39c90901190415o5fc08255w2649df5b85520c74@mail.gmail.com> On Mon, Jan 19, 2009 at 12:11 PM, Brett Wilkins wrote: > The only language I've run into so far (I haven't used many, mind) that > doesn't have this issue is Scheme :) > (Just learning it at the moment.) It doesn't? That would surprise me. The only one that I know to do this kind of thing correctly is Matlab. -- Andr? Engels, andreengels at gmail.com From lupin at orcon.net.nz Mon Jan 19 13:20:48 2009 From: lupin at orcon.net.nz (Brett Wilkins) Date: Tue, 20 Jan 2009 01:20:48 +1300 (NZDT) Subject: [Tutor] cube root Message-ID: <18363.131.203.105.1.1232367648.squirrel@mail.orcon.net.nz> Hmm, Well I thought it was both, but the latter seems untrue (now that I test a bit more) (expt 64 (/ 1 3)) gives the value 4, but turning any of those into floating point numbers seems to give me the infamous 3.999999999999996 thing all over again. I was originally thinking that scheme would handle exponents as floating point numbers, the way that C does (ie 2e20 is a fp number...), and I tested 2e20+1-2e20, which stumps most languages (python just gives 0.0, gcc 4.0.1 gives the same). Oh well, sorry to get your hopes up! Btw, I'm using MIT/GNU scheme, in case that makes a difference. Cheers --Brett Kent Johnson wrote: > On Mon, Jan 19, 2009 at 6:11 AM, Brett Wilkins wrote: >> The only language I've run into so far (I haven't used many, mind) that >> doesn't have this issue is Scheme :) > > It doesn't have an issue with cube roots or with floating point > inaccuracies in general? If the latter, I would like to know how they > do that... > > Kent From andreengels at gmail.com Mon Jan 19 13:22:59 2009 From: andreengels at gmail.com (Andre Engels) Date: Mon, 19 Jan 2009 13:22:59 +0100 Subject: [Tutor] cube root In-Reply-To: <20090119131353.4c5d6b2a@o> References: <6a1b26420901182228v760bdaddweccbfed9b2495b12@mail.gmail.com> <4974209E.104@orcon.net.nz> <20090119131353.4c5d6b2a@o> Message-ID: <6faf39c90901190422g77265d0ewc673fcbde46fc532@mail.gmail.com> On Mon, Jan 19, 2009 at 1:13 PM, spir wrote: > Do you know any common algorithm to convert decimal (in the sense of fractional) decimals (in the sense of base 10 numbers) into binaries? > > 123.456 --> 1111011.bbb... > and/or > 123456 * 10**(-3) --> bbb... * 2**(-bbb...) > > How do python/C achieve that? There's probably more efficient methods, but a simple method to convert a decimal fraction to a binary would be the following (untested): def tobinary(n,precision=12) # n is a number between 0 and 1 that should be converted, precision is the number of binary digits to use. assert 0.0 <= n < 1.0 outcome = "0." compare = 0.5 for i in xrange(precision): if n > compare: outcome += "1" n -= compare if n == 0.0: break else: outcome += "0" compare /= 2 return outcome -- Andr? Engels, andreengels at gmail.com From denis.spir at free.fr Mon Jan 19 13:26:15 2009 From: denis.spir at free.fr (spir) Date: Mon, 19 Jan 2009 13:26:15 +0100 Subject: [Tutor] help on making python tictactoe In-Reply-To: <502624.34781.qm@web63305.mail.re1.yahoo.com> References: <502624.34781.qm@web63305.mail.re1.yahoo.com> Message-ID: <20090119132615.7cb8025f@o> Le Mon, 19 Jan 2009 01:18:41 -0800 (PST), jammy007 pp a ?crit : > guys , i need immediate help on creating a simple tictactoe game . > > i read micheal dawson's book but didnt quiet get it . > > please help . > > thanks . > > jammy > > > > try googling: "software developpment company python xxx" (name of your city here) --------------^ More seriously: This is a list for (mutual) help. You would have better results providing concrete information on what precise issue you "didnt quiet get" than demanding "immediate help". (I guess.) denis ------ la vida e estranya From ksterling at mindspring.com Mon Jan 19 14:46:21 2009 From: ksterling at mindspring.com (Ken Oliver) Date: Mon, 19 Jan 2009 08:46:21 -0500 (EST) Subject: [Tutor] cube root Message-ID: <23945681.1232372781650.JavaMail.root@mswamui-billy.atl.sa.earthlink.net> -----Original Message----- >From: Andre Engels >Sent: Jan 19, 2009 7:22 AM >To: spir >Cc: tutor at python.org >Subject: Re: [Tutor] cube root > >On Mon, Jan 19, 2009 at 1:13 PM, spir wrote: >> Do you know any common algorithm to convert decimal (in the sense of fractional) decimals (in the sense of base 10 numbers) into binaries? >> >> 123.456 --> 1111011.bbb... >> and/or >> 123456 * 10**(-3) --> bbb... * 2**(-bbb...) >> >> How do python/C achieve that? > >There's probably more efficient methods, but a simple method to >convert a decimal fraction to a binary would be the following >(untested): > >def tobinary(n,precision=12) > # n is a number between 0 and 1 that should be converted, >precision is the number of binary digits to use. > assert 0.0 <= n < 1.0 > outcome = "0." > compare = 0.5 > for i in xrange(precision): > if n > compare: > outcome += "1" > n -= compare > if n == 0.0: break > else: > outcome += "0" > compare /= 2 > return outcome > >-- >Andr? Engels, andreengels at gmail.com I hope my memory serves. To convert decimal fraction into binary fraction, do the following repeatedly to the decimal until desired accuracy is achieved. Multiply by 2, if result is less than 1, next digit is 0 else next digit is 1 and you drop the whole number part of the result. Continue... .456 * 2 = .912 (first digit is 0) .912 * 2 = 1.824 (next digit is 1) .824 * 2 = 1.648 (next digit is 1) .648 * 2 = 1.296 (next digit is 1) .296 * 2 = .592 (next digit is 0) 0.456 ~ 0.01110 From irimia.suleapa at unknownsoftware.ro Mon Jan 19 15:11:44 2009 From: irimia.suleapa at unknownsoftware.ro (Irimia, Suleapa) Date: Mon, 19 Jan 2009 16:11:44 +0200 Subject: [Tutor] Ip address Message-ID: <49748A20.50604@unknownsoftware.ro> Hello list, I am new to python and i have a question. I managed to build a client which connect to an website and grab things from there. I run this client on a linux box, which have multiple ip address. What do i want is to run 3 clients and each one to use different ip address to access that website. Anyone can point me to some documentation about how this can be done? Thanks and advance, From bhaaluu at gmail.com Mon Jan 19 15:55:55 2009 From: bhaaluu at gmail.com (bhaaluu) Date: Mon, 19 Jan 2009 09:55:55 -0500 Subject: [Tutor] help on making python tictactoe In-Reply-To: <502624.34781.qm@web63305.mail.re1.yahoo.com> References: <502624.34781.qm@web63305.mail.re1.yahoo.com> Message-ID: On Mon, Jan 19, 2009 at 4:18 AM, jammy007 pp wrote: > guys , i need immediate help on creating a simple tictactoe game . > > i read micheal dawson's book but didnt quiet get it . > > please help . > > thanks . > > jammy Python Programming for the Absolute Beginner 2E by Michael Dawson has the BEST explanation there is of programming a Tic-Tac-Toe game! It is explained in Chapter 6 Functions The Tic-Tac-Toe Game. If you've read and done the Challenges in Chapters 1-5, then the 'new' concept on Chapter 6 is how to program with functions. Otherwise, the Tic-Tac-Toe game is covered step-by-step. 1. Read Chapter 6. 2. Go back and highlight the important new concepts. 3. Key the Tic-Tac-Toe program into your computer. (It is better to key it in than copy/paste it from the CD) 4. Get the game running on your computer. You'll find typos. This is part of learning Python. You need to make mistakes. Finding and correcting your mistakes is an important part of learning how to program a computer.. 5. Make a hard-copy print-out of the source code for the game you just got running.. 6. Play computer by reading and following the program flow in the printout. Underline, highlight, and write notes in the margins of the printout as you 'play computer'. 7. Do the Challenges for Chapter 6. Challenge No. 4 is to plug the hole in the strategy of the game in the book. To do that, you'll need to modify the game in the book. If you've followed the above instructions, you should have no problems. 8. If you still have problems, post _your_ problem source code to this list with an explanation of what your problem is. Happy Programming! -- b h a a l u u at g m a i l dot c o m Kid on Bus: What are you gonna do today, Napoleon? Napoleon Dynamite: Whatever I feel like I wanna do. Gosh! From srilyk at gmail.com Mon Jan 19 16:27:07 2009 From: srilyk at gmail.com (W W) Date: Mon, 19 Jan 2009 09:27:07 -0600 Subject: [Tutor] Ip address In-Reply-To: <49748A20.50604@unknownsoftware.ro> References: <49748A20.50604@unknownsoftware.ro> Message-ID: <333efb450901190727s261437dbi3cdb8fe55e85b8bb@mail.gmail.com> On Mon, Jan 19, 2009 at 8:11 AM, Irimia, Suleapa < irimia.suleapa at unknownsoftware.ro> wrote: > Hello list, > > I am new to python and i have a question. I managed to build a client which > connect to an website and grab things from there. I run this client on a > linux box, which have multiple ip address. What do i want is to run 3 > clients and each one to use different ip address to access that website. > Anyone can point me to some documentation about how this can be done? > I'm not 100% sure if I understand what you're saying, so let me clarify: You have one linux box, with 3 instances of your program running, and you want the server to see these as three unique IPs? I'm not aware of any way to do this without proxy servers or IP spoofing. HTH, Wayne -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn't. - Primo Levi -------------- next part -------------- An HTML attachment was scrubbed... URL: From brian.mathis at gmail.com Mon Jan 19 17:15:57 2009 From: brian.mathis at gmail.com (Brian Mathis) Date: Mon, 19 Jan 2009 11:15:57 -0500 Subject: [Tutor] help on making python tictactoe In-Reply-To: <502624.34781.qm@web63305.mail.re1.yahoo.com> References: <502624.34781.qm@web63305.mail.re1.yahoo.com> Message-ID: <183c528b0901190815oa11eb63rb7a902e4f92af077@mail.gmail.com> On Mon, Jan 19, 2009 at 4:18 AM, jammy007 pp wrote: > guys , i need immediate help on creating a simple tictactoe game . > > i read micheal dawson's book but didnt quiet get it . > > please help . > > thanks . > > jammy The purpose of homework is that you figure it out for yourself and learn something. From eike.welk at gmx.net Mon Jan 19 18:57:35 2009 From: eike.welk at gmx.net (Eike Welk) Date: Mon, 19 Jan 2009 18:57:35 +0100 Subject: [Tutor] Non-blocking non-interactive graphics display In-Reply-To: <4a289b480901142200k3e376eaeg39de1ed8de1e239c@mail.gmail.com> References: <4a289b480901142200k3e376eaeg39de1ed8de1e239c@mail.gmail.com> Message-ID: <200901191857.36613.eike.welk@gmx.net> You should look at IPython it is a frontend for the Python interpreter that runs the eventloop of Matplotlib in a separate thread. http://ipython.scipy.org/moin/ http://matplotlib.sourceforge.net/ Matplotlib and Ipython might be in your Python distribution from Enthougt. A session with Ipython looks like this: ---------------------------------------------------- eike at lixie:~> ipython --pylab Welcome to pylab, a matplotlib-based Python environment. For more information, type 'help(pylab)'. In [1]:plot([1,2,4,8]) Out[1]:[] In [2]:#A window with a graph has appeared. One can pan and zoom this graph. In [3]:1+2+3 Out[3]:6 In [4]: ----------------------------------------------------- In the Matplotlib newsgroup you would have to ask how to draw graphical primitives (lines). HTH, Eike. From steve at alchemy.com Mon Jan 19 19:05:22 2009 From: steve at alchemy.com (Steve Willoughby) Date: Mon, 19 Jan 2009 10:05:22 -0800 Subject: [Tutor] Question about pygame/tkinter interaction In-Reply-To: <200901191857.36613.eike.welk@gmx.net> References: <4a289b480901142200k3e376eaeg39de1ed8de1e239c@mail.gmail.com> <200901191857.36613.eike.welk@gmx.net> Message-ID: <20090119180522.GA66977@dragon.alchemy.com> I have a game I'm porting to Python which is currently written using TCL/Tk. Now it would be fairly easy to make it work in Python with Tkinter, of course, since the way the GUI would be organized and implemented would be essentially the same. However, I'd also like to implement some fancier (but minor) animated effects and embed video and audio clips. So I was thinking that pygame (or pymedia) would be reasonable choices, but I've never used either of those before. Is it reasonable to expect that I could use Tkinter for everything else, but use pygame/pymedia to handle things like creating a video playback window on the screen, or is pygame going to want to run the whole GUI event loop and screen updates in competition with Tkinter? Any general nudges in the right direction would be appreciated. Thanks, steve -- Steve Willoughby | Using billion-dollar satellites steve at alchemy.com | to hunt for Tupperware. From wescpy at gmail.com Mon Jan 19 19:36:07 2009 From: wescpy at gmail.com (wesley chun) Date: Mon, 19 Jan 2009 10:36:07 -0800 Subject: [Tutor] Convert String to Int In-Reply-To: References: <40af687b0901181735j58d1c1adq5c654efeed9b6ab1@mail.gmail.com> Message-ID: <78b3a9580901191036l4ed1912ele606b6e47535e858@mail.gmail.com> > if type(x) == int: # check its an integer i also understand that it's "isinstance(x, int)" should be used instead of the above or "if type(x) is int" but i'm running a blank as to why at this exact moment... perhaps it's an all-C function? however, all of these comparisons are only good if 'x' represents the object of desire. if it's output from raw_input() [in 2.x] or input() [in 3.x], it won't do any good because 'x' would still be a str. so before converting to an int, i would go with the isdigit() method, perhaps x.strip().isdigit() because you don't want to be messed up by a user who may have inadvertently typed one or more spaces before or after the number. hope this helps! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 "Python Fundamentals", Prentice Hall, (c)2009 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From srilyk at gmail.com Mon Jan 19 19:45:29 2009 From: srilyk at gmail.com (W W) Date: Mon, 19 Jan 2009 12:45:29 -0600 Subject: [Tutor] Question about pygame/tkinter interaction In-Reply-To: <20090119180522.GA66977@dragon.alchemy.com> References: <4a289b480901142200k3e376eaeg39de1ed8de1e239c@mail.gmail.com> <200901191857.36613.eike.welk@gmx.net> <20090119180522.GA66977@dragon.alchemy.com> Message-ID: <333efb450901191045j234d0cch621032eed00c4f0a@mail.gmail.com> On Mon, Jan 19, 2009 at 12:05 PM, Steve Willoughby wrote: > Is it reasonable to expect that I could use Tkinter for > everything else, but use pygame/pymedia to handle things like > creating a video playback window on the screen, or is pygame > going to want to run the whole GUI event loop and screen updates > in competition with Tkinter? > > Any general nudges in the right direction would be appreciated. > Thanks, > steve > As far as I know it would be a fairly reasonable expectation - you would simply hide the Tkinter screen when you show the pygame/pymedia window. However, I'm not nearly as versed on any of the above as a lot of folks here, so they may be able to confirm/contradict my advice. But with my limited knowledge, that's probably how I'd do it (unless you have a burning desire to learn pygame). HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From eike.welk at gmx.net Mon Jan 19 21:16:20 2009 From: eike.welk at gmx.net (Eike Welk) Date: Mon, 19 Jan 2009 21:16:20 +0100 Subject: [Tutor] Question about pygame/tkinter interaction In-Reply-To: <20090119180522.GA66977@dragon.alchemy.com> References: <4a289b480901142200k3e376eaeg39de1ed8de1e239c@mail.gmail.com> <200901191857.36613.eike.welk@gmx.net> <20090119180522.GA66977@dragon.alchemy.com> Message-ID: <200901192116.21021.eike.welk@gmx.net> You could use Qt and PyQt (bindings) for your application. QT is a library for buttons and similar things; it can show images, play video and play sound. They should both be part of every big Linux distribution. They are also available for Windows and Mac OS. http://doc.trolltech.com/4.4/index.html http://www.riverbankcomputing.co.uk/news List of tutorials: http://www.diotavelli.net/PyQtWiki/Tutorials Kind regards, Eike. From kent37 at tds.net Mon Jan 19 21:11:16 2009 From: kent37 at tds.net (Kent Johnson) Date: Mon, 19 Jan 2009 15:11:16 -0500 Subject: [Tutor] Convert String to Int In-Reply-To: <78b3a9580901191036l4ed1912ele606b6e47535e858@mail.gmail.com> References: <40af687b0901181735j58d1c1adq5c654efeed9b6ab1@mail.gmail.com> <78b3a9580901191036l4ed1912ele606b6e47535e858@mail.gmail.com> Message-ID: <1c2a2c590901191211xc993913q4ab164ac470e80b@mail.gmail.com> On Mon, Jan 19, 2009 at 1:36 PM, wesley chun wrote: >> if type(x) == int: # check its an integer > > > i also understand that it's "isinstance(x, int)" should be used > instead of the above or "if type(x) is int" but i'm running a blank as > to why at this exact moment... perhaps it's an all-C function? If x is an instance of a subclass of Y, 'type(x) == Y" and "type(x) is Y" will fail; isinstance(x, Y) will succeed. Generally it's preferable to allow subclasses so isinstance() is preferred. Kent From kent37 at tds.net Mon Jan 19 23:30:01 2009 From: kent37 at tds.net (Kent Johnson) Date: Mon, 19 Jan 2009 17:30:01 -0500 Subject: [Tutor] Question about pygame/tkinter interaction In-Reply-To: <20090119180522.GA66977@dragon.alchemy.com> References: <4a289b480901142200k3e376eaeg39de1ed8de1e239c@mail.gmail.com> <200901191857.36613.eike.welk@gmx.net> <20090119180522.GA66977@dragon.alchemy.com> Message-ID: <1c2a2c590901191430o561da1a6o952229c05c4afd6f@mail.gmail.com> On Mon, Jan 19, 2009 at 1:05 PM, Steve Willoughby wrote: > Is it reasonable to expect that I could use Tkinter for > everything else, but use pygame/pymedia to handle things like > creating a video playback window on the screen, or is pygame > going to want to run the whole GUI event loop and screen updates > in competition with Tkinter? My guess is that pygame and Tkinter are both going to want to control the event loop. Googling 'pygame tkinter' gives both hints that it might be possible and hints of trouble... Kent From benjamin.serrato at gmail.com Mon Jan 19 23:36:54 2009 From: benjamin.serrato at gmail.com (Benjamin Serrato) Date: Mon, 19 Jan 2009 16:36:54 -0600 Subject: [Tutor] Tutor Digest, Vol 59, Issue 90 In-Reply-To: References: Message-ID: I would like to add that 'A Byte of Python has been updated for python3.0 print statements are corrected and Swaroop looks to be still working on it. It's a wiki now, so the text can be edited if you find a better explanation and would like to add to it. I like Swaroop's style though. B Serrato > Hello all, I just joined this mailing list. > > I am a beginner to programming in general and would really appreciate a > > tutorial for Python3000 that at least covers the basics. I have tried > > reading the manual, but I think it was written for more experienced > > programmers wishing to switch to python rather than a beginner looking for > > where to start. Most of the other tutorials I have found were for earlier > > versions of Python, and because Python 3.0 was released on my birthday, I > > decided I was meant to learn that release. ;-) > > Anyway, any help would be appreciated. I will do my best to return the > > favor. > > -Ian > -------------- next part -------------- An HTML attachment was scrubbed... URL: From lidereshumanistas at gmail.com Mon Jan 19 23:40:37 2009 From: lidereshumanistas at gmail.com (Lideres Humanistas) Date: Mon, 19 Jan 2009 19:40:37 -0300 Subject: [Tutor] Python in the World March For Peace and Nonviolence Message-ID: Designers Python: We may use the Global March for Peace and Nonviolence to position the Python language and free software in the world. And joined the World March Richard Sallman. http://marchamundial.org/en/participation-participation-forms/listados-de-adhesiones/some-of-our-participants/163-richard-stallman Emilio Castro. -- Inter?s Cehum.cl: Desarrollar el conocimiento por encima de los pre-dialogales aceptados o impuestos al pensamiento como verdades consideradas intencionalmente como absolutas e inamovibles. Sitios Web de inter?s humanizador: http://humanistasenaccion.org http://www.cehum.cl http://groups.google.es/group/punta-de-vacas-2010 http://groups.google.es/group/revolucion-industrial-humanista http://groups.google.es/group/revolucion-educacional-humanista http://groups.google.es/group/revolucion-salud-humanista http://groups.google.es/group/revolucion-deportiva-humanista http://groups.google.es/group/desarme-nuclear-universal http://flickr.com/photos/humanizador/ http://flickr.com/photos/humanizate/ http://humanizador.blogspot.com/ http://www.youtube.com/humanizador http://www.panoramio.com/user/650187 http://www.florcitamotuda.tk http://www.yonopago.cl http://www.silo.net http://www.silo.ws http://www.parquemanantiales.org http://www.parquepuntadevacas.org -------------- next part -------------- An HTML attachment was scrubbed... URL: From srilyk at gmail.com Tue Jan 20 00:04:33 2009 From: srilyk at gmail.com (W W) Date: Mon, 19 Jan 2009 17:04:33 -0600 Subject: [Tutor] 2.5 vs 3k? Message-ID: <333efb450901191504p3be78737xff89463226e1c701@mail.gmail.com> So, I'm curious about this whole python 3k thing. Is python migrating to 3k only? Will 2.x no longer be "officially" supported? If so/not, what are some of the arguments for migrating to 3k? What makes it "better" than the python we all know and love? Thanks for the info/comments, Wayne -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn't. - Primo Levi -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Jan 20 00:36:33 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 19 Jan 2009 23:36:33 -0000 Subject: [Tutor] 2.5 vs 3k? References: <333efb450901191504p3be78737xff89463226e1c701@mail.gmail.com> Message-ID: "W W" wrote > So, I'm curious about this whole python 3k thing. Is python > migrating to 3k > only? Will 2.x no longer be "officially" supported? If you look at what happened with other major language changes (Perl 4->5 for example) there is likely to be a lot of support for 2.X Python for several years. This will likely be driven by necessity, there is an awful lot of code out there that won't be upgraded to 3 for a long time. But new features will likely start to only appear in 3. And 2.X releases will be focused on bug fixes etc. > If so/not, what are some of the arguments for migrating to 3k? What > makes it > "better" than the python we all know and love? There is a web page somewhere on the web site that gives a list of the new features/improvements. None of them are totally compelling for me but I am starting to look into it now. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/l From john at fouhy.net Tue Jan 20 00:38:11 2009 From: john at fouhy.net (John Fouhy) Date: Tue, 20 Jan 2009 12:38:11 +1300 Subject: [Tutor] 2.5 vs 3k? In-Reply-To: <333efb450901191504p3be78737xff89463226e1c701@mail.gmail.com> References: <333efb450901191504p3be78737xff89463226e1c701@mail.gmail.com> Message-ID: <5e58f2e40901191538v43cc49d6j283bb441f4c602f9@mail.gmail.com> 2009/1/20 W W : > So, I'm curious about this whole python 3k thing. Is python migrating to 3k > only? Will 2.x no longer be "officially" supported? Python might be transitioning to 3.0, but the full migration will take years. Python 2.6 is not going away -- in fact, I see on python.org that new versions of python 2.5 and 2.4 have just been released -- and python 2.7 will come out in time. > If so/not, what are some of the arguments for migrating to 3k? What makes it > "better" than the python we all know and love? You can see the short list of what's new/different here: http://docs.python.org/3.0/whatsnew/3.0.html If any of that appeals to you, then go for it :-) An argument for _not_ migrating (yet) is that most 3rd party libraries are still python 2.x. I expect they'll start to change, though, and you might need to migrate eventually if you want access to new stuff. -- John. From steve at alchemy.com Tue Jan 20 00:46:27 2009 From: steve at alchemy.com (Steve Willoughby) Date: Mon, 19 Jan 2009 15:46:27 -0800 Subject: [Tutor] Question about pygame/tkinter interaction In-Reply-To: <1c2a2c590901191430o561da1a6o952229c05c4afd6f@mail.gmail.com> References: <4a289b480901142200k3e376eaeg39de1ed8de1e239c@mail.gmail.com> <200901191857.36613.eike.welk@gmx.net> <20090119180522.GA66977@dragon.alchemy.com> <1c2a2c590901191430o561da1a6o952229c05c4afd6f@mail.gmail.com> Message-ID: <20090119234627.GA91182@dragon.alchemy.com> On Mon, Jan 19, 2009 at 05:30:01PM -0500, Kent Johnson wrote: > My guess is that pygame and Tkinter are both going to want to control > the event loop. Googling 'pygame tkinter' gives both hints that it > might be possible and hints of trouble... Yeah, I was thinking that, but since what I saw up until the point I asked the list was that for pygame you seem to write your own event loop, like while True: handle_event_myself(pygame.event.get()) whereas Tkinter wants you to just hand it control and let your program flow disappear into that black box entirely, until it pokes callbacks at you, I thought... "Well, maybe..." -- Steve Willoughby | Using billion-dollar satellites steve at alchemy.com | to hunt for Tupperware. From ajarncolin at gmail.com Tue Jan 20 01:56:39 2009 From: ajarncolin at gmail.com (col speed) Date: Tue, 20 Jan 2009 07:56:39 +0700 Subject: [Tutor] cube root In-Reply-To: <50ed08f40901190228h1a2858c1g1061068d16515560@mail.gmail.com> References: <6a1b26420901182228v760bdaddweccbfed9b2495b12@mail.gmail.com> <4974209E.104@orcon.net.nz> <50ed08f40901190228h1a2858c1g1061068d16515560@mail.gmail.com> Message-ID: <6a1b26420901191656t205e4271n15490bf962d44ec4@mail.gmail.com> Wow! I seem to have caused a great deal of comments! I actually am looking to see if a number is a "perfect cube". I will try out all the suggestions. Thanks a lot. Colin P.S. I have a small programme that changes decimal to binary (I don't know if it can be changed to work with fractions or not), maybe it will help. def dec2bin(dec): bin = '' while dec > 0: bin = str(dec & 1) + bin dec >>= 1 return bin 2009/1/19 Vicent > > > > > On Mon, Jan 19, 2009 at 07:41, Brett Wilkins wrote: > >> >> What you're running into here is the limited accuracy of floating point >> values... >> You'll likely find this happens a lot in python.. CPython, at least. (I >> know, as I do) >> I'm not sure, as I've never used it... but perhaps Numeric/Numpy handle >> this kinda stuff better (for accuracy's sake) >> >> > Maybe this issue can be overcome by using symbolic notation when possible > (maybe by using SymPy)? Has anyone any experience with this? > > -- > Vicent > -------------- next part -------------- An HTML attachment was scrubbed... URL: From cfuller084 at thinkingplanet.net Tue Jan 20 02:07:38 2009 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Mon, 19 Jan 2009 19:07:38 -0600 Subject: [Tutor] cube root In-Reply-To: <6a1b26420901191656t205e4271n15490bf962d44ec4@mail.gmail.com> References: <6a1b26420901182228v760bdaddweccbfed9b2495b12@mail.gmail.com> <50ed08f40901190228h1a2858c1g1061068d16515560@mail.gmail.com> <6a1b26420901191656t205e4271n15490bf962d44ec4@mail.gmail.com> Message-ID: <200901191907.38608.cfuller084@thinkingplanet.net> On Monday 19 January 2009 18:56, col speed wrote: > Wow! I seem to have caused a great deal of comments! > I actually am looking to see if a number is a "perfect cube". I will try > out all the suggestions. > Thanks a lot. > Colin The reliable way to do this is to store a list of cubes. If the number you want to check is not in your list, then compute more cubes until you exceed that number. Unless you are dealing with absurdly huge numbers, this won't be very onerous on computing time. Cheers From emadnawfal at gmail.com Tue Jan 20 03:18:45 2009 From: emadnawfal at gmail.com (=?windows-1256?B?RW1hZCBOYXdmYWwgKNrjx88g5Obd4Sk=?=) Date: Mon, 19 Jan 2009 21:18:45 -0500 Subject: [Tutor] Finding the shortest word in a list of words Message-ID: <652641e90901191818i43253d11p25db401076b13e81@mail.gmail.com> Hello tutors, I need to find the shortest / longest word(s) in a sequence of words. I've done this and it works, but I'm wondering whether this is a good way: >>> words = "man woman children he".split() >>> words ['man', 'woman', 'children', 'he'] >>> lens = [len(word) for word in words] >>> lens [3, 5, 8, 2] >>> for word in words: ... if len(word) == min(lens): print word ... he >>> -- ?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? ????????.....???? ??????? "No victim has ever been more repressed and alienated than the truth" Emad Soliman Nawfal Indiana University, Bloomington -------------------------------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: From john at fouhy.net Tue Jan 20 03:31:41 2009 From: john at fouhy.net (John Fouhy) Date: Tue, 20 Jan 2009 15:31:41 +1300 Subject: [Tutor] Finding the shortest word in a list of words In-Reply-To: <652641e90901191818i43253d11p25db401076b13e81@mail.gmail.com> References: <652641e90901191818i43253d11p25db401076b13e81@mail.gmail.com> Message-ID: <5e58f2e40901191831n45ab7d07h558244efeb52dd99@mail.gmail.com> 2009/1/20 Emad Nawfal (???? ????) : > Hello tutors, > I need to find the shortest / longest word(s) in a sequence of words. I've > done this and it works, but I'm wondering whether this is a good way: >>>> words = "man woman children he".split() >>>> words > ['man', 'woman', 'children', 'he'] >>>> lens = [len(word) for word in words] >>>> lens > [3, 5, 8, 2] >>>> for word in words: > ... if len(word) == min(lens): print word > ... > he Hi Emad, You can use the decorate-sort-undecorate idiom to make this technique a bit nicer. "decorate" means "add information to the things in the list": >>> words_and_lengths = [(len(w), w) for w in words] >>> words_and_lengths [(3, 'man'), (5, 'woman'), (8, 'children'), (2, 'he')] Now I can sort it and get the shortest element easily: >>> words_and_lengths.sort() >>> words_and_lengths[0] (2, 'he') Or I can undecorate: >>> words2 = [w[1] for w in words_and_lengths] >>> words2 ['he', 'man', 'woman', 'children'] Python 2.5+ provides another way of doing this, using the key= argument to sort(): >>> words ['man', 'woman', 'children', 'he'] >>> words.sort(key=len) >>> words ['he', 'man', 'woman', 'children'] This essentially does the decorate-sort-undecorate in one step, where len is the function we used to do the decoration. Of course, this is not necessarily the best answer for your particular problem. The problem with sorting is that you have to look at some elements more than once. For short lists, it's not a problem, but it can slow you down on bigger lists. You could also find the shortest element by going through the list, remembering the shortest element you've seen so far. This will be quicker if you only want to find the single shortest. -- John. From emadnawfal at gmail.com Tue Jan 20 03:47:44 2009 From: emadnawfal at gmail.com (=?windows-1256?B?RW1hZCBOYXdmYWwgKNrjx88g5Obd4Sk=?=) Date: Mon, 19 Jan 2009 21:47:44 -0500 Subject: [Tutor] Finding the shortest word in a list of words In-Reply-To: <5e58f2e40901191831n45ab7d07h558244efeb52dd99@mail.gmail.com> References: <652641e90901191818i43253d11p25db401076b13e81@mail.gmail.com> <5e58f2e40901191831n45ab7d07h558244efeb52dd99@mail.gmail.com> Message-ID: <652641e90901191847m40c1853ibac006364519ad54@mail.gmail.com> 2009/1/19 John Fouhy > 2009/1/20 Emad Nawfal (???? ????) : > > Hello tutors, > > I need to find the shortest / longest word(s) in a sequence of words. > I've > > done this and it works, but I'm wondering whether this is a good way: > >>>> words = "man woman children he".split() > >>>> words > > ['man', 'woman', 'children', 'he'] > >>>> lens = [len(word) for word in words] > >>>> lens > > [3, 5, 8, 2] > >>>> for word in words: > > ... if len(word) == min(lens): print word > > ... > > he > > Hi Emad, > > You can use the decorate-sort-undecorate idiom to make this technique > a bit nicer. > > "decorate" means "add information to the things in the list": > > >>> words_and_lengths = [(len(w), w) for w in words] > >>> words_and_lengths > [(3, 'man'), (5, 'woman'), (8, 'children'), (2, 'he')] > > Now I can sort it and get the shortest element easily: > > >>> words_and_lengths.sort() > >>> words_and_lengths[0] > (2, 'he') > > Or I can undecorate: > > >>> words2 = [w[1] for w in words_and_lengths] > >>> words2 > ['he', 'man', 'woman', 'children'] > > Python 2.5+ provides another way of doing this, using the key= > argument to sort(): > > >>> words > ['man', 'woman', 'children', 'he'] > >>> words.sort(key=len) > >>> words > ['he', 'man', 'woman', 'children'] > > This essentially does the decorate-sort-undecorate in one step, where > len is the function we used to do the decoration. > > Of course, this is not necessarily the best answer for your particular > problem. The problem with sorting is that you have to look at some > elements more than once. For short lists, it's not a problem, but it > can slow you down on bigger lists. You could also find the shortest > element by going through the list, remembering the shortest element > you've seen so far. This will be quicker if you only want to find the > single shortest. > > -- > John. > Thanks John for this. Although the decorate-sort-undecorate idiom looks so natural to me now, I don't think I would have found it on my own. I have that deja vu effect towards it. Thanks again. -- ?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? ????????.....???? ??????? "No victim has ever been more repressed and alienated than the truth" Emad Soliman Nawfal Indiana University, Bloomington http://emnawfal.googlepages.com -------------------------------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: From marc.tompkins at gmail.com Tue Jan 20 04:13:32 2009 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Mon, 19 Jan 2009 19:13:32 -0800 Subject: [Tutor] Finding the shortest word in a list of words In-Reply-To: <5e58f2e40901191831n45ab7d07h558244efeb52dd99@mail.gmail.com> References: <652641e90901191818i43253d11p25db401076b13e81@mail.gmail.com> <5e58f2e40901191831n45ab7d07h558244efeb52dd99@mail.gmail.com> Message-ID: <40af687b0901191913s6f566835h8e518cec7c47d734@mail.gmail.com> 2009/1/19 John Fouhy > 2009/1/20 Emad Nawfal (???? ????) : > Of course, this is not necessarily the best answer for your particular > problem. The problem with sorting is that you have to look at some > elements more than once. For short lists, it's not a problem, but it > can slow you down on bigger lists. You could also find the shortest > element by going through the list, remembering the shortest element > you've seen so far. This will be quicker if you only want to find the > single shortest. > Here's the first thing that came to mind: > from sys import maxint > > def MinMax(Sentence=""): > minLen = maxint > maxLen = 0 > > for word in Sentence.split(): > if len(word) > maxLen: > maxWord = word > maxLen = len(word) > if len(word) < minLen: > minWord = word > minLen = len(word) > return minLen, minWord, maxLen, maxWord > > > print MinMax("No victim has ever been more repressed and alienated than the > truth") > Using sys.maxint to prime minLen is overkill, of course - "antidisestablishmentarianism" is only 28 letters long, after all - but it should be larger than any word you can expect to see. This doesn't catch ties, though... could do that like so: for word in Sentence.split(): > if len(word) == minLen: > minWord.append(word) > if len(word) == maxLen: > maxWord.append(word) > if len(word) > maxLen: > maxWord = [word] > maxLen = len(word) > if len(word) < minLen: > minWord = [word] > minLen = len(word) > > -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From wormwood_3 at yahoo.com Tue Jan 20 04:47:54 2009 From: wormwood_3 at yahoo.com (wormwood_3) Date: Mon, 19 Jan 2009 19:47:54 -0800 (PST) Subject: [Tutor] Ip address References: <49748A20.50604@unknownsoftware.ro> <333efb450901190727s261437dbi3cdb8fe55e85b8bb@mail.gmail.com> Message-ID: <386909.88079.qm@web110802.mail.gq1.yahoo.com> Hello, This is definitely possible. It's more a matter of system and OS configuration than Python though, so you might want to check out some Linux forums ( http://www.linuxforums.org/ ) for additional help. In short, I think the simplest would be: Have 3 separate network interfaces in your physical box, have your router provide one of the three addresses to each. Then you could configure the client to only connect through its associated interface/IP. If this sort of setup wouldn't work, please tell us more about your configuration between your client and your network. -Sam _______________________ Samuel Huckins Homepage - http://samuelhuckins.com Tech blog - http://dancingpenguinsoflight.com/ Photos - http://www.flickr.com/photos/samuelhuckins/ AIM - samushack | Gtalk - samushack | Skype - shuckins ________________________________ From: W W To: irimia.suleapa at unknownsoftware.ro Cc: tutor at python.org Sent: Monday, January 19, 2009 10:27:07 AM Subject: Re: [Tutor] Ip address On Mon, Jan 19, 2009 at 8:11 AM, Irimia, Suleapa wrote: Hello list, I am new to python and i have a question. I managed to build a client which connect to an website and grab things from there. I run this client on a linux box, which have multiple ip address. What do i want is to run 3 clients and each one to use different ip address to access that website. Anyone can point me to some documentation about how this can be done? I'm not 100% sure if I understand what you're saying, so let me clarify: You have one linux box, with 3 instances of your program running, and you want the server to see these as three unique IPs? I'm not aware of any way to do this without proxy servers or IP spoofing. HTH, Wayne -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn't. - Primo Levi -------------- next part -------------- An HTML attachment was scrubbed... URL: From cfuller084 at thinkingplanet.net Tue Jan 20 05:16:01 2009 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Mon, 19 Jan 2009 22:16:01 -0600 Subject: [Tutor] Question about pygame/tkinter interaction In-Reply-To: <20090119180522.GA66977@dragon.alchemy.com> References: <4a289b480901142200k3e376eaeg39de1ed8de1e239c@mail.gmail.com> <200901191857.36613.eike.welk@gmx.net> <20090119180522.GA66977@dragon.alchemy.com> Message-ID: <200901192216.01190.cfuller084@thinkingplanet.net> On Monday 19 January 2009 12:05, Steve Willoughby wrote: > I have a game I'm porting to Python which is currently written > using TCL/Tk. Now it would be fairly easy to make it work in > Python with Tkinter, of course, since the way the GUI would be > organized and implemented would be essentially the same. > > However, I'd also like to implement some fancier (but minor) > animated effects and embed video and audio clips. So I was > thinking that pygame (or pymedia) would be reasonable choices, > but I've never used either of those before. > > Is it reasonable to expect that I could use Tkinter for > everything else, but use pygame/pymedia to handle things like > creating a video playback window on the screen, or is pygame > going to want to run the whole GUI event loop and screen updates > in competition with Tkinter? > > Any general nudges in the right direction would be appreciated. > Thanks, > steve I have successfully run dual GUI managers at once (Tkinter and wxPython) by suspending the mainloop of one and starting the other. You might be able to setup a timeout in one GUI to service pending events in the other if this approach would be difficult. GUIs tend to want to be in the main thread. Certainly any GUI functions called from other threads must be via locks. You could try experimenting with having a thread for each GUI, but I would expect problems. Another solution would be to have two separate Python instances with some form of interprocess communications. This doesn't have to be all that difficult, if you are careful with the design. You can use pickle to convert complex objects into strings, for instance. Cheers From jammy007_pp at yahoo.com Tue Jan 20 06:37:43 2009 From: jammy007_pp at yahoo.com (jammy007 pp) Date: Mon, 19 Jan 2009 21:37:43 -0800 (PST) Subject: [Tutor] thanks Message-ID: <274188.91264.qm@web63308.mail.re1.yahoo.com> thanks a lot for responding to my emails , the suggestions that i got from the members were pretty good , i like the suggestion that bhaalu gave me . feeling motivated now . will read the chapter again . god bless us all . -------------- next part -------------- An HTML attachment was scrubbed... URL: From norman at khine.net Tue Jan 20 10:49:55 2009 From: norman at khine.net (Norman Khine) Date: Tue, 20 Jan 2009 10:49:55 +0100 Subject: [Tutor] creating a sound file from a string Message-ID: <49759E43.2020902@khine.net> hello, i have a string that is generated that contains letters and numbers. i also have a folder which contains the following: sounds/ upper-a.wav upper-b.wav .. lower-a.wav lower-b.wav ... sign-?.wav sign-|.wav .. number-0.wav number-1.wav .. does anyone know of a python module which would create a single sound file based on the randomly generated string? i have looked at the python wave module, but if i am not wrong this works with one file at the time. any advise much appreciated. many thanks norman From manoj_kumar2512 at rediffmail.com Tue Jan 20 12:10:14 2009 From: manoj_kumar2512 at rediffmail.com (Manoj kumar) Date: 20 Jan 2009 11:10:14 -0000 Subject: [Tutor] MySqldb problem Message-ID: <20090120111014.59680.qmail@f5mail-237-208.rediffmail.com> ? hi all, i am a newbie to python programming. i just know basics of the language. i came across MySqldb. i able to manipulate database with MySqldb but i wasn't able to add files in database through the lib MySqldb. any help will be welcomed gracefully. thanks. MANOJ SHEOKAND (+919728523528) "some day there won't be a song in ur heart, sing anyway" -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Tue Jan 20 12:45:58 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 20 Jan 2009 06:45:58 -0500 Subject: [Tutor] Finding the shortest word in a list of words In-Reply-To: <652641e90901191847m40c1853ibac006364519ad54@mail.gmail.com> References: <652641e90901191818i43253d11p25db401076b13e81@mail.gmail.com> <5e58f2e40901191831n45ab7d07h558244efeb52dd99@mail.gmail.com> <652641e90901191847m40c1853ibac006364519ad54@mail.gmail.com> Message-ID: <1c2a2c590901200345y2e7ef466s42be9975328363a1@mail.gmail.com> On Mon, Jan 19, 2009 at 9:47 PM, Emad Nawfal (???? ????) wrote: > Thanks John for this. Although the decorate-sort-undecorate idiom looks so > natural to me now, I don't think I would have found it on my own. I have > that deja vu effect towards it. decorate-sort-undecorate is pretty much obsolete since the key= parameter was added to sort() in Python 2.4. Since Python 2.5 you can also use key= with min() and max() so your problem can be solved very simply and tersely: In [1]: words = "man woman children he".split() In [2]: min(words, key=len) Out[2]: 'he' Kent From lie.1296 at gmail.com Tue Jan 20 12:48:19 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Tue, 20 Jan 2009 11:48:19 +0000 (UTC) Subject: [Tutor] Question about pygame/tkinter interaction References: <4a289b480901142200k3e376eaeg39de1ed8de1e239c@mail.gmail.com> <200901191857.36613.eike.welk@gmx.net> <20090119180522.GA66977@dragon.alchemy.com> <1c2a2c590901191430o561da1a6o952229c05c4afd6f@mail.gmail.com> <20090119234627.GA91182@dragon.alchemy.com> Message-ID: On Mon, 19 Jan 2009 15:46:27 -0800, Steve Willoughby wrote: > On Mon, Jan 19, 2009 at 05:30:01PM -0500, Kent Johnson wrote: >> My guess is that pygame and Tkinter are both going to want to control >> the event loop. Googling 'pygame tkinter' gives both hints that it >> might be possible and hints of trouble... > > Yeah, I was thinking that, but since what I saw up until the point I > asked the list was that for pygame you seem to write your own event > loop, like > > while True: > handle_event_myself(pygame.event.get()) > > whereas Tkinter wants you to just hand it control and let your program > flow disappear into that black box entirely, until it pokes callbacks at > you, I thought... "Well, maybe..." I guess it shouldn't be too difficult if what you're intending is to have one window controlled by Tkinter and the other by pygame, it's just a matter of having Tkinter calling pygame's event handler once in a while (so instead of while True: handle_pygame_event() insert an event that makes Tkinter calls handle_pygame_event() every once in a while. ) What I don't know is whether it is possible to "embed" a pygame- controlled frame into Tkinter-controlled window. From kent37 at tds.net Tue Jan 20 13:03:55 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 20 Jan 2009 07:03:55 -0500 Subject: [Tutor] creating a sound file from a string In-Reply-To: <49759E43.2020902@khine.net> References: <49759E43.2020902@khine.net> Message-ID: <1c2a2c590901200403k3a4008d2la504ed9746d0fdcb@mail.gmail.com> On Tue, Jan 20, 2009 at 4:49 AM, Norman Khine wrote: > does anyone know of a python module which would create a single sound file > based on the randomly generated string? > > i have looked at the python wave module, but if i am not wrong this works > with one file at the time. I think you can do this with the wave module. The code would be something like this: open output file and set number of channels, etc for each letter of input: open wave file for the letter read frames from letter file write frames to output file close output file Kent From emadnawfal at gmail.com Tue Jan 20 13:13:10 2009 From: emadnawfal at gmail.com (=?windows-1256?B?RW1hZCBOYXdmYWwgKNrjx88g5Obd4Sk=?=) Date: Tue, 20 Jan 2009 07:13:10 -0500 Subject: [Tutor] Finding the shortest word in a list of words In-Reply-To: <1c2a2c590901200345y2e7ef466s42be9975328363a1@mail.gmail.com> References: <652641e90901191818i43253d11p25db401076b13e81@mail.gmail.com> <5e58f2e40901191831n45ab7d07h558244efeb52dd99@mail.gmail.com> <652641e90901191847m40c1853ibac006364519ad54@mail.gmail.com> <1c2a2c590901200345y2e7ef466s42be9975328363a1@mail.gmail.com> Message-ID: <652641e90901200413x64f662bdsb91f04b2ee574ee9@mail.gmail.com> 2009/1/20 Kent Johnson > On Mon, Jan 19, 2009 at 9:47 PM, Emad Nawfal (???? ????) > wrote: > > > Thanks John for this. Although the decorate-sort-undecorate idiom looks > so > > natural to me now, I don't think I would have found it on my own. I have > > that deja vu effect towards it. > > decorate-sort-undecorate is pretty much obsolete since the key= > parameter was added to sort() in Python 2.4. Since Python 2.5 you can > also use key= with min() and max() so your problem can be solved very > simply and tersely: > > In [1]: words = "man woman children he".split() > > In [2]: min(words, key=len) > Out[2]: 'he' > > Kent > Thank you all for the beautiful solutions. When you say that something is obsolete, what does this mean? Is that just because there is a simpler way, or are there other technical considerations? -- ?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? ????????.....???? ??????? "No victim has ever been more repressed and alienated than the truth" Emad Soliman Nawfal Indiana University, Bloomington http://emnawfal.googlepages.com -------------------------------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: From norman at khine.net Tue Jan 20 13:25:05 2009 From: norman at khine.net (Norman Khine) Date: Tue, 20 Jan 2009 13:25:05 +0100 Subject: [Tutor] creating a sound file from a string In-Reply-To: <1c2a2c590901200403k3a4008d2la504ed9746d0fdcb@mail.gmail.com> References: <49759E43.2020902@khine.net> <1c2a2c590901200403k3a4008d2la504ed9746d0fdcb@mail.gmail.com> Message-ID: <4975C2A1.70403@khine.net> Thanks I am looking at this now. From unix I could run sox so that $ sox uppercase-a.wav uppercase-b.wav ab.wav this produces a merged uppercase-a.wav uppercase-b.wav perhaps this is a better way, but requires having to execute an external programme. any thoughts? cheers norman Kent Johnson wrote: > On Tue, Jan 20, 2009 at 4:49 AM, Norman Khine wrote: >> does anyone know of a python module which would create a single sound file >> based on the randomly generated string? >> >> i have looked at the python wave module, but if i am not wrong this works >> with one file at the time. > > I think you can do this with the wave module. The code would be > something like this: > > open output file and set number of channels, etc > for each letter of input: > open wave file for the letter > read frames from letter file > write frames to output file > close output file > > Kent > From cbabcock at asciiking.com Tue Jan 20 13:30:18 2009 From: cbabcock at asciiking.com (Chris Babcock) Date: Tue, 20 Jan 2009 05:30:18 -0700 Subject: [Tutor] MySqldb problem In-Reply-To: <20090120111014.59680.qmail@f5mail-237-208.rediffmail.com> References: <20090120111014.59680.qmail@f5mail-237-208.rediffmail.com> Message-ID: <20090120053018.58f9937d@mail.asciiking.com> On 20 Jan 2009 11:10:14 -0000 "Manoj kumar" wrote: > i am a newbie to python programming. i just know basics of the > language. i came across MySqldb. i able to manipulate database with > MySqldb but i wasn't able to add files in database through the lib > MySqldb. Right. Whatever you want to do in the database, you'll have to have a user defined in MySQL with the necessary permissions and have that user configured in your program. Details: Generally, you want to follow the principle of least permissions for security in your app. Almost all database apps need select privileges for their database user. A good many need insert, update and/or delete privileges. Dynamically generated tables aren't sound relational design, so your tables should be created using an administrative user for the database rather than giving the MySQL user defined for your app unnecessary privileges. As long as you're in development and no untrusted users have access to the app, do what you want. Before setting it wild or running it as server, whatever it does, replace the user that you've defined as having "ALL" privilege on the database with one that has only those privileges needed for what the app does. Alternative: Also, MySqldb is the manual way to use a MySQL database. It's fine if you want to generate query strings manually because you know what you're doing and you're sure that your code will never be used with a different database. The problem for a new user is that using MySqldb means learning Python and SQL at the same time to build your app. You aren't learning Python because you're a mental masochist. You're learning Python because it's an easy way to get programs working. A more Pythonic way to work with databases would be to use an Object Relational Mapper like SQLAlchemy. The simple explanation is that the ORM lets you just work with objects in your app instead of generating query strings. This approach also gets you a lot of other features for free like independence from being database specific and protection from SQL injection attacks. Chris -- Thank you everyone! USAK is live on its new connection. So far you have given $198 towards next quarter. To make a donation, use this link (opens on PayPal): http://tinyurl.com/USAK2009 From norman at khine.net Tue Jan 20 14:12:33 2009 From: norman at khine.net (Norman Khine) Date: Tue, 20 Jan 2009 14:12:33 +0100 Subject: [Tutor] creating a sound file from a string In-Reply-To: <1c2a2c590901200403k3a4008d2la504ed9746d0fdcb@mail.gmail.com> References: <49759E43.2020902@khine.net> <1c2a2c590901200403k3a4008d2la504ed9746d0fdcb@mail.gmail.com> Message-ID: <4975CDC1.9020203@khine.net> Is this a safe way to generate random sound files on a web server? >>> from os import popen >>> merge = popen('sox uppercase-b.wav uppercase-a.wav merge.wav') Thanks Norman Kent Johnson wrote: > On Tue, Jan 20, 2009 at 4:49 AM, Norman Khine wrote: >> does anyone know of a python module which would create a single sound file >> based on the randomly generated string? >> >> i have looked at the python wave module, but if i am not wrong this works >> with one file at the time. > > I think you can do this with the wave module. The code would be > something like this: > > open output file and set number of channels, etc > for each letter of input: > open wave file for the letter > read frames from letter file > write frames to output file > close output file > > Kent > From kent37 at tds.net Tue Jan 20 14:27:56 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 20 Jan 2009 08:27:56 -0500 Subject: [Tutor] Finding the shortest word in a list of words In-Reply-To: <652641e90901200413x64f662bdsb91f04b2ee574ee9@mail.gmail.com> References: <652641e90901191818i43253d11p25db401076b13e81@mail.gmail.com> <5e58f2e40901191831n45ab7d07h558244efeb52dd99@mail.gmail.com> <652641e90901191847m40c1853ibac006364519ad54@mail.gmail.com> <1c2a2c590901200345y2e7ef466s42be9975328363a1@mail.gmail.com> <652641e90901200413x64f662bdsb91f04b2ee574ee9@mail.gmail.com> Message-ID: <1c2a2c590901200527j76c50d8cyb33a71d56ba1b1b5@mail.gmail.com> On Tue, Jan 20, 2009 at 7:13 AM, Emad Nawfal (???? ????) wrote: > 2009/1/20 Kent Johnson >> decorate-sort-undecorate is pretty much obsolete since the key= >> parameter was added to sort() in Python 2.4. > When you say that something is obsolete, what does this mean? Is that just > because there is a simpler way, or are there other technical considerations? In this case, it is because there is a better, simpler way. Decorate-sort-undecorate used to be the recommended way to sort on a key; now key= is preferred. Kent From kent37 at tds.net Tue Jan 20 14:35:11 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 20 Jan 2009 08:35:11 -0500 Subject: [Tutor] creating a sound file from a string In-Reply-To: <4975CDC1.9020203@khine.net> References: <49759E43.2020902@khine.net> <1c2a2c590901200403k3a4008d2la504ed9746d0fdcb@mail.gmail.com> <4975CDC1.9020203@khine.net> Message-ID: <1c2a2c590901200535n624a55b7l12b3391ec4294197@mail.gmail.com> On Tue, Jan 20, 2009 at 8:12 AM, Norman Khine wrote: > Is this a safe way to generate random sound files on a web server? > >>>> from os import popen >>>> merge = popen('sox uppercase-b.wav uppercase-a.wav merge.wav') I'm not sure but you may have to read from merge to allow the process to complete. You might want to use os.system() or one of the subprocess replacements: http://docs.python.org/library/subprocess.html#subprocess-replacements if your webserver allows multiple simultaneous connections, and you are going to serve merge.wav to a client, make sure you use different names for each connection so they don't collide. Kent From lie.1296 at gmail.com Tue Jan 20 14:42:42 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Tue, 20 Jan 2009 13:42:42 +0000 (UTC) Subject: [Tutor] Finding the shortest word in a list of words References: <652641e90901191818i43253d11p25db401076b13e81@mail.gmail.com> <5e58f2e40901191831n45ab7d07h558244efeb52dd99@mail.gmail.com> <40af687b0901191913s6f566835h8e518cec7c47d734@mail.gmail.com> Message-ID: On Mon, 19 Jan 2009 19:13:32 -0800, Marc Tompkins wrote: > 2009/1/19 John Fouhy > >> 2009/1/20 Emad Nawfal (???? ????) : Of course, >> this is not necessarily the best answer for your particular problem. >> The problem with sorting is that you have to look at some elements more >> than once. For short lists, it's not a problem, but it can slow you >> down on bigger lists. You could also find the shortest element by >> going through the list, remembering the shortest element you've seen so >> far. This will be quicker if you only want to find the single >> shortest. >> >> > Here's the first thing that came to mind: > Using sys.maxint to prime minLen is overkill, of course - > "antidisestablishmentarianism" is only 28 letters long, after all - but > it should be larger than any word you can expect to see. This doesn't > catch ties, though... could do that like so: Other than overkill, it is wrong. If the shortest "word" is longer than maxint it'd give wrong result. You could just simply use the len of the first word. The best solution though, have been answered by Kent Johnson. From norman at khine.net Tue Jan 20 15:00:09 2009 From: norman at khine.net (Norman Khine) Date: Tue, 20 Jan 2009 15:00:09 +0100 Subject: [Tutor] creating a sound file from a string In-Reply-To: <1c2a2c590901200535n624a55b7l12b3391ec4294197@mail.gmail.com> References: <49759E43.2020902@khine.net> <1c2a2c590901200403k3a4008d2la504ed9746d0fdcb@mail.gmail.com> <4975CDC1.9020203@khine.net> <1c2a2c590901200535n624a55b7l12b3391ec4294197@mail.gmail.com> Message-ID: <4975D8E9.7090704@khine.net> Thanks, Kent Johnson wrote: > On Tue, Jan 20, 2009 at 8:12 AM, Norman Khine wrote: >> Is this a safe way to generate random sound files on a web server? >> >>>>> from os import popen >>>>> merge = popen('sox uppercase-b.wav uppercase-a.wav merge.wav') > > I'm not sure but you may have to read from merge to allow the process > to complete. You might want to use os.system() or one of the > subprocess replacements: > http://docs.python.org/library/subprocess.html#subprocess-replacements How do I check if the process has completed? Would I have to explicitly close the file? > > if your webserver allows multiple simultaneous connections, and you > are going to serve merge.wav to a client, make sure you use different > names for each connection so they don't collide. Each merge.wav file will be unique and only for the specific session, after which it will be removed from the server. > > Kent What I am trying to do is a sound captcha, just to learn in putting the pieces together. Norman > From kent37 at tds.net Tue Jan 20 15:11:34 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 20 Jan 2009 09:11:34 -0500 Subject: [Tutor] creating a sound file from a string In-Reply-To: <4975D8E9.7090704@khine.net> References: <49759E43.2020902@khine.net> <1c2a2c590901200403k3a4008d2la504ed9746d0fdcb@mail.gmail.com> <4975CDC1.9020203@khine.net> <1c2a2c590901200535n624a55b7l12b3391ec4294197@mail.gmail.com> <4975D8E9.7090704@khine.net> Message-ID: <1c2a2c590901200611neea872ew40ddbce272a99076@mail.gmail.com> On Tue, Jan 20, 2009 at 9:00 AM, Norman Khine wrote: >>>>>> from os import popen >>>>>> merge = popen('sox uppercase-b.wav uppercase-a.wav merge.wav') >> >> I'm not sure but you may have to read from merge to allow the process >> to complete. You might want to use os.system() or one of the >> subprocess replacements: >> http://docs.python.org/library/subprocess.html#subprocess-replacements > > How do I check if the process has completed? > > Would I have to explicitly close the file? I suggest something like subprocess.call(['sox', 'uppercase-b.wav', 'uppercase-a.wav', 'merge.wav']) which will wait for the process to complete. sox is responsible for closing the file. Kent From lie.1296 at gmail.com Tue Jan 20 15:18:14 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Tue, 20 Jan 2009 14:18:14 +0000 (UTC) Subject: [Tutor] Ip address References: <49748A20.50604@unknownsoftware.ro> <333efb450901190727s261437dbi3cdb8fe55e85b8bb@mail.gmail.com> <386909.88079.qm@web110802.mail.gq1.yahoo.com> Message-ID: On Mon, 19 Jan 2009 19:47:54 -0800, wormwood_3 wrote: > Hello, > > This is definitely possible. It's more a matter of system and OS > configuration than Python though, so you might want to check out some > Linux forums ( http://www.linuxforums.org/ ) for additional help. In > short, I think the simplest would be: Have 3 separate network interfaces > in your physical box, have your router provide one of the three > addresses to each. Then you could configure the client to only connect > through its associated interface/IP. > > If this sort of setup wouldn't work, please tell us more about your > configuration between your client and your network. Definitely not what he expected, I'm sure. It is impossible for a single network interface to have more than 1 IP address. I want to ask what is he going to do with such set up though. It is trivial to emulate IP addressess through ports, so use that instead. Also inter-process communication in a single machine is usually better done using pipes. From ptmcg at austin.rr.com Tue Jan 20 16:33:40 2009 From: ptmcg at austin.rr.com (Paul McGuire) Date: Tue, 20 Jan 2009 09:33:40 -0600 Subject: [Tutor] Finding the shortest word in a list of words In-Reply-To: References: Message-ID: <05B96BA361DD4053A753FD05C17CDB4E@AWA2> "Finding the shortest word among a list of words" sounds like something of a trick question to me. I think a more complete problem statement would be "Find the list of words that are the shortest", since there is no guarantee that the list does not contain two words of the same shortest length. If you just add "me" to your sample set, you now get misleading answers: words = "man woman children he me".split() print min(words, key=len) prints: he What happened to "me"? It is just as short as "he"! To get *all* the words that are the shortest length, I'll show two approaches. The first uses a defaultdict, from the collections module of the Python stdlib. With a defaultdict, I can have new dict entries get initialized with a default value using a specified factory function, without first having to check to see if that entry exists. I would like to create a dict of lists of words, keyed by the lengths of the words. Something that would give me this dict: { 2 : ['he', 'me'], 3 : ['man'], ... etc. } from which I could then find the minimum length using min(wordlendict.keys()). By using a defaultdict, I can just build things up by iterating over the list and adding each word to the entry for the current word's length - if the current word is the first one for this length to be found, the defaultdict will initialize the value to an empty list for me. This allows me to safely append the current word regardless of whether there was an existing entry or not. Here is the code that does this: from collections import defaultdict wordlendict = defaultdict(list) for w in words: wordlendict[len(w)].append(w) minlen = min(wordlendict.keys()) minlist = wordlendict[minlen] print minlist prints: ['he', 'me'] Now we are getting a more complete answer! A second approach uses the groupby method of the itertools module in the stdlib. groupby usually takes me several attempts to get everything right: the input must be sorted by the grouping feature, and then the results returned by groupby are in the form of an iterator that returns key-iterator tuples. I need to go through some mental gymnastics to unwind the data to get the group I'm really interested in. Here is a step-by-step code to use groupby: from itertools import groupby grpsbylen = groupby(sorted(words,key=len),len) mingrp = grpsbylen.next() minlen = mingrp[0] minlist = list(mingrp[1]) print minlist The input list of words gets sorted, and then passed to groupby, which uses len as the grouping criteria (groupby is not inherently aware of how the input list was sorted, so len must be repeated). The first group tuple is pulled from the grpsbylen iterator using next(). The 0'th tuple element is the grouping value - in this case, it is the minimum length 2. The 1'th tuple element is the group itself, given as an iterator. Passing this to the list constructor gives us the list of all the 2-character words, which then gets printed: ['he', 'me'] Again, 'me' no longer gets left out. Maybe this will get you some extra credit... -- Paul From irimia.suleapa at unknownsoftware.ro Tue Jan 20 16:56:18 2009 From: irimia.suleapa at unknownsoftware.ro (Irimia, Suleapa) Date: Tue, 20 Jan 2009 17:56:18 +0200 Subject: [Tutor] Ip address In-Reply-To: <386909.88079.qm@web110802.mail.gq1.yahoo.com> References: <49748A20.50604@unknownsoftware.ro> <333efb450901190727s261437dbi3cdb8fe55e85b8bb@mail.gmail.com> <386909.88079.qm@web110802.mail.gq1.yahoo.com> Message-ID: <4975F422.6080003@unknownsoftware.ro> wormwood_3 wrote: > Hello, > > This is definitely possible. It's more a matter of system and OS > configuration than Python though, so you might want to check out some > Linux forums ( http://www.linuxforums.org/ ) for additional help. In > short, I think the simplest would be: Have 3 separate network interfaces > in your physical box, have your router provide one of the three > addresses to each. Then you could configure the client to only connect > through its associated interface/IP. > > If this sort of setup wouldn't work, please tell us more about your > configuration between your client and your network. > > -Sam > > _______________________ > Samuel Huckins > > Homepage - http://samuelhuckins.com > Tech blog - http://dancingpenguinsoflight.com/ > Photos - http://www.flickr.com/photos/samuelhuckins/ > AIM - samushack | Gtalk - samushack | Skype - shuckins > > It is about Ubuntu 8.04. I have 5 Ip address there (4 aliases). The idea is simple, i want to grab something from internet (website) using this client which was created in python. When the client is running, on the other server i see the first ip address from client server interface. What do i want is to have the possibility to chose or to use another ip from the list. I think Wayne told me the answer, using proxy or i was thinking about socks. But if anyone know anything better than this, i will be glad to hear. Thank you, From emadnawfal at gmail.com Tue Jan 20 17:12:18 2009 From: emadnawfal at gmail.com (=?windows-1256?B?RW1hZCBOYXdmYWwgKNrjx88g5Obd4Sk=?=) Date: Tue, 20 Jan 2009 11:12:18 -0500 Subject: [Tutor] Finding the shortest word in a list of words In-Reply-To: <05B96BA361DD4053A753FD05C17CDB4E@AWA2> References: <05B96BA361DD4053A753FD05C17CDB4E@AWA2> Message-ID: <652641e90901200812r1c0c0849l40f3cab0c2f95e90@mail.gmail.com> On Tue, Jan 20, 2009 at 10:33 AM, Paul McGuire wrote: > "Finding the shortest word among a list of words" sounds like something of > a > trick question to me. I think a more complete problem statement would be > "Find the list of words that are the shortest", since there is no guarantee > that the list does not contain two words of the same shortest length. If > you just add "me" to your sample set, you now get misleading answers: > > words = "man woman children he me".split() > print min(words, key=len) > > prints: > he > > What happened to "me"? It is just as short as "he"! > > To get *all* the words that are the shortest length, I'll show two > approaches. The first uses a defaultdict, from the collections module of > the Python stdlib. With a defaultdict, I can have new dict entries get > initialized with a default value using a specified factory function, > without > first having to check to see if that entry exists. I would like to create > a > dict of lists of words, keyed by the lengths of the words. Something that > would give me this dict: > > { 2 : ['he', 'me'], 3 : ['man'], ... etc. } > > from which I could then find the minimum length using > min(wordlendict.keys()). By using a defaultdict, I can just build things > up > by iterating over the list and adding each word to the entry for the > current > word's length - if the current word is the first one for this length to be > found, the defaultdict will initialize the value to an empty list for me. > This allows me to safely append the current word regardless of whether > there > was an existing entry or not. Here is the code that does this: > > from collections import defaultdict > wordlendict = defaultdict(list) > for w in words: > wordlendict[len(w)].append(w) > minlen = min(wordlendict.keys()) > minlist = wordlendict[minlen] > print minlist > > prints: > ['he', 'me'] > > Now we are getting a more complete answer! > > A second approach uses the groupby method of the itertools module in the > stdlib. groupby usually takes me several attempts to get everything right: > the input must be sorted by the grouping feature, and then the results > returned by groupby are in the form of an iterator that returns > key-iterator > tuples. I need to go through some mental gymnastics to unwind the data to > get the group I'm really interested in. Here is a step-by-step code to use > groupby: > > from itertools import groupby > grpsbylen = groupby(sorted(words,key=len),len) > mingrp = grpsbylen.next() > minlen = mingrp[0] > minlist = list(mingrp[1]) > print minlist > > The input list of words gets sorted, and then passed to groupby, which uses > len as the grouping criteria (groupby is not inherently aware of how the > input list was sorted, so len must be repeated). The first group tuple is > pulled from the grpsbylen iterator using next(). The 0'th tuple element is > the grouping value - in this case, it is the minimum length 2. The 1'th > tuple element is the group itself, given as an iterator. Passing this to > the list constructor gives us the list of all the 2-character words, which > then gets printed: > ['he', 'me'] > > Again, 'me' no longer gets left out. > > Maybe this will get you some extra credit... > > -- Paul Thank you so much Paul for this. In my original post, I wrote word(s), which means word or words. Your solutions look a little bit too advanced to me. I never used the collections module, and used itertools only once or twice. I will study these solutions for sure, not for extra credit, simply because I'm simply a linguistics person who uses corpora to find information without any official interest in computer science or programming classes. Maybe when I'm good enough at programming, I will take a Python class for credit, although I'm past the classes thing now. Thank you all again for helping me get a better understanding of Python. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- ?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? ????????.....???? ??????? "No victim has ever been more repressed and alienated than the truth" Emad Soliman Nawfal Indiana University, Bloomington -------------------------------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: From david at abbottdavid.com Tue Jan 20 16:04:51 2009 From: david at abbottdavid.com (David) Date: Tue, 20 Jan 2009 10:04:51 -0500 Subject: [Tutor] MySqldb problem In-Reply-To: <20090120111014.59680.qmail@f5mail-237-208.rediffmail.com> References: <20090120111014.59680.qmail@f5mail-237-208.rediffmail.com> Message-ID: <4975E813.3010402@abbottdavid.com> Manoj kumar wrote: > > > hi all, > > i am a newbie to python programming. i just know basics of the > language. i came across MySqldb. i able to manipulate database with > MySqldb but i wasn't able to add files in database through the lib > MySqldb. > > any help will be welcomed gracefully. > > thanks. > > MANOJ SHEOKAND > > (+919728523528) > > "some day there won't be a song in ur heart, sing anyway" > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > I am new to python also, here are my notes, it helps me understand how it works, may be of some help; http://asterisklinks.com/wiki/doku.php?id=wiki:mysql_fun -david -- powered by Gentoo/GNU Linux http://linuxcrazy.com From lie.1296 at gmail.com Tue Jan 20 17:19:28 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Tue, 20 Jan 2009 23:19:28 +0700 Subject: [Tutor] Question about pygame/tkinter interaction In-Reply-To: <4975F5FA.1040708@alchemy.com> References: <4a289b480901142200k3e376eaeg39de1ed8de1e239c@mail.gmail.com> <200901191857.36613.eike.welk@gmx.net> <20090119180522.GA66977@dragon.alchemy.com> <1c2a2c590901191430o561da1a6o952229c05c4afd6f@mail.gmail.com> <20090119234627.GA91182@dragon.alchemy.com> <4975F5FA.1040708@alchemy.com> Message-ID: <1232468368.24572.5.camel@lieryan-laptop> On Tue, 2009-01-20 at 08:04 -0800, Steve Willoughby wrote: > > In this case, that might be enough. I just need to show a video clip > in > an otherwise fairly simple GUI. A decorationless, borderless window > popped up on the screen over the Tk stuff would probably work. Thanks > for the advice, I'll play with this a bit. I've never used decoration-less pygame window, but I suspect it'd be much easier/better to popup a fully decorated window with a separate control panel (like mplayer). I think a lot of problems might arise with decorator-less window, such as minimizing/resizing/moving Tk window doesn't minimize/resize/move pygame's. From norman at khine.net Tue Jan 20 17:30:19 2009 From: norman at khine.net (Norman Khine) Date: Tue, 20 Jan 2009 17:30:19 +0100 Subject: [Tutor] lists Message-ID: <4975FC1B.4050306@khine.net> Hi What am I doing wrong >>> media_list = ['upper_b.wav', 'upper_a.wav'] >>> print '%s' % (for x in media_list) File "", line 1 print '%s' % (for x in media_list) ^ SyntaxError: invalid syntax >>> print '%s' % (x for x in media_list) I want to replace %s with the items of the list as individual item string, i.e 'upper_b.wav', 'upper_a.wav' if I change the list to string I still get one item: "'upper_b.wav', 'upper_a.wav'" thanks norman From kent37 at tds.net Tue Jan 20 18:00:58 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 20 Jan 2009 12:00:58 -0500 Subject: [Tutor] lists In-Reply-To: <4975FC1B.4050306@khine.net> References: <4975FC1B.4050306@khine.net> Message-ID: <1c2a2c590901200900i550fe646if7a8ace4e45a73a3@mail.gmail.com> On Tue, Jan 20, 2009 at 11:30 AM, Norman Khine wrote: > Hi > What am I doing wrong > >>>> media_list = ['upper_b.wav', 'upper_a.wav'] >>>> print '%s' % (for x in media_list) > File "", line 1 > print '%s' % (for x in media_list) > ^ > SyntaxError: invalid syntax >>>> print '%s' % (x for x in media_list) > > > I want to replace %s with the items of the list as individual item string, > i.e > > 'upper_b.wav', 'upper_a.wav' I'm not sure what you want, maybe one of these? In [1]: media_list = ['upper_b.wav', 'upper_a.wav'] In [2]: print ', '.join(media_list) upper_b.wav, upper_a.wav In [3]: print ', '.join(repr(x) for x in media_list) 'upper_b.wav', 'upper_a.wav' Kent From marc.tompkins at gmail.com Tue Jan 20 18:20:22 2009 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Tue, 20 Jan 2009 09:20:22 -0800 Subject: [Tutor] Finding the shortest word in a list of words In-Reply-To: References: <652641e90901191818i43253d11p25db401076b13e81@mail.gmail.com> <5e58f2e40901191831n45ab7d07h558244efeb52dd99@mail.gmail.com> <40af687b0901191913s6f566835h8e518cec7c47d734@mail.gmail.com> Message-ID: <40af687b0901200920h2cecdddfma59eb961af61341e@mail.gmail.com> On Tue, Jan 20, 2009 at 5:42 AM, Lie Ryan wrote: > > Using sys.maxint to prime minLen is overkill, of course - > > "antidisestablishmentarianism" is only 28 letters long, after all - but > > it should be larger than any word you can expect to see. This doesn't > > catch ties, though... could do that like so: > > > Other than overkill, it is wrong. If the shortest "word" is longer than > maxint it'd give wrong result. What language do you speak (or machine do you use), where the shortest word in a potential list is longer than maxint? On my machine maxint is 2,147,483,647. That's what I meant by overkill. You could just simply use the len of the first word. True dat. Requires an extra step or two, though - initializing with some impossibly huge number is quick. > The best solution though, have been answered by Kent Johnson. > Extremely terse and elegant, doesn't find ties. def MinKent(corpora=""): > words= corpora.split() > return min(words, key=len) > > print MinKent("No victim has ever been more repressed and alienated than > the truth is") > Output: No Mine returns (2, ['No', 'is'], 9, ['repressed', 'alienated']). I could be wrong - it seemed more like what the OP actually wanted, but he'd be the judge of that. -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From tomar.arun at gmail.com Tue Jan 20 18:34:52 2009 From: tomar.arun at gmail.com (Arun Tomar) Date: Tue, 20 Jan 2009 23:04:52 +0530 Subject: [Tutor] lists In-Reply-To: <1c2a2c590901200900i550fe646if7a8ace4e45a73a3@mail.gmail.com> References: <4975FC1B.4050306@khine.net> <1c2a2c590901200900i550fe646if7a8ace4e45a73a3@mail.gmail.com> Message-ID: <202c460901200934u3e73497cq656d9e94de213c05@mail.gmail.com> hi! On Tue, Jan 20, 2009 at 10:30 PM, Kent Johnson wrote: > On Tue, Jan 20, 2009 at 11:30 AM, Norman Khine wrote: >> Hi >> What am I doing wrong >> >>>>> media_list = ['upper_b.wav', 'upper_a.wav'] >>>>> print '%s' % (for x in media_list) >> File "", line 1 >> print '%s' % (for x in media_list) >> ^ >> SyntaxError: invalid syntax >>>>> print '%s' % (x for x in media_list) >> >> >> I want to replace %s with the items of the list as individual item string, >> i.e >> >> 'upper_b.wav', 'upper_a.wav' > > I'm not sure what you want, maybe one of these? > > In [1]: media_list = ['upper_b.wav', 'upper_a.wav'] > > In [2]: print ', '.join(media_list) > upper_b.wav, upper_a.wav > > In [3]: print ', '.join(repr(x) for x in media_list) > 'upper_b.wav', 'upper_a.wav' > > Kent may be you want to do it this way: In [10]: for x in media_list: ....: print "%s" % x ....: ....: upper_b.wav upper_a.wav -- Regards, Arun Tomar blog: http://linuxguy.in website: http://www.solutionenterprises.co.in From norman at khine.net Tue Jan 20 19:02:57 2009 From: norman at khine.net (Norman Khine) Date: Tue, 20 Jan 2009 19:02:57 +0100 Subject: [Tutor] lists In-Reply-To: <1c2a2c590901200900i550fe646if7a8ace4e45a73a3@mail.gmail.com> References: <4975FC1B.4050306@khine.net> <1c2a2c590901200900i550fe646if7a8ace4e45a73a3@mail.gmail.com> Message-ID: <497611D1.2050505@khine.net> Hi, actually what I was trying to do carries from my last post, where my media files are a list that I want to add to the subprocess.call(['sox', ', '.join(media_list), 'list.wav']) >>> print ', '.join(media_list) upper_b.wav, upper_a.wav >>> subprocess.call(['sox', ', '.join(media_list), 'list.wav']) sox formats: can't open input file `upper_b.wav, upper_a.wav': No such file or directory 2 >>> but this is treated as one item, rather than the two. Kent Johnson wrote: > On Tue, Jan 20, 2009 at 11:30 AM, Norman Khine wrote: >> Hi >> What am I doing wrong >> >>>>> media_list = ['upper_b.wav', 'upper_a.wav'] >>>>> print '%s' % (for x in media_list) >> File "", line 1 >> print '%s' % (for x in media_list) >> ^ >> SyntaxError: invalid syntax >>>>> print '%s' % (x for x in media_list) >> >> >> I want to replace %s with the items of the list as individual item string, >> i.e >> >> 'upper_b.wav', 'upper_a.wav' > > I'm not sure what you want, maybe one of these? > > In [1]: media_list = ['upper_b.wav', 'upper_a.wav'] > > In [2]: print ', '.join(media_list) > upper_b.wav, upper_a.wav > > In [3]: print ', '.join(repr(x) for x in media_list) > 'upper_b.wav', 'upper_a.wav' > > Kent > From dbibarra at ucdavis.edu Tue Jan 20 19:04:17 2009 From: dbibarra at ucdavis.edu (Donna Belle Ibarra) Date: Tue, 20 Jan 2009 10:04:17 -0800 Subject: [Tutor] Concerning Programming Exercise #6 of Chapter 2 of Python Programming John Zelle Textbook Message-ID: Hi! I need help with program exericse #6 entitled "Futval.py" which is a program that computes the value of an investment carried 10 years into the future. This is the coding I have.. yet it does not seem to spit out the correct numbers (Am I using an incorrect equation?) *def main(): print "This program calculates the future value" print "of a 10-year investment." principal = input("Enter the amount invested each year: ") apr = input("Enter the annual interest rate: ") years = input("Enter the number of years: ") for i in range (1, years + 1): principal = principal * (1 + apr)**i print "The value in", i, " years is:", principal main()* The output is suppose to appear like this: This program calculates the future value of a 10-year investment. Enter the amount invested each year: 100.00 Enter the annual interst rate: 0.05 Enter the number of years: 10 The value in 1 years is 105.0 The value in 2 years is 215.25 The value in 3 years is 331.0125 The value in 4 years is 452.563125 And so on.. ^Please help me!!! -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Tue Jan 20 19:57:14 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 20 Jan 2009 13:57:14 -0500 Subject: [Tutor] lists In-Reply-To: <497611D1.2050505@khine.net> References: <4975FC1B.4050306@khine.net> <1c2a2c590901200900i550fe646if7a8ace4e45a73a3@mail.gmail.com> <497611D1.2050505@khine.net> Message-ID: <1c2a2c590901201057s2077e5b6y34d6cc2a88e6b853@mail.gmail.com> On Tue, Jan 20, 2009 at 1:02 PM, Norman Khine wrote: > Hi, > actually what I was trying to do carries from my last post, where my media > files are a list that I want to add to the > > subprocess.call(['sox', ', '.join(media_list), 'list.wav']) OK, you want a list, not a string. You can use + to concatenate lists: ['sox'] + media_list + ['list.wav'] or args = ['sox'] args.extend(media_list) args.add('list.wav') Kent From bgailer at gmail.com Tue Jan 20 20:02:52 2009 From: bgailer at gmail.com (bob gailer) Date: Tue, 20 Jan 2009 14:02:52 -0500 Subject: [Tutor] Concerning Programming Exercise #6 of Chapter 2 of Python Programming John Zelle Textbook In-Reply-To: References: Message-ID: <49761FDC.5020800@gmail.com> An HTML attachment was scrubbed... URL: From lie.1296 at gmail.com Tue Jan 20 20:23:43 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Tue, 20 Jan 2009 19:23:43 +0000 (UTC) Subject: [Tutor] Finding the shortest word in a list of words References: <652641e90901191818i43253d11p25db401076b13e81@mail.gmail.com> <5e58f2e40901191831n45ab7d07h558244efeb52dd99@mail.gmail.com> <40af687b0901191913s6f566835h8e518cec7c47d734@mail.gmail.com> <40af687b0901200920h2cecdddfma59eb961af61341e@mail.gmail.com> Message-ID: On Tue, 20 Jan 2009 09:20:22 -0800, Marc Tompkins wrote: > On Tue, Jan 20, 2009 at 5:42 AM, Lie Ryan wrote: > >> > Using sys.maxint to prime minLen is overkill, of course - >> > "antidisestablishmentarianism" is only 28 letters long, after all - >> > but it should be larger than any word you can expect to see. This >> > doesn't catch ties, though... could do that like so: > >> Other than overkill, it is wrong. If the shortest "word" is longer than >> maxint it'd give wrong result. > > What language do you speak (or machine do you use), where the shortest > word in a potential list is longer than maxint? On my machine maxint is > 2,147,483,647. That's what I meant by overkill. what I meant as wrong is that it is possible that the code would be used for a string that doesn't represent human language, but arbitrary array of bytes. Also, it is a potential security issue. > You could just simply use the len of the first word. > > True dat. Requires an extra step or two, though - initializing with > some impossibly huge number is quick. len() is fast, and it also removes the need to import sys, which actually removes an extra step or two >> The best solution though, have been answered by Kent Johnson. >> > Extremely terse and elegant, doesn't find ties. > Output: No which, at the time of writing, was my impression on the OP's request. > Mine returns (2, ['No', 'is'], 9, ['repressed', 'alienated']). I could > be wrong - it seemed more like what the OP actually wanted, but he'd be > the judge of that. From david at abbottdavid.com Tue Jan 20 20:29:02 2009 From: david at abbottdavid.com (David) Date: Tue, 20 Jan 2009 14:29:02 -0500 Subject: [Tutor] lists In-Reply-To: <497611D1.2050505@khine.net> References: <4975FC1B.4050306@khine.net> <1c2a2c590901200900i550fe646if7a8ace4e45a73a3@mail.gmail.com> <497611D1.2050505@khine.net> Message-ID: <497625FE.6090302@abbottdavid.com> Norman Khine wrote: > Hi, > actually what I was trying to do carries from my last post, where my > media files are a list that I want to add to the > > subprocess.call(['sox', ', '.join(media_list), 'list.wav']) Something like this may work; #!/usr/bin/python import subprocess def play(filename): player = "/usr/bin/sox" fname = "/home/yorname/dir/" + filname subprocess.call([player, fname]) def playall(files): for name in files: play(name) def run(): files =['wav1.wav', 'wav2.wav'] playall(files) run() -- powered by Gentoo/GNU Linux http://linuxcrazy.com From marc.tompkins at gmail.com Tue Jan 20 21:14:36 2009 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Tue, 20 Jan 2009 12:14:36 -0800 Subject: [Tutor] Finding the shortest word in a list of words In-Reply-To: References: <652641e90901191818i43253d11p25db401076b13e81@mail.gmail.com> <5e58f2e40901191831n45ab7d07h558244efeb52dd99@mail.gmail.com> <40af687b0901191913s6f566835h8e518cec7c47d734@mail.gmail.com> <40af687b0901200920h2cecdddfma59eb961af61341e@mail.gmail.com> Message-ID: <40af687b0901201214v22cb2aa9v560fe10fbbbac31e@mail.gmail.com> On Tue, Jan 20, 2009 at 11:23 AM, Lie Ryan wrote: > what I meant as wrong is that it is possible that the code would be used > for a string that doesn't represent human language, but arbitrary array > of bytes. Also, it is a potential security issue. This is something I need to know, then - sys.maxint is a potential security issue? How? Should it be avoided? (Guess I'd better get Googling...) > > You could just simply use the len of the first word. > > > > True dat. Requires an extra step or two, though - initializing with > > some impossibly huge number is quick. > > len() is fast, and it also removes the need to import sys, which actually > removes an extra step or two > Unintended consequence - initializing minLen with the length of the first word results in trying to append to a list that doesn't exist yet - so must create minWord and maxWord ahead of time. (Could use try/except... no.) Also - it occurred to me that the input might be sentences, and sentences contain punctuation... I already took the liberty of adding "is" to the end of the OP's signature quotation; now I add a period: > corpus = "No victim has ever been more repressed and alienated than the > truth is." Now "is." has length 3, not 2; probably not what we had in mind. So, new version: > def MinMax(corpus=""): > import string > corpus = "".join( [x for x in corpus if x not in string.punctuation] ) > words = corpus.split() > minLen = len(words[0]) > maxLen = 0 > minWord, maxWord = [],[] > for word in words: > curLen = len(word) > if curLen == minLen: > minWord.append(word) > if curLen == maxLen: > maxWord.append(word) > if curLen > maxLen: > maxWord = [word] > maxLen = curLen > if curLen < minLen: > minWord = [word] > minLen = curLen > return minLen, minWord, maxLen, maxWord > Is there a good/efficient way to do this without importing string? Obviously best to move the import outside the function to minimize redundancy, but any way to avoid it at all? which, at the time of writing, was my impression on the OP's request. > Quote: "I need to find the shortest / longest word(s) in a sequence of words." I'm sure the OP has moved on by now... time I did likewise. -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From emadnawfal at gmail.com Tue Jan 20 22:08:00 2009 From: emadnawfal at gmail.com (=?windows-1256?B?RW1hZCBOYXdmYWwgKNrjx88g5Obd4Sk=?=) Date: Tue, 20 Jan 2009 16:08:00 -0500 Subject: [Tutor] Finding the shortest word in a list of words In-Reply-To: <40af687b0901201214v22cb2aa9v560fe10fbbbac31e@mail.gmail.com> References: <652641e90901191818i43253d11p25db401076b13e81@mail.gmail.com> <5e58f2e40901191831n45ab7d07h558244efeb52dd99@mail.gmail.com> <40af687b0901191913s6f566835h8e518cec7c47d734@mail.gmail.com> <40af687b0901200920h2cecdddfma59eb961af61341e@mail.gmail.com> <40af687b0901201214v22cb2aa9v560fe10fbbbac31e@mail.gmail.com> Message-ID: <652641e90901201308w1f9102bap12edfe1d1f69850f@mail.gmail.com> On Tue, Jan 20, 2009 at 3:14 PM, Marc Tompkins wrote: > On Tue, Jan 20, 2009 at 11:23 AM, Lie Ryan wrote: > >> what I meant as wrong is that it is possible that the code would be used >> for a string that doesn't represent human language, but arbitrary array >> of bytes. Also, it is a potential security issue. > > > This is something I need to know, then - sys.maxint is a potential security > issue? How? Should it be avoided? (Guess I'd better get Googling...) > > >> > You could just simply use the len of the first word. >> > >> > True dat. Requires an extra step or two, though - initializing with >> > some impossibly huge number is quick. >> >> len() is fast, and it also removes the need to import sys, which actually >> removes an extra step or two >> > Unintended consequence - initializing minLen with the length of the first > word results in trying to append to a list that doesn't exist yet - so must > create minWord and maxWord ahead of time. (Could use try/except... no.) > Also - it occurred to me that the input might be sentences, and sentences > contain punctuation... I already took the liberty of adding "is" to the end > of the OP's signature quotation; now I add a period: > >> corpus = "No victim has ever been more repressed and alienated than the >> truth is." > > Now "is." has length 3, not 2; probably not what we had in mind. > So, new version: > > >> def MinMax(corpus=""): >> import string >> corpus = "".join( [x for x in corpus if x not in string.punctuation] ) >> words = corpus.split() >> minLen = len(words[0]) >> maxLen = 0 >> minWord, maxWord = [],[] >> for word in words: >> curLen = len(word) >> if curLen == minLen: >> minWord.append(word) >> if curLen == maxLen: >> maxWord.append(word) >> if curLen > maxLen: >> maxWord = [word] >> maxLen = curLen >> if curLen < minLen: >> minWord = [word] >> minLen = curLen >> return minLen, minWord, maxLen, maxWord >> > > Is there a good/efficient way to do this without importing string? > Obviously best to move the import outside the function to minimize > redundancy, but any way to avoid it at all? > > > which, at the time of writing, was my impression on the OP's request. >> > > Quote: "I need to find the shortest / longest word(s) in a sequence of > words." > > I'm sure the OP has moved on by now... time I did likewise. > -- > www.fsrtechnologies.com > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > Yes, I have moved on. I got what i needed . I have nonetheless been following your advanced discussion trying to understand what you're saying. Have not done this fully yet As far as punctuation is concerned, I separate the punctuation marks from the text before I find for the shortest / longest words. I'm working with two agglutinative languages (Swahili and Arabic), and I wanted to see how much agglutination there could be in both languages. Thank you all for your help -- ?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? ????????.....???? ??????? "No victim has ever been more repressed and alienated than the truth" Emad Soliman Nawfal Indiana University, Bloomington http://emnawfal.googlepages.com -------------------------------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: From metolone+gmane at gmail.com Wed Jan 21 04:18:11 2009 From: metolone+gmane at gmail.com (Mark Tolonen) Date: Tue, 20 Jan 2009 19:18:11 -0800 Subject: [Tutor] Concerning Programming Exercise #6 of Chapter 2 of Python Programming John Zelle Textbook References: <49761FDC.5020800@gmail.com> Message-ID: Since you are updating the principal value each year, use the following to grow the principal by the interest rate each year: principal = principal * (1 + apr) -Mark "bob gailer" wrote in message news:49761FDC.5020800 at gmail.com... Donna Belle Ibarra wrote: Hi! I need help with program exericse #6 entitled "Futval.py" which is a program that computes the value of an investment carried 10 years into the future. This is the coding I have.. yet it does not seem to spit out the correct numbers (Am I using an incorrect equation?) Take a look at http://en.wikipedia.org/wiki/Time_value_of_money#Present_value_of_a_future_sum for the various formulas. I am not sure which applies in your case. def main(): print "This program calculates the future value" print "of a 10-year investment." principal = input("Enter the amount invested each year: ") apr = input("Enter the annual interest rate: ") years = input("Enter the number of years: ") for i in range (1, years + 1): principal = principal * (1 + apr)**i print "The value in", i, " years is:", principal main() The output is suppose to appear like this: This program calculates the future value of a 10-year investment. Enter the amount invested each year: 100.00 Enter the annual interst rate: 0.05 Enter the number of years: 10 The value in 1 years is 105.0 The value in 2 years is 215.25 The value in 3 years is 331.0125 The value in 4 years is 452.563125 And so on.. ^Please help me!!! ---------------------------------------------------------------------------- _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor -- Bob Gailer Chapel Hill NC 919-636-4239 ------------------------------------------------------------------------------ _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From bermanrl at cfl.rr.com Wed Jan 21 14:33:50 2009 From: bermanrl at cfl.rr.com (Robert Berman) Date: Wed, 21 Jan 2009 08:33:50 -0500 Subject: [Tutor] The better Python approach Message-ID: <4977243E.4010507@cfl.rr.com> Good Morning, Given a string consisting of numbers separated by spaces such as '1234 5678 1 233 476'. I can see I have two obvious choices to extract or parse out the numbers. The first relying on iteration so that as I search for a blank, I build a substring of all characters found before the space and then, once the space is found, I can then use the int(n) function to determine the number. From my C++ background, that is the approach that seems not only most natural but also most efficient......but....the rules of Python are different and I easily see that I can also search for the first blank, then using the character count, I can use the slice operation to get the characters. Of even further interest I see a string built-in function called split which, I think, will return all the distinct character sub strings for me. My question is what is the most correct python oriented solution for extracting those substrings? Thanks, Robert Berman From jadrifter at gmail.com Wed Jan 21 14:40:00 2009 From: jadrifter at gmail.com (jadrifter) Date: Wed, 21 Jan 2009 05:40:00 -0800 Subject: [Tutor] The better Python approach In-Reply-To: <4977243E.4010507@cfl.rr.com> References: <4977243E.4010507@cfl.rr.com> Message-ID: <1232545201.6121.3.camel@ltop> >>>a = '1234 5678 1 233 476' >>>a.split() ['1234', '5678', '1', '233', '476'] Where the '>>>' are the command prompt from python. Don't type those. A space is the default split delimiter. If you wish to use a '-' or new line feed them as strings to the split method. John On Wed, 2009-01-21 at 08:33 -0500, Robert Berman wrote: > Good Morning, > > Given a string consisting of numbers separated by spaces such as '1234 > 5678 1 233 476'. I can see I have two obvious choices to extract or > parse out the numbers. The first relying on iteration so that as I > search for a blank, I build a substring of all characters found before > the space and then, once the space is found, I can then use the int(n) > function to determine the number. From my C++ background, that is the > approach that seems not only most natural but also most > efficient......but....the rules of Python are different and I easily see > that I can also search for the first blank, then using the character > count, I can use the slice operation to get the characters. Of even > further interest I see a string built-in function called split which, I > think, will return all the distinct character sub strings for me. > > My question is what is the most correct python oriented solution for > extracting those substrings? > > Thanks, > > > Robert Berman > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From mail at timgolden.me.uk Wed Jan 21 14:40:15 2009 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 21 Jan 2009 13:40:15 +0000 Subject: [Tutor] The better Python approach In-Reply-To: <4977243E.4010507@cfl.rr.com> References: <4977243E.4010507@cfl.rr.com> Message-ID: <497725BF.9060501@timgolden.me.uk> Robert Berman wrote: > Given a string consisting of numbers separated by spaces such as '1234 > 5678 1 233 476'. I can see I have two obvious choices to extract or > parse out the numbers. The first relying on iteration so that as I > search for a blank, I build a substring of all characters found before > the space and then, once the space is found, I can then use the int(n) > function to determine the number. From my C++ background, that is the > approach that seems not only most natural but also most > efficient......but....the rules of Python are different and I easily see > that I can also search for the first blank, then using the character > count, I can use the slice operation to get the characters. Of even > further interest I see a string built-in function called split which, I > think, will return all the distinct character sub strings for me. > > My question is what is the most correct python oriented solution for > extracting those substrings? Correct? I don't know. Working; try this: s = '1234 5678 1 233 476' nums = [int (i) for i in s.split ()] print nums If you had some more sophisticated need (he says, inventing requirements as he goes along) such as pulling the numbers out of a string of mixed numbers and letters, you could use a regular expression: import re s = '1234 abc 5678 *** 1 233 xyz 476' nums = [int (i) for i in re.findall ("\d+", s)] print nums TJG From bermanrl at cfl.rr.com Wed Jan 21 14:50:29 2009 From: bermanrl at cfl.rr.com (Robert Berman) Date: Wed, 21 Jan 2009 08:50:29 -0500 Subject: [Tutor] The better Python approach In-Reply-To: <497725BF.9060501@timgolden.me.uk> References: <4977243E.4010507@cfl.rr.com> <497725BF.9060501@timgolden.me.uk> Message-ID: <49772825.5060000@cfl.rr.com> An HTML attachment was scrubbed... URL: From teachv at taconic.net Wed Jan 21 14:59:08 2009 From: teachv at taconic.net (Vince Teachout) Date: Wed, 21 Jan 2009 08:59:08 -0500 Subject: [Tutor] The better Python approach In-Reply-To: <1232545201.6121.3.camel@ltop> References: <4977243E.4010507@cfl.rr.com> <1232545201.6121.3.camel@ltop> Message-ID: <49772A2C.6010107@taconic.net> jadrifter wrote: >>>> a = '1234 5678 1 233 476' >>>> a.split() > ['1234', '5678', '1', '233', '476'] > > Where the '>>>' are the command prompt from python. Don't type those. > A space is the default split delimiter. If you wish to use a '-' or new > line feed them as strings to the split method. > Ok, that's it. That was the last straw. I'm digging up my copy of "Dive into Python" and starting today! From alan.gauld at btinternet.com Wed Jan 21 15:44:18 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 21 Jan 2009 14:44:18 -0000 Subject: [Tutor] The better Python approach References: <4977243E.4010507@cfl.rr.com> <497725BF.9060501@timgolden.me.uk> <49772825.5060000@cfl.rr.com> Message-ID: "Robert Berman" wrote > Perhaps i should not have said the most Python correct. > It looks as if it may well be the approach using the least > amount of work the interpreter must complete. That's generally true. Python can always do things the long way but its generally more efficient both in programmer time and performance speed to use the built-in functions/methods as much as possible. Most of them are written in C after all! Alan G From andreas at kostyrka.org Wed Jan 21 18:29:03 2009 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Wed, 21 Jan 2009 18:29:03 +0100 Subject: [Tutor] The better Python approach In-Reply-To: <1232545201.6121.3.camel@ltop> References: <4977243E.4010507@cfl.rr.com> <1232545201.6121.3.camel@ltop> Message-ID: <20090121182903.0602ac78@andi-lap> Am Wed, 21 Jan 2009 05:40:00 -0800 schrieb jadrifter : > >>>a = '1234 5678 1 233 476' > >>>a.split() > ['1234', '5678', '1', '233', '476'] [int(x) for x in a.split()] # [1234, 5678, 1, 233, 476] Andreas From andreas at kostyrka.org Wed Jan 21 18:39:57 2009 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Wed, 21 Jan 2009 18:39:57 +0100 Subject: [Tutor] Finding the shortest word in a list of words In-Reply-To: <05B96BA361DD4053A753FD05C17CDB4E@AWA2> References: <05B96BA361DD4053A753FD05C17CDB4E@AWA2> Message-ID: <20090121183957.3b8b093b@andi-lap> Am Tue, 20 Jan 2009 09:33:40 -0600 schrieb "Paul McGuire" : No need for a defaultdict, all dicts have a setdefault method that works fine for this assign an empty dict/list as starting point problem: wordlendict = {} for w in words: wordlendict.setdefault(len(w), []).append(w) try: minlen, minlist = min(wordlendict.items()) except ValueError: minlen = 0 minlist = [] Andreas > from collections import defaultdict > wordlendict = defaultdict(list) > for w in words: > wordlendict[len(w)].append(w) > minlen = min(wordlendict.keys()) > minlist = wordlendict[minlen] > print minlist > > prints: > ['he', 'me'] > > Now we are getting a more complete answer! > > A second approach uses the groupby method of the itertools module in > the stdlib. groupby usually takes me several attempts to get > everything right: the input must be sorted by the grouping feature, > and then the results returned by groupby are in the form of an > iterator that returns key-iterator tuples. I need to go through some > mental gymnastics to unwind the data to get the group I'm really > interested in. Here is a step-by-step code to use groupby: > > from itertools import groupby > grpsbylen = groupby(sorted(words,key=len),len) > mingrp = grpsbylen.next() > minlen = mingrp[0] > minlist = list(mingrp[1]) > print minlist > > The input list of words gets sorted, and then passed to groupby, > which uses len as the grouping criteria (groupby is not inherently > aware of how the input list was sorted, so len must be repeated). > The first group tuple is pulled from the grpsbylen iterator using > next(). The 0'th tuple element is the grouping value - in this case, > it is the minimum length 2. The 1'th tuple element is the group > itself, given as an iterator. Passing this to the list constructor > gives us the list of all the 2-character words, which then gets > printed: ['he', 'me'] > > Again, 'me' no longer gets left out. > > Maybe this will get you some extra credit... > > -- Paul > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From ptmcg at austin.rr.com Wed Jan 21 19:45:34 2009 From: ptmcg at austin.rr.com (Paul McGuire) Date: Wed, 21 Jan 2009 12:45:34 -0600 Subject: [Tutor] Tutor Digest, Vol 59, Issue 109 In-Reply-To: References: Message-ID: -----Original Message----- From: tutor-bounces+ptmcg=austin.rr.com at python.org [mailto:tutor-bounces+ptmcg=austin.rr.com at python.org] On Behalf Of tutor-request at python.org Sent: Wednesday, January 21, 2009 11:29 AM To: tutor at python.org Subject: Tutor Digest, Vol 59, Issue 109 Send Tutor mailing list submissions to tutor at 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 at python.org You can reach the person managing the list at tutor-owner at python.org When replying, please edit your Subject line so it is more specific than "Re: Contents of Tutor digest..." Today's Topics: 1. The better Python approach (Robert Berman) 2. Re: The better Python approach (jadrifter) 3. Re: The better Python approach (Tim Golden) 4. Re: The better Python approach (Robert Berman) 5. Re: The better Python approach (Vince Teachout) 6. Re: The better Python approach (Alan Gauld) 7. Re: The better Python approach (Andreas Kostyrka) ---------------------------------------------------------------------- Message: 1 Date: Wed, 21 Jan 2009 08:33:50 -0500 From: Robert Berman Subject: [Tutor] The better Python approach To: Tutor at python.org Message-ID: <4977243E.4010507 at cfl.rr.com> Content-Type: text/plain; charset=ISO-8859-1; format=flowed Good Morning, Given a string consisting of numbers separated by spaces such as '1234 5678 1 233 476'. I can see I have two obvious choices to extract or parse out the numbers. The first relying on iteration so that as I search for a blank, I build a substring of all characters found before the space and then, once the space is found, I can then use the int(n) function to determine the number. From my C++ background, that is the approach that seems not only most natural but also most efficient......but....the rules of Python are different and I easily see that I can also search for the first blank, then using the character count, I can use the slice operation to get the characters. Of even further interest I see a string built-in function called split which, I think, will return all the distinct character sub strings for me. My question is what is the most correct python oriented solution for extracting those substrings? Thanks, Robert Berman ------------------------------ Message: 2 Date: Wed, 21 Jan 2009 05:40:00 -0800 From: jadrifter Subject: Re: [Tutor] The better Python approach To: Robert Berman Cc: Tutor at python.org Message-ID: <1232545201.6121.3.camel at ltop> Content-Type: text/plain >>>a = '1234 5678 1 233 476' >>>a.split() ['1234', '5678', '1', '233', '476'] Where the '>>>' are the command prompt from python. Don't type those. A space is the default split delimiter. If you wish to use a '-' or new line feed them as strings to the split method. John On Wed, 2009-01-21 at 08:33 -0500, Robert Berman wrote: > Good Morning, > > Given a string consisting of numbers separated by spaces such as '1234 > 5678 1 233 476'. I can see I have two obvious choices to extract or > parse out the numbers. The first relying on iteration so that as I > search for a blank, I build a substring of all characters found before > the space and then, once the space is found, I can then use the int(n) > function to determine the number. From my C++ background, that is the > approach that seems not only most natural but also most > efficient......but....the rules of Python are different and I easily > see that I can also search for the first blank, then using the > character count, I can use the slice operation to get the characters. > Of even further interest I see a string built-in function called split > which, I think, will return all the distinct character sub strings for me. > > My question is what is the most correct python oriented solution for > extracting those substrings? > > Thanks, > > > Robert Berman > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor ------------------------------ Message: 3 Date: Wed, 21 Jan 2009 13:40:15 +0000 From: Tim Golden Subject: Re: [Tutor] The better Python approach Cc: Tutor at python.org Message-ID: <497725BF.9060501 at timgolden.me.uk> Content-Type: text/plain; charset=ISO-8859-1; format=flowed Robert Berman wrote: > Given a string consisting of numbers separated by spaces such as '1234 > 5678 1 233 476'. I can see I have two obvious choices to extract or > parse out the numbers. The first relying on iteration so that as I > search for a blank, I build a substring of all characters found before > the space and then, once the space is found, I can then use the int(n) > function to determine the number. From my C++ background, that is the > approach that seems not only most natural but also most > efficient......but....the rules of Python are different and I easily > see that I can also search for the first blank, then using the > character count, I can use the slice operation to get the characters. > Of even further interest I see a string built-in function called split > which, I think, will return all the distinct character sub strings for me. > > My question is what is the most correct python oriented solution for > extracting those substrings? Correct? I don't know. Working; try this: s = '1234 5678 1 233 476' nums = [int (i) for i in s.split ()] print nums If you had some more sophisticated need (he says, inventing requirements as he goes along) such as pulling the numbers out of a string of mixed numbers and letters, you could use a regular expression: import re s = '1234 abc 5678 *** 1 233 xyz 476' nums = [int (i) for i in re.findall ("\d+", s)] print nums TJG ------------------------------ Message: 4 Date: Wed, 21 Jan 2009 08:50:29 -0500 From: Robert Berman Subject: Re: [Tutor] The better Python approach To: Tutor at python.org Message-ID: <49772825.5060000 at cfl.rr.com> Content-Type: text/plain; charset="us-ascii" An HTML attachment was scrubbed... URL: ------------------------------ Message: 5 Date: Wed, 21 Jan 2009 08:59:08 -0500 From: Vince Teachout Subject: Re: [Tutor] The better Python approach To: Tutor at python.org Message-ID: <49772A2C.6010107 at taconic.net> Content-Type: text/plain; charset=ISO-8859-1; format=flowed jadrifter wrote: >>>> a = '1234 5678 1 233 476' >>>> a.split() > ['1234', '5678', '1', '233', '476'] > > Where the '>>>' are the command prompt from python. Don't type those. > A space is the default split delimiter. If you wish to use a '-' or > new line feed them as strings to the split method. > Ok, that's it. That was the last straw. I'm digging up my copy of "Dive into Python" and starting today! ------------------------------ Message: 6 Date: Wed, 21 Jan 2009 14:44:18 -0000 From: "Alan Gauld" Subject: Re: [Tutor] The better Python approach To: tutor at python.org Message-ID: Content-Type: text/plain; format=flowed; charset="iso-8859-1"; reply-type=original "Robert Berman" wrote > Perhaps i should not have said the most Python correct. > It looks as if it may well be the approach using the least > amount of work the interpreter must complete. That's generally true. Python can always do things the long way but its generally more efficient both in programmer time and performance speed to use the built-in functions/methods as much as possible. Most of them are written in C after all! Alan G ------------------------------ Message: 7 Date: Wed, 21 Jan 2009 18:29:03 +0100 From: Andreas Kostyrka Subject: Re: [Tutor] The better Python approach To: jadrifter at gmail.com Cc: Tutor at python.org Message-ID: <20090121182903.0602ac78 at andi-lap> Content-Type: text/plain; charset=US-ASCII Am Wed, 21 Jan 2009 05:40:00 -0800 schrieb jadrifter : > >>>a = '1234 5678 1 233 476' > >>>a.split() > ['1234', '5678', '1', '233', '476'] [int(x) for x in a.split()] # [1234, 5678, 1, 233, 476] Andreas ------------------------------ _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor End of Tutor Digest, Vol 59, Issue 109 ************************************** From bermanrl at cfl.rr.com Wed Jan 21 20:02:01 2009 From: bermanrl at cfl.rr.com (Robert Berman) Date: Wed, 21 Jan 2009 14:02:01 -0500 Subject: [Tutor] The better Python approach In-Reply-To: References: <4977243E.4010507@cfl.rr.com> <497725BF.9060501@timgolden.me.uk> <49772825.5060000@cfl.rr.com> Message-ID: <49777129.7060709@cfl.rr.com> Alan, Thank you for the clarification. Using that as my guide, I revamped my solution to this small challenge and attempted to make the script as concise as possible. The challenge is at the Challenge-You web page, http://www.challenge-you.com/challenge?id=61 I am relatively certain I could have made it more concise with some more detailed examination. If there are some obvious glaring deficiencies, please, anyone feel free to comment. Thanks, Robert Berman #!/usr/bin/env python #findsum.py import string def openinput(thepath = '/home/bermanrl/usbdirbig/Challenges/sum.txt'): ''' Opens text file ''' try: infile = open(thepath, 'r') except: print 'Open file failure.' return infile def runprocess(): '''Reads file and passes string to parsing function ''' bigtotal = 0 myfile = openinput() for line in myfile: jlist = line.split() for x in jlist: bigtotal += int(x) print bigtotal return if __name__ == '__main__': runprocess() Alan Gauld wrote: > > "Robert Berman" wrote > >> Perhaps i should not have said the most Python correct. >> It looks as if it may well be the approach using the least >> amount of work the interpreter must complete. > > That's generally true. Python can always do things the long way but its > generally more efficient both in programmer time and performance > speed to use the built-in functions/methods as much as possible. > Most of them are written in C after all! > > Alan G > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Wed Jan 21 20:47:36 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 21 Jan 2009 14:47:36 -0500 Subject: [Tutor] The better Python approach In-Reply-To: <49777129.7060709@cfl.rr.com> References: <4977243E.4010507@cfl.rr.com> <497725BF.9060501@timgolden.me.uk> <49772825.5060000@cfl.rr.com> <49777129.7060709@cfl.rr.com> Message-ID: <1c2a2c590901211147v3e62eaf5kab9e25614888a058@mail.gmail.com> On Wed, Jan 21, 2009 at 2:02 PM, Robert Berman wrote: > myfile = openinput() > for line in myfile: > jlist = line.split() > for x in jlist: > bigtotal += int(x) Python has a sum() function that sums the elements of a numeric sequence, so the inner loop can be written as bigtotal += sum(int(x) for x in line.split()) But this is just summing another sequence - the line sums - so the whole thing can be written as bigtotal = sum(sum(int(x) for x in line.split()) for line in myfile) or more simply as a single sum over a double loop: bigtotal = sum(int(x) for line in myfile for x in line.split()) which you may or may not see as an improvement... Kent From bermanrl at cfl.rr.com Wed Jan 21 21:42:04 2009 From: bermanrl at cfl.rr.com (Robert Berman) Date: Wed, 21 Jan 2009 15:42:04 -0500 Subject: [Tutor] The better Python approach In-Reply-To: <1c2a2c590901211147v3e62eaf5kab9e25614888a058@mail.gmail.com> References: <4977243E.4010507@cfl.rr.com> <497725BF.9060501@timgolden.me.uk> <49772825.5060000@cfl.rr.com> <49777129.7060709@cfl.rr.com> <1c2a2c590901211147v3e62eaf5kab9e25614888a058@mail.gmail.com> Message-ID: <4977889C.9020703@cfl.rr.com> An HTML attachment was scrubbed... URL: From david at abbottdavid.com Wed Jan 21 23:29:19 2009 From: david at abbottdavid.com (David) Date: Wed, 21 Jan 2009 17:29:19 -0500 Subject: [Tutor] bruteforce match word in text file Message-ID: <4977A1BF.5040801@abbottdavid.com> I have to ask for a pointer, not sure what I am doing wrong. thanks -david #!/usr/bin/python password = 'loser' wordlist = '/home/david/Challenge-You/wordlist.txt' try: words = open(wordlist, 'r').readlines() except IOError, e: print "Sorry no words" for word in words: word = word.replace("\n","") if password in word: print word else: print 'You are a loser' -- Powered by Gentoo GNU/LINUX http://www.linuxcrazy.com pgp.mit.edu From bgailer at gmail.com Wed Jan 21 23:41:50 2009 From: bgailer at gmail.com (bob gailer) Date: Wed, 21 Jan 2009 17:41:50 -0500 Subject: [Tutor] bruteforce match word in text file In-Reply-To: <4977A1BF.5040801@abbottdavid.com> References: <4977A1BF.5040801@abbottdavid.com> Message-ID: <4977A4AE.30403@gmail.com> David wrote: > I have to ask for a pointer, not sure what I am doing wrong. The first thing you are doing "wrong" is failing to tell us what is in the wordlist file and what results you get when you run the program. Please re-post with that information. > > #!/usr/bin/python > password = 'loser' > wordlist = '/home/david/Challenge-You/wordlist.txt' > try: > words = open(wordlist, 'r').readlines() > except IOError, e: > print "Sorry no words" > for word in words: > word = word.replace("\n","") > if password in word: > print word > else: > print 'You are a loser' > -- Bob Gailer Chapel Hill NC 919-636-4239 From david at abbottdavid.com Wed Jan 21 23:52:05 2009 From: david at abbottdavid.com (David) Date: Wed, 21 Jan 2009 17:52:05 -0500 Subject: [Tutor] bruteforce match word in text file In-Reply-To: <4977A4AE.30403@gmail.com> References: <4977A1BF.5040801@abbottdavid.com> <4977A4AE.30403@gmail.com> Message-ID: <4977A715.4020601@abbottdavid.com> bob gailer wrote: > David wrote: >> I have to ask for a pointer, not sure what I am doing wrong. > > The first thing you are doing "wrong" is failing to tell us what is in > the wordlist file and what results you get when you run the program. > > Please re-post with that information. >> >> #!/usr/bin/python >> password = 'loser' >> wordlist = '/home/david/Challenge-You/wordlist.txt' >> try: >> words = open(wordlist, 'r').readlines() >> except IOError, e: >> print "Sorry no words" >> for word in words: >> word = word.replace("\n","") >> if password in word: >> print word >> else: >> print 'You are a loser' >> > > wordlist.txt next block is the meat the script will go through the list of words create our form with information encode that form and then apply that loser get source added comments above each line to help you understand results; ./py_bruteforce.py next block is the meat the script will go through the list of words create our form with information encode that form and then apply that loser get source added comments above each line to help you understand You are a loser -- Powered by Gentoo GNU/LINUX http://www.linuxcrazy.com pgp.mit.edu From bgailer at gmail.com Thu Jan 22 00:00:51 2009 From: bgailer at gmail.com (bob gailer) Date: Wed, 21 Jan 2009 18:00:51 -0500 Subject: [Tutor] bruteforce match word in text file In-Reply-To: <4977A715.4020601@abbottdavid.com> References: <4977A1BF.5040801@abbottdavid.com> <4977A4AE.30403@gmail.com> <4977A715.4020601@abbottdavid.com> Message-ID: <4977A923.4090403@gmail.com> David wrote: > bob gailer wrote: >> David wrote: >>> I have to ask for a pointer, not sure what I am doing wrong. >> >> The first thing you are doing "wrong" is failing to tell us what is >> in the wordlist file and what results you get when you run the program. >> >> Please re-post with that information. >>> >>> #!/usr/bin/python >>> password = 'loser' >>> wordlist = '/home/david/Challenge-You/wordlist.txt' >>> try: >>> words = open(wordlist, 'r').readlines() >>> except IOError, e: >>> print "Sorry no words" >>> for word in words: >>> word = word.replace("\n","") >>> if password in word: >>> print word >>> else: >>> print 'You are a loser' >>> >> >> > wordlist.txt > > next block is the meat the script will go through the list of words > create our form with information encode that form and then apply that > loser get source added comments above each line to help you understand > > results; > > ./py_bruteforce.py > next block is the meat the script will go through the list of words > create our form with information encode that form and then apply that > loser get source added comments above each line to help you understand > You are a loser > Thank you. Please always post the relevant information, and if you get an exception, post the full traceback. It looks like the file contains 1 line. So the for statement will put that line in word. 'loser' is in word so the print statement prints the line. The program is working as written. Now what can you change to get it to do what (I assume) you want - examine each "word" in the file, print the word if 'loser' is in it, and print 'You are a loser' ONLY if no words match. -- Bob Gailer Chapel Hill NC 919-636-4239 From alan.gauld at btinternet.com Thu Jan 22 00:25:18 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 21 Jan 2009 23:25:18 -0000 Subject: [Tutor] The better Python approach References: <4977243E.4010507@cfl.rr.com> <497725BF.9060501@timgolden.me.uk> <49772825.5060000@cfl.rr.com> <49777129.7060709@cfl.rr.com><1c2a2c590901211147v3e62eaf5kab9e25614888a058@mail.gmail.com> <4977889C.9020703@cfl.rr.com> Message-ID: "Robert Berman" wrote > Wow! That is all worth knowing. I am fascinated by the single sum > over a double loop. > > > or more simply as a single sum over a double loop: > > bigtotal = sum(int(x) for line in myfile for x in line.split()) > > > which you may or may not see as an improvement... And that nicely illustrates the caveat with using the most concise form. You have to make a judgement about when it becomes too concise to be readable and therefore maintainable. Personally I prefer the double loop to the double sum, but in practice I'd probably have been happy to stick with the outer for loop and only one sum() call inside that. But that uis where taste comes into programming, there is no absolute correct form - which takes us back to your original post! :-) -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From david at abbottdavid.com Thu Jan 22 01:01:36 2009 From: david at abbottdavid.com (David) Date: Wed, 21 Jan 2009 19:01:36 -0500 Subject: [Tutor] bruteforce match word in text file In-Reply-To: <4977A923.4090403@gmail.com> References: <4977A1BF.5040801@abbottdavid.com> <4977A4AE.30403@gmail.com> <4977A715.4020601@abbottdavid.com> <4977A923.4090403@gmail.com> Message-ID: <4977B760.3020601@abbottdavid.com> bob gailer wrote: > David wrote: >> bob gailer wrote: >>> David wrote: >>>> I have to ask for a pointer, not sure what I am doing wrong. >>> >>> The first thing you are doing "wrong" is failing to tell us what is >>> in the wordlist file and what results you get when you run the program. >>> >>> Please re-post with that information. >>>> >>>> #!/usr/bin/python >>>> password = 'loser' >>>> wordlist = '/home/david/Challenge-You/wordlist.txt' >>>> try: >>>> words = open(wordlist, 'r').readlines() >>>> except IOError, e: >>>> print "Sorry no words" >>>> for word in words: >>>> word = word.replace("\n","") >>>> if password in word: >>>> print word >>>> else: >>>> print 'You are a loser' > > Now what can you change to get it to do what (I assume) you want - > examine each "word" in the file, print the word if 'loser' is in it, and > print 'You are a loser' ONLY if no words match. > Thanks Bob, I changed the wordlist.txt to next block is meat and the program; #!/usr/bin/python import re password = 'loser' wordlist = '/home/david/Challenge-You/wordlist.txt' try: words = open(wordlist, 'r').readlines() except IOError, e: print "Sorry no words" for word in words: word = word.replace("\n","") if password in word: print "The password is: ", word else: pass I could not figure out how to split the file into words. -- Powered by Gentoo GNU/LINUX http://www.linuxcrazy.com pgp.mit.edu From david at abbottdavid.com Thu Jan 22 01:09:14 2009 From: david at abbottdavid.com (David) Date: Wed, 21 Jan 2009 19:09:14 -0500 Subject: [Tutor] bruteforce match word in text file In-Reply-To: <4977B760.3020601@abbottdavid.com> References: <4977A1BF.5040801@abbottdavid.com> <4977A4AE.30403@gmail.com> <4977A715.4020601@abbottdavid.com> <4977A923.4090403@gmail.com> <4977B760.3020601@abbottdavid.com> Message-ID: <4977B92A.3000008@abbottdavid.com> > #!/usr/bin/python > import re > password = 'loser' > wordlist = '/home/david/Challenge-You/wordlist.txt' > try: > words = open(wordlist, 'r').readlines() > except IOError, e: > print "Sorry no words" > for word in words: > word = word.replace("\n","") > if password in word: > print "The password is: ", word > else: > pass > > I could not figure out how to split the file into words. > > I removed the import re as that was left over from my experimenting. -- Powered by Gentoo GNU/LINUX http://www.linuxcrazy.com pgp.mit.edu From bgailer at gmail.com Thu Jan 22 02:19:03 2009 From: bgailer at gmail.com (bob gailer) Date: Wed, 21 Jan 2009 20:19:03 -0500 Subject: [Tutor] bruteforce match word in text file In-Reply-To: <4977B760.3020601@abbottdavid.com> References: <4977A1BF.5040801@abbottdavid.com> <4977A4AE.30403@gmail.com> <4977A715.4020601@abbottdavid.com> <4977A923.4090403@gmail.com> <4977B760.3020601@abbottdavid.com> Message-ID: <4977C987.7080809@gmail.com> David wrote: > > Thanks Bob, > I changed the wordlist.txt to > next > block > is > meat > > and the program; > > #!/usr/bin/python > password = 'loser' > wordlist = '/home/david/Challenge-You/wordlist.txt' > try: > words = open(wordlist, 'r').readlines() > except IOError, e: > print "Sorry no words" > for word in words: > word = word.replace("\n","") > if password in word: > print "The password is: ", word > else: > pass Good work! > > I could not figure out how to split the file into words. look up the string method split. Also take a look at the syntax of the for statement and notice it has an else clause. -- Bob Gailer Chapel Hill NC 919-636-4239 From dorseye at gmail.com Thu Jan 22 02:38:33 2009 From: dorseye at gmail.com (Eric Dorsey) Date: Wed, 21 Jan 2009 18:38:33 -0700 Subject: [Tutor] Volunteer Opportunities? Message-ID: -- eric dorsey | www.perfecteyedesign.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From dorseye at gmail.com Thu Jan 22 03:07:48 2009 From: dorseye at gmail.com (Eric Dorsey) Date: Wed, 21 Jan 2009 19:07:48 -0700 Subject: [Tutor] Volunteer opportunities Message-ID: (My apologies if a blank message comes up first with this heading -- The first time I meant to type this I managed to tab accidently to Send and hit it before even filling out the message.. :/ ) Does anyone know of any good volunteer opportunities for projects that learning Python coders can work on? Or possibly nonprofits or the like that need smaller-type applications worked on? Much thanks! -- eric dorsey | www.perfecteyedesign.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Thu Jan 22 04:53:29 2009 From: bgailer at gmail.com (bob gailer) Date: Wed, 21 Jan 2009 22:53:29 -0500 Subject: [Tutor] Volunteer opportunities In-Reply-To: References: Message-ID: <4977EDB9.8030306@gmail.com> Eric Dorsey wrote: > > Does anyone know of any good volunteer opportunities for projects that > learning Python coders can work on? Or possibly nonprofits or the like > that need smaller-type applications worked on? I have an open source project that could use some help. See http://en.wikipedia.org/wiki/Python_Pipelines for a brief description. Let me know if you want to know more. -- Bob Gailer Chapel Hill NC 919-636-4239 From wormwood_3 at yahoo.com Thu Jan 22 04:54:23 2009 From: wormwood_3 at yahoo.com (wormwood_3) Date: Wed, 21 Jan 2009 19:54:23 -0800 (PST) Subject: [Tutor] dict() versus {} Message-ID: <411938.23613.qm@web110813.mail.gq1.yahoo.com> When creating a list of dictionaries through a loop, I ran into a strange issue. I'll let the code talk: >>> l = 'i am a special new list'.split() >>> t = [] >>> for thing in l: ... t.append({thing: 1}) ... >>> t [{'i': 1}, {'am': 1}, {'a': 1}, {'special': 1}, {'new': 1}, {'list': 1}] This is what I expected. {} says to make a dictionary. Thing, not being quoted, is clearing a variable, which needs to be evaluated and used as the key. >>> t = [] >>> for thing in l: ... t.append(dict(thing=1)) ... >>> t [{'thing': 1}, {'thing': 1}, {'thing': 1}, {'thing': 1}, {'thing': 1}, {'thing': 1}] This was what threw me. Why would the dict() function not evaluate thing? How can it take it as a literal string without quotes? Thanks for any insight, Sam _______________________ Samuel Huckins Homepage - http://samuelhuckins.com Tech blog - http://dancingpenguinsoflight.com/ Photos - http://www.flickr.com/photos/samuelhuckins/ AIM - samushack | Gtalk - samushack | Skype - shuckins -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Thu Jan 22 05:02:35 2009 From: bgailer at gmail.com (bob gailer) Date: Wed, 21 Jan 2009 23:02:35 -0500 Subject: [Tutor] dict() versus {} In-Reply-To: <411938.23613.qm@web110813.mail.gq1.yahoo.com> References: <411938.23613.qm@web110813.mail.gq1.yahoo.com> Message-ID: <4977EFDB.6070405@gmail.com> An HTML attachment was scrubbed... URL: From wormwood_3 at yahoo.com Thu Jan 22 05:14:23 2009 From: wormwood_3 at yahoo.com (wormwood_3) Date: Wed, 21 Jan 2009 20:14:23 -0800 (PST) Subject: [Tutor] dict() versus {} References: <411938.23613.qm@web110813.mail.gq1.yahoo.com> <4977EFDB.6070405@gmail.com> Message-ID: <677806.43227.qm@web110802.mail.gq1.yahoo.com> Hmm, looked through the latest docs, in the sections on dictionary types, don't see examples that point to this case well. Can you link to what you had in mind? _______________________ Samuel Huckins Homepage - http://samuelhuckins.com Tech blog - http://dancingpenguinsoflight.com/ Photos - http://www.flickr.com/photos/samuelhuckins/ AIM - samushack | Gtalk - samushack | Skype - shuckins ________________________________ From: bob gailer To: wormwood_3 Cc: Python Tutorlist Sent: Wednesday, January 21, 2009 11:02:35 PM Subject: Re: [Tutor] dict() versus {} wormwood_3 wrote: When creating a list of dictionaries through a loop, I ran into a strange issue. I'll let the code talk: >>> l = 'i am a special new list'.split() >>> t = [] >>> for thing in l: ... t.append({thing: 1}) ... >>> t [{'i': 1}, {'am': 1}, {'a': 1}, {'special': 1}, {'new': 1}, {'list': 1}] This is what I expected. {} says to make a dictionary. Thing, not being quoted, is clearing a variable, which needs to be evaluated and used as the key. >>> t = [] >>> for thing in l: ... t.append(dict(thing=1)) ... >>> t [{'thing': 1}, {'thing': 1}, {'thing': 1}, {'thing': 1}, {'thing': 1}, {'thing': 1}] This was what threw me. Why would the dict() function not evaluate thing? How can it take it as a literal string without quotes? I suggest you look dict up in the Python documentation. There it shows the result you got as an example. When in doubt read the manual. -- Bob Gailer Chapel Hill NC 919-636-4239 -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Thu Jan 22 05:25:12 2009 From: bgailer at gmail.com (bob gailer) Date: Wed, 21 Jan 2009 23:25:12 -0500 Subject: [Tutor] dict() versus {} In-Reply-To: <677806.43227.qm@web110802.mail.gq1.yahoo.com> References: <411938.23613.qm@web110813.mail.gq1.yahoo.com> <4977EFDB.6070405@gmail.com> <677806.43227.qm@web110802.mail.gq1.yahoo.com> Message-ID: <4977F528.2050907@gmail.com> An HTML attachment was scrubbed... URL: From bgailer at gmail.com Thu Jan 22 05:31:23 2009 From: bgailer at gmail.com (bob gailer) Date: Wed, 21 Jan 2009 23:31:23 -0500 Subject: [Tutor] Volunteer opportunities In-Reply-To: <1232597996.6121.19.camel@ltop> References: <4977EDB9.8030306@gmail.com> <1232597996.6121.19.camel@ltop> Message-ID: <4977F69B.60408@gmail.com> An HTML attachment was scrubbed... URL: From wormwood_3 at yahoo.com Thu Jan 22 05:39:07 2009 From: wormwood_3 at yahoo.com (wormwood_3) Date: Wed, 21 Jan 2009 20:39:07 -0800 (PST) Subject: [Tutor] dict() versus {} References: <411938.23613.qm@web110813.mail.gq1.yahoo.com> <4977EFDB.6070405@gmail.com> <677806.43227.qm@web110802.mail.gq1.yahoo.com> <4977F528.2050907@gmail.com> Message-ID: <454349.94041.qm@web110811.mail.gq1.yahoo.com> dict( [arg]) Return a new dictionary initialized from an optional positional argument or from a set of keyword arguments. If no arguments are given, return a new empty dictionary. If the positional argument arg is a mapping object, return a dictionary mapping the same keys to the same values as does the mapping object. But why doesn't the optional positional argument arg in this case, not being a mapping type, get evaluated?: dict(thing=1) And even if it makes sense for it not to be evaluated, wouldn't it be better for dict() to complain that it didn't get a string or an int as it expects for a keyword argument? Maybe I am missing the use case, so far it just seems strange to force the keyword to a string. -Sam ________________________________ From: bob gailer To: wormwood_3 Cc: Python Tutorlist Sent: Wednesday, January 21, 2009 11:25:12 PM Subject: Re: [Tutor] dict() versus {} wormwood_3 wrote: Hmm, looked through the latest docs, in the sections on dictionary types, don't see examples that point to this case well. Can you link to what you had in mind? 2.1 Built-in Functions ... dict( [mapping-or-sequence]) ... these all return a dictionary equal to {"one": 2, "two": 3}: ... dict(one=2, two=3) ________________________________ From: bob gailer To: wormwood_3 Cc: Python Tutorlist Sent: Wednesday, January 21, 2009 11:02:35 PM Subject: Re: [Tutor] dict() versus {} wormwood_3 wrote: When creating a list of dictionaries through a loop, I ran into a strange issue. I'll let the code talk: >>> l = 'i am a special new list'.split() >>> t = [] >>> for thing in l: ... t.append({thing: 1}) ... >>> t [{'i': 1}, {'am': 1}, {'a': 1}, {'special': 1}, {'new': 1}, {'list': 1}] This is what I expected. {} says to make a dictionary. Thing, not being quoted, is clearing a variable, which needs to be evaluated and used as the key. >>> t = [] >>> for thing in l: ... t.append(dict(thing=1)) ... >>> t [{'thing': 1}, {'thing': 1}, {'thing': 1}, {'thing': 1}, {'thing': 1}, {'thing': 1}] This was what threw me. Why would the dict() function not evaluate thing? How can it take it as a literal string without quotes? I suggest you look dict up in the Python documentation. There it shows the result you got as an example. When in doubt read the manual. -- Bob Gailer Chapel Hill NC 919-636-4239 ________________________________ _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor -- Bob Gailer Chapel Hill NC 919-636-4239 -------------- next part -------------- An HTML attachment was scrubbed... URL: From jadrifter at gmail.com Thu Jan 22 06:05:11 2009 From: jadrifter at gmail.com (jadrifter) Date: Wed, 21 Jan 2009 21:05:11 -0800 Subject: [Tutor] Volunteer opportunities In-Reply-To: <4977F69B.60408@gmail.com> References: <4977EDB9.8030306@gmail.com> <1232597996.6121.19.camel@ltop> <4977F69B.60408@gmail.com> Message-ID: <1232600711.6121.26.camel@ltop> On Wed, 2009-01-21 at 23:31 -0500, bob gailer wrote: > Depends on your knowledge of Python and (if any) CMS Pipelines. > > Testing > Design critique (devil's advocate) > Cleaning up and fine-tuning the parser > Coding built-in stages > Documentation > Financial support > > Let me know what sparks your interest. And say a bit about your > background and why this interests you. > > -- > Bob Gailer > Chapel Hill NC > 919-636-4239 Bob, Honestly the first thing that caught my eye was that you were in Chapel Hill. I grew up in Durham NC. I'm in Tacoma WA now. I'm a disabled vet who got into computers and programming from an accounting career. Most of what I've done has been database oriented. I started playing with Python a few years ago and just enjoy the language and would like to find some practical application to use it with. I'm more of a consumer than producer on the tutor list. I read a lot, mostly technical stuff, but nothing that complex. I took a peek at the 889 manual for Pipelines from the wiki page you linked to. It seems to assume a LOT of knowledge I don't have so I'm not sure I'm suitable at all for the project. John Purser From metolone+gmane at gmail.com Thu Jan 22 07:01:08 2009 From: metolone+gmane at gmail.com (Mark Tolonen) Date: Wed, 21 Jan 2009 22:01:08 -0800 Subject: [Tutor] dict() versus {} References: <411938.23613.qm@web110813.mail.gq1.yahoo.com><4977EFDB.6070405@gmail.com><677806.43227.qm@web110802.mail.gq1.yahoo.com><4977F528.2050907@gmail.com> <454349.94041.qm@web110811.mail.gq1.yahoo.com> Message-ID: This: >>> dict(one=1,two=2,three=3) {'three': 3, 'two': 2, 'one': 1} Is a shortcut for the longer: >>> dict((('one',1),('two',2),('three',3))) {'three': 3, 'two': 2, 'one': 1} and given how this works: >>> def function(**kwargs): ... print kwargs ... >>> function(one=1,two=2,three=3) {'three': 3, 'two': 2, 'one': 1} One can guess how the shortcut is implemented. -Mark "wormwood_3" wrote in message news:454349.94041.qm at web110811.mail.gq1.yahoo.com... dict( [arg]) Return a new dictionary initialized from an optional positional argument or from a set of keyword arguments. If no arguments are given, return a new empty dictionary. If the positional argument arg is a mapping object, return a dictionary mapping the same keys to the same values as does the mapping object. But why doesn't the optional positional argument arg in this case, not being a mapping type, get evaluated?: dict(thing=1) And even if it makes sense for it not to be evaluated, wouldn't it be better for dict() to complain that it didn't get a string or an int as it expects for a keyword argument? Maybe I am missing the use case, so far it just seems strange to force the keyword to a string. -Sam ------------------------------------------------------------------------------ From: bob gailer To: wormwood_3 Cc: Python Tutorlist Sent: Wednesday, January 21, 2009 11:25:12 PM Subject: Re: [Tutor] dict() versus {} wormwood_3 wrote: Hmm, looked through the latest docs, in the sections on dictionary types, don't see examples that point to this case well. Can you link to what you had in mind? 2.1 Built-in Functions ... dict( [mapping-or-sequence]) ... these all return a dictionary equal to {"one": 2, "two": 3}: ... dict(one=2, two=3) ---------------------------------------------------------------------------- From: bob gailer To: wormwood_3 Cc: Python Tutorlist Sent: Wednesday, January 21, 2009 11:02:35 PM Subject: Re: [Tutor] dict() versus {} wormwood_3 wrote: When creating a list of dictionaries through a loop, I ran into a strange issue. I'll let the code talk: >>> l = 'i am a special new list'.split() >>> t = [] >>> for thing in l: ... t.append({thing: 1}) ... >>> t [{'i': 1}, {'am': 1}, {'a': 1}, {'special': 1}, {'new': 1}, {'list': 1}] This is what I expected. {} says to make a dictionary. Thing, not being quoted, is clearing a variable, which needs to be evaluated and used as the key. >>> t = [] >>> for thing in l: ... t.append(dict(thing=1)) ... >>> t [{'thing': 1}, {'thing': 1}, {'thing': 1}, {'thing': 1}, {'thing': 1}, {'thing': 1}] This was what threw me. Why would the dict() function not evaluate thing? How can it take it as a literal string without quotes? I suggest you look dict up in the Python documentation. There it shows the result you got as an example. When in doubt read the manual. -- Bob Gailer Chapel Hill NC 919-636-4239 ---------------------------------------------------------------------------- _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor -- Bob Gailer Chapel Hill NC 919-636-4239 ------------------------------------------------------------------------------ _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From norman at khine.net Thu Jan 22 10:18:21 2009 From: norman at khine.net (Norman Khine) Date: Thu, 22 Jan 2009 10:18:21 +0100 Subject: [Tutor] profiling python code Message-ID: <497839DD.6060604@khine.net> Hello, I have this output when running the profile on one of my modules: 9815/9644 0.009 0.000 0.009 0.000 {len} 6 0.000 0.000 0.000 0.000 {locals} 5 0.000 0.000 0.001 0.000 {map} 1 0.000 0.000 0.000 0.000 {math.exp} 3 0.000 0.000 0.000 0.000 {math.log} 1 0.000 0.000 0.000 0.000 {math.sqrt} 97 0.000 0.000 0.000 0.000 {max} 9 0.001 0.000 0.001 0.000 {method '__reduce_ex__' of 'object' objects} 7539 0.009 0.000 0.009 0.000 {method 'append' of 'list' objects} The 9815/9644 0.009 0.000 0.009 0.000 {len} line does it mean that the module is making 9815 requests to the len function? Also the line 7539 0.009 0.000 0.009 0.000 {method 'append' of 'list' objects} it looks high!?! How should I interpret this? Cheers Norman From kent37 at tds.net Thu Jan 22 12:33:27 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 22 Jan 2009 06:33:27 -0500 Subject: [Tutor] dict() versus {} In-Reply-To: <411938.23613.qm@web110813.mail.gq1.yahoo.com> References: <411938.23613.qm@web110813.mail.gq1.yahoo.com> Message-ID: <1c2a2c590901220333r7a77f6ecude827cca2ea9d257@mail.gmail.com> On Wed, Jan 21, 2009 at 10:54 PM, wormwood_3 wrote: > When creating a list of dictionaries through a loop, I ran into a strange > issue. I'll let the code talk: >>>> t = [] >>>> for thing in l: > ... t.append(dict(thing=1)) > ... >>>> t > [{'thing': 1}, {'thing': 1}, {'thing': 1}, {'thing': 1}, {'thing': 1}, > {'thing': 1}] > > This was what threw me. Why would the dict() function not evaluate thing? > How can it take it as a literal string without quotes? The call dict(thing=1) is using the standard keyword parameter syntax, and it handles the keywords the same as any other function call - the keywords are tokens, not variable names or expressions, and they are not evaluated. The current behaviour is consistent with other uses of keyword arguments. Use your first method if you want to evaluate the key. Kent From kent37 at tds.net Thu Jan 22 12:41:48 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 22 Jan 2009 06:41:48 -0500 Subject: [Tutor] profiling python code In-Reply-To: <497839DD.6060604@khine.net> References: <497839DD.6060604@khine.net> Message-ID: <1c2a2c590901220341i2845f16eq8c11b8825b9b3246@mail.gmail.com> On Thu, Jan 22, 2009 at 4:18 AM, Norman Khine wrote: > Hello, > > I have this output when running the profile on one of my modules: > It's a bit easier to intepret with the headers: ncalls tottime percall cumtime percall filename:lineno(function) > 9815/9644 0.009 0.000 0.009 0.000 {len} > 6 0.000 0.000 0.000 0.000 {locals} > 5 0.000 0.000 0.001 0.000 {map} > 1 0.000 0.000 0.000 0.000 {math.exp} > 3 0.000 0.000 0.000 0.000 {math.log} > 1 0.000 0.000 0.000 0.000 {math.sqrt} > 97 0.000 0.000 0.000 0.000 {max} > 9 0.001 0.000 0.001 0.000 {method '__reduce_ex__' of > 'object' objects} > 7539 0.009 0.000 0.009 0.000 {method 'append' of 'list' > objects} > > > The > 9815/9644 0.009 0.000 0.009 0.000 {len} > > line does it mean that the module is making 9815 requests to the len > function? Yes. > Also the line > > 7539 0.009 0.000 0.009 0.000 {method 'append' of 'list' objects} > > it looks high!?! That depends on what the code is doing. > How should I interpret this? That your code is spending most of its time in len() and list.append(). The cumtime column is the most useful for figuring out where the time goes. If ncalls is higher than expected then it might be worth figuring out why. Is this an exercise to understand the profiler or real code you are trying to speed up? Showing the code might help. Kent From amit.pureenergy at gmail.com Thu Jan 22 18:08:28 2009 From: amit.pureenergy at gmail.com (amit sethi) Date: Thu, 22 Jan 2009 22:38:28 +0530 Subject: [Tutor] fetching wikipedia articles Message-ID: hi , I need help as to how i can fetch a wikipedia article i tried changing my user agent but it did not work . Although as far as my knowledge of robots.txt goes , looking at en.wikipedia.org/robots.txt it does not seem it should block a useragent (*, which is what i would normally use) from accesing a simple article like say " http://en.wikipedia.org/wiki/Sachin_Tendulkar" but still robotparser returns false status=rp.can_fetch("*", "http://en.wikipedia.org/wiki/Sachin_Tendulkar") where rp is a robot parser object . why is that? -- A-M-I-T S|S -------------- next part -------------- An HTML attachment was scrubbed... URL: From andreengels at gmail.com Thu Jan 22 18:15:09 2009 From: andreengels at gmail.com (Andre Engels) Date: Thu, 22 Jan 2009 18:15:09 +0100 Subject: [Tutor] fetching wikipedia articles In-Reply-To: <6faf39c90901220913h585ce27bue36a111e0c34e6f6@mail.gmail.com> References: <6faf39c90901220913h585ce27bue36a111e0c34e6f6@mail.gmail.com> Message-ID: <6faf39c90901220915i67696c3iff28afc15ed85f92@mail.gmail.com> On Thu, Jan 22, 2009 at 6:08 PM, amit sethi wrote: > hi , I need help as to how i can fetch a wikipedia article i tried changing > my user agent but it did not work . Although as far as my knowledge of > robots.txt goes , looking at en.wikipedia.org/robots.txt it does not seem it > should block a useragent (*, which is what i would normally use) from > accesing a simple article like say > "http://en.wikipedia.org/wiki/Sachin_Tendulkar" but still robotparser > returns false > status=rp.can_fetch("*", "http://en.wikipedia.org/wiki/Sachin_Tendulkar") > where rp is a robot parser object . why is that? Yes, Wikipedia is blocking the Python default user agent. This was done to block the main internal bot in its early days (it was misbehaving by getting each page twice); when it got to allowing the bot again, it had already changed to having its own user agent string, and apparently it was not deemed necessary to unblock the user string... -- Andr? Engels, andreengels at gmail.com From juryef at yahoo.com Thu Jan 22 20:33:20 2009 From: juryef at yahoo.com (Judith Flores) Date: Thu, 22 Jan 2009 11:33:20 -0800 (PST) Subject: [Tutor] Writing long strings (that include commas) to a csv file Message-ID: <745293.44861.qm@web34706.mail.mud.yahoo.com> Hello dear Python experts, How can I write a complete string (which sometimes will include many commas) to a cell in a CSV file? With the code below, what I obtain is a cell per letter of every string: file1=open('myfile.csv','w') writer=csv.writer(file1) mylist=[ " first , txt+words , more" , " second, text + words, and more"] listnumbers=["0","5"] for i in range(0,len(mylist)): writer.writerow(mylist[i] + listnumbers[i]) file1.close() So the first element of mylist should fill up only one cell in the csv file, and the same for the second elemente, and so on. Any help would be very much appreciated. Thank you! Judith From magoldfish at gmail.com Thu Jan 22 21:04:45 2009 From: magoldfish at gmail.com (Marcus Goldfish) Date: Thu, 22 Jan 2009 15:04:45 -0500 Subject: [Tutor] class design - base classes with optional properties? Message-ID: <5e183f3d0901221204wadbdfb6gcdb47da20bf7b5fd@mail.gmail.com> I'm trying to design a base class for a hierarchy. The properties I want to specify for the base class depend on the values of other properties of the base class. For instance, in this toy example of a base FoodProcessor class: class FoodProcessor: "Model for a kitchen appliance food processor" speed_settings # example [1, 2, 3, 4] blade_settings # example ["slice", "grate", "grind"] slice_thickness # example ["thin", "thick"], but only if blade_setting is "slice" it only make sense to have the slice_thickness property set when blade_settings = "slice"; otherwise, it would be preferable to only define the speed_settings and blade_settings properties. For example: class ProcessorA(FoodProcessor): "A slicing-only processor" speed_settings = [1, 2, 3, 4] blade_settings = "slice" slice_thickness = ["thin", "thick"] class ProcessorB(FoodProcessor): "A non-slicing processor" speed_settings = [1,2,3,4] blade_settings = ["grate", "grind"] slice_thickness = None Can anyone suggest some work-arounds, or refactoring for this type of design? Is there a design pattern for this? Thanks! Marcus -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Thu Jan 22 21:36:49 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 22 Jan 2009 15:36:49 -0500 Subject: [Tutor] Writing long strings (that include commas) to a csv file In-Reply-To: <745293.44861.qm@web34706.mail.mud.yahoo.com> References: <745293.44861.qm@web34706.mail.mud.yahoo.com> Message-ID: <1c2a2c590901221236g450ab89atee7a46c574a01cc7@mail.gmail.com> On Thu, Jan 22, 2009 at 2:33 PM, Judith Flores wrote: > Hello dear Python experts, > > How can I write a complete string (which sometimes will include many commas) to a cell in a CSV file? With the code below, what I obtain is a cell per letter of every string: > > > file1=open('myfile.csv','w') > writer=csv.writer(file1) > > mylist=[ " first , txt+words , more" , " second, text + words, and more"] > listnumbers=["0","5"] > > for i in range(0,len(mylist)): > > writer.writerow(mylist[i] + listnumbers[i]) The argument passed to writerow() is a sequence where each element of the sequence is one cell value. Here, you are passing a string as the argument. A string is a sequence of characters, so you are telling writerow() to write one character per cell. What you want to give writerow() is a list containing the two strings that you want placed in the two cells. Like this: writer.writerow([mylist[i], listnumbers[i]]) You could also use the zip() function and writerows() to do this more simply. zip(mylist, listnumbers) returns a list of pairs: In [3]: zip(mylist, listnumbers) Out[3]: [(' first , txt+words , more', '0'), (' second, text + words, and more', '5')] This is exactly the rows you want to write to the file, so writer.writerows(zip(mylist, listnumbers)) will do what you want without an explicit loop. Kent From kent37 at tds.net Thu Jan 22 21:41:08 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 22 Jan 2009 15:41:08 -0500 Subject: [Tutor] class design - base classes with optional properties? In-Reply-To: <5e183f3d0901221204wadbdfb6gcdb47da20bf7b5fd@mail.gmail.com> References: <5e183f3d0901221204wadbdfb6gcdb47da20bf7b5fd@mail.gmail.com> Message-ID: <1c2a2c590901221241r5c52b669o5422fba5c1a2e9c8@mail.gmail.com> On Thu, Jan 22, 2009 at 3:04 PM, Marcus Goldfish wrote: > I'm trying to design a base class for a hierarchy. The properties I want to > specify for the base class depend on the values of other properties of the > base class. For instance, in this toy example of a base FoodProcessor > class: > class FoodProcessor: > "Model for a kitchen appliance food processor" > speed_settings # example [1, 2, 3, 4] > blade_settings # example ["slice", "grate", "grind"] > slice_thickness # example ["thin", "thick"], but only if > blade_setting is "slice" > it only make sense to have the slice_thickness property set when > blade_settings = "slice"; otherwise, it would be preferable to only define > the speed_settings and blade_settings properties. For example: > class ProcessorA(FoodProcessor): > "A slicing-only processor" > speed_settings = [1, 2, 3, 4] > blade_settings = "slice" > slice_thickness = ["thin", "thick"] > class ProcessorB(FoodProcessor): > "A non-slicing processor" > speed_settings = [1,2,3,4] > blade_settings = ["grate", "grind"] > slice_thickness = None > Can anyone suggest some work-arounds, or refactoring for this type of > design? Is there a design pattern for this? I'm not sure what the problem is. You can provide default values in the base class: class FoodProcessor(object): speed_settings = None blade_settings = None slice_thickness = None Then in a derived class you can override just the ones you want to use: class ProcessorB(FoodProcessor): "A non-slicing processor" speed_settings = [1,2,3,4] blade_settings = ["grate", "grind"] If you want to validate that the current settings make sense, you could put a test in the __init__() method, which is simple to implement but happens at instance creation time, or you could write a metaclass to validate the settings at class creation time, which is more difficult (to understand, anyway). Kent From denis.spir at free.fr Thu Jan 22 22:51:04 2009 From: denis.spir at free.fr (spir) Date: Thu, 22 Jan 2009 22:51:04 +0100 Subject: [Tutor] class arguments? Message-ID: <20090122225104.03c677f4@o> Hello, is there a way to give arguments to a class definition? Eg class MonoList(list, typ, number): item_type = typ item_number = number [I guess you understand what I try to do...] denis ------ la vida e estranya From alan.gauld at btinternet.com Thu Jan 22 23:01:39 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 22 Jan 2009 22:01:39 -0000 Subject: [Tutor] class arguments? References: <20090122225104.03c677f4@o> Message-ID: "spir" wrote > is there a way to give arguments to a class definition? Eg > > class MonoList(list, typ, number): > item_type = typ > item_number = number Yes thats what the __init__ method is for. class MonoList: def __init__(self, lst, typ, num): self.item_type = typ self.number = num etc... myList = MonoList([1,2,3], int, 3) # or whatever... HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Thu Jan 22 23:18:54 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 22 Jan 2009 17:18:54 -0500 Subject: [Tutor] class arguments? In-Reply-To: <20090122225104.03c677f4@o> References: <20090122225104.03c677f4@o> Message-ID: <1c2a2c590901221418h418f5030ua2ae253be3e6099e@mail.gmail.com> On Thu, Jan 22, 2009 at 4:51 PM, spir wrote: > Hello, > > is there a way to give arguments to a class definition? Eg > > class MonoList(list, typ, number): > item_type = typ > item_number = number Use the type() function (which is the constructor for the type 'type') to dynamically create classes (i.e. types), e.g. In [1]: typ = int In [2]: number = 3 In [3]: MonoList = type("MonoList", (list,), dict(item_type=typ, item_number=number)) In [4]: ml = MonoList() In [5]: ml.item_type Out[5]: In [6]: ml.item_number Out[6]: 3 In [7]: isinstance(ml, list) Out[7]: True http://docs.python.org/library/functions.html#type Kent From kent37 at tds.net Thu Jan 22 23:47:46 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 22 Jan 2009 17:47:46 -0500 Subject: [Tutor] class arguments? In-Reply-To: <1c2a2c590901221418h418f5030ua2ae253be3e6099e@mail.gmail.com> References: <20090122225104.03c677f4@o> <1c2a2c590901221418h418f5030ua2ae253be3e6099e@mail.gmail.com> Message-ID: <1c2a2c590901221447s78b5588fw534fcbb20b8757d3@mail.gmail.com> On Thu, Jan 22, 2009 at 5:18 PM, Kent Johnson wrote: > On Thu, Jan 22, 2009 at 4:51 PM, spir wrote: >> Hello, >> >> is there a way to give arguments to a class definition? Eg >> >> class MonoList(list, typ, number): >> item_type = typ >> item_number = number > > Use the type() function (which is the constructor for the type 'type') > to dynamically create classes (i.e. types), e.g. > > In [1]: typ = int > > In [2]: number = 3 > > In [3]: MonoList = type("MonoList", (list,), dict(item_type=typ, > item_number=number)) > > In [4]: ml = MonoList() > > In [5]: ml.item_type > Out[5]: > > In [6]: ml.item_number > Out[6]: 3 > > In [7]: isinstance(ml, list) > Out[7]: True And to show that these are class attributes: In [4]: MonoList.item_number Out[4]: 3 In [5]: MonoList.item_type Out[5]: Kent From alan.gauld at btinternet.com Fri Jan 23 00:24:22 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 22 Jan 2009 23:24:22 -0000 Subject: [Tutor] class design - base classes with optional properties? References: <5e183f3d0901221204wadbdfb6gcdb47da20bf7b5fd@mail.gmail.com> Message-ID: "Marcus Goldfish" wrote > I'm trying to design a base class for a hierarchy. The properties I > want to > specify for the base class depend on the values of other properties > of the > base class. Don't worry so much about the properties, the important thing to focus on in your base classes is the behaviour. What exactly will these classes do? What methods will they have? How will they be overridden in your subclasses. Ideally the properties are invisible to the users of the class so the interactions of the properties should all be controlled by the methods. > class FoodProcessor: > "Model for a kitchen appliance food processor" > speed_settings # example [1, 2, 3, 4] > blade_settings # example ["slice", "grate", "grind"] > slice_thickness # example ["thin", "thick"], but only if > blade_setting is "slice" > > it only make sense to have the slice_thickness property set when > blade_settings = "slice"; otherwise, it would be preferable to only > define > the speed_settings and blade_settings properties. For example: So create a method to initialise slicing which sets both properties (with appropriate default values if you like) Similarly define methods for grating and grinding. Think about what you want to *do* with a class not what you want to store. The function should dictate the attributes. > class ProcessorA(FoodProcessor): > "A slicing-only processor" > speed_settings = [1, 2, 3, 4] > blade_settings = "slice" > slice_thickness = ["thin", "thick"] > > class ProcessorB(FoodProcessor): > "A non-slicing processor" > speed_settings = [1,2,3,4] > blade_settings = ["grate", "grind"] > slice_thickness = None Unless this is a multi function food processor I'd probably go for a heirarchy of FoodProcessor Slicer Grater Grinder In fact I might do that anyway and then create MultiFunction as a subclass of of all 3 food processors... class MultiFunction(Slicer, Grater, Grinder): etc... Remember that ideally nothing outside the class should be manipulating the attributes directly, everything should be done by sending messages (ie calling methods) to the objects. The fact that you want a heirarchy suggests that you have some form of polymorphic operations to be performed? What are those operations at the abstract FoodProcessor level? It is actually very common that the root object in a heirarchy has very few if any attributes but will have all the methods needed for the concept to work. As you subclass you add attributes to support the subclass specific implementation of the methods. If you truly want a multi purpose mixer and don't want to subclass from all 3 types then you could have a changeBlade method that specifies the blade type and any additional attributes. The Blades could even be a class heirarchy in their own right: Blade Slicer Grinder Grater # create a new processor with initially a slicer blade p = FoodProcessor(Slicer(thickness)) p..process(spam) p.changeBlade(Grater(granularity)) p.process(Cheese(5, 'oz')) # uses a Cheese object with weight in ounces... and so on... But the only real solution will depend on what you intend to do with your classes. Think about how you want to write the client code. Think about doing that using method calls rather than manipulating the inner data. That way you can leverage polymorphism to your advantage. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Fri Jan 23 00:29:59 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 22 Jan 2009 23:29:59 -0000 Subject: [Tutor] class arguments? References: <20090122225104.03c677f4@o> Message-ID: "Alan Gauld" wrote >> is there a way to give arguments to a class definition? I see that Kent interpreted your question differently to me. If you do mean that you want to dynamically define class attributes rather than instance attributes then __init__() won't work. But I'd be interested to understand why and how you would want to do that? And in particular how you would use them after creating them? > Yes thats what the __init__ method is for. > > class MonoList: > def __init__(self, lst, typ, num): > self.item_type = typ > self.number = num > etc... > > myList = MonoList([1,2,3], int, 3) # or whatever... Alan G. From kent37 at tds.net Fri Jan 23 01:05:44 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 22 Jan 2009 19:05:44 -0500 Subject: [Tutor] class design - base classes with optional properties? In-Reply-To: References: <5e183f3d0901221204wadbdfb6gcdb47da20bf7b5fd@mail.gmail.com> Message-ID: <1c2a2c590901221605l77ac5f28id6883d75d0d607b2@mail.gmail.com> On Thu, Jan 22, 2009 at 6:24 PM, Alan Gauld wrote: > "Marcus Goldfish" wrote > >> I'm trying to design a base class for a hierarchy. The properties I want >> to >> specify for the base class depend on the values of other properties of the >> base class. > > Don't worry so much about the properties, the important thing to focus on > in your base classes is the behaviour. What exactly will these classes do? > What methods will they have? How will they be overridden in your > subclasses. > > Ideally the properties are invisible to the users of the class so the > interactions of the properties should all be controlled by the > methods. Class attributes can be a useful way to configure behaviour of subclasses. For example an HTML rendering widget might have attributes giving the type of tag to use to render or other HTML attributes. The Django HTML widgets are an example of this: http://code.djangoproject.com/browser/django/trunk/django/forms/widgets.py Look at the Input class and subclasses. Kent From sierra_mtnview at sbcglobal.net Fri Jan 23 01:44:36 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Thu, 22 Jan 2009 16:44:36 -0800 Subject: [Tutor] Available filetypes for AskSaveasfilenam in Tkinter? Message-ID: <497912F4.3020803@sbcglobal.net> An HTML attachment was scrubbed... URL: From john at fouhy.net Fri Jan 23 01:52:44 2009 From: john at fouhy.net (John Fouhy) Date: Fri, 23 Jan 2009 13:52:44 +1300 Subject: [Tutor] Available filetypes for AskSaveasfilenam in Tkinter? In-Reply-To: <497912F4.3020803@sbcglobal.net> References: <497912F4.3020803@sbcglobal.net> Message-ID: <5e58f2e40901221652j1dbfefedtadb916ee2a37b5ec@mail.gmail.com> 2009/1/23 Wayne Watson : > How do I know what file types are available for asksaveasfilename? Suppose > one isn't available, for example, FITS. How do I get it? You pass the file types as an argument to the function. tkFileDialog.asksaveasfilename(filetypes=[('Text', '*.txt'), ('Stuff', '*.stf'), ('Et cetera', '*.etc')]) http://www.pythonware.com/library/tkinter/introduction/x1164-data-entry.htm -- John. From sierra_mtnview at sbcglobal.net Fri Jan 23 02:41:10 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Thu, 22 Jan 2009 17:41:10 -0800 Subject: [Tutor] Available filetypes for AskSaveasfilenam in Tkinter? In-Reply-To: <5e58f2e40901221652j1dbfefedtadb916ee2a37b5ec@mail.gmail.com> References: <497912F4.3020803@sbcglobal.net> <5e58f2e40901221652j1dbfefedtadb916ee2a37b5ec@mail.gmail.com> Message-ID: <49792036.9090709@sbcglobal.net> An HTML attachment was scrubbed... URL: From john at fouhy.net Fri Jan 23 02:53:29 2009 From: john at fouhy.net (John Fouhy) Date: Fri, 23 Jan 2009 14:53:29 +1300 Subject: [Tutor] Available filetypes for AskSaveasfilenam in Tkinter? In-Reply-To: <49792036.9090709@sbcglobal.net> References: <497912F4.3020803@sbcglobal.net> <5e58f2e40901221652j1dbfefedtadb916ee2a37b5ec@mail.gmail.com> <49792036.9090709@sbcglobal.net> Message-ID: <5e58f2e40901221753q2b90b78n9d780e3de43f2f34@mail.gmail.com> 2009/1/23 Wayne Watson : > And if I pass it, 'pcx', 'fits', 'dog', 'cat', ...? I don't understand your question. You can certainly do this: tkFileDialog.asksaveasfilename(filetypes=[('PCX files', '*.pcx'), ('FITS files', '*.fits'), ('Dogs', '*.dog')]) If that's not what you want, you need to explain yourself better.. -- John. From sierra_mtnview at sbcglobal.net Fri Jan 23 03:29:29 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Thu, 22 Jan 2009 18:29:29 -0800 Subject: [Tutor] Available filetypes for AskSaveasfilenam in Tkinter? In-Reply-To: <5e58f2e40901221753q2b90b78n9d780e3de43f2f34@mail.gmail.com> References: <497912F4.3020803@sbcglobal.net> <5e58f2e40901221652j1dbfefedtadb916ee2a37b5ec@mail.gmail.com> <49792036.9090709@sbcglobal.net> <5e58f2e40901221753q2b90b78n9d780e3de43f2f34@mail.gmail.com> Message-ID: <49792B89.5080807@sbcglobal.net> An HTML attachment was scrubbed... URL: From john at fouhy.net Fri Jan 23 03:34:56 2009 From: john at fouhy.net (John Fouhy) Date: Fri, 23 Jan 2009 15:34:56 +1300 Subject: [Tutor] Available filetypes for AskSaveasfilenam in Tkinter? In-Reply-To: <49792B89.5080807@sbcglobal.net> References: <497912F4.3020803@sbcglobal.net> <5e58f2e40901221652j1dbfefedtadb916ee2a37b5ec@mail.gmail.com> <49792036.9090709@sbcglobal.net> <5e58f2e40901221753q2b90b78n9d780e3de43f2f34@mail.gmail.com> <49792B89.5080807@sbcglobal.net> Message-ID: <5e58f2e40901221834g159c7309gb72d94c48abb5948@mail.gmail.com> 2009/1/23 Wayne Watson : > What I'm getting at it is when I see something in a program as: > path = asksaveasfilename(defaultextension=".jpg", > title="Save as JPEG", > initialfile=default_path, > filetypes=IMAGE_FILE_TYPES) > > I'm guessing when the program executes this, it's really saves a file in the > jpg format. [...] All asksaveasfilename does is give you a filename/path. You then have to open the file and write the data to it. It's up to you to make sure the data is in the right format.. -- John. From sierra_mtnview at sbcglobal.net Fri Jan 23 03:48:23 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Thu, 22 Jan 2009 18:48:23 -0800 Subject: [Tutor] Available filetypes for AskSaveasfilenam in Tkinter? In-Reply-To: <5e58f2e40901221834g159c7309gb72d94c48abb5948@mail.gmail.com> References: <497912F4.3020803@sbcglobal.net> <5e58f2e40901221652j1dbfefedtadb916ee2a37b5ec@mail.gmail.com> <49792036.9090709@sbcglobal.net> <5e58f2e40901221753q2b90b78n9d780e3de43f2f34@mail.gmail.com> <49792B89.5080807@sbcglobal.net> <5e58f2e40901221834g159c7309gb72d94c48abb5948@mail.gmail.com> Message-ID: <49792FF7.7030703@sbcglobal.net> An HTML attachment was scrubbed... URL: From john at fouhy.net Fri Jan 23 04:03:23 2009 From: john at fouhy.net (John Fouhy) Date: Fri, 23 Jan 2009 16:03:23 +1300 Subject: [Tutor] Available filetypes for AskSaveasfilenam in Tkinter? In-Reply-To: <49792FF7.7030703@sbcglobal.net> References: <497912F4.3020803@sbcglobal.net> <5e58f2e40901221652j1dbfefedtadb916ee2a37b5ec@mail.gmail.com> <49792036.9090709@sbcglobal.net> <5e58f2e40901221753q2b90b78n9d780e3de43f2f34@mail.gmail.com> <49792B89.5080807@sbcglobal.net> <5e58f2e40901221834g159c7309gb72d94c48abb5948@mail.gmail.com> <49792FF7.7030703@sbcglobal.net> Message-ID: <5e58f2e40901221903y36439944wcc3802e5fe2b09e3@mail.gmail.com> 2009/1/23 Wayne Watson : > Continuing. The code that is eventually used to do the save is: > =================== > def SaveGIF(self): > if self.current_path: > default_path = splitext(basename(self.current_path))[0] + ".gif" > path = asksaveasfilename(defaultextension=".gif", > title="Save as GIF", > initialfile=default_path, > filetypes=GIF_FILE_TYPES) > else: > path = asksaveasfilename(defaultextension=".gif", > title="Save as GIF", > filetypes=GIF_FILE_TYPES): > if not path: > return > gif = self.current_image.convert("RGB") > gif.save(path) > ================== > > I would think convert makes the conversion. If so, then it must know a lot > of formats. How do I know which ones it has available? If it has a small > set, is there some way to find another "convert" that produces, say, a 'pcx" > formated file. > > Apparently, "RGB" and "GIF" mean the same thing. Seems a bit odd. Well, "RGB" stands for "Red Green Blue". I'm not much of a graphics format guy, but I think it means basically a bitmap, where each pixel has an associated tuple (red, green, blue) containing the proportion of each (on a range from 0..255). (as opposed to vector formats like EPS, or layered formats that programs like photoshop use) It is possible that the save() function inspects the file name extension and produces output appropriately. At any rate, your question seems more to do with the image library you are using, and nothing at all to do with tkFileDialog.asksaveasformat. It's probably PIL -- the Python Image Library. See the documentation here: http://www.pythonware.com/library/pil/handbook/index.htm -- John. From sierra_mtnview at sbcglobal.net Fri Jan 23 04:27:08 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Thu, 22 Jan 2009 19:27:08 -0800 Subject: [Tutor] Available filetypes for AskSaveasfilenam in Tkinter? In-Reply-To: <5e58f2e40901221903y36439944wcc3802e5fe2b09e3@mail.gmail.com> References: <497912F4.3020803@sbcglobal.net> <5e58f2e40901221652j1dbfefedtadb916ee2a37b5ec@mail.gmail.com> <49792036.9090709@sbcglobal.net> <5e58f2e40901221753q2b90b78n9d780e3de43f2f34@mail.gmail.com> <49792B89.5080807@sbcglobal.net> <5e58f2e40901221834g159c7309gb72d94c48abb5948@mail.gmail.com> <49792FF7.7030703@sbcglobal.net> <5e58f2e40901221903y36439944wcc3802e5fe2b09e3@mail.gmail.com> Message-ID: <4979390C.1020003@sbcglobal.net> An HTML attachment was scrubbed... URL: From amit.pureenergy at gmail.com Fri Jan 23 09:09:19 2009 From: amit.pureenergy at gmail.com (amit sethi) Date: Fri, 23 Jan 2009 13:39:19 +0530 Subject: [Tutor] fetching wikipedia articles In-Reply-To: <6faf39c90901220915i67696c3iff28afc15ed85f92@mail.gmail.com> References: <6faf39c90901220913h585ce27bue36a111e0c34e6f6@mail.gmail.com> <6faf39c90901220915i67696c3iff28afc15ed85f92@mail.gmail.com> Message-ID: Well that is interesting but why should that happen in case I am using a different User Agent because I tried doing status=rp.can_fetch('Mozilla/5.0', " http://en.wikipedia.org/wiki/Sachin_Tendulkar") but even that returns false Is there something wrong with the syntax , Is there a catch that i don't understand. On Thu, Jan 22, 2009 at 10:45 PM, Andre Engels wrote: > On Thu, Jan 22, 2009 at 6:08 PM, amit sethi > wrote: > > hi , I need help as to how i can fetch a wikipedia article i tried > changing > > my user agent but it did not work . Although as far as my knowledge of > > robots.txt goes , looking at en.wikipedia.org/robots.txt it does not > seem it > > should block a useragent (*, which is what i would normally use) from > > accesing a simple article like say > > "http://en.wikipedia.org/wiki/Sachin_Tendulkar" but still robotparser > > returns false > > status=rp.can_fetch("*", "http://en.wikipedia.org/wiki/Sachin_Tendulkar > ") > > where rp is a robot parser object . why is that? > > Yes, Wikipedia is blocking the Python default user agent. This was > done to block the main internal bot in its early days (it was > misbehaving by getting each page twice); when it got to allowing the > bot again, it had already changed to having its own user agent string, > and apparently it was not deemed necessary to unblock the user > string... > > > > > -- > Andr? Engels, andreengels at gmail.com > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- A-M-I-T S|S -------------- next part -------------- An HTML attachment was scrubbed... URL: From andreengels at gmail.com Fri Jan 23 09:55:03 2009 From: andreengels at gmail.com (Andre Engels) Date: Fri, 23 Jan 2009 09:55:03 +0100 Subject: [Tutor] fetching wikipedia articles In-Reply-To: References: <6faf39c90901220913h585ce27bue36a111e0c34e6f6@mail.gmail.com> <6faf39c90901220915i67696c3iff28afc15ed85f92@mail.gmail.com> Message-ID: <6faf39c90901230055r2f1d5469r85d1eadc4ed3adf8@mail.gmail.com> On Fri, Jan 23, 2009 at 9:09 AM, amit sethi wrote: > Well that is interesting but why should that happen in case I am using a > different User Agent because I tried doing > status=rp.can_fetch('Mozilla/5.0', > "http://en.wikipedia.org/wiki/Sachin_Tendulkar") > but even that returns false > Is there something wrong with the syntax , Is there a catch that i don't > understand. The problem is that you are using the standard Python user agent when getting the robots.txt. Because the user agent is refused, it cannot get the robots.txt file itself to look at. -- Andr? Engels, andreengels at gmail.com From amit.pureenergy at gmail.com Fri Jan 23 10:37:09 2009 From: amit.pureenergy at gmail.com (amit sethi) Date: Fri, 23 Jan 2009 15:07:09 +0530 Subject: [Tutor] fetching wikipedia articles In-Reply-To: <6faf39c90901230055r2f1d5469r85d1eadc4ed3adf8@mail.gmail.com> References: <6faf39c90901220913h585ce27bue36a111e0c34e6f6@mail.gmail.com> <6faf39c90901220915i67696c3iff28afc15ed85f92@mail.gmail.com> <6faf39c90901230055r2f1d5469r85d1eadc4ed3adf8@mail.gmail.com> Message-ID: so is there a way around that problem ?? On Fri, Jan 23, 2009 at 2:25 PM, Andre Engels wrote: > On Fri, Jan 23, 2009 at 9:09 AM, amit sethi > wrote: > > Well that is interesting but why should that happen in case I am using a > > different User Agent because I tried doing > > status=rp.can_fetch('Mozilla/5.0', > > "http://en.wikipedia.org/wiki/Sachin_Tendulkar") > > but even that returns false > > Is there something wrong with the syntax , Is there a catch that i don't > > understand. > > The problem is that you are using the standard Python user agent when > getting the robots.txt. Because the user agent is refused, it cannot > get the robots.txt file itself to look at. > > -- > Andr? Engels, andreengels at gmail.com > -- A-M-I-T S|S -------------- next part -------------- An HTML attachment was scrubbed... URL: From vginer at gmail.com Fri Jan 23 11:17:15 2009 From: vginer at gmail.com (Vicent) Date: Fri, 23 Jan 2009 11:17:15 +0100 Subject: [Tutor] Customizing Eclipse text editor Message-ID: <50ed08f40901230217h473e98c4r5b26e4858b6d8dd9@mail.gmail.com> Hello everyone. I work with Eclipse+PyDev. I've managed to customize colors and fonts of the text editor, but I don't know how to change the appearance of the vertical zone that contains folding controls which is next to the line number zone, at the left of the editor window. Here you can see a screenshot for what I mean (it is the white vertical zone close to the line number zone): http://dl.getdropbox.com/u/155485/screenshot01.png Can you help me? As you can see there, I prefer a black background, so I've changed colors a little. My second question is: do you know any kind of recomended (I mean, optimized for a good working experience, good for eyes health, etc.) color palette or color combination with black background? Thank you in advance. -- Vicent -------------- next part -------------- An HTML attachment was scrubbed... URL: From andreengels at gmail.com Fri Jan 23 11:25:43 2009 From: andreengels at gmail.com (Andre Engels) Date: Fri, 23 Jan 2009 11:25:43 +0100 Subject: [Tutor] fetching wikipedia articles In-Reply-To: References: <6faf39c90901220913h585ce27bue36a111e0c34e6f6@mail.gmail.com> <6faf39c90901220915i67696c3iff28afc15ed85f92@mail.gmail.com> <6faf39c90901230055r2f1d5469r85d1eadc4ed3adf8@mail.gmail.com> Message-ID: <6faf39c90901230225q3d6ec030sb224315810f584a0@mail.gmail.com> On Fri, Jan 23, 2009 at 10:37 AM, amit sethi wrote: > so is there a way around that problem ?? Ok, I have done some checking around, and it seems that the Wikipedia server is giving a return code of 403 (forbidden), but still giving the page - which I think is weird behaviour. I will check with the developers of Wikimedia why this is done, but for now you can resolve this by editing robotparser.py in the following way: In the __init__ of the class URLopener, add the following at the end: self.addheaders = [header for header in self.addheaders if header[0] != "User-Agent"] + [('User-Agent', '')] (probably self.addheaders = [('User-Agent', '')] does the same, but my version is more secure) -- Andr? Engels, andreengels at gmail.com From andreengels at gmail.com Fri Jan 23 11:37:53 2009 From: andreengels at gmail.com (Andre Engels) Date: Fri, 23 Jan 2009 11:37:53 +0100 Subject: [Tutor] fetching wikipedia articles In-Reply-To: <6faf39c90901230225q3d6ec030sb224315810f584a0@mail.gmail.com> References: <6faf39c90901220913h585ce27bue36a111e0c34e6f6@mail.gmail.com> <6faf39c90901220915i67696c3iff28afc15ed85f92@mail.gmail.com> <6faf39c90901230055r2f1d5469r85d1eadc4ed3adf8@mail.gmail.com> <6faf39c90901230225q3d6ec030sb224315810f584a0@mail.gmail.com> Message-ID: <6faf39c90901230237v724df84dgeebac6075f2b798f@mail.gmail.com> On Fri, Jan 23, 2009 at 11:25 AM, Andre Engels wrote: > In the __init__ of the class URLopener, add the following at the end: > > self.addheaders = [header for header in self.addheaders if header[0] > != "User-Agent"] + [('User-Agent', '')] > > (probably > > self.addheaders = [('User-Agent', '')] > > does the same, but my version is more secure) Looking further I found that a 'cleaner' way to make the same change is to add to the code of URLopener (outside any method): version = '' -- Andr? Engels, andreengels at gmail.com From denis.spir at free.fr Fri Jan 23 12:04:39 2009 From: denis.spir at free.fr (spir) Date: Fri, 23 Jan 2009 12:04:39 +0100 Subject: [Tutor] class arguments? In-Reply-To: References: <20090122225104.03c677f4@o> Message-ID: <20090123120439.1a12b4db@o> Le Thu, 22 Jan 2009 23:29:59 -0000, "Alan Gauld" a ?crit : > > "Alan Gauld" wrote > > >> is there a way to give arguments to a class definition? > > I see that Kent interpreted your question differently to me. > If you do mean that you want to dynamically define class > attributes rather than instance attributes then __init__() > won't work. But I'd be interested to understand why and > how you would want to do that? And in particular how > you would use them after creating them? Thank you Alan and sorry for not having been clear enough. The point actually was class (definition) attributes. I thought at e.g. Guido's views that lists were for homogeneous sequences as opposed to tuples rather like records. And a way to ensure sich a homogeneity, in the sense of items beeing of the same type or super type. The straightforward path to ensure that, as I see it, is to add proper argument to a class definition. But I couldn't find a way to do this. In pseudo-code, it would look like that: class MonoList(list, item_type): typ = item_type def __init__(self,items): self._check_types(items) list.__init__(self,items) def _check_types(self,items): for item in items: if not isinstance(item,MonoList.typ): message = "blah!" raise TypeError(message) def __setitem__(self,index,item): if not isinstance(item,MonoList.typ): message = "blah!" raise TypeError(message) list.__setitem__(self,index,item) def __add__(self,other): self._check_types(other) list.__add__(self,other) ....... Well, I realize now that it is a bit more complicated. MonoList itself should be an intermediate base class between list and and subclasses that each allow only a single item type. Otherwise all monolist-s have the same item type ;-) Just exploring around... denis > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > ------ la vida e estranya From amit.pureenergy at gmail.com Fri Jan 23 12:07:53 2009 From: amit.pureenergy at gmail.com (amit sethi) Date: Fri, 23 Jan 2009 16:37:53 +0530 Subject: [Tutor] fetching wikipedia articles In-Reply-To: <6faf39c90901230225q3d6ec030sb224315810f584a0@mail.gmail.com> References: <6faf39c90901220913h585ce27bue36a111e0c34e6f6@mail.gmail.com> <6faf39c90901220915i67696c3iff28afc15ed85f92@mail.gmail.com> <6faf39c90901230055r2f1d5469r85d1eadc4ed3adf8@mail.gmail.com> <6faf39c90901230225q3d6ec030sb224315810f584a0@mail.gmail.com> Message-ID: well thanks ... it worked well ... but robotparser is in urllib isn't there a module like robotparser in urllib2 On Fri, Jan 23, 2009 at 3:55 PM, Andre Engels wrote: > On Fri, Jan 23, 2009 at 10:37 AM, amit sethi > wrote: > > so is there a way around that problem ?? > > Ok, I have done some checking around, and it seems that the Wikipedia > server is giving a return code of 403 (forbidden), but still giving > the page - which I think is weird behaviour. I will check with the > developers of Wikimedia why this is done, but for now you can resolve > this by editing robotparser.py in the following way: > > In the __init__ of the class URLopener, add the following at the end: > > self.addheaders = [header for header in self.addheaders if header[0] > != "User-Agent"] + [('User-Agent', '')] > > (probably > > self.addheaders = [('User-Agent', '')] > > does the same, but my version is more secure) > > -- > Andr? Engels, andreengels at gmail.com > -- A-M-I-T S|S -------------- next part -------------- An HTML attachment was scrubbed... URL: From andreengels at gmail.com Fri Jan 23 12:11:32 2009 From: andreengels at gmail.com (Andre Engels) Date: Fri, 23 Jan 2009 12:11:32 +0100 Subject: [Tutor] fetching wikipedia articles In-Reply-To: References: <6faf39c90901220913h585ce27bue36a111e0c34e6f6@mail.gmail.com> <6faf39c90901220915i67696c3iff28afc15ed85f92@mail.gmail.com> <6faf39c90901230055r2f1d5469r85d1eadc4ed3adf8@mail.gmail.com> <6faf39c90901230225q3d6ec030sb224315810f584a0@mail.gmail.com> Message-ID: <6faf39c90901230311r229114b7r219d601977551319@mail.gmail.com> On Fri, Jan 23, 2009 at 12:07 PM, amit sethi wrote: > well thanks ... it worked well ... but robotparser is in urllib isn't there > a module like robotparser in > urllib2 You'll have to ask someone else about that part... -- Andr? Engels, andreengels at gmail.com From alan.gauld at btinternet.com Fri Jan 23 12:23:11 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 23 Jan 2009 11:23:11 -0000 Subject: [Tutor] fetching wikipedia articles References: <6faf39c90901220913h585ce27bue36a111e0c34e6f6@mail.gmail.com><6faf39c90901220915i67696c3iff28afc15ed85f92@mail.gmail.com><6faf39c90901230055r2f1d5469r85d1eadc4ed3adf8@mail.gmail.com> <6faf39c90901230225q3d6ec030sb224315810f584a0@mail.gmail.com> Message-ID: "Andre Engels" wrote > developers of Wikimedia why this is done, but for now you can > resolve > this by editing robotparser.py in the following way: > > In the __init__ of the class URLopener, add the following at the > end: > > self.addheaders = [header for header in self.addheaders if header[0] > != "User-Agent"] + [('User-Agent', '')] Rather than editing the existing code and making it non standard why not subclass robotparser: class WP_RobotParser(robotparser): def __init__(self, *args, *kwargs): robotparser.__init__(self, *args, *kwargs) self.addheaders = .......blah.... Thats one of the advantages of OOP, you can change the way classes work without modifying the original code. And thus not breaking any code that relies on the original behaviour. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From denis.spir at free.fr Fri Jan 23 12:36:39 2009 From: denis.spir at free.fr (spir) Date: Fri, 23 Jan 2009 12:36:39 +0100 Subject: [Tutor] Customizing Eclipse text editor In-Reply-To: <50ed08f40901230217h473e98c4r5b26e4858b6d8dd9@mail.gmail.com> References: <50ed08f40901230217h473e98c4r5b26e4858b6d8dd9@mail.gmail.com> Message-ID: <20090123123639.115d048a@o> Le Fri, 23 Jan 2009 11:17:15 +0100, Vicent a ?crit : > Hello everyone. [...] > As you can see there, I prefer a black background, so I've changed colors a > little. My second question is: do you know any kind of recomended (I mean, > optimized for a good working experience, good for eyes health, etc.) color > palette or color combination with black background? > > Thank you in advance. I have long talked about that with a web designer who is particuliarly aware of user comfort in relation to colors, brightness, etc. What I remember is the following rules about what factors make reading/watching harmful, difficult and/or tiring: -1- overall brightness --> white background forbidden -2- difficulty to read or distingush shapes (e.g. too small or badly designed fonts) -3- physical effects of low quality monitors -4- too low (rule -2-) or too high (rule -1-) contrast In addition to that, a basic rule of graphical design in any domain is that too many colors or styles -- as usually done in standard syntax highlighting -- rather prevents readibility that helps it. There should be some research done on this topic. After all, it's a relevant aspect of all programmers' everyday life, no? I'm rather sure that for most PLs, a combination of 3 to 5 colors, and bold/italics properties given to only 1 or 2 token types is optimal. I haven't yet found a style sheet to be really happy with, nevertheless. Now, for a language that becomes more and more complex like python... maybe it will be easier with py3 ;-) denis ------ la vida e estranya From kent37 at tds.net Fri Jan 23 12:45:04 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 23 Jan 2009 06:45:04 -0500 Subject: [Tutor] class arguments? In-Reply-To: <20090123120439.1a12b4db@o> References: <20090122225104.03c677f4@o> <20090123120439.1a12b4db@o> Message-ID: <1c2a2c590901230345xfb7dbd2i83bc8ff1928c1f40@mail.gmail.com> On Fri, Jan 23, 2009 at 6:04 AM, spir wrote: > Thank you Alan and sorry for not having been clear enough. The point actually was class (definition) attributes. I thought at e.g. Guido's views that lists were for homogeneous sequences as opposed to tuples rather like records. And a way to ensure sich a homogeneity, in the sense of items beeing of the same type or super type. > The straightforward path to ensure that, as I see it, is to add proper argument to a class definition. A simple way to do this is with a class factory function, for example: def makeMonoList(typ, number): class MonoListSubtype(MonoList): item_type = type item_number = number return MonoListSubtype then e.g. IntegerList = makeMonoList(int, 5) myIntegerList = IntegerList() This is similar in spirit to collections.namedtuple() in Python 2.6 though the implementation is different; namedtuple() actually creates and evaluates the text of the new class definition: http://docs.python.org/library/collections.html#namedtuple-factory-function-for-tuples-with-named-fields http://svn.python.org/view/python/trunk/Lib/collections.py?rev=68853&view=auto Kent From kent37 at tds.net Fri Jan 23 13:27:40 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 23 Jan 2009 07:27:40 -0500 Subject: [Tutor] fetching wikipedia articles In-Reply-To: References: <6faf39c90901220913h585ce27bue36a111e0c34e6f6@mail.gmail.com> <6faf39c90901220915i67696c3iff28afc15ed85f92@mail.gmail.com> <6faf39c90901230055r2f1d5469r85d1eadc4ed3adf8@mail.gmail.com> <6faf39c90901230225q3d6ec030sb224315810f584a0@mail.gmail.com> Message-ID: <1c2a2c590901230427h2a20969s192217ebccd406c5@mail.gmail.com> On Fri, Jan 23, 2009 at 6:23 AM, Alan Gauld wrote: > Rather than editing the existing code and making it non standard > why not subclass robotparser: > > class WP_RobotParser(robotparser): > def __init__(self, *args, *kwargs): > robotparser.__init__(self, *args, *kwargs) > self.addheaders = .......blah.... > > Thats one of the advantages of OOP, you can change the way > classes work without modifying the original code. And thus not > breaking any code that relies on the original behaviour. That won't work, it is urllib.URLOpener() that he is patching and robotparser does not supply a way to change the URLOpener subclass that it uses. Ken From kent37 at tds.net Fri Jan 23 13:29:28 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 23 Jan 2009 07:29:28 -0500 Subject: [Tutor] fetching wikipedia articles In-Reply-To: <6faf39c90901230237v724df84dgeebac6075f2b798f@mail.gmail.com> References: <6faf39c90901220913h585ce27bue36a111e0c34e6f6@mail.gmail.com> <6faf39c90901220915i67696c3iff28afc15ed85f92@mail.gmail.com> <6faf39c90901230055r2f1d5469r85d1eadc4ed3adf8@mail.gmail.com> <6faf39c90901230225q3d6ec030sb224315810f584a0@mail.gmail.com> <6faf39c90901230237v724df84dgeebac6075f2b798f@mail.gmail.com> Message-ID: <1c2a2c590901230429j519ce649r52f71afdbb08d8f1@mail.gmail.com> On Fri, Jan 23, 2009 at 5:37 AM, Andre Engels wrote: > Looking further I found that a 'cleaner' way to make the same change > is to add to the code of URLopener (outside any method): > > version = '' You can do this without modifying the standard library source, by import urllib urllib.URLopener.version = '' The version string is used as the User-Agent, that is why this works at all. Kent From alan.gauld at btinternet.com Fri Jan 23 14:51:58 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 23 Jan 2009 13:51:58 -0000 Subject: [Tutor] fetching wikipedia articles References: <6faf39c90901220913h585ce27bue36a111e0c34e6f6@mail.gmail.com><6faf39c90901220915i67696c3iff28afc15ed85f92@mail.gmail.com><6faf39c90901230055r2f1d5469r85d1eadc4ed3adf8@mail.gmail.com><6faf39c90901230225q3d6ec030sb224315810f584a0@mail.gmail.com> <1c2a2c590901230427h2a20969s192217ebccd406c5@mail.gmail.com> Message-ID: "Kent Johnson" wrote >> Rather than editing the existing code and making it non standard >> why not subclass robotparser: > That won't work, it is urllib.URLOpener() that he is patching and Sorry, yes I misread that post as modifying robotparser, it should have been URLOpener. But... > robotparser does not supply a way to change the URLOpener subclass > that it uses. I didn't realize that. So you would need to cut n' paste the robotparser read() method into a subclass of robotparser too. Which is almost as messy as editing the original source. Such a shame that the author didn't either put the opener as an attribute or as a defaulted parameter of read! Pity, I hate to see editing of existing classes in an OO system. Alan G. From vginer at gmail.com Fri Jan 23 14:57:10 2009 From: vginer at gmail.com (Vicent) Date: Fri, 23 Jan 2009 14:57:10 +0100 Subject: [Tutor] Why dictionaries? Message-ID: <50ed08f40901230557w5de9861cj8fd81a3050e97c49@mail.gmail.com> A simple but maybe too wide question: When is it / isn't it useful to use dictionaries, in a Python program? I mean, what kind of tasks are they interesting for? Maybe you can give me some references where they explain it. Thank you!! -- Vicent From alan.gauld at btinternet.com Fri Jan 23 15:00:02 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 23 Jan 2009 14:00:02 -0000 Subject: [Tutor] Customizing Eclipse text editor References: <50ed08f40901230217h473e98c4r5b26e4858b6d8dd9@mail.gmail.com> <20090123123639.115d048a@o> Message-ID: "spir" wrote > There should be some research done on this topic. After all, > it's a relevant aspect of all programmers' everyday life, no? I suspect there has been - just not in our field. The reason I changed the colours on my web tutor about a year ago was because one of my users who was a graphics designer chided me for the use of contrasting colours. It is apparently easier to read something if all the colours on a page are from the same family - different shades of red say. Contrasting colours clash and so should only be used where you want to draw attention away from the main text. I'm no expert but he sounded like he knew what he was talking about and the end result pleases me so I stuck with it! :-) Alan G. From alan.gauld at btinternet.com Fri Jan 23 15:07:36 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 23 Jan 2009 14:07:36 -0000 Subject: [Tutor] Why dictionaries? References: <50ed08f40901230557w5de9861cj8fd81a3050e97c49@mail.gmail.com> Message-ID: "Vicent" wrote > When is it / isn't it useful to use dictionaries, in a Python > program? > I mean, what kind of tasks are they interesting for? They are interesting for any place where you need to store associations of objects and data. Think of a glossary or an index in a book. Both are a type of dictionary. A Glossary takes a single word and returns a paragraph of definition. An index takes a word and retirns a list of page numbers where that word appears. A dictionary can also model a simple database where a single key can retrieve an entire record. It goes on and on, they are one of the most powerful data structures available to us. The biggest snags are that they are not ordered so if you need a sorted data store dictionaries may not be the best choice. > Maybe you can give me some references where they explain it. Try Wikipedia under Associative Array (a fancy term for a dictionary) or Hash Table for a description of the inner workings... HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Fri Jan 23 15:15:19 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 23 Jan 2009 09:15:19 -0500 Subject: [Tutor] Why dictionaries? In-Reply-To: <50ed08f40901230557w5de9861cj8fd81a3050e97c49@mail.gmail.com> References: <50ed08f40901230557w5de9861cj8fd81a3050e97c49@mail.gmail.com> Message-ID: <1c2a2c590901230615l2b6f2f7j7f45867b16542c50@mail.gmail.com> On Fri, Jan 23, 2009 at 8:57 AM, Vicent wrote: > A simple but maybe too wide question: > > When is it / isn't it useful to use dictionaries, in a Python program? > I mean, what kind of tasks are they interesting for? Lists are ordered, dicts are not List indices are consecutive integers, dict keys can be any hashable value (most often a number or string) and do not have to be consecutive. Dict lookup is fast, even for large dictionaries. List search is sequential and gets slow for long lists. This can be a performance killer, for example a common performance problem is code like this: for item1 in very_long_list_1: if item1 in very_long_list_2: # do something with item1 that matches This particular example is best solved with a set, not a dict, but the performance of both is similar and sometimes a dict is the correct solution. This will be significantly faster than the previous code: list_2_items = set(very_long_list_2) for item1 in very_long_list_1: if item1 in list_2_items: # do something with item1 Kent From sidewalking at gmail.com Fri Jan 23 19:25:02 2009 From: sidewalking at gmail.com (Scott Stueben) Date: Fri, 23 Jan 2009 11:25:02 -0700 Subject: [Tutor] Possible to search text file for multiple string values at once? Message-ID: <99004bb30901231025i6c04e338tcc373aa9469d0550@mail.gmail.com> Hi all, I understand that python excels at text processing, and wondered if there is a way to use python to accomplish a certain task. I am trying to search large text files for multiple strings (like employee ID number, or name). Any text editor (I use Windows mostly) will certainly have a "find", "replace", or even "find in files" (to search multiple files for a value) function, but this is searching for one string at a time. I would like to search a text file for a list of strings, like a sql query. For instance: To search a text file for the values 'Bob', 'John', 'Joe', 'Jim', and 'Fred', you would have to open the dialog and do five separate searches. Lots of copying and pasting, lots of room for typos. But if you were in a SQL database, you could do something like: "SELECT * FROM my_table WHERE first_name IN ('Bob', 'John', 'Joe', 'Jim', 'Fred')" and you would get results for all five values. I would love to set up a script to parse a file and show results from a list of strings. Is this possible with python? Thanks for the input and help, Scott From bgailer at gmail.com Fri Jan 23 19:38:50 2009 From: bgailer at gmail.com (bob gailer) Date: Fri, 23 Jan 2009 13:38:50 -0500 Subject: [Tutor] Possible to search text file for multiple string values at once? In-Reply-To: <99004bb30901231025i6c04e338tcc373aa9469d0550@mail.gmail.com> References: <99004bb30901231025i6c04e338tcc373aa9469d0550@mail.gmail.com> Message-ID: <497A0EBA.6080305@gmail.com> Scott Stueben wrote: > Hi all, > > I understand that python excels at text processing, and wondered if > there is a way to use python to accomplish a certain task. I am > trying to search large text files for multiple strings (like employee > ID number, or name). Any text editor (I use Windows mostly) will > certainly have a "find", "replace", or even "find in files" (to search > multiple files for a value) function, but this is searching for one > string at a time. > > I would like to search a text file for a list of strings, like a sql query. > > For instance: To search a text file for the values 'Bob', 'John', > 'Joe', 'Jim', and 'Fred', you would have to open the dialog and do > five separate searches. Lots of copying and pasting, lots of room for > typos. > > But if you were in a SQL database, you could do something like: > > "SELECT * FROM my_table WHERE first_name IN ('Bob', 'John', 'Joe', > 'Jim', 'Fred')" > > and you would get results for all five values. > > I would love to set up a script to parse a file and show results from > a list of strings. Is this possible with python? > Yes - and also possible with almost all other programming languages. Here is one of several ways to do it in Python: for first_name in ('Bob', 'John', 'Joe', 'Jim', 'Fred'): if first_name in text: print first_name, 'found' -- Bob Gailer Chapel Hill NC 919-636-4239 From srilyk at gmail.com Fri Jan 23 19:47:07 2009 From: srilyk at gmail.com (W W) Date: Fri, 23 Jan 2009 12:47:07 -0600 Subject: [Tutor] Possible to search text file for multiple string values at once? In-Reply-To: <497A0EBA.6080305@gmail.com> References: <99004bb30901231025i6c04e338tcc373aa9469d0550@mail.gmail.com> <497A0EBA.6080305@gmail.com> Message-ID: <333efb450901231047y63da6f7rf03f9227aea373c0@mail.gmail.com> On Fri, Jan 23, 2009 at 12:38 PM, bob gailer wrote: > Scott Stueben wrote: > >> Hi all, >> >> I understand that python excels at text processing, and wondered if >> there is a way to use python to accomplish a certain task. >> I would love to set up a script to parse a file and show results from >> a list of strings. Is this possible with python? >> >> > > Yes - and also possible with almost all other programming languages. > Here is one of several ways to do it in Python: > > for first_name in ('Bob', 'John', 'Joe', 'Jim', 'Fred'): > if first_name in text: > print first_name, 'found' > Another option, if you really like sql, is to import sqlite3 and then parse your text file into a sqlite database. That's probably overkill, of course. But it's a possibility. It really depends on what matters most. Speed? Comfort(with syntax)? Ease of use? That will give you an idea of which tools you should use. HTH, Wayne -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn't. - Primo Levi -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Fri Jan 23 19:52:26 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 23 Jan 2009 13:52:26 -0500 Subject: [Tutor] Possible to search text file for multiple string values at once? In-Reply-To: <99004bb30901231025i6c04e338tcc373aa9469d0550@mail.gmail.com> References: <99004bb30901231025i6c04e338tcc373aa9469d0550@mail.gmail.com> Message-ID: <1c2a2c590901231052v5f40b318wfef45f0d437ce59a@mail.gmail.com> On Fri, Jan 23, 2009 at 1:25 PM, Scott Stueben wrote: > I would like to search a text file for a list of strings, like a sql query. What do you want to do if you find one? Do you want to get every line that contains any of the strings, or a list of which strings are found, or just find out if any of the strings are there? > For instance: To search a text file for the values 'Bob', 'John', > 'Joe', 'Jim', and 'Fred', you would have to open the dialog and do > five separate searches. Lots of copying and pasting, lots of room for > typos. You can do this with a regular expression. For example, import re findAny = re.compile('Bob|John|Joe|Jim|Fred') for found in findAny.findall(s): print found will print all occurrences of any of the target names. You can build the regex string dynamically from user input; if 'toFind' is a list of target words, use findAny = re.compile('|'.join(re.escape(target) for target in toFind)) re.escape() cleans up targets that have special characters in them. From andreengels at gmail.com Fri Jan 23 19:53:18 2009 From: andreengels at gmail.com (Andre Engels) Date: Fri, 23 Jan 2009 19:53:18 +0100 Subject: [Tutor] fetching wikipedia articles In-Reply-To: <6faf39c90901230225q3d6ec030sb224315810f584a0@mail.gmail.com> References: <6faf39c90901220913h585ce27bue36a111e0c34e6f6@mail.gmail.com> <6faf39c90901220915i67696c3iff28afc15ed85f92@mail.gmail.com> <6faf39c90901230055r2f1d5469r85d1eadc4ed3adf8@mail.gmail.com> <6faf39c90901230225q3d6ec030sb224315810f584a0@mail.gmail.com> Message-ID: <6faf39c90901231053x6662ceep773a0b755ff4511a@mail.gmail.com> On Fri, Jan 23, 2009 at 11:25 AM, Andre Engels wrote: > On Fri, Jan 23, 2009 at 10:37 AM, amit sethi wrote: >> so is there a way around that problem ?? > > Ok, I have done some checking around, and it seems that the Wikipedia > server is giving a return code of 403 (forbidden), but still giving > the page - which I think is weird behaviour. I will check with the > developers of Wikimedia why this is done, It appears that this is done on purpose, not just for Python but also for the 'standard' user agent in other languages. The idea is that it forces programmers to add their own user agent, so that if the program trying to contact Wikipedia misbehaves, it can be blocked or otherwise handeled with; as a bonus it also gives programmers a small extra hurdle so that the most amateuristic attempts are stopped, but more thought out programs are not. -- Andr? Engels, andreengels at gmail.com From kent37 at tds.net Fri Jan 23 20:02:20 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 23 Jan 2009 14:02:20 -0500 Subject: [Tutor] class arguments? In-Reply-To: <20090123193529.1eeb68aa@o> References: <20090122225104.03c677f4@o> <20090123120439.1a12b4db@o> <1c2a2c590901230345xfb7dbd2i83bc8ff1928c1f40@mail.gmail.com> <20090123193529.1eeb68aa@o> Message-ID: <1c2a2c590901231102u6eb26ab9jefa27c62f20ad33c@mail.gmail.com> Forwarding to the list with my reply... On Fri, Jan 23, 2009 at 1:35 PM, spir wrote: > Le Fri, 23 Jan 2009 06:45:04 -0500, > Kent Johnson a ?crit : > >> On Fri, Jan 23, 2009 at 6:04 AM, spir wrote: >> >> > Thank you Alan and sorry for not having been clear enough. The point actually was class (definition) attributes. I thought at e.g. Guido's views that lists were for homogeneous sequences as opposed to tuples rather like records. And a way to ensure sich a homogeneity, in the sense of items beeing of the same type or super type. >> > The straightforward path to ensure that, as I see it, is to add proper argument to a class definition. >> >> A simple way to do this is with a class factory function, for example: >> >> def makeMonoList(typ, number): >> class MonoListSubtype(MonoList): >> item_type = type >> item_number = number >> return MonoListSubtype > > That's it! Stupid me!! [Just realize I have a kind of mental blocage that prevents me *imagining* a class beeing defined inside a func. As for me a class is a higher level kind of thing. Actually I also have problems with defs insides defs. Maybe there should be more introduction to that in python literature. Probably it may help and simplify a whole lot of models.] > Thank you again. >> then e.g. >> IntegerList = makeMonoList(int, 5) >> myIntegerList = IntegerList() >> >> This is similar in spirit to collections.namedtuple() in Python 2.6 >> though the implementation is different; namedtuple() actually creates >> and evaluates the text of the new class definition: >> http://docs.python.org/library/collections.html#namedtuple-factory-function-for-tuples-with-named-fields >> http://svn.python.org/view/python/trunk/Lib/collections.py?rev=68853&view=auto > > I have watched that some time ago -- as you pointed to it already. I take the opportunity to ask why this contruct is so complicated. There is an alternative in the cookbook (also pointed by Kent, if I remmember well) that is only a few lines long. Something like: > > class Record(dict): > def __init__(self,**kwargs): > dict.__init__(self,kwargs) > # and/or > self.__dict__ = kwargs > > [There are several versons around, +/- based on the same principle] namedtuple() creates a new class that has exactly the desired attributes, so it is a bit more specific and typesafe - you have to have the correct number of points. The generated class subclasses tuple so it can be used as a dict key (if the items themselves can be). Class instances are lightweight because they don't have a __dict__ member. > Actually, the thing I like at least in the namedtuple recipe is that it writes the class def as a string to be executed: Yeah, I know...with all the time we spend on the list telling people not to use eval()... > > I know there are several advantages: > * a docstring > * For large collections of records of the same (sub)type, as the list of field is held by the class (instances record the actual data only), which spares memory. But doesn't this lead to lower performance, as attribute access by name requires adressing a class level attribute? The attributes are properties, so attribute access is like a method call, I suppose this is slower than direct field access but it is a common Python technique. > * attributes can be accessed by index, too > > Also, as this factory create kinds of records, meaning data constructs with an identical structure, that would perfectly hold table records, why isn't it simply called "record". > To sum up in a word: why so much *complication*? I guess you would have to search comp.lang.python or python-dev to find the reasons, I don't think there is a PEP for this (at least not referenced in the What's New). Kent > > Denis > ------ > la vida e estranya > From sidewalking at gmail.com Fri Jan 23 20:11:33 2009 From: sidewalking at gmail.com (Scott Stueben) Date: Fri, 23 Jan 2009 12:11:33 -0700 Subject: [Tutor] Possible to search text file for multiple string values at once? In-Reply-To: <1c2a2c590901231052v5f40b318wfef45f0d437ce59a@mail.gmail.com> References: <99004bb30901231025i6c04e338tcc373aa9469d0550@mail.gmail.com> <1c2a2c590901231052v5f40b318wfef45f0d437ce59a@mail.gmail.com> Message-ID: <99004bb30901231111x2e82b99v82b560e1a4da4a05@mail.gmail.com> Thanks for the help so far - it seems easy enough. To clarify on the points you have asked me about: A sqlite3 database on my machine would be an excellent idea for personal use. I would like to be able to get a functional script for others on my team to use, so maybe a script or compiled program (Win32) eventually. As for output, I would probably like to return the entire lines that contain any search results of those strings. Maybe just output to a results.txt that would have the entire line of each line that contains 'Bob', 'John', 'Joe', 'Jim', and or 'Fred'. Speed isn't as important as ease of use, I suppose, since non-technical people should be able to use it, ideally. Maybe, since I am on Win32, I could have a popup window that asks for input filename and path, and then asks for string(s) to search for, and then it would process the search and output all lines to a file. Something like that is what I am imagining, but I am open to suggestions on items that may be easier to use or code. Is that reasonably simple to code for a beginner? Thanks again, Scott On Fri, Jan 23, 2009 at 11:52 AM, Kent Johnson wrote: > On Fri, Jan 23, 2009 at 1:25 PM, Scott Stueben wrote: > >> I would like to search a text file for a list of strings, like a sql query. > > What do you want to do if you find one? Do you want to get every line > that contains any of the strings, or a list of which strings are > found, or just find out if any of the strings are there? > >> For instance: To search a text file for the values 'Bob', 'John', >> 'Joe', 'Jim', and 'Fred', you would have to open the dialog and do >> five separate searches. Lots of copying and pasting, lots of room for >> typos. > > You can do this with a regular expression. For example, > > import re > findAny = re.compile('Bob|John|Joe|Jim|Fred') > > for found in findAny.findall(s): > print found > > will print all occurrences of any of the target names. > > You can build the regex string dynamically from user input; if > 'toFind' is a list of target words, use > findAny = re.compile('|'.join(re.escape(target) for target in toFind)) > > re.escape() cleans up targets that have special characters in them. > -- "Shine on me baby, cause it's rainin' in my heart" --Elliott Smith From srilyk at gmail.com Fri Jan 23 21:45:32 2009 From: srilyk at gmail.com (W W) Date: Fri, 23 Jan 2009 14:45:32 -0600 Subject: [Tutor] Possible to search text file for multiple string values at once? In-Reply-To: <99004bb30901231111x2e82b99v82b560e1a4da4a05@mail.gmail.com> References: <99004bb30901231025i6c04e338tcc373aa9469d0550@mail.gmail.com> <1c2a2c590901231052v5f40b318wfef45f0d437ce59a@mail.gmail.com> <99004bb30901231111x2e82b99v82b560e1a4da4a05@mail.gmail.com> Message-ID: <333efb450901231245j71608f48m48f9c6ab16f99398@mail.gmail.com> On Fri, Jan 23, 2009 at 1:11 PM, Scott Stueben wrote: > Thanks for the help so far - it seems easy enough. To clarify on the > points you have asked me about: > > A sqlite3 database on my machine would be an excellent idea for > personal use. I would like to be able to get a functional script for > others on my team to use, so maybe a script or compiled program > (Win32) eventually. As long as everyone on your team has python installed (or as long as python is installed on the machines they'll be using), a functional script would be fairly easy to get rolling. Sqlite is (AFAIK) included with the newer versions of python by default. Heck, it's on the version I have installed on my phone! (Cingular 8525). Simply zipping up the directory should provide an easy enough distribution method. Although, you *could* even write a python script that does the "install" for them. > As for output, I would probably like to return the entire lines that > contain any search results of those strings. Maybe just output to a > results.txt that would have the entire line of each line that contains > 'Bob', 'John', 'Joe', 'Jim', and or 'Fred'. The simplest method: In [5]: f = open('interculturalinterview2.txt', 'r') In [6]: searchstrings = ('holy', 'hand', 'grenade', 'potato') In [7]: for line in f.readlines(): ...: for word in searchstrings: ...: if word in line: ...: print line ...: ...: Hana: have a bonfire n candy apples n make potatoes on a car lol! Wayne: potatoes on a car? Hana .: yer lol its fun and they taste nicer lol, you wrap a potato in tinfoil a nd put in on the engine of a car and close the bonnet and have the engine run an d it cooks it in about 30 mins Speed isn't as important as ease of use, I suppose, since > non-technical people should be able to use it, ideally. Although that wouldn't be quite so easy to use ;) Of course simple modifications would provide a little more user friendliness. > Maybe, since I am on Win32, I could have a popup window that asks for > input filename and path, and then asks for string(s) to search for, > and then it would process the search and output all lines to a file. > Something like that is what I am imagining, but I am open to > suggestions on items that may be easier to use or code. Using Tkinter (again, which AFAIK comes with all versions of python) is pretty simple. import Tkinter, tkFileDialog, tkMessageBox root = Tkinter.Tk() root.withdraw() if tkMessageBox.askyesno("Choose a file?", "Would you like to choose a file to search?"): f = tkFileDialog.askopenfile() You could also use this method to select a file that contains search strings, or allow the user to input them in some other way. > Is that reasonably simple to code for a beginner? > Yes, it's fairly simple. If you've had minimal programming experience you might encounter some bigger problems, but if you've programmed in PHP or some other language you should find it fairly easy to pick up python, and use all the commands you'll need. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From emadnawfal at gmail.com Sat Jan 24 00:02:13 2009 From: emadnawfal at gmail.com (=?windows-1256?B?RW1hZCBOYXdmYWwgKNrjx88g5Obd4Sk=?=) Date: Fri, 23 Jan 2009 18:02:13 -0500 Subject: [Tutor] finding words that contain some letters in their respective order Message-ID: <652641e90901231502l4f5c76bbw3e273b0818af3465@mail.gmail.com> Hello Tutors, Arabic words are build around a root of 3 or 4 consonants with lots of letters in between, and also prefixes and suffixes. The root ktb (write) for example, could be found in words like: ktab : book mktob: letter, written wktabhm: and their book yktb: to write lyktbha: in order for him to write it I need to find all the word forms made up of a certain root in a corpus. My idea, which is not completely right, but nonetheless works most of the time, is to find words that have the letters of the root in their respective order. For example, the words that contain k followed by t then followed by b, no matter whether there is something in between. I came up with following which works fine. For learning purposes, please let me know whether this is a good way, and how else I can achieve that. I appreciate your help, as I always did. def getRoot(root, word): result = "" for letter in word: if letter not in root: continue result +=letter return result # main infile = open("myCorpus.txt").read().split() query = "ktb" outcome = set([word for word in infile if query == getRoot(query, word)]) for word in outcome: print(word) -- ?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? ????????.....???? ??????? "No victim has ever been more repressed and alienated than the truth" Emad Soliman Nawfal Indiana University, Bloomington http://emnawfal.googlepages.com -------------------------------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: From andreengels at gmail.com Sat Jan 24 00:55:51 2009 From: andreengels at gmail.com (Andre Engels) Date: Sat, 24 Jan 2009 00:55:51 +0100 Subject: [Tutor] finding words that contain some letters in their respective order In-Reply-To: <652641e90901231502l4f5c76bbw3e273b0818af3465@mail.gmail.com> References: <652641e90901231502l4f5c76bbw3e273b0818af3465@mail.gmail.com> Message-ID: <6faf39c90901231555r1cbeff26w15f4a403cc3735d4@mail.gmail.com> On Sat, Jan 24, 2009 at 12:02 AM, Emad Nawfal (???? ????) wrote: > Hello Tutors, > Arabic words are build around a root of 3 or 4 consonants with lots of > letters in between, and also prefixes and suffixes. > The root ktb (write) for example, could be found in words like: > ktab : book > mktob: letter, written > wktabhm: and their book > yktb: to write > lyktbha: in order for him to write it > > I need to find all the word forms made up of a certain root in a corpus. My > idea, which is not completely right, but nonetheless works most of the > time, is to find words that have the letters of the root in their > respective order. For example, the words that contain k followed by t > then followed by b, no matter whether there is something in between. I came > up with following which works fine. For learning purposes, please let me > know whether this is a good way, and how else I can achieve that. > I appreciate your help, as I always did. > > > > def getRoot(root, word): > result = "" > > for letter in word: > if letter not in root: > continue > result +=letter > return result > > # main > > infile = open("myCorpus.txt").read().split() > query = "ktb" > outcome = set([word for word in infile if query == getRoot(query, word)]) > for word in outcome: > > print(word) This gets into problems if the letters of the root occur somewhere else in the word as well. For example, if there would be a word bktab, then getRoot("ktb","bktab") would be "bktb", not "ktb". I would use the find method of the string class here - if A and B are strings, and n is a number, then A.find(B,n) is the first location, starting at n, where B is a substring of A, or -1 if there isn't any. Using this, I get: def hasRoot(word, root): # This order I find more logical loc = 0 for letter in root: loc = word.find(letter) if loc == -1: return false return true # main infile = open("myCorpus.txt").read().split() query = "ktb" outcome = [word for word in infile if hasRoot(word,query)] for word in outcome: print(word) -- Andr? Engels, andreengels at gmail.com From andreengels at gmail.com Sat Jan 24 00:57:59 2009 From: andreengels at gmail.com (Andre Engels) Date: Sat, 24 Jan 2009 00:57:59 +0100 Subject: [Tutor] finding words that contain some letters in their respective order In-Reply-To: <6faf39c90901231555r1cbeff26w15f4a403cc3735d4@mail.gmail.com> References: <652641e90901231502l4f5c76bbw3e273b0818af3465@mail.gmail.com> <6faf39c90901231555r1cbeff26w15f4a403cc3735d4@mail.gmail.com> Message-ID: <6faf39c90901231557x1a1ecb20k8284ec03c541300a@mail.gmail.com> I made an error in my program... Sorry, it should be: def hasRoot(word, root): # This order I find more logical loc = 0 for letter in root: loc = word.find(letter,loc) # I missed the ,loc here... if loc == -1: return false return true # main infile = open("myCorpus.txt").read().split() query = "ktb" outcome = [word for word in infile if hasRoot(word,query)] -- Andr? Engels, andreengels at gmail.com From emadnawfal at gmail.com Sat Jan 24 01:14:08 2009 From: emadnawfal at gmail.com (=?windows-1256?B?RW1hZCBOYXdmYWwgKNrjx88g5Obd4Sk=?=) Date: Fri, 23 Jan 2009 19:14:08 -0500 Subject: [Tutor] finding words that contain some letters in their respective order In-Reply-To: <6faf39c90901231557x1a1ecb20k8284ec03c541300a@mail.gmail.com> References: <652641e90901231502l4f5c76bbw3e273b0818af3465@mail.gmail.com> <6faf39c90901231555r1cbeff26w15f4a403cc3735d4@mail.gmail.com> <6faf39c90901231557x1a1ecb20k8284ec03c541300a@mail.gmail.com> Message-ID: <652641e90901231614i55a04d39v5cde094ddf504fc9@mail.gmail.com> On Fri, Jan 23, 2009 at 6:57 PM, Andre Engels wrote: > I made an error in my program... Sorry, it should be: > > def hasRoot(word, root): # This order I find more logical > loc = 0 > for letter in root: > loc = word.find(letter,loc) # I missed the ,loc here... > if loc == -1: > return false > return true > > # main > > infile = open("myCorpus.txt").read().split() > query = "ktb" > outcome = [word for word in infile if hasRoot(word,query)] > > > -- > Andr? Engels, andreengels at gmail.com > Thank you so much. bktab is a legal Arabic word. I also found the word bmktbha in the corpus. I would have missed that. Thank you again. -- ?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? ????????.....???? ??????? "No victim has ever been more repressed and alienated than the truth" Emad Soliman Nawfal Indiana University, Bloomington http://emnawfal.googlepages.com -------------------------------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: From emadnawfal at gmail.com Sat Jan 24 02:00:39 2009 From: emadnawfal at gmail.com (=?windows-1256?B?RW1hZCBOYXdmYWwgKNrjx88g5Obd4Sk=?=) Date: Fri, 23 Jan 2009 20:00:39 -0500 Subject: [Tutor] finding words that contain some letters in their respective order In-Reply-To: <652641e90901231614i55a04d39v5cde094ddf504fc9@mail.gmail.com> References: <652641e90901231502l4f5c76bbw3e273b0818af3465@mail.gmail.com> <6faf39c90901231555r1cbeff26w15f4a403cc3735d4@mail.gmail.com> <6faf39c90901231557x1a1ecb20k8284ec03c541300a@mail.gmail.com> <652641e90901231614i55a04d39v5cde094ddf504fc9@mail.gmail.com> Message-ID: <652641e90901231700l579c7c8y643b92477aac1bbb@mail.gmail.com> 2009/1/23 Emad Nawfal (???? ????) > > > On Fri, Jan 23, 2009 at 6:57 PM, Andre Engels wrote: > >> I made an error in my program... Sorry, it should be: >> >> def hasRoot(word, root): # This order I find more logical >> loc = 0 >> for letter in root: >> loc = word.find(letter,loc) # I missed the ,loc here... >> if loc == -1: >> return false >> return true >> >> # main >> >> infile = open("myCorpus.txt").read().split() >> query = "ktb" >> outcome = [word for word in infile if hasRoot(word,query)] >> >> >> -- >> Andr? Engels, andreengels at gmail.com >> > > > Thank you so much. bktab is a legal Arabic word. I also found the word > bmktbha in the corpus. I would have missed that. > Thank you again. > > -- > ?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? ????????.....???? > ??????? > "No victim has ever been more repressed and alienated than the truth" > > Emad Soliman Nawfal > Indiana University, Bloomington > http://emnawfal.googlepages.com > -------------------------------------------------------- > Hi again, If I want to use a regular expression to find the root ktb in all its derivations, would this be a good way around it: >>> x = re.compile("[a-z]*k[a-z]*t[a-z]*b[a-z]*") >>> text = "hw syktbha ghda wlktab ktb" >>> re.findall(x, text) ['syktbha', 'wlktab', 'ktb'] >>> -- ?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? ????????.....???? ??????? "No victim has ever been more repressed and alienated than the truth" Emad Soliman Nawfal Indiana University, Bloomington http://emnawfal.googlepages.com -------------------------------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: From andreengels at gmail.com Sat Jan 24 02:04:22 2009 From: andreengels at gmail.com (Andre Engels) Date: Sat, 24 Jan 2009 02:04:22 +0100 Subject: [Tutor] finding words that contain some letters in their respective order In-Reply-To: <652641e90901231700l579c7c8y643b92477aac1bbb@mail.gmail.com> References: <652641e90901231502l4f5c76bbw3e273b0818af3465@mail.gmail.com> <6faf39c90901231555r1cbeff26w15f4a403cc3735d4@mail.gmail.com> <6faf39c90901231557x1a1ecb20k8284ec03c541300a@mail.gmail.com> <652641e90901231614i55a04d39v5cde094ddf504fc9@mail.gmail.com> <652641e90901231700l579c7c8y643b92477aac1bbb@mail.gmail.com> Message-ID: <6faf39c90901231704m6696e07fgbd801ed9261d6113@mail.gmail.com> 2009/1/24 Emad Nawfal (???? ????) : > > > 2009/1/23 Emad Nawfal (???? ????) >> >> >> On Fri, Jan 23, 2009 at 6:57 PM, Andre Engels >> wrote: >>> >>> I made an error in my program... Sorry, it should be: >>> >>> def hasRoot(word, root): # This order I find more logical >>> loc = 0 >>> for letter in root: >>> loc = word.find(letter,loc) # I missed the ,loc here... >>> if loc == -1: >>> return false >>> return true >>> >>> # main >>> >>> infile = open("myCorpus.txt").read().split() >>> query = "ktb" >>> outcome = [word for word in infile if hasRoot(word,query)] >>> >>> >>> -- >>> Andr? Engels, andreengels at gmail.com >> >> >> Thank you so much. bktab is a legal Arabic word. I also found the word >> bmktbha in the corpus. I would have missed that. >> Thank you again. >> -- >> ?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? ????????.....???? >> ??????? >> "No victim has ever been more repressed and alienated than the truth" >> >> Emad Soliman Nawfal >> Indiana University, Bloomington >> http://emnawfal.googlepages.com >> -------------------------------------------------------- > > Hi again, > If I want to use a regular expression to find the root ktb in all its > derivations, would this be a good way around it: > >>>> x = re.compile("[a-z]*k[a-z]*t[a-z]*b[a-z]*") >>>> text = "hw syktbha ghda wlktab ktb" >>>> re.findall(x, text) > ['syktbha', 'wlktab', 'ktb'] >>>> Yes, that looks correct - and a regular expression solution also is easier to adapt - for example, the little that I know of Arab makes me believe that _between_ the letters of a root there may only be vowels. If that's correct, the RE can be changed to "[a-z]*k[aeiou]*t[aeiou]*b[a-z]*" -- Andr? Engels, andreengels at gmail.com From emadnawfal at gmail.com Sat Jan 24 02:15:23 2009 From: emadnawfal at gmail.com (=?windows-1256?B?RW1hZCBOYXdmYWwgKNrjx88g5Obd4Sk=?=) Date: Fri, 23 Jan 2009 20:15:23 -0500 Subject: [Tutor] finding words that contain some letters in their respective order In-Reply-To: <6faf39c90901231704m6696e07fgbd801ed9261d6113@mail.gmail.com> References: <652641e90901231502l4f5c76bbw3e273b0818af3465@mail.gmail.com> <6faf39c90901231555r1cbeff26w15f4a403cc3735d4@mail.gmail.com> <6faf39c90901231557x1a1ecb20k8284ec03c541300a@mail.gmail.com> <652641e90901231614i55a04d39v5cde094ddf504fc9@mail.gmail.com> <652641e90901231700l579c7c8y643b92477aac1bbb@mail.gmail.com> <6faf39c90901231704m6696e07fgbd801ed9261d6113@mail.gmail.com> Message-ID: <652641e90901231715m5fe4fbd7p43ebe3722ac7efcf@mail.gmail.com> On Fri, Jan 23, 2009 at 8:04 PM, Andre Engels wrote: > 2009/1/24 Emad Nawfal (???? ????) : > > > > > > 2009/1/23 Emad Nawfal (???? ????) > >> > >> > >> On Fri, Jan 23, 2009 at 6:57 PM, Andre Engels > >> wrote: > >>> > >>> I made an error in my program... Sorry, it should be: > >>> > >>> def hasRoot(word, root): # This order I find more logical > >>> loc = 0 > >>> for letter in root: > >>> loc = word.find(letter,loc) # I missed the ,loc here... > >>> if loc == -1: > >>> return false > >>> return true > >>> > >>> # main > >>> > >>> infile = open("myCorpus.txt").read().split() > >>> query = "ktb" > >>> outcome = [word for word in infile if hasRoot(word,query)] > >>> > >>> > >>> -- > >>> Andr? Engels, andreengels at gmail.com > >> > >> > >> Thank you so much. bktab is a legal Arabic word. I also found the word > >> bmktbha in the corpus. I would have missed that. > >> Thank you again. > >> -- > >> ?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? > ????????.....???? > >> ??????? > >> "No victim has ever been more repressed and alienated than the truth" > >> > >> Emad Soliman Nawfal > >> Indiana University, Bloomington > >> http://emnawfal.googlepages.com > >> -------------------------------------------------------- > > > > Hi again, > > If I want to use a regular expression to find the root ktb in all its > > derivations, would this be a good way around it: > > > >>>> x = re.compile("[a-z]*k[a-z]*t[a-z]*b[a-z]*") > >>>> text = "hw syktbha ghda wlktab ktb" > >>>> re.findall(x, text) > > ['syktbha', 'wlktab', 'ktb'] > >>>> > > Yes, that looks correct - and a regular expression solution also is > easier to adapt - for example, the little that I know of Arab makes me > believe that _between_ the letters of a root there may only be vowels. > If that's correct, the RE can be changed to > > "[a-z]*k[aeiou]*t[aeiou]*b[a-z]*" The letter t does very often occur between the root consonants as well. For example, we have akttb, katatib, and for the root fsr you can have astfsr. Thank you Andre for your helpfulness, and thank you Eugene for suggesting the use of regular expressions. > > > > > -- > Andr? Engels, andreengels at gmail.com > -- ?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? ????????.....???? ??????? "No victim has ever been more repressed and alienated than the truth" Emad Soliman Nawfal Indiana University, Bloomington http://emnawfal.googlepages.com -------------------------------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: From emadnawfal at gmail.com Sat Jan 24 02:17:21 2009 From: emadnawfal at gmail.com (=?windows-1256?B?RW1hZCBOYXdmYWwgKNrjx88g5Obd4Sk=?=) Date: Fri, 23 Jan 2009 20:17:21 -0500 Subject: [Tutor] finding words that contain some letters in their respective order In-Reply-To: <652641e90901231715m5fe4fbd7p43ebe3722ac7efcf@mail.gmail.com> References: <652641e90901231502l4f5c76bbw3e273b0818af3465@mail.gmail.com> <6faf39c90901231555r1cbeff26w15f4a403cc3735d4@mail.gmail.com> <6faf39c90901231557x1a1ecb20k8284ec03c541300a@mail.gmail.com> <652641e90901231614i55a04d39v5cde094ddf504fc9@mail.gmail.com> <652641e90901231700l579c7c8y643b92477aac1bbb@mail.gmail.com> <6faf39c90901231704m6696e07fgbd801ed9261d6113@mail.gmail.com> <652641e90901231715m5fe4fbd7p43ebe3722ac7efcf@mail.gmail.com> Message-ID: <652641e90901231717w2815827bw5cd78cdd73f142f5@mail.gmail.com> 2009/1/23 Emad Nawfal (???? ????) > > > On Fri, Jan 23, 2009 at 8:04 PM, Andre Engels wrote: > >> 2009/1/24 Emad Nawfal (???? ????) : >> > >> > >> > 2009/1/23 Emad Nawfal (???? ????) >> >> >> >> >> >> On Fri, Jan 23, 2009 at 6:57 PM, Andre Engels >> >> wrote: >> >>> >> >>> I made an error in my program... Sorry, it should be: >> >>> >> >>> def hasRoot(word, root): # This order I find more logical >> >>> loc = 0 >> >>> for letter in root: >> >>> loc = word.find(letter,loc) # I missed the ,loc here... >> >>> if loc == -1: >> >>> return false >> >>> return true >> >>> >> >>> # main >> >>> >> >>> infile = open("myCorpus.txt").read().split() >> >>> query = "ktb" >> >>> outcome = [word for word in infile if hasRoot(word,query)] >> >>> >> >>> >> >>> -- >> >>> Andr? Engels, andreengels at gmail.com >> >> >> >> >> >> Thank you so much. bktab is a legal Arabic word. I also found the word >> >> bmktbha in the corpus. I would have missed that. >> >> Thank you again. >> >> -- >> >> ?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? >> ????????.....???? >> >> ??????? >> >> "No victim has ever been more repressed and alienated than the truth" >> >> >> >> Emad Soliman Nawfal >> >> Indiana University, Bloomington >> >> http://emnawfal.googlepages.com >> >> -------------------------------------------------------- >> > >> > Hi again, >> > If I want to use a regular expression to find the root ktb in all its >> > derivations, would this be a good way around it: >> > >> >>>> x = re.compile("[a-z]*k[a-z]*t[a-z]*b[a-z]*") >> >>>> text = "hw syktbha ghda wlktab ktb" >> >>>> re.findall(x, text) >> > ['syktbha', 'wlktab', 'ktb'] >> >>>> >> >> Yes, that looks correct - and a regular expression solution also is >> easier to adapt - for example, the little that I know of Arab makes me >> believe that _between_ the letters of a root there may only be vowels. >> If that's correct, the RE can be changed to >> >> "[a-z]*k[aeiou]*t[aeiou]*b[a-z]*" > > The letter t does very often occur between the root consonants as well. For > example, we have akttb, katatib, and for the root fsr you can have astfsr. > > Thank you Andre for your helpfulness, and thank you Eugene for suggesting > the use of regular expressions. > >> >> >> >> >> -- >> Andr? Engels, andreengels at gmail.com >> > > > > -- > ?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? ????????.....???? > ??????? > "No victim has ever been more repressed and alienated than the truth" > > Emad Soliman Nawfal > Indiana University, Bloomington > http://emnawfal.googlepages.com > -------------------------------------------------------- > Sorry, the last example was incorrect. A correct example would be fqr and aftqr, slf and astlf -- ?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? ????????.....???? ??????? "No victim has ever been more repressed and alienated than the truth" Emad Soliman Nawfal Indiana University, Bloomington http://emnawfal.googlepages.com -------------------------------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Sat Jan 24 07:25:05 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Fri, 23 Jan 2009 22:25:05 -0800 Subject: [Tutor] Finding the End of a Def? Message-ID: <497AB441.1050102@sbcglobal.net> An HTML attachment was scrubbed... URL: From denis.spir at free.fr Sat Jan 24 10:16:51 2009 From: denis.spir at free.fr (spir) Date: Sat, 24 Jan 2009 10:16:51 +0100 Subject: [Tutor] Possible to search text file for multiple string values at once? In-Reply-To: <333efb450901231245j71608f48m48f9c6ab16f99398@mail.gmail.com> References: <99004bb30901231025i6c04e338tcc373aa9469d0550@mail.gmail.com> <1c2a2c590901231052v5f40b318wfef45f0d437ce59a@mail.gmail.com> <99004bb30901231111x2e82b99v82b560e1a4da4a05@mail.gmail.com> <333efb450901231245j71608f48m48f9c6ab16f99398@mail.gmail.com> Message-ID: <20090124101651.3ff68667@o> Le Fri, 23 Jan 2009 14:45:32 -0600, W W a ?crit : > On Fri, Jan 23, 2009 at 1:11 PM, Scott Stueben wrote: > > > Thanks for the help so far - it seems easy enough. To clarify on the > > points you have asked me about: > > > > A sqlite3 database on my machine would be an excellent idea for > > personal use. I would like to be able to get a functional script for > > others on my team to use, so maybe a script or compiled program > > (Win32) eventually. > > > As long as everyone on your team has python installed (or as long as python > is installed on the machines they'll be using), a functional script would be > fairly easy to get rolling. Sqlite is (AFAIK) included with the newer > versions of python by default. Heck, it's on the version I have installed on > my phone! (Cingular 8525). Simply zipping up the directory should provide an > easy enough distribution method. Although, you *could* even write a python > script that does the "install" for them. > > > > As for output, I would probably like to return the entire lines that > > contain any search results of those strings. Maybe just output to a > > results.txt that would have the entire line of each line that contains > > 'Bob', 'John', 'Joe', 'Jim', and or 'Fred'. > > > The simplest method: > > In [5]: f = open('interculturalinterview2.txt', 'r') > > In [6]: searchstrings = ('holy', 'hand', 'grenade', 'potato') > > In [7]: for line in f.readlines(): > ...: for word in searchstrings: > ...: if word in line: > ...: print line > ...: > ...: > Hana: have a bonfire n candy apples n make potatoes on a car lol! > > Wayne: potatoes on a car? > > Hana .: yer lol its fun and they taste nicer lol, you wrap a potato in > tinfoil a > nd put in on the engine of a car and close the bonnet and have the engine > run an > d it cooks it in about 30 mins > > Speed isn't as important as ease of use, I suppose, since > > non-technical people should be able to use it, ideally. I guess the easiest for your team would be to: * let the script write the result lines into a text file * let the script open the result in an editor (using module called subprocess) * put a link to your script on the desk ### just an example # write to file target = open("target.txt",'w') for line in lines: target.write(line) target.close() # open in editor import subprocess subprocess.call(["gedit","target.txt"]) print "*** end ***" denis ------ la vida e estranya From alan.gauld at btinternet.com Sat Jan 24 12:43:00 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 24 Jan 2009 11:43:00 -0000 Subject: [Tutor] Finding the End of a Def? References: <497AB441.1050102@sbcglobal.net> Message-ID: "Wayne Watson" wrote > I'm using pythonWin. > Is there some way to skip from the start of a def to the end? That doesn't seem to be supported. The documentation is found in the help structure under PyWin32 Documentation -Pythonwin and win32ui -Overviews -Keyboard Bindings If using Pythonwin keyboard commands you should look at the docs for the underlying editing widget Scintilla: http://www.scintilla.org/SciTEDoc.html That reveals quite a number of extra navigation commands. The nearest to what you want is next paragraph (Ctr-] ) Pythonwin does modify a few of the standard commands so you need to look in the Pythonwin help first then at Scintilla. But I'm surprised there are no block movement commands given Scintilla's primary goal of supporting programmers You can of couse use the folding feature to speed navigation between functions etc... Keypad * will fold/unfold everything... HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From sierra_mtnview at sbcglobal.net Sat Jan 24 14:06:23 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sat, 24 Jan 2009 05:06:23 -0800 Subject: [Tutor] Finding the End of a Def? In-Reply-To: <20090124105324.6780b0df@o> References: <497AB441.1050102@sbcglobal.net> <20090124105324.6780b0df@o> Message-ID: <497B124F.3080501@sbcglobal.net> An HTML attachment was scrubbed... URL: From srilyk at gmail.com Sat Jan 24 14:37:50 2009 From: srilyk at gmail.com (W W) Date: Sat, 24 Jan 2009 07:37:50 -0600 Subject: [Tutor] Finding the End of a Def? In-Reply-To: <497B124F.3080501@sbcglobal.net> References: <497AB441.1050102@sbcglobal.net> <20090124105324.6780b0df@o> <497B124F.3080501@sbcglobal.net> Message-ID: <333efb450901240537j5f2bf80axbcca54168fe6ffd7@mail.gmail.com> On Sat, Jan 24, 2009 at 7:06 AM, Wayne Watson wrote: > If you are familiar with vi and C, one could enter a simple keystroke and > jump from an opening paren to the corresponding closing one. > > I've long forgotten most of C, but here's a rough segment of a program: > > main() > ( > while (x ==True) > ( > a =5; > > ) > ... > ) > If your cursor was on the second "(", pressing a key would take you to the > third one. I want something like it for def. Where's the end of the def. > Some def blocks are so long it's almost impossible to find where they end. > > Presuming, of course, that your def statement is followed by another, finding the "next" def would get you there. Other than that... you may just have to figure out how to write your own bindings. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Sat Jan 24 14:42:50 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sat, 24 Jan 2009 05:42:50 -0800 Subject: [Tutor] Finding the End of a Def? In-Reply-To: References: <497AB441.1050102@sbcglobal.net> Message-ID: <497B1ADA.5000500@sbcglobal.net> An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: moz-screenshot-160.jpg Type: image/jpeg Size: 6809 bytes Desc: not available URL: From vginer at gmail.com Sat Jan 24 15:25:58 2009 From: vginer at gmail.com (Vicent) Date: Sat, 24 Jan 2009 15:25:58 +0100 Subject: [Tutor] Defining "bit" type Message-ID: <50ed08f40901240625vd1b4980ta751326038adcc6c@mail.gmail.com> Hello. As fas as I know, there is a "bytes" type in Python 3, which is a sequence of bytes. Anyway, I am working with Python 2.5.4, and I am interested in defining a new type called "bit" (if possible), which represents a number that can only take values 0 or 1 ?that's what we would call a "binary variable", in a Mathematical Programming context. I want to define that new data type within my code, so that I can use it in the same way I would use "int", "long" and "float" data types, for instance. How can I do that? If you can give me some hint or any web reference, I would appreciate it. Thank you in advance. -- Vicent -------------- next part -------------- An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Sat Jan 24 15:46:06 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sat, 24 Jan 2009 06:46:06 -0800 Subject: [Tutor] Finding the End of a Def? In-Reply-To: <333efb450901240537j5f2bf80axbcca54168fe6ffd7@mail.gmail.com> References: <497AB441.1050102@sbcglobal.net> <20090124105324.6780b0df@o> <497B124F.3080501@sbcglobal.net> <333efb450901240537j5f2bf80axbcca54168fe6ffd7@mail.gmail.com> Message-ID: <497B29AE.9030008@sbcglobal.net> An HTML attachment was scrubbed... URL: From vginer at gmail.com Sat Jan 24 16:36:23 2009 From: vginer at gmail.com (Vicent) Date: Sat, 24 Jan 2009 16:36:23 +0100 Subject: [Tutor] Fwd: Defining "bit" type In-Reply-To: <50ed08f40901240642w54805b3r9f3babcd5929abfc@mail.gmail.com> References: <50ed08f40901240625vd1b4980ta751326038adcc6c@mail.gmail.com> <35253ca50901240631t40ba5d9dhaa5b0990d75e0f03@mail.gmail.com> <50ed08f40901240642w54805b3r9f3babcd5929abfc@mail.gmail.com> Message-ID: <50ed08f40901240736h1cae2836v815478b29412d067@mail.gmail.com> Sorry, I answered only to Eugene... ---------- Forwarded message ---------- From: Vicent Date: Sat, Jan 24, 2009 at 15:42 Subject: Re: [Tutor] Defining "bit" type To: Eugene Perederey On Sat, Jan 24, 2009 at 15:31, Eugene Perederey wrote: > Hi, > type 'bool' takes only True and False. Is it what you want? > > Well, it would be similar, but... This is OK: >>> a = True >>> type(a) >>> a == 1 True >>> not a False >>> (not a) == 0 True >>> a*0.5 0.5 >>> a*a 1 >>> type(a) But this is not nice: >>> type(a) >>> a True >>> a = 0 >>> type(a) I mean, being "a" a boolean variable, it works as if it was a number, but every time I want to update the value of "a", I must put "False" for 0 and "True" for 1, or it will change into an integer variable. So, maybe I can adapt the definition of "bool" type, I don't know... Anyway, I want to manage 0's and 1's, not "Falses" and "Trues". -- Vicent -------------- next part -------------- An HTML attachment was scrubbed... URL: From vginer at gmail.com Sat Jan 24 16:38:29 2009 From: vginer at gmail.com (Vicent) Date: Sat, 24 Jan 2009 16:38:29 +0100 Subject: [Tutor] Defining "bit" type In-Reply-To: <50ed08f40901240642w54805b3r9f3babcd5929abfc@mail.gmail.com> References: <50ed08f40901240625vd1b4980ta751326038adcc6c@mail.gmail.com> <35253ca50901240631t40ba5d9dhaa5b0990d75e0f03@mail.gmail.com> <50ed08f40901240642w54805b3r9f3babcd5929abfc@mail.gmail.com> Message-ID: <50ed08f40901240738n4e37594che3feb0599178c7b4@mail.gmail.com> On Sat, Jan 24, 2009 at 15:42, Vicent wrote: > > > > I mean, being "a" a boolean variable, it works as if it was a number, but > every time I want to update the value of "a", I must put "False" for 0 and > "True" for 1, or it will change into an integer variable. > > So, maybe I can adapt the definition of "bool" type, I don't know... > Anyway, I want to manage 0's and 1's, not "Falses" and "Trues". > I don't know if it is possible to define a "bit" class based on the "bool" type. I mean, I don't know how to do those kind of things... -- Vicent -------------- next part -------------- An HTML attachment was scrubbed... URL: From srilyk at gmail.com Sat Jan 24 16:55:06 2009 From: srilyk at gmail.com (W W) Date: Sat, 24 Jan 2009 09:55:06 -0600 Subject: [Tutor] Defining "bit" type In-Reply-To: <50ed08f40901240738n4e37594che3feb0599178c7b4@mail.gmail.com> References: <50ed08f40901240625vd1b4980ta751326038adcc6c@mail.gmail.com> <35253ca50901240631t40ba5d9dhaa5b0990d75e0f03@mail.gmail.com> <50ed08f40901240642w54805b3r9f3babcd5929abfc@mail.gmail.com> <50ed08f40901240738n4e37594che3feb0599178c7b4@mail.gmail.com> Message-ID: <333efb450901240755t4f12d25el9eaf62041a31b390@mail.gmail.com> On Sat, Jan 24, 2009 at 9:38 AM, Vicent wrote: > >> So, maybe I can adapt the definition of "bool" type, I don't know... >> Anyway, I want to manage 0's and 1's, not "Falses" and "Trues". >> > Well, I can think of something that might be of some help: In [18]: bit = {True:1, False:0} In [19]: bit[True] Out[19]: 1 In [20]: bit[False] Out[20]: 0 In [21]: bit Out[21]: {False: 0, True: 1} In [22]: x = False In [23]: bit[x] Out[23]: 0 That might give you something to work with. Anyway, HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From ptmcg at austin.rr.com Sat Jan 24 17:31:07 2009 From: ptmcg at austin.rr.com (Paul McGuire) Date: Sat, 24 Jan 2009 10:31:07 -0600 Subject: [Tutor] Defining "bit" type In-Reply-To: References: Message-ID: <702FB31898194DDE9B0F930A25012B51@AWA2> If your actual interest in defining a bit type is to work with an array of bits, try Ilan Schnell's bitarray module (http://pypi.python.org/pypi/bitarray/0.3.4). It uses a compiled extension, so it is quite fast and space-efficient. Ilan gave a presentation on this at the Texas Unconference last fall, and some of the applications were pretty interesting/novel. If you download the tarball from PyPI, there is an included examples directory. -- Paul From vginer at gmail.com Sat Jan 24 17:51:59 2009 From: vginer at gmail.com (Vicent) Date: Sat, 24 Jan 2009 17:51:59 +0100 Subject: [Tutor] Defining "bit" type In-Reply-To: <702FB31898194DDE9B0F930A25012B51@AWA2> References: <702FB31898194DDE9B0F930A25012B51@AWA2> Message-ID: <50ed08f40901240851w69b505eelf008a36a2ebbdf7c@mail.gmail.com> On Sat, Jan 24, 2009 at 17:31, Paul McGuire wrote: > If your actual interest in defining a bit type is to work with an array of > bits, try Ilan Schnell's bitarray module > (http://pypi.python.org/pypi/bitarray/0.3.4). It uses a compiled > extension, > so it is quite fast and space-efficient. > > Ilan gave a presentation on this at the Texas Unconference last fall, and > some of the applications were pretty interesting/novel. If you download > the > tarball from PyPI, there is an included examples directory. > Well, not necessarily ?but I'll give it a look. Thanks. -- Vicent -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sat Jan 24 18:13:00 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 24 Jan 2009 17:13:00 -0000 Subject: [Tutor] Finding the End of a Def? References: <497AB441.1050102@sbcglobal.net> <497B1ADA.5000500@sbcglobal.net> Message-ID: "Wayne Watson" wrote > You can of couse use the folding feature to speed navigation > between functions etc... > Keypad * will fold/unfold everything... > > Interesting, but it folds way too much. yes but you can use other keys to fold just the current function, or even a while loop within a function or an if statement etc. Its a very powerful feature and one of the reasons I use SciTe as an alternative editor to vim (vim supports folding too but its much more clunky IMHO). Using folding you can always collapse a function to fit on a single screen and focus on just the 10-20 lines that really interrest you.. But for rapid movement around files Fold All, a mouse click and then un-Fold All is very effective. But I do agree that block level navigation seems a glaring gap in Scintilla's features as a programmers editor -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Sat Jan 24 18:19:53 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 24 Jan 2009 17:19:53 -0000 Subject: [Tutor] Defining "bit" type References: <50ed08f40901240625vd1b4980ta751326038adcc6c@mail.gmail.com> Message-ID: "Vicent" wrote > Anyway, I am working with Python 2.5.4, and I am interested in > defining a > new type called "bit" (if possible), which represents a number that > can only > take values 0 or 1 ?that's what we would call a "binary variable", > in a > Mathematical Programming context. If its a single binary digit you want then it would be relatively easy to define a class. The operations you need would largely be the comparison and arithmetic ones. But while its not difficult it is tedious and you would need to think about the Exceptions you need to raise for carry errors etc. For example what would be the result of adding two Bits both valued 1. Would the result be a new zero Bit or an Overflow exception? Alan G. From vginer at gmail.com Sat Jan 24 18:37:52 2009 From: vginer at gmail.com (Vicent) Date: Sat, 24 Jan 2009 18:37:52 +0100 Subject: [Tutor] Defining "bit" type In-Reply-To: References: <50ed08f40901240625vd1b4980ta751326038adcc6c@mail.gmail.com> Message-ID: <50ed08f40901240937l49815e35t329a17913c351a18@mail.gmail.com> On Sat, Jan 24, 2009 at 18:19, Alan Gauld wrote: > > If its a single binary digit you want then it would be relatively easy to > define a class. The operations you need would largely be the > comparison and arithmetic ones. But while its not difficult it is > tedious and you would need to think about the Exceptions you > need to raise for carry errors etc. For example what would be the > result of adding two Bits both valued 1. Would the result be a > new zero Bit or an Overflow exception? > > Alan G. > That's a good question... Now, when you add up two booleans valued "True", you get 2: >>> a = True >>> b = True >>> a+b 2 So, maybe I can just build a class that is like a "translator" of True/False into 1/0, but that also admits 1/0 in assignation statements. For my purposes, maybe it is not necessary to handle with many unexpected behaviors... As I am a beginner, I still don't know how to build that class, but I guess Wayne gave me the clue, or something to play with. -- Vicent -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Sat Jan 24 19:48:16 2009 From: bgailer at gmail.com (bob gailer) Date: Sat, 24 Jan 2009 13:48:16 -0500 Subject: [Tutor] Defining "bit" type In-Reply-To: <50ed08f40901240625vd1b4980ta751326038adcc6c@mail.gmail.com> References: <50ed08f40901240625vd1b4980ta751326038adcc6c@mail.gmail.com> Message-ID: <497B6270.4000706@gmail.com> An HTML attachment was scrubbed... URL: From vginer at gmail.com Sat Jan 24 20:03:42 2009 From: vginer at gmail.com (Vicent) Date: Sat, 24 Jan 2009 20:03:42 +0100 Subject: [Tutor] Defining "bit" type In-Reply-To: <497B6270.4000706@gmail.com> References: <50ed08f40901240625vd1b4980ta751326038adcc6c@mail.gmail.com> <497B6270.4000706@gmail.com> Message-ID: <50ed08f40901241103y60836806pffa1feb7a81bd360@mail.gmail.com> On Sat, Jan 24, 2009 at 19:48, bob gailer wrote: > The problem is: there is no way that I know of to add fundamental types to > Python. Also realize that variables are dynamically typed - so any > assignment can create a variable of a new type. That is why a = 0 results in > an int. > > So one must resort, as others have mentioned, to classes. > Yes, that's what I understood from previous answers. > Framework (untested): > > class Bit: > _value = 0 # default > def __init__(self, value): > self._value = int(bool(value)) > def getvalue(self): > return self._x > def setvalue(self, value): > self._x = int(bool(value)) > value = property(getvalue, setvalue) > def __add__(self, other): # causes + to act as or > self._value |= other > def __mul__(self, other): # causes * to act as and > self._value &= other > > b = Bit(1) > b.value # returns 1 > b.value = 0 > b.value # returns 0 > b.value + 1 # sets value to 1 > b.value * 0 # sets value to 0 > > Wow! that's great. I'll give it a try. It would be great if "b.value = 0" could be just written as "b = 0" without changing type as a result. What happens if every time I want to update the value of "b", I use "b= Bit(0)" , "b=Bit(1)", and so on?? Is like "building" the object each time? It is less efficient, isn't it? You are going to kill me, but... Maybe the solution is not to re-define what already exists ?boolean data type, but just using it, as suggested at the beginning of the thread... b = bool(1) b = bool(0) After all, it's not so bad... I'll think about it. -- Vicent -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Sat Jan 24 20:43:23 2009 From: bgailer at gmail.com (bob gailer) Date: Sat, 24 Jan 2009 14:43:23 -0500 Subject: [Tutor] Defining "bit" type In-Reply-To: <50ed08f40901241103y60836806pffa1feb7a81bd360@mail.gmail.com> References: <50ed08f40901240625vd1b4980ta751326038adcc6c@mail.gmail.com> <497B6270.4000706@gmail.com> <50ed08f40901241103y60836806pffa1feb7a81bd360@mail.gmail.com> Message-ID: <497B6F5B.70403@gmail.com> An HTML attachment was scrubbed... URL: From Olivier.roger at student.uclouvain.be Sat Jan 24 16:10:04 2009 From: Olivier.roger at student.uclouvain.be (Olivier Roger) Date: Sat, 24 Jan 2009 16:10:04 +0100 Subject: [Tutor] [Web] Using pyCrypto - pyscard Message-ID: Hello, I have a question concerning the use of python to make web application. I don't know if it is possible. I would like to create an applet capable of using the client smardcard (with pyscard/pyCrypto module) reader to read and display the contained data on the page. I already have a simple python application that does it. My question is the following: Is it possible to port it into an applet? Thank in advance, Olivier -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Sat Jan 24 22:46:37 2009 From: kent37 at tds.net (Kent Johnson) Date: Sat, 24 Jan 2009 16:46:37 -0500 Subject: [Tutor] Fwd: Defining "bit" type In-Reply-To: <50ed08f40901240736h1cae2836v815478b29412d067@mail.gmail.com> References: <50ed08f40901240625vd1b4980ta751326038adcc6c@mail.gmail.com> <35253ca50901240631t40ba5d9dhaa5b0990d75e0f03@mail.gmail.com> <50ed08f40901240642w54805b3r9f3babcd5929abfc@mail.gmail.com> <50ed08f40901240736h1cae2836v815478b29412d067@mail.gmail.com> Message-ID: <1c2a2c590901241346k24fed95dr654a4bcd2983050d@mail.gmail.com> On Sat, Jan 24, 2009 at 10:36 AM, Vicent wrote: > But this is not nice: > >>>> type(a) > >>>> a > True >>>> a = 0 >>>> type(a) > > > > I mean, being "a" a boolean variable, it works as if it was a number, but > every time I want to update the value of "a", I must put "False" for 0 and > "True" for 1, or it will change into an integer variable. > > So, maybe I can adapt the definition of "bool" type, I don't know... Anyway, > I want to manage 0's and 1's, not "Falses" and "Trues". You have an incorrect idea about how variables and assignment work in Python. Type is associated with a value, not a name. You might want to read this: http://personalpages.tds.net/~kent37/kk/00012.html and this classic: http://effbot.org/zone/python-objects.htm Kent From kent37 at tds.net Sat Jan 24 22:49:07 2009 From: kent37 at tds.net (Kent Johnson) Date: Sat, 24 Jan 2009 16:49:07 -0500 Subject: [Tutor] [Web] Using pyCrypto - pyscard In-Reply-To: References: Message-ID: <1c2a2c590901241349v7a0b8b71hc43580a1bc24cda1@mail.gmail.com> On Sat, Jan 24, 2009 at 10:10 AM, Olivier Roger wrote: > Hello, > > I have a question concerning the use of python to make web application. > I don't know if it is possible. I would like to create an applet capable of > using the client smardcard (with pyscard/pyCrypto module) reader to read and > display the contained data on the page. > > I already have a simple python application that does it. My question is the > following: Is it possible to port it into an applet Presuming that by 'applet' you mean something that runs client-side in a web browser, your options for doing this with Python are very limited. - You can use IronPython within MS Silverlight - There may be ways to do this with Firefox and IE but they are obscure Kent From lie.1296 at gmail.com Sat Jan 24 23:23:26 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Sat, 24 Jan 2009 22:23:26 +0000 (UTC) Subject: [Tutor] Finding the End of a Def? References: <497AB441.1050102@sbcglobal.net> Message-ID: On Sat, 24 Jan 2009 11:43:00 +0000, Alan Gauld wrote: > > But I'm surprised there are no block movement commands given Scintilla's > primary goal of supporting programmers > I guess because block level movement is ambiguous in any programming language supporting nested class/function definition? From sierra_mtnview at sbcglobal.net Sat Jan 24 23:50:00 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sat, 24 Jan 2009 14:50:00 -0800 Subject: [Tutor] Finding the End of a Def? In-Reply-To: References: <497AB441.1050102@sbcglobal.net> Message-ID: <497B9B18.9060509@sbcglobal.net> An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sun Jan 25 00:09:11 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 24 Jan 2009 23:09:11 -0000 Subject: [Tutor] [Web] Using pyCrypto - pyscard References: Message-ID: "Olivier Roger" wrote > I have a question concerning the use of python to make web > application. > I don't know if it is possible. I would like to create an applet > capable of > using the client smardcard (with pyscard/pyCrypto module) reader to > read and > display the contained data on the page. > > I already have a simple python application that does it. My question > is the > following: Is it possible to port it into an applet? Let me check my understanding... This existing application runs on the same computer as the card reader, right? Presumably it is doing some kind of low level OS calls to read the hardware? If that's the case you probably couldn't use an applet even if you could write it since the applet wouldn't normally be able to access the local PCs hardware - way too much security risk! If on the other hand the card reader is on a server then you don't need an applet you need a web app on the server that calls your existing application then displays the result as a web page. Does that help? -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Sun Jan 25 00:18:05 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 24 Jan 2009 23:18:05 -0000 Subject: [Tutor] Finding the End of a Def? References: <497AB441.1050102@sbcglobal.net> Message-ID: "Lie Ryan" wrote >> But I'm surprised there are no block movement commands given >> Scintilla's >> primary goal of supporting programmers > > I guess because block level movement is ambiguous in any programming > language supporting nested class/function definition? Most programmers editors I've used in the past have had some kind of block commands.vim and emacs both use the end-of-paragraph text mode commands as end of block commands when in code modes. Thats why, as I said earlier, the next-paragraph seems to be the best scintilla can do. Alan G From sierra_mtnview at sbcglobal.net Sun Jan 25 02:45:29 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sat, 24 Jan 2009 17:45:29 -0800 Subject: [Tutor] Finding the End of a Def? In-Reply-To: References: <497AB441.1050102@sbcglobal.net> Message-ID: <497BC439.30803@sbcglobal.net> An HTML attachment was scrubbed... URL: From sidewalking at gmail.com Sun Jan 25 04:43:55 2009 From: sidewalking at gmail.com (Scott Stueben) Date: Sat, 24 Jan 2009 20:43:55 -0700 Subject: [Tutor] Possible to search text file for multiple string values at once? In-Reply-To: <20090124101651.3ff68667@o> References: <99004bb30901231025i6c04e338tcc373aa9469d0550@mail.gmail.com> <1c2a2c590901231052v5f40b318wfef45f0d437ce59a@mail.gmail.com> <99004bb30901231111x2e82b99v82b560e1a4da4a05@mail.gmail.com> <333efb450901231245j71608f48m48f9c6ab16f99398@mail.gmail.com> <20090124101651.3ff68667@o> Message-ID: <99004bb30901241943h14ece66dj60a30028cf22faa5@mail.gmail.com> Excellent ideas...thanks to you all for the input. I will see what I can work out in the next few days and report back. :) Scott On Sat, Jan 24, 2009 at 2:16 AM, spir wrote: > Le Fri, 23 Jan 2009 14:45:32 -0600, > W W a ?crit : > >> On Fri, Jan 23, 2009 at 1:11 PM, Scott Stueben wrote: >> >> > Thanks for the help so far - it seems easy enough. To clarify on the >> > points you have asked me about: >> > >> > A sqlite3 database on my machine would be an excellent idea for >> > personal use. I would like to be able to get a functional script for >> > others on my team to use, so maybe a script or compiled program >> > (Win32) eventually. >> >> >> As long as everyone on your team has python installed (or as long as python >> is installed on the machines they'll be using), a functional script would be >> fairly easy to get rolling. Sqlite is (AFAIK) included with the newer >> versions of python by default. Heck, it's on the version I have installed on >> my phone! (Cingular 8525). Simply zipping up the directory should provide an >> easy enough distribution method. Although, you *could* even write a python >> script that does the "install" for them. >> >> >> > As for output, I would probably like to return the entire lines that >> > contain any search results of those strings. Maybe just output to a >> > results.txt that would have the entire line of each line that contains >> > 'Bob', 'John', 'Joe', 'Jim', and or 'Fred'. >> >> >> The simplest method: >> >> In [5]: f = open('interculturalinterview2.txt', 'r') >> >> In [6]: searchstrings = ('holy', 'hand', 'grenade', 'potato') >> >> In [7]: for line in f.readlines(): >> ...: for word in searchstrings: >> ...: if word in line: >> ...: print line >> ...: >> ...: >> Hana: have a bonfire n candy apples n make potatoes on a car lol! >> >> Wayne: potatoes on a car? >> >> Hana .: yer lol its fun and they taste nicer lol, you wrap a potato in >> tinfoil a >> nd put in on the engine of a car and close the bonnet and have the engine >> run an >> d it cooks it in about 30 mins >> >> Speed isn't as important as ease of use, I suppose, since >> > non-technical people should be able to use it, ideally. > > I guess the easiest for your team would be to: > * let the script write the result lines into a text file > * let the script open the result in an editor (using module called subprocess) > * put a link to your script on the desk > > ### just an example > # write to file > target = open("target.txt",'w') > for line in lines: > target.write(line) > target.close() > > # open in editor > import subprocess > subprocess.call(["gedit","target.txt"]) > print "*** end ***" > > denis > > ------ > la vida e estranya > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- "Shine on me baby, cause it's rainin' in my heart" --Elliott Smith From dineshbvadhia at hotmail.com Sun Jan 25 05:31:44 2009 From: dineshbvadhia at hotmail.com (Dinesh B Vadhia) Date: Sat, 24 Jan 2009 20:31:44 -0800 Subject: [Tutor] Traversing XML Tree with ElementTree Message-ID: I want to traverse an xml file and at each node retain the full path from the parent to that node ie. if we have: this is node b this is node c this is node d this is node e ... then require: this is node b this is node c this is node d this is node e I found this code on the Comp.Lang.Python list but it doesn't retain the full path. import xml.etree.ElementTree as ET tree = ET.parse(xmlfile) def traverse(node): for c in node.getchildren(): print c.tag, ':', c.text traverse(c) root = tree.getroot() traverse(root) Any ideas how to do this? Thanks Dinesh -------------- next part -------------- An HTML attachment was scrubbed... URL: From dineshbvadhia at hotmail.com Sun Jan 25 08:00:00 2009 From: dineshbvadhia at hotmail.com (Dinesh B Vadhia) Date: Sat, 24 Jan 2009 23:00:00 -0800 Subject: [Tutor] Fw: Traversing XML Tree with ElementTree Message-ID: i've got most of this working now so hold off (for now). thanks. dinesh From: Dinesh B Vadhia Sent: Saturday, January 24, 2009 8:31 PM To: tutor at python.org Subject: Traversing XML Tree with ElementTree I want to traverse an xml file and at each node retain the full path from the parent to that node ie. if we have: this is node b this is node c this is node d this is node e ... then require: this is node b this is node c this is node d this is node e I found this code on the Comp.Lang.Python list but it doesn't retain the full path. import xml.etree.ElementTree as ET tree = ET.parse(xmlfile) def traverse(node): for c in node.getchildren(): print c.tag, ':', c.text traverse(c) root = tree.getroot() traverse(root) Any ideas how to do this? Thanks Dinesh -------------- next part -------------- An HTML attachment was scrubbed... URL: From vginer at gmail.com Sun Jan 25 11:13:52 2009 From: vginer at gmail.com (Vicent) Date: Sun, 25 Jan 2009 11:13:52 +0100 Subject: [Tutor] Defining "bit" type In-Reply-To: <497B6F5B.70403@gmail.com> References: <50ed08f40901240625vd1b4980ta751326038adcc6c@mail.gmail.com> <497B6270.4000706@gmail.com> <50ed08f40901241103y60836806pffa1feb7a81bd360@mail.gmail.com> <497B6F5B.70403@gmail.com> Message-ID: <50ed08f40901250213u53212dbdw3704a9dc7109502c@mail.gmail.com> On Sat, Jan 24, 2009 at 20:43, bob gailer wrote: > Vicent wrote: > > > It would be great if "b.value = 0" could be just written as "b = 0" > without changing type as a result. > > > Assignment in effect does a del b, then creates a new b based on the > expression. There is no way in Python right now to do that. The closest I > can come is to support the syntax b(0) and b(1) to emulate assignment. That > would require that I add to the Bit class: > > def __call__(self, value): > self.value = value > OK, I think I understand... > > > What happens if every time I want to update the value of "b", I use "b= > Bit(0)" , "b=Bit(1)", and so on?? Is like "building" the object each time? > It is less efficient, isn't it? > > > Yes and yes. > Ok... > > > You are going to kill me > > > Are you saying that to prepare your self for a negative response from me, > or in hopes that I would not have such? I view everything we do here as > incremental improvement. I am glad you are thinking of alternatives. > Thank you... > > > , but... Maybe the solution is not to re-define what already exists > ?boolean data type, but just using it, as suggested at the beginning of the > thread... > > b = bool(1) > b = bool(0) > > After all, it's not so bad... > > > It really depends on your goals for having this new type. > I was thinking about this during this night (sometimes, it is near to sleep or when having a shower when new ideas come out!, isn't it?). Maybe, all I need to do is this: >>> bit = bool And then, I can do this: >>> b = bit(0) I mean, just using "bit" as an "alias" for "bool" [, and forget about any new class or whatever]. In fact, type for "b" is "bool": >>> type(b) On Sat, Jan 24, 2009 at 22:46, Kent Johnson wrote: > > > You have an incorrect idea about how variables and assignment work in > Python. Type is associated with a value, not a name. You might want to > read this: > http://personalpages.tds.net/~kent37/kk/00012.html > > and this classic: > http://effbot.org/zone/python-objects.htm > > Yes, I was a bit confused, although I've already read those links you provide (I think you gave them to me in another recent post). They are very good explanations. I think I hadn't get that "0" is always integer, but now I get it. If I want to make it boolean (bit-like), it should be referred as "bool(0)". [It is like that, isn't it????] -- Vicent -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Sun Jan 25 14:03:54 2009 From: kent37 at tds.net (Kent Johnson) Date: Sun, 25 Jan 2009 08:03:54 -0500 Subject: [Tutor] Defining "bit" type In-Reply-To: <50ed08f40901250213u53212dbdw3704a9dc7109502c@mail.gmail.com> References: <50ed08f40901240625vd1b4980ta751326038adcc6c@mail.gmail.com> <497B6270.4000706@gmail.com> <50ed08f40901241103y60836806pffa1feb7a81bd360@mail.gmail.com> <497B6F5B.70403@gmail.com> <50ed08f40901250213u53212dbdw3704a9dc7109502c@mail.gmail.com> Message-ID: <1c2a2c590901250503w124c800fm2b1587b47dc0c161@mail.gmail.com> On Sun, Jan 25, 2009 at 5:13 AM, Vicent wrote: > I think I hadn't get that "0" is always integer, but now I get it. If I want > to make it boolean (bit-like), it should be referred as "bool(0)". [It is > like that, isn't it????] Yes, though bool(0) is actually creating a new bool object with the same true/false value as the integer 0. It's not the same as a cast in C that just looks at the same value in a new way. You can also do things like In [1]: bool("hello") Out[1]: True In [2]: bool("") Out[2]: False In [3]: bool([1,2,3]) Out[3]: True In [4]: bool([]) Out[4]: False In each case it is creating a new bool value. Kent From sierra_mtnview at sbcglobal.net Sun Jan 25 14:24:13 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sun, 25 Jan 2009 05:24:13 -0800 Subject: [Tutor] Creating a PDF from http://effbot.org/imagingbook/ Message-ID: <497C67FD.2090903@sbcglobal.net> An HTML attachment was scrubbed... URL: From manoj_kumar2512 at rediffmail.com Sun Jan 25 14:21:02 2009 From: manoj_kumar2512 at rediffmail.com (Manoj kumar) Date: 25 Jan 2009 13:21:02 -0000 Subject: [Tutor] string problem Message-ID: <20090125132102.64930.qmail@f5mail-237-242.rediffmail.com> ? i was trying to write a script for a port scanner. i was able to get a working scanner which can scan a given host. now i want to upgrade it to scan for a given range of ip address. for example: starting ip:166.43.234.43 last ip:234.23.45.123 no problem i am facing is that i am really NOT able to split ip addresses into nodes like: 166.43.234.43 would be like '166','43','234','43' help me please. thanks in advance MANOJ SHEOKAND (+919728523528) "some day there won't be a song in ur heart, sing anyway" -------------- next part -------------- An HTML attachment was scrubbed... URL: From eugene.perederey at gmail.com Sun Jan 25 14:57:35 2009 From: eugene.perederey at gmail.com (Eugene Perederey) Date: Sun, 25 Jan 2009 16:57:35 +0300 Subject: [Tutor] string problem In-Reply-To: <20090125132102.64930.qmail@f5mail-237-242.rediffmail.com> References: <20090125132102.64930.qmail@f5mail-237-242.rediffmail.com> Message-ID: <35253ca50901250557u3b9164f2g2b0c7ccbc7947932@mail.gmail.com> What's a problem to split the string like >>>'166.43.234.43'.split('.') Maybe I misunderstand you problem... 2009/1/25 Manoj kumar : > > i was trying to write a script for a port scanner. i was able to get a > working scanner which can scan a given host. > > now i want to upgrade it to scan for a given range of ip address. > for example: > starting ip:166.43.234.43 > last ip:234.23.45.123 > > no problem i am facing is that i am really NOT able to split ip addresses > into nodes like: > 166.43.234.43 would be like '166','43','234','43' > > > help me please. > > thanks in advance > > MANOJ SHEOKAND > > (+919728523528) > > "some day there won't be a song in ur heart, sing anyway" > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Sincerely yours, Eugene Perederey From sierra_mtnview at sbcglobal.net Sun Jan 25 16:31:36 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sun, 25 Jan 2009 07:31:36 -0800 Subject: [Tutor] Find a Word in *.py (Win XP) Message-ID: <497C85D8.8010702@sbcglobal.net> An HTML attachment was scrubbed... URL: From kent37 at tds.net Sun Jan 25 17:24:25 2009 From: kent37 at tds.net (Kent Johnson) Date: Sun, 25 Jan 2009 11:24:25 -0500 Subject: [Tutor] Find a Word in *.py (Win XP) In-Reply-To: <497C85D8.8010702@sbcglobal.net> References: <497C85D8.8010702@sbcglobal.net> Message-ID: <1c2a2c590901250824r2b295608s4c466c5977350a21@mail.gmail.com> On Sun, Jan 25, 2009 at 10:31 AM, Wayne Watson wrote: > If I open a folder in Win XP with a number of py files, and when I search > for *.py for the word angle, I get zippo. However, the word exists in one of > the py files. Probably the py files are scrambled in some way. How > nevertheless do I find the file. BTW, I know where it is, but I'm wondering > why this doesn't work. How are you searching? .py files are plain text. Kent From bermanrl at cfl.rr.com Sun Jan 25 18:22:43 2009 From: bermanrl at cfl.rr.com (Robert Berman) Date: Sun, 25 Jan 2009 12:22:43 -0500 Subject: [Tutor] No module named 'module name' Message-ID: <497C9FE3.4070901@cfl.rr.com> In the following code: import sys from PyQt4 import QtCore, QtGui from testwin import Ui_TestWindow class StartQT4(QtGui.QMainWindow): def __init__(self, parent = None): QtGui.QWidget.__init__(self, parent) self.ui = Ui_TestWindow() self.ui.setupUi(self) if __name__ == "__main__": app = QtGui.QApplication(sys.argv) myapp = StartQT4() myapp.show() sys.exit(app.exec_()) I receive the following error message: Import error: No module named testwin. If I use ipython and do the from statement, it works just fine. I think it may have something to do with a path value although I hate to even bring that up as I am using Linux Ubuntu 8.10 and cannot remember a "path" error since working under Windows XP. The editor in use is Wing IDE Personal version. I am building my form(s) using QT4 and testwin.py is built with pyuic4. I have sen some reference to something called "Python Path", but it seems to be referenced most often by Windows users so I am now totally confused. Would a few of you who understand these relationships far better than I please elaborate as to what I might be doing wrong. Thanks for the assistance. Robert Berman From alan.gauld at btinternet.com Sun Jan 25 19:04:00 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 25 Jan 2009 18:04:00 -0000 Subject: [Tutor] No module named 'module name' References: <497C9FE3.4070901@cfl.rr.com> Message-ID: "Robert Berman" wrote > > from testwin import Ui_TestWindow > > I receive the following error message: Import error: No module named > testwin. > If I use ipython and do the from statement, it works just fine. I > think it may have something to do with a path value I think you are right! Try putting import sys print sys.path At the top of the file then run it from both IPython and Wing. Also try running the file from an OS prompt rather than from inside the IDE. > I have seen some reference to something called "Python Path", but it > seems to be referenced most often by Windows users Nope, PYTHONPATH applies to any OS. You need to use it if you have any modules in folders other than the default locations used by Python. I think the preferred place to set PYTHONPATH is in your .login script but if I'm wrong I'm sure a more regular *nix user will say so :-) HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From bermanrl at cfl.rr.com Sun Jan 25 21:14:59 2009 From: bermanrl at cfl.rr.com (Robert Berman) Date: Sun, 25 Jan 2009 15:14:59 -0500 Subject: [Tutor] No module named 'module name' In-Reply-To: References: <497C9FE3.4070901@cfl.rr.com> Message-ID: <497CC843.2030606@cfl.rr.com> Alan, After you gave me the blatant hint to look at the system path; the problem became obvious. Wing assigns the path of the project file to one of the paths revealed by sys.path. I, of course, had put the project file in the folder above my working folder. Another learning experience. Thank you for the key that unlocked the obvious. Robert Alan Gauld wrote: > "Robert Berman" wrote >> >> from testwin import Ui_TestWindow >> >> I receive the following error message: Import error: No module named >> testwin. > >> If I use ipython and do the from statement, it works just fine. I >> think it may have something to do with a path value > > I think you are right! > > Try putting > > import sys > print sys.path > > At the top of the file then run it from both IPython and Wing. > > Also try running the file from an OS prompt rather than > from inside the IDE. > >> I have seen some reference to something called "Python Path", but it >> seems to be referenced most often by Windows users > > Nope, PYTHONPATH applies to any OS. > You need to use it if you have any modules in folders other than > the default locations used by Python. I think the preferred place > to set PYTHONPATH is in your .login script but if I'm wrong I'm > sure a more regular *nix user will say so :-) > > HTH, > From denis.spir at free.fr Sun Jan 25 22:21:00 2009 From: denis.spir at free.fr (spir) Date: Sun, 25 Jan 2009 22:21:00 +0100 Subject: [Tutor] No module named 'module name' -- sub-folders? In-Reply-To: References: <497C9FE3.4070901@cfl.rr.com> Message-ID: <20090125222100.69afd00e@o> Le Sun, 25 Jan 2009 18:04:00 -0000, "Alan Gauld" a ?crit : > Nope, PYTHONPATH applies to any OS. > You need to use it if you have any modules in folders other than > the default locations used by Python. I think the preferred place > to set PYTHONPATH is in your .login script but if I'm wrong I'm > sure a more regular *nix user will say so :-) > > HTH, I take the opportunity to ask a question about module lookup. I was *sure* that, when searching for a module, python automatically explores sub-folders (both of the current folder and of the pathes listed in PYTHONPATH). But this does not work by me (anymore): from ospyp.py, located in /home/spir/prog/ospyp, I cannot simply import wikilang which is in /home/spir/prog/ospyp/samples ??? Denis ------ la vida e estranya From kent37 at tds.net Mon Jan 26 00:10:46 2009 From: kent37 at tds.net (Kent Johnson) Date: Sun, 25 Jan 2009 18:10:46 -0500 Subject: [Tutor] No module named 'module name' -- sub-folders? In-Reply-To: <20090125222100.69afd00e@o> References: <497C9FE3.4070901@cfl.rr.com> <20090125222100.69afd00e@o> Message-ID: <1c2a2c590901251510p9180e0cw3a56774c0f58b66d@mail.gmail.com> On Sun, Jan 25, 2009 at 4:21 PM, spir wrote: > I take the opportunity to ask a question about module lookup. I was *sure* that, when searching for a module, python automatically explores sub-folders (both of the current folder and of the pathes listed in PYTHONPATH). But this does not work by me (anymore): > from ospyp.py, located in /home/spir/prog/ospyp, I cannot simply import wikilang which is in /home/spir/prog/ospyp/samples No, Python does not automatically search subfolders of directories in PYTHONPATH. It will search package folders and subfolders if you ask it to. For example if your samples folder includes a file __init__.py (marking it as a package) then you can import samples.wikilang. Kent From sierra_mtnview at sbcglobal.net Mon Jan 26 00:12:11 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sun, 25 Jan 2009 15:12:11 -0800 Subject: [Tutor] To Arc (PIL) or Not to Arc (Tkinter) Message-ID: <497CF1CB.7090908@sbcglobal.net> An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Jan 26 00:33:36 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 25 Jan 2009 23:33:36 -0000 Subject: [Tutor] To Arc (PIL) or Not to Arc (Tkinter) References: <497CF1CB.7090908@sbcglobal.net> Message-ID: "Wayne Watson" wrote > When I noticed that both have an arc method that gave me pause. > Apparently, PIL provides IP (image processing: ...while Tkinter > provides widgets. In PIL, arc allows one to draw on images but > doesn't allow one to display them. The display and presentation > is the function of Tkinter, and can draw on the widget canvas > where an image, from PIL, might be placed. Comments? Yes you have understood pretty well. PIL provides more sophisticated IP than Tkinter can do on its own. For simple images such as charts/graphs you might decide to draw them direct in Tkinter without using PIL. For that reason Tkinter canvas allows you to draw shapes, such as arc, directly on the canvas. For more sophisticated use (such as complex charts) you might use a plotting library to create the image and then display the image in Tkinter. Or to manipulate sophisticated graphics (like photos) you would probably use PIL or ImageMagik or somesuch. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From donnaibarra at gmail.com Mon Jan 26 00:11:50 2009 From: donnaibarra at gmail.com (Donna Ibarra) Date: Sun, 25 Jan 2009 15:11:50 -0800 Subject: [Tutor] Python Program: Newton's Method Message-ID: <85d27a00901251511k40d709d2ie0bf87b04ce59b8c@mail.gmail.com> Hello, I need to write a program that implements Newton's method ((guess + x/guess) / (2)). The program should prompt the user for the value to find the squareroot of (x) and the number of times to improve the guess. Starting with a guess value of x/2, your program should loop the specified number of times applying newton's method and report the final value of guess. You should also subtract your estimate from the value of math.sqrt() to show how close it is. So far.. I got: Help with Code Tags (Toggle Plain Text ) import math def main(): value, guess = input("Please enter the value, and the number of times to loop: ") for i in range(guess): top = guess + value / guess final_value = float(top) / 2 close = final_value - math.sqrt(x) close_two = math.sqrt(x) print "The guess is", final_value, "which is", close, "away from", close_two main() Could you please help me out? Thanks - Donna -------------- next part -------------- An HTML attachment was scrubbed... URL: From john at fouhy.net Mon Jan 26 03:36:07 2009 From: john at fouhy.net (John Fouhy) Date: Mon, 26 Jan 2009 15:36:07 +1300 Subject: [Tutor] Python Program: Newton's Method In-Reply-To: <85d27a00901251511k40d709d2ie0bf87b04ce59b8c@mail.gmail.com> References: <85d27a00901251511k40d709d2ie0bf87b04ce59b8c@mail.gmail.com> Message-ID: <5e58f2e40901251836s1445cca1je274be599a7c1f50@mail.gmail.com> 2009/1/26 Donna Ibarra : > I need to write a program that implements Newton's method [...] What problems are you having? -- John. From kent37 at tds.net Mon Jan 26 04:13:08 2009 From: kent37 at tds.net (Kent Johnson) Date: Sun, 25 Jan 2009 22:13:08 -0500 Subject: [Tutor] Python Program: Newton's Method In-Reply-To: <85d27a00901251511k40d709d2ie0bf87b04ce59b8c@mail.gmail.com> References: <85d27a00901251511k40d709d2ie0bf87b04ce59b8c@mail.gmail.com> Message-ID: <1c2a2c590901251913s1ccf443ey6d3f7b7859541dfe@mail.gmail.com> On Sun, Jan 25, 2009 at 6:11 PM, Donna Ibarra wrote: > Hello, > > I need to write a program that implements Newton's method ((guess + x/guess) > / (2)). The program should prompt the user for the value to find the > squareroot of (x) and the number of times to improve the guess. Starting > with a guess value of x/2, your program should loop the specified number of > times applying newton's method and report the final value of guess. You > should also subtract your estimate from the value of math.sqrt() to show how > close it is. > > So far.. I got: > > Help with Code Tags > (Toggle Plain Text) > > import math > > > def main(): > value, guess = input("Please enter the value, and the number of times to > loop: ") > > for i in range(guess): > top = guess + value / guess > final_value = float(top) / 2 > > > close = final_value - math.sqrt(x) > close_two = math.sqrt(x) > > print "The guess is", final_value, "which is", close, "away from", > close_two > > main() > > Could you please help me out? Thanks This looks like homework, so we are limited in how we can help. Some hints: What does the variable guess represent in the input line? How about in the for loop? What does final_value represent? why do you divide it by 2? Kent From eric at ericabrahamsen.net Mon Jan 26 05:23:21 2009 From: eric at ericabrahamsen.net (Eric Abrahamsen) Date: Mon, 26 Jan 2009 12:23:21 +0800 Subject: [Tutor] import confusion Message-ID: <38935000-792F-4F0D-A10E-23DC940C9EBB@ericabrahamsen.net> Hi there, I'm trying to understand how module imports work, and am seeing some behavior I don't understand: >>> import django >>> from django import forms >>> from forms import DecimalField Traceback (most recent call last): File "", line 1, in ImportError: No module named forms >>> import django.contrib >>> from django.contrib import auth >>> from auth import ImproperlyConfigured Traceback (most recent call last): File "", line 1, in ImportError: No module named auth So what I'm seeing is that you can import X, then from X import Y, but only if Y is another module and not an object. The import chains above work until I try to import a class definition. Can someone explain what it is about module imports that makes it work this way? And why the unhelpful error message? Thanks! Eric From sierra_mtnview at sbcglobal.net Mon Jan 26 05:28:23 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sun, 25 Jan 2009 20:28:23 -0800 Subject: [Tutor] How Do I Put an Image on a Canvas and Display it? Message-ID: <497D3BE7.1030701@sbcglobal.net> An HTML attachment was scrubbed... URL: From marc.tompkins at gmail.com Mon Jan 26 06:31:53 2009 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Sun, 25 Jan 2009 21:31:53 -0800 Subject: [Tutor] import confusion In-Reply-To: <38935000-792F-4F0D-A10E-23DC940C9EBB@ericabrahamsen.net> References: <38935000-792F-4F0D-A10E-23DC940C9EBB@ericabrahamsen.net> Message-ID: <40af687b0901252131k68a8a115hc91b6abc749a1b6d@mail.gmail.com> On Sun, Jan 25, 2009 at 8:23 PM, Eric Abrahamsen wrote: > Hi there, > > I'm trying to understand how module imports work, and am seeing some > behavior I don't understand: > > >>> import django > >>> from django import forms > >>> from forms import DecimalField > Traceback (most recent call last): > File "", line 1, in > ImportError: No module named forms > >>> import django.contrib > >>> from django.contrib import auth > >>> from auth import ImproperlyConfigured > Traceback (most recent call last): > File "", line 1, in > ImportError: No module named auth > > > So what I'm seeing is that you can import X, then from X import Y, but only > if Y is another module and not an object. The import chains above work until > I try to import a class definition. Can someone explain what it is about > module imports that makes it work this way? And why the unhelpful error > message? > Someone will no doubt phrase this better, but let's take a shot... 1) You don't need to import django before you import forms; it's redundant. 2) You DO need to give Python enough information (i.e. the full name path) to find the most-specific thing you're trying to import. 2) "import django" makes the entire django package and all sub-modules available. You could then refer to django.forms.DecimalField and django.contrib.auth.ImproperlyConfigured (for example) in your program, no further imports needed. 3) "from django import forms" ONLY imports django.forms, and makes it available as "forms" (i.e. no need to refer to django.forms) - but not for further imports; for those you still need to specify the full name. 4) To import ONLY DecimalField or ImproperlyConfigured, you would do the following: from django.forms import DecimalField from django.contrib.auth import ImproperlConfigured 5) You can also create aliases: from django.forms import DecimalField as decField from django.contrib.auth import ImproperlyConfigured as Oopsie Hope that helps... -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From marc.tompkins at gmail.com Mon Jan 26 07:36:20 2009 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Sun, 25 Jan 2009 22:36:20 -0800 Subject: [Tutor] import confusion In-Reply-To: References: <38935000-792F-4F0D-A10E-23DC940C9EBB@ericabrahamsen.net> <40af687b0901252131k68a8a115hc91b6abc749a1b6d@mail.gmail.com> Message-ID: <40af687b0901252236v629b75day2873dc1818ee10f3@mail.gmail.com> On Sun, Jan 25, 2009 at 9:45 PM, Eric Abrahamsen wrote: > > Thanks for the break-down! I've got a fairly good handle on how to make all > this work correctly, I guess what I'm after is an understand of why the > above produces an error. What's going on in the system's module accounting > that makes one thing work and the other fail? > Don't know about the internals, but here's a passage from the 2.61 docs ( http://docs.python.org/tutorial/modules.html): > Note that when using from package import item, the item can be either a > submodule (or subpackage) of the package, or some other name defined in the > package, like a function, class or variable. The import statement first > tests whether the item is defined in the package; if not, it assumes it is a > module and attempts to load it. If it fails to find it, an ImportErrorexception is raised. > > Contrarily, when using syntax like import item.subitem.subsubitem, each > item except for the last must be a package; the last item can be a module or > a package but can't be a class or function or variable defined in the > previous item. > > -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From pine508 at hotmail.com Mon Jan 26 08:23:05 2009 From: pine508 at hotmail.com (Che M) Date: Mon, 26 Jan 2009 02:23:05 -0500 Subject: [Tutor] clipboard questions Message-ID: I'm curious about how to interact with the contents of the clipboard effectively and have a couple of questions... 1) Is there one cross-platform way to read the clipboard, or does one have to have a different way to do it for Win, Mac, and Linux? (I have seen some ways with the win32clipboard module, and so thought maybe one has to do a similar thing for each platform). 2) I would like to be able to copy formatting (bold, italics, bullets, hyperlinks, etc.) into the clipboard and then have Python have access to the text content and its formatting in such a way that it could be pasted somewhere within a Python app with formatting preserved. How can that be done? Thanks for any suggestions or thoughts. Che _________________________________________________________________ Windows Live? Hotmail??more than just e-mail. http://windowslive.com/howitworks?ocid=TXT_TAGLM_WL_t2_hm_justgotbetter_howitworks_012009 From alan.gauld at btinternet.com Mon Jan 26 10:53:45 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 26 Jan 2009 09:53:45 -0000 Subject: [Tutor] How Do I Put an Image on a Canvas and Display it? References: <497D3BE7.1030701@sbcglobal.net> Message-ID: "Wayne Watson" wrote I'm not familiar with the Image and ImageDraw modules but what I think is happening is... > import Image, ImageDraw > from Tkinter import * By doing this you have hidden Image because Tkinter has its own Image class. > im = Image.open("wagon.tif") This is calling open() on Tkinter.Image You need to either import Image as an alias or use import Tkinter instead of from Tkinter. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld. From alan.gauld at btinternet.com Mon Jan 26 11:13:15 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 26 Jan 2009 10:13:15 -0000 Subject: [Tutor] clipboard questions References: Message-ID: "Che M" wrote > I'm curious about how to interact with the contents of the clipboard > effectively and have a couple of questions... > > 1) Is there one cross-platform way to read the clipboard, In a generic sense no. But if the cut n paste is within a single application then yes, you can use a cross platform GUI framework. That will work across OS versions. Where it gets messy is if you want to paste from the generic OS clipboard into your application and different frameworks vary in how well they handle that. > 2) I would like to be able to copy formatting (bold, italics, > bullets, > hyperlinks, etc.) into the clipboard and then have Python have > access > to the text content and its formatting Thats even more tricky because not all clipboards will capture formatting codes in their original form. Some require special commands/events. It may also depend on the application that you are copying from. For example consider a MacOS web browser. Do you want to copy the underlying HTML formatting tags? Or the display PDF codes which are used by the Aqua graphics system used by the browser to actually display the output? In other words your display mechanism will need to be able to display whatever the clipboard passes. And your applucatin will need to be able to extract the data from it (eg parse PDF or RTF etc) Cut n paste between apps is non trivial even on a single OS and within a single framework. But if you have mixed environments it can get really messy in my experience! If it's all within a single framework then its not so bad. Alan G From denis.spir at free.fr Mon Jan 26 11:44:59 2009 From: denis.spir at free.fr (spir) Date: Mon, 26 Jan 2009 11:44:59 +0100 Subject: [Tutor] clipboard questions In-Reply-To: References: Message-ID: <20090126114459.132dd14c@o> Le Mon, 26 Jan 2009 02:23:05 -0500, Che M a ?crit : > > I'm curious about how to interact with the contents of the clipboard > effectively and have a couple of questions... > > 1) Is there one cross-platform way to read the clipboard, or does one > have to have a different way to do it for Win, Mac, and Linux? (I have > seen some ways with the win32clipboard module, and so thought maybe one > has to do a similar thing for each platform). > > 2) I would like to be able to copy formatting (bold, italics, bullets, > hyperlinks, etc.) into the clipboard and then have Python have access > to the text content and its formatting in such a way that it could be > pasted somewhere within a Python app with formatting preserved. How > can that be done? The way content text will actually be rendered is specified by additional information. There are tons of dedicated languages for that, usually "markup" languages. Some are plain text (and usually open), some binary (and usually proprietary). When you copy a snippet of text from formatted document, depending on the kind of format, on the source application, and even on the copying program, you may or may not copy the formatting together with the content. This will work e.g. for plain text formatting copied from a plain text editor, such as a wikitext copied from its edition frame. Now, this will not give you a styled text. The text will show properly rendered only if the target application (say, your own program) is able to parse, interpret and process the formatting information supplied together with the content. Meaning it must 'know' the markup language. Or, you must use a translation tool from the source markup to another that is known by the target application. Also note that most markup languages such as the various wikilang dialects & the various versions of x/html do not (or rather should not) actually describe the *aspect* of the rendered text, instead they specify the kind, class, meaning of portions of text, such as "this is title" or "this is an important note", "this a book reference". Then, at rendering time, the engine will look for a description of each of these text style classes, which is most often specified in separate style sheets, e.g. CSS files. There are several relevant reasons for that. Denis > Thanks for any suggestions or thoughts. > Che ------ la vida e estranya From kent37 at tds.net Mon Jan 26 12:42:20 2009 From: kent37 at tds.net (Kent Johnson) Date: Mon, 26 Jan 2009 06:42:20 -0500 Subject: [Tutor] import confusion In-Reply-To: <40af687b0901252131k68a8a115hc91b6abc749a1b6d@mail.gmail.com> References: <38935000-792F-4F0D-A10E-23DC940C9EBB@ericabrahamsen.net> <40af687b0901252131k68a8a115hc91b6abc749a1b6d@mail.gmail.com> Message-ID: <1c2a2c590901260342w403b4d53g14525f4e60089cf9@mail.gmail.com> On Mon, Jan 26, 2009 at 12:31 AM, Marc Tompkins wrote: > Someone will no doubt phrase this better, but let's take a shot... > > 2) "import django" makes the entire django package and all sub-modules > available. You could then refer to django.forms.DecimalField and > django.contrib.auth.ImproperlyConfigured (for example) in your program, no > further imports needed. No; in general, import x does not make module x.y available for use, you have to explicitly import x.y In [1]: import django In [2]: django.forms --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) /Users/kent/ in () AttributeError: 'module' object has no attribute 'forms' There are some exceptions that confuse the issue, for example you can import os and then use os.path.whatever. Other than that you are correct. Kent From timomlists at gmail.com Mon Jan 26 14:58:43 2009 From: timomlists at gmail.com (Timo) Date: Mon, 26 Jan 2009 14:58:43 +0100 Subject: [Tutor] Sort of database & "family tree" question Message-ID: <497DC193.40301@gmail.com> Hello, I'm writing an application that stores people with some info. I'm doing this with ConfigParser and it works, but currently (for testing), there are only 10 persons in it. What if I add, let's say, about 500-600 or even more? Is this still a good choice? So my entry's look like this (more or less ;)): [person1] firstName = foo lastName = bar father = person2 mother = person3 Now, I want to make a family tree out of this, something that looks like the following scheme (hope the formating will be kept): For person "foo bar", on his father-side, and mother-side the same. | father | father--< | | mother person2--< | | father | mother--< | mother Greets, Timo From a.t.hofkamp at tue.nl Mon Jan 26 15:36:12 2009 From: a.t.hofkamp at tue.nl (A.T.Hofkamp) Date: Mon, 26 Jan 2009 15:36:12 +0100 Subject: [Tutor] Sort of database & "family tree" question In-Reply-To: <497DC193.40301@gmail.com> References: <497DC193.40301@gmail.com> Message-ID: <497DCA5C.8070800@tue.nl> Timo wrote: > Hello, > > I'm writing an application that stores people with some info. I'm doing > this with ConfigParser and it works, but currently (for testing), there > are only 10 persons in it. What if I add, let's say, about 500-600 or > even more? Is this still a good choice? Last week, I created a 31MB ConfigParser file with 1 section and 7 or 8 key/value pairs (the values were a bit long-ish). Constructing it and writing it to disk took about 50 seconds. I don't expect that 600 people will give you that much data. Before you start optimizing the data format, I'd suggest you first check whether you have a problem in the first place. Generate 1000 or 2000 (or 5000 or more!) entries with a small program, try loading the file, and see what happens. > So my entry's look like this (more or less ;)): > [person1] > firstName = foo > lastName = bar > father = person2 > mother = person3 Imho the BIG advantage of ConfigParser over just about any other format is that it is simple, human-readable, and human-editable. That makes it an ideal format for development. If the relations you want to express in the data fit in the format, then I'd stick with ConfigParser format until I encounter serious problems. If you do encounter serious problems somewhere in the future, you can decide at that moment what to do (you'd make a better informed choice at that time too), and convert your data to a better format then. Sincerely, Albert From denis.spir at free.fr Mon Jan 26 15:54:37 2009 From: denis.spir at free.fr (spir) Date: Mon, 26 Jan 2009 15:54:37 +0100 Subject: [Tutor] Sort of database & "family tree" question In-Reply-To: <497DC193.40301@gmail.com> References: <497DC193.40301@gmail.com> Message-ID: <20090126155437.1d446482@o> Le Mon, 26 Jan 2009 14:58:43 +0100, Timo a ?crit : > Hello, > > I'm writing an application that stores people with some info. I'm doing > this with ConfigParser and it works, but currently (for testing), there > are only 10 persons in it. What if I add, let's say, about 500-600 or > even more? Is this still a good choice? > > So my entry's look like this (more or less ;)): > [person1] > firstName = foo > lastName = bar > father = person2 > mother = person3 > > > Now, I want to make a family tree out of this, something that looks like > the following scheme (hope the formating will be kept): > > For person "foo bar", on his father-side, and mother-side the same. > > | father > | father--< > | | mother > person2--< > | | father > | mother--< > | mother > > Greets, > Timo > You may build a custom type with 2 attributes 'father' & 'mother', plus a name. The list of objects of this type would be directly populated from your data file. "Terminal" persons (the tree's leaves) could have a special value (e.g. None) for their parent attributes, or you could add a special 'leaf' logical attribute to identify them. This type can also implement a proper output using __str__ or __repr__ Not tested: class Person(object): def __init__(self, name, father=None, mother=None): self.name = name self,father,self.mother = father,mother if mother and father: self.is_leaf = True else: self.is_leaf = False def __str__(self): if self.is_leaf: return self.name return "\t\t%s\n%s %s" % (self.name,self.father.name,self.mother.name) [As the "family" structure is recursive, you can also easily define a recursive "treeView" method that recursively calls parent's own treeView.] Denis ------ la vida e estranya From alan.gauld at btinternet.com Mon Jan 26 17:11:34 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 26 Jan 2009 16:11:34 -0000 Subject: [Tutor] Sort of database & "family tree" question References: <497DC193.40301@gmail.com> Message-ID: "Timo" wrote > I'm writing an application that stores people with some info. I'm > doing this with ConfigParser and it works, but currently (for > testing), there are only 10 persons in it. What if I add, let's say, > about 500-600 or even more? Is this still a good choice? I'd be happy with this for up to say 1000 people(arbitrary choice) but for more than that I'd go with shelve. > So my entry's look like this (more or less ;)): > [person1] > firstName = foo > lastName = bar > father = person2 > mother = person3 And I assume you are reading these into a Person class and storing these classes in a persons dictionary? Then to access a father becomes: x = 'Person5' print Persons[x].father.firstName > Now, I want to make a family tree out of this, something that looks > like the following scheme (hope the formating will be kept): > > For person "foo bar", on his father-side, and mother-side the same. > > | father > | father--< > | | mother > person2--< > | | father > | mother--< > | mother > You don't necessarily need to store the tree if you only want to display it. Using the Persons dictionary approach you can easily write a function to traverse the tree by following the links to the top of the tree. (Note this means some people will have to have None as father/mother!) Similarly you can write a function to find everyone whose father or mother is X and so on. For small scale data this is probably easier than building a full tree structure from your config file. Although that's always an option too and for larger datasets would be more performant. But then I'd move to pickle or shelve because you could load/save the whole tree in one go. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From sierra_mtnview at sbcglobal.net Mon Jan 26 17:54:34 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Mon, 26 Jan 2009 08:54:34 -0800 Subject: [Tutor] How Do I Put an Image on a Canvas and Display it? In-Reply-To: References: <497D3BE7.1030701@sbcglobal.net> Message-ID: <497DEACA.9080206@sbcglobal.net> An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Jan 26 18:14:25 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 26 Jan 2009 17:14:25 -0000 Subject: [Tutor] How Do I Put an Image on a Canvas and Display it? References: <497D3BE7.1030701@sbcglobal.net> <497DEACA.9080206@sbcglobal.net> Message-ID: "Wayne Watson" wrote > lIts own image class. Interesting. ImageTk, apparently. No just image. imageTk wouldn't hide your Image. >>> from Tkinter import * >>> Image >>> help(Image) Help on class Image in module Tkinter: class Image | Base class for images. | | Methods defined here: | | __del__(self) | | __getitem__(self, key) | | __init__(self, imgtype, name=None, cnf={}, master=None, **kw) | | __setitem__(self, key, value) | | __str__(self) | | config = configure(self, **kw) | | configure(self, **kw) | Configure the image. | | height(self) | Return the height of the image. | | type(self) | Return the type of the imgage, e.g. "photo" or "bitmap". | | width(self) | Return the width of the image. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From bgailer at gmail.com Mon Jan 26 18:25:14 2009 From: bgailer at gmail.com (bob gailer) Date: Mon, 26 Jan 2009 12:25:14 -0500 Subject: [Tutor] Python Program: Newton's Method In-Reply-To: <85d27a00901251511k40d709d2ie0bf87b04ce59b8c@mail.gmail.com> References: <85d27a00901251511k40d709d2ie0bf87b04ce59b8c@mail.gmail.com> Message-ID: <497DF1FA.6050604@gmail.com> Welcome - this seems to be your first encounter with Python Tutor. It is essential when asking questions like this that you state explicitly what problem you are having. If the program runs and gives unexpected results, tell us that, and show some input, the expected results and the actual results. If the program raises an exception, post the entire traceback. If something else, explain that. -- Bob Gailer Chapel Hill NC 919-636-4239 From sierra_mtnview at sbcglobal.net Mon Jan 26 18:40:11 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Mon, 26 Jan 2009 09:40:11 -0800 Subject: [Tutor] How Do I Put an Image on a Canvas and Display it? In-Reply-To: References: <497D3BE7.1030701@sbcglobal.net> <497DEACA.9080206@sbcglobal.net> Message-ID: <497DF57B.5050004@sbcglobal.net> An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Jan 26 19:00:13 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 26 Jan 2009 18:00:13 -0000 Subject: [Tutor] How Do I Put an Image on a Canvas and Display it? References: <497D3BE7.1030701@sbcglobal.net> <497DEACA.9080206@sbcglobal.net> <497DF57B.5050004@sbcglobal.net> Message-ID: "Wayne Watson" wrote >>>> Image > >>>> help(Image) > Help on class Image in module Image: > ... > This is definitely different than the Tkimage help you showed. > So what's happening? You import your Image module as Image. Then you import all; the names from Tkinter which includes the name Image. Thus the Tkinter Imahe hides the original imported Image. You need to either import Image as im # or some other alias or not use from Tkinter, ie use import Tkinter as T Then use T.Image to refer to the Tkinter Image and im to refer to the imported Image module Its all about controlling namespaces. It is exactly because of these kinds of problems that the from X import * style is considered a bad idea. (In Tkinter it usually works because the names are pretty GUI specific but if, as you are doing, you mix GUI and graphics you get overlaps. > How do I use the two Image classes to navigate between > an image that uses PIL methods and one than uses Tkinter? Just use the appropriate module prefix (or an alias) See the namespaces topic in my tutor for a refresher on namespaces! :-) -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Mon Jan 26 19:05:34 2009 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Mon, 26 Jan 2009 18:05:34 +0000 (GMT) Subject: [Tutor] How Do I Put an Image on a Canvas and Display it? References: <497D3BE7.1030701@sbcglobal.net> <497DEACA.9080206@sbcglobal.net> <497DF57B.5050004@sbcglobal.net> Message-ID: <566057.76018.qm@web86710.mail.ird.yahoo.com> > how do I clear the keyboard imports? I'm not sure what you mean by keyboard imports? Do you mean how to restore an interactive session? If so, then in IDLE you can use: Shell->Restart shell. I don't know how to do that in any of the other IDEs... You can of course del() any name, including modules... Alan G. -------------- next part -------------- An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Mon Jan 26 19:20:28 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Mon, 26 Jan 2009 10:20:28 -0800 Subject: [Tutor] What Centroid Algorithm Is This? Message-ID: <497DFEEC.7090702@sbcglobal.net> I'm looking at a GUI program that handles meteor images. They leave a trail across the sky. Each video frame (30 fps) provides data on the track, and a centroid is found around each track point. 'm not familiar with the algorithm that does this, but part of it is in the three def stmts below. Maybe someone can hazard a guess? It looks like someone had fun doing this. def MakeSelectsAndWeights( self ): global SELECT1, SELECT2 global WEIGHT1, WEIGHT2 a1 = indices((640,))[0] a2 = a1 + a1 * (701.0-640.0)/702.0 a3 = floor(a2) SELECT1 = a3.astype( intc ) SELECT2 = SELECT1 + 1 WEIGHT2 = a2 - a3 WEIGHT1 = 1.0 - WEIGHT2 One more def Centroid( self, ref, curr, mask ): slopes = indices((488,722),int32) nada = zeros((488,722),uint8) result = where(curr > ref, curr-ref, nada) result = where(result > mask, result-mask, nada) xresult = result * slopes[1] yresult = result * slopes[0] total = sum(ravel(asarray(result,int32))) count = sum(ravel(result > 0)) if total == 0: return 360,240,0,0 xpos = sum(ravel(xresult))/total ypos = sum(ravel(yresult))/total return xpos,ypos,total,count Another def Central( self, ref, curr, mask ): slopes = indices((488,722),int32) nada = zeros((488,722),uint8) result = where(curr > ref, curr-ref, nada) result = where(result > mask, result-mask, nada) total = sum(ravel(asarray(result,int32))) count = sum(ravel(result > 0)) if total == 0: print "Count: %d Total: %d" % (count,total) return 361,244,0,0 blur = result[0:-2, 0:-2] blur += result[0:-2, 1:-1] blur += result[0:-2, 2: ] blur += result[1:-1, 0:-2] blur += result[1:-1, 1:-1] blur += result[1:-1, 2: ] blur += result[2: , 0:-2] blur += result[2: , 1:-1] blur += result[2: , 2: ] index = argmax(ravel(blur)) ypos, xpos = divmod(index, 720) xpos += 1 ypos += 1 return xpos,ypos,total,count -- Wayne Watson (Watson Adventures, Prop., Nevada City, CA) (121.01 Deg. W, 39.26 Deg. N) GMT-8 hr std. time) Copper and its alloys have been found effective in hospital sinks, hand rails, beds, ... in significantly reducing bacteria. Estimates are 1/20 people admitted to a hospital become infected, and 1/20 die from the infection. -- NPR Science Friday, 01/16/2009 Web Page: From pine508 at hotmail.com Mon Jan 26 19:23:00 2009 From: pine508 at hotmail.com (Che M) Date: Mon, 26 Jan 2009 13:23:00 -0500 Subject: [Tutor] clipboard questions In-Reply-To: References: Message-ID: ---------------------------------------- > To: tutor at python.org > From: alan.gauld at btinternet.com > Date: Mon, 26 Jan 2009 10:13:15 +0000 > Subject: Re: [Tutor] clipboard questions > > > "Che M" wrote > >> I'm curious about how to interact with the contents of the clipboard >> effectively and have a couple of questions... >> >> 1) Is there one cross-platform way to read the clipboard, > > In a generic sense no. But if the cut n paste is within a single > application then yes, you can use a cross platform GUI framework. > That will work across OS versions. Where it gets messy is if you > want to paste from the generic OS clipboard into your application > and different frameworks vary in how well they handle that. Ahh, yes, that's a problem, because I am interested in using the clipboard for cross-application cut/copy/paste, in fact from/to my apps to any apps on any platform. (One to all; all to one). >> 2) I would like to be able to copy formatting (bold, italics, >> bullets, >> hyperlinks, etc.) into the clipboard and then have Python have >> access >> to the text content and its formatting > > Thats even more tricky because not all clipboards will capture > formatting codes in their original form. Some require special > commands/events. It may also depend on the application that > you are copying from. For example consider a MacOS web > browser. Do you want to copy the underlying HTML formatting > tags? Or the display PDF codes which are used by the Aqua > graphics system used by the browser to actually display the > output? I would like to copy whatever makes the most sense for that context, similarly to how Word can accept a lot of different formatting one could copy from, say, the web, and have it show up in a similar way in the document. Bold, italics, colors, underline, paragraph breaks, bullets, fonts, font-size, alignment, etc., such that it looks the same in both windows. Ideally, images, too. >> In other words your display mechanism will need to be able > to display whatever the clipboard passes. And your applucatin > will need to be able to extract the data from it (eg parse PDF > or RTF etc) Right. OK. > Cut n paste between apps is non trivial even on a single OS > and within a single framework. But if you have mixed environments > it can get really messy in my experience! If it's all within a single > framework then its not so bad. I thought that was probably the reality, and I find that too bad. Easy inter-app communication is a great thing, and I can't help but wish there was some built-in module in Python to help with this (I know, I know, I'm being greedy, there are already so many great modules!) in this most complete way that I am hoping for. There is, e.g., a very nice rich text control in wxPython, but for a few years now it has been bereft of rich text input/output, including cut/copy/paste or open/save, and so it sort of isolates the widget from inter-use with Word or OpenOffice.org, AbiWord, etc., though it can save as HTML. I don't know C++, so I feel I cannot be helpful on adding this (wanted) functionality to the wxWidget itself, but was wondering if, while the actual widget was still waiting for that enhancement (which may or may not ever come, it depends on if someone takes it on), I could maybe take a misguided scratch at making some kind of pure Python go-between that could read out the clipboard and paste it into the richtextctrl and tell the control how to handle the formatting, and then vice-versa. Maybe there is a way to start to do this with HTML at least; Phillip Piper made this code for that purpose, here: http://code.activestate.com/recipes/474121/ Although I don't understand this statement by him, "It would be nice to have this as a data object in wxPython, but that doesn't support the necessary clipboard system calls (RegisterClipboardFormat is essential)." What does he mean by necessary clipboard system calls? Note, this will not of course copy Word formatting codes, so there is no Word --> Python pasting, though he claims there is Python --> Word pasting (of HTML I guess). All this makes me think this is probably beyond what I can reasonably accomplish at this point in my understanding. Thanks for the insight. Che > Alan G > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor _________________________________________________________________ Windows Live?: E-mail. Chat. Share. Get more ways to connect. http://windowslive.com/explore?ocid=TXT_TAGLM_WL_t2_allup_explore_012009 From denis.spir at free.fr Mon Jan 26 19:42:08 2009 From: denis.spir at free.fr (spir) Date: Mon, 26 Jan 2009 19:42:08 +0100 Subject: [Tutor] import imports Message-ID: <20090126194208.47f33aad@o> Hello, Here are some ideas around import. I wish to receive comments and to learn whether they fit python. As I am not a highly experimented programmer, there may be some features or practices I do know know or do not know well. The following ideas are not dependant of each other, but as they all concern the import topic, I thought they could be grouped in a single message anyway. === import transmission === The module attribute __all__ allows defining names to be exported. I always use it for my own modules, and also sometimes define it in external modules, when absent, or adapt it to my needs. Then I'm happy with a secure "import *". I find nevertheless an issue in the common case of import "transmission" from module to module, where all imported names usually have to repeated to export. This is not only ugly, imo, but also unpracticle when a single change in an name export list has to be corrected anywhere else; there can easily be a whole chain or even a 'tree' of imports. I have found a way to deal with that, illustrated in below in a case where module M0 imports M1 and M2, which itself imports M3: *** M3 *** M3_names = [actual list of relevant names] __all__ = ["M3_names"] + M3_names *** M2 *** from M3 import * M2_names = [actual list of relevant /local/ names] + M3_names __all__ = ["M2_names"] + M2_names *** M1 *** M1_names = [actual list of relevant names] __all__ = ["M1_names"] + M1_names *** M0 *** from M1 import * from M2 import * M0_names = [actual list of relevant /local/ names] + M1_names + M2_names __all__ = ["M0_names"] + M0_names This has the advantage to avoid repetition, and allow a change in a name export list with no need of "chain correction". Still, it is only a personal trick. I wonder whether such a practice could be officialised with a kind of __imported_names__ module attribute, then understood and usable by all: from Mx import * __all__ = __imported_names__ + [actual list of relevant /local/ names] === semantics of "import *" === "import *" is not recommanded for good reasons, as a blind and risky practice. Now, when this is done consciously, kwowing that the imported module defines __all__, then the meaning is totally different, if not opposite. As a consequence, I am not happy at all with the present ambiguity. My proposal would be: * Either a slightly different syntactic form, meaning "import all names defined for export". [I would like "import **", for '*' and '**' are associated in other cases and this is all about named things. But this point is no issue.] As an additional advantage, imo important, trying this kind of import from a module that does not define __all__ would raise an exception; for instance: ImportError("Module does not define any name list for export.") * Or change the semantics of "import *" to require __all__ to be defined in the pointed module. Obviously, this raises compatibility issues that may or may not be adressed using warnings (and/or "from __future__ import import" ;-}) in a change path. === package module lookup === There is a similar issue at the package/application level: I do not know of any practice or feature that simply allows changing a filename, a directory name, or the organisation of the package's directory tree, without having then to correct all dependance information inside the concerned modules. I would love a kind of import lookup to be based on the following assumption: "The main/startup module resides in the package's root dir." Then any import lookup would automatically explore local, relative, sub directories. E basta! This would also encourage the good practice of never writing absolute imports -- which is a plague. There are probably many good ways to implement that feature clearly and efficiently. Here is proposed an example that only aims at clarifying the feature's meaning & usefulness; but does not pretend to be good. The purpose is python to know not only which modules exist, or which modules are intended to be imported, but also where actually they are -- or should be. This does not only address import from client code but also intra-module dependances. A file called __init__.py is used to identify a package as package and provide information about it. I propose to add a __dir__ attribute to a package, defined inside its __init__.py, that would hold a module directory (in the sense of 'index'). This could be implemented as a python dict holding a set of name:path bindings -- while actually it is pure information. It would be either a complement, or an alternative, to a package's __all__ attribute that lists the module names: __all__ = ["main", "compute", "userinput"] __dir__ = ["main":"/", "compute":"/tools", "userinput":"/interface/dialogs"] Note that the pathes are *relative*. The main point is that __dir__'s value would be set by python itself when it is absent from __init__.py or when it needs beeing updated after any change in the package's tree. So that the process of module lookup would be as follows (provided I properly understand it): * If current module is not part of a package: usual module lookup is performed. * If it is part of a package which __dir__ is not yet defined, perform a local tree traversal starting from the module's root dir to reference the modules, then write the result into __dir__. Use it to import. * If __dir__ is defined, try and import using it. If import fails (maybe the package's organisation has changed), while the module is referenced by __all__, update __dir__ as necessary. Then, try import again. * When intra-package import finally fails, use PYTHONPATH to try external import, as usual. Obviously, as long as the package's organisation does not change, a single traversal is necessary for all further imports during all further program executions. Intra-package imports may be faster, even if it is not the primary purpose of the proposal. Actually, this seems so simple that python aware editors may even provide this automatically: meaning maintain __dir__ inside an __init__.py file. (This is close to the notion of "project" that many editors provide.) Denis ------ la vida e estranya From sierra_mtnview at sbcglobal.net Mon Jan 26 19:44:35 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Mon, 26 Jan 2009 10:44:35 -0800 Subject: [Tutor] How Do I Put an Image on a Canvas and Display it? In-Reply-To: References: <497D3BE7.1030701@sbcglobal.net> <497DEACA.9080206@sbcglobal.net> <497DF57B.5050004@sbcglobal.net> Message-ID: <497E0493.6030501@sbcglobal.net> An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Mon Jan 26 19:47:18 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Mon, 26 Jan 2009 10:47:18 -0800 Subject: [Tutor] How Do I Put an Image on a Canvas and Display it? In-Reply-To: <566057.76018.qm@web86710.mail.ird.yahoo.com> References: <497D3BE7.1030701@sbcglobal.net> <497DEACA.9080206@sbcglobal.net> <497DF57B.5050004@sbcglobal.net> <566057.76018.qm@web86710.mail.ird.yahoo.com> Message-ID: <497E0536.4090106@sbcglobal.net> An HTML attachment was scrubbed... URL: From eike.welk at gmx.net Mon Jan 26 21:20:55 2009 From: eike.welk at gmx.net (Eike Welk) Date: Mon, 26 Jan 2009 21:20:55 +0100 Subject: [Tutor] What Centroid Algorithm Is This? In-Reply-To: <497DFEEC.7090702@sbcglobal.net> References: <497DFEEC.7090702@sbcglobal.net> Message-ID: <200901262120.55668.eike.welk@gmx.net> On Monday 26 January 2009, Wayne Watson wrote: > the three def stmts below. Maybe someone can hazard a guess? It > looks like someone had fun doing this. First bookmark this webpage. It explains every important function in Numpy: http://www.scipy.org/Numpy_Example_List_With_Doc > def Centroid( self, ref, curr, mask ): ref is maybe dark frame > slopes = indices((488,722),int32) > nada = zeros((488,722),uint8) > Do discrimination; areas that are not covered by the meteor are 0 > result = where(curr > ref, curr-ref, nada) > result = where(result > mask, result-mask, nada) > Compute center of mass http://en.wikipedia.org/wiki/Center_of_mass#Definition Look at first formula - result is m - slopes[1] is x-component of r - slopes[0] is y-component of r > xresult = result * slopes[1] > yresult = result * slopes[0] > total = sum(ravel(asarray(result,int32))) > count = sum(ravel(result > 0)) > if total == 0: > return 360,240,0,0 > > xpos = sum(ravel(xresult))/total > ypos = sum(ravel(yresult))/total > > return xpos,ypos,total,count Example algorithm done in Ipython invoked with ipython --pylab ---- In [20]:weights = array([0,0,1,1,1],'d') #These are three weights of mass 1. #They are located at the positions 2, 3, 4. #The center of gravity is therefore at position 3. In [21]:distances = indices(weights.shape) In [22]:distances Out[22]:array([[0, 1, 2, 3, 4]]) In [23]:moments = weights * distances In [24]:moments Out[24]:array([[ 0., 0., 2., 3., 4.]]) In [25]:tot_weight = sum(weights) In [26]:tot_moment = sum(moments) In [27]:center = tot_moment/tot_weight In [28]:center Out[28]:3.0 #Yay, this is the correct result! Kind regards, Eike. From srilyk at gmail.com Mon Jan 26 21:43:40 2009 From: srilyk at gmail.com (W W) Date: Mon, 26 Jan 2009 14:43:40 -0600 Subject: [Tutor] Tk+Ipython unexpected behavior Message-ID: <333efb450901261243i5e596b59s89208644e62925fc@mail.gmail.com> Hi all, I'm going through "An Introduction to Tkinter" by Fredrik Lundh and came across (what seems to be) some slightly unexpected behavior. I'm editing the python file with my favorite text editor, and using the %run magic function in Ipython to test my program(s). On the second example(pg 4 of the PDF), the frame.quit method is bound to a quit button. When I double click the .py file to run it, it closes when the quit button is pressed. But with Ipython, when the quit button is pressed, it unblocks the Ipython input but doesn't actually quit the window. A call to root.quit() will not close the window, only a call to root.destroy(). I'm not terribly worried about it, but I'm curious if it should be considered a bug or simply "unexpected behavior". -Wayne -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn't. - Primo Levi -------------- next part -------------- An HTML attachment was scrubbed... URL: From tmikk at umn.edu Mon Jan 26 21:55:00 2009 From: tmikk at umn.edu (Tonu Mikk) Date: Mon, 26 Jan 2009 14:55:00 -0600 Subject: [Tutor] using a for loop with feedparser Message-ID: <497E2324.9080906@umn.edu> Hello, I am trying to parse a feed and insert some feed elements into a Django project database. I believe I should be able to use for loop to iterate over the list elements. I am using the Universal Feed parser (http://www.feedparser.org/). I am able to extract items one by one and insert them into a database (code below). As my first try at this, I would like to print the titles of all the feed entries. I tried this import feedparser d = feedparser.parse('http://feeds.delicious.com/v2/rss/utools') for item in d.entries: print item This prints all the feed entries and their values. Any thoughts on how I could just print the titles? Thank you, Tonu Code to save a single feed item into the database: #!/usr/local/bin/python import feedparser import os.path import sys, os import django.contrib.auth sys.path.append ('/home/dmc/projects/django_bookmarks') os.environ['DJANGO_SETTINGS_MODULE']='settings' from django.contrib.auth.models import User from bookmarks.models import * d = feedparser.parse('http://feeds.delicious.com/v2/rss/utools') link1 = Link(url=d.entries[0].link) link1.save() user = User.objects.get(id=1) link = Link.objects.get(id=1) bookmark = Bookmark ( title = d.entries[0].title, desc = d.entries[0].description, link = link, user = user, ) bookmark.save() From tmikk at umn.edu Mon Jan 26 22:22:41 2009 From: tmikk at umn.edu (Tonu Mikk) Date: Mon, 26 Jan 2009 15:22:41 -0600 Subject: [Tutor] using a for loop with feedparser In-Reply-To: <497E2324.9080906@umn.edu> References: <497E2324.9080906@umn.edu> Message-ID: <497E29A1.4040704@umn.edu> Tonu Mikk wrote: > Hello, > > I am trying to parse a feed and insert some feed elements into a > Django project database. I believe I should be able to use for loop > to iterate over the list elements. I am using the Universal Feed > parser (http://www.feedparser.org/). I am able to extract items one > by one and insert them into a database (code below). As my first try > at this, I would like to print the titles of all the feed entries. I > tried this > > import feedparser > d = feedparser.parse('http://feeds.delicious.com/v2/rss/utools') > for item in d.entries: > print item > > This prints all the feed entries and their values. Any thoughts on > how I could just print the titles? I found out the answer after trying some more. To print the title only, I need to do this: for item in d.entries: print item.title > > > Code to save a single feed item into the database: > #!/usr/local/bin/python > import feedparser > import os.path > import sys, os > import django.contrib.auth > sys.path.append ('/home/dmc/projects/django_bookmarks') > os.environ['DJANGO_SETTINGS_MODULE']='settings' > from django.contrib.auth.models import User > from bookmarks.models import * > d = feedparser.parse('http://feeds.delicious.com/v2/rss/utools') > > link1 = Link(url=d.entries[0].link) > link1.save() > user = User.objects.get(id=1) > link = Link.objects.get(id=1) > bookmark = Bookmark ( > title = d.entries[0].title, > desc = d.entries[0].description, > link = link, > user = user, > ) > bookmark.save() > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Tonu Mikk Educational Technology Consultant Digital Media Center - dmc.umn.edu tmikk at umn.edu 612 625-9221 From sierra_mtnview at sbcglobal.net Mon Jan 26 22:51:09 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Mon, 26 Jan 2009 13:51:09 -0800 Subject: [Tutor] What Centroid Algorithm Is This? In-Reply-To: <200901262120.55668.eike.welk@gmx.net> References: <497DFEEC.7090702@sbcglobal.net> <200901262120.55668.eike.welk@gmx.net> Message-ID: <497E304D.4000806@sbcglobal.net> An HTML attachment was scrubbed... URL: From tmikk at umn.edu Mon Jan 26 22:53:50 2009 From: tmikk at umn.edu (Tonu Mikk) Date: Mon, 26 Jan 2009 15:53:50 -0600 Subject: [Tutor] using a for loop with feedparser In-Reply-To: <497E29A1.4040704@umn.edu> References: <497E2324.9080906@umn.edu> <497E29A1.4040704@umn.edu> Message-ID: <497E30EE.6080505@umn.edu> I now have a new question related to the same project. I currently have a code snippet like this: 1.for item in d.entries: 2. link = Link(url=item.link) 3. link.save() 4. user = User.objects.get(id=1) 5. link = Link.objects.get(id=1) 6. bookmark = Bookmark ( 7. title = item.title, 8. desc = item.description, 9. link = link, 10. user = user, 11. ) 12. bookmark.save() I need to increment the link id (line 5) for each item in the d.entries. I tried "link = Link.objects.get(id=id+1)" and "link = Link.objects.get((id=1)+1)", but both of them generated errors. I am not quite sure where to go from here. Thank you, Tonu Tonu Mikk wrote: > Tonu Mikk wrote: >> Hello, >> >> I am trying to parse a feed and insert some feed elements into a >> Django project database. I believe I should be able to use for loop >> to iterate over the list elements. I am using the Universal Feed >> parser (http://www.feedparser.org/). I am able to extract items one >> by one and insert them into a database (code below). As my first >> try at this, I would like to print the titles of all the feed >> entries. I tried this >> >> import feedparser >> d = feedparser.parse('http://feeds.delicious.com/v2/rss/utools') >> for item in d.entries: >> print item >> >> This prints all the feed entries and their values. Any thoughts on >> how I could just print the titles? > I found out the answer after trying some more. To print the title > only, I need to do this: > > for item in d.entries: > print item.title >> >> >> Code to save a single feed item into the database: >> #!/usr/local/bin/python >> import feedparser >> import os.path >> import sys, os >> import django.contrib.auth >> sys.path.append ('/home/dmc/projects/django_bookmarks') >> os.environ['DJANGO_SETTINGS_MODULE']='settings' >> from django.contrib.auth.models import User >> from bookmarks.models import * >> d = feedparser.parse('http://feeds.delicious.com/v2/rss/utools') >> >> link1 = Link(url=d.entries[0].link) >> link1.save() >> user = User.objects.get(id=1) >> link = Link.objects.get(id=1) >> bookmark = Bookmark ( >> title = d.entries[0].title, >> desc = d.entries[0].description, >> link = link, >> user = user, >> ) >> bookmark.save() >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor > > From alan.gauld at btinternet.com Mon Jan 26 23:17:48 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 26 Jan 2009 22:17:48 -0000 Subject: [Tutor] How Do I Put an Image on a Canvas and Display it? References: <497D3BE7.1030701@sbcglobal.net> <497DEACA.9080206@sbcglobal.net> <497DF57B.5050004@sbcglobal.net> <497E0493.6030501@sbcglobal.net> Message-ID: "Wayne Watson" wrote > Where is your namespace tutorial? Check my .sig... :-) -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Mon Jan 26 23:38:24 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 26 Jan 2009 22:38:24 -0000 Subject: [Tutor] import imports References: <20090126194208.47f33aad@o> Message-ID: "spir" wrote > Here are some ideas around import. I wish to receive comments > The module attribute __all__ allows defining names to be exported. > I always use it for my own modules, and also sometimes define it in > external modules, when absent, or adapt it to my needs. I've never defined it in any of my modules. It encourages people to use from X import * which is nearly always a bad idea. > Then I'm happy with a secure "import *". I'm not sure what you mean by a secure import *. The only danger is that of name collisions and limiting the exported names only helps by a tiny amount. There is still a good chance that another module will have the same name exported. > ...unpracticle when a single change in an name export list has > to be corrected anywhere else; there can easily be a whole > chain or even a 'tree' of imports. Exactly, thats why its a bad idea IMHO. You can never predict what other modules your module might be used with and to start customising other peoples modules to your own envirohnment leads to madness in my view! > "import *" is not recommanded for good reasons, as a > blind and risky practice. Now, when this is done consciously, > knowing that the imported module defines __all__, then > the meaning is totally different, if not opposite. Not at all. Two modules could still have conflicting names. I don;t see how you can avoid it. Thats why using import foo is better. import foo also has the advantage of forcing code to explicitly flag where imported functions and classes are found. This makes debugging and maintence far easier. import * is a "bad idea" for all sorts of reasons. Namespaces are powerful tools - lets use them. > === package module lookup === > > There is a similar issue at the package/application level: > I do not know of any practice or feature that simply allows > changing a filename, a directory name, or the organisation > of the package's directory tree, without having then to > correct all dependance information inside the concerned modules. This is a more valid issue although if you always import both package and subpackages directly and especially if you use aliases to protect your code references from change import foo as f means even if foo changes name you only need to change the import statement not all the references to f.x > I would love a kind of import lookup to be based on the following > assumption: > "The main/startup module resides in the package's root dir." But most packages don;t have a startup or main module. They are libraries that the application writer uses. Thus the app writer provides the main or startup module not the package writer. > This would also encourage the good practice of never > writing absolute imports -- which is a plague. I'm not sure what you mean by absolute imports. If you mean giving the physical path to the file then You cannot really do that in Python. I don't understand the comment? > The purpose is python to know not only which modules exist, > or which modules are intended to be imported, but also > where actually they are -- or should be. I thought it did that already? It looks in sys.path for modules and when it finds them it sets the __file__ attribute if appropriate.. I got lost around here. I assume you are having problems with modules that I've never encountered? -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Mon Jan 26 23:41:49 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 26 Jan 2009 22:41:49 -0000 Subject: [Tutor] Tk+Ipython unexpected behavior References: <333efb450901261243i5e596b59s89208644e62925fc@mail.gmail.com> Message-ID: "W W" wrote > the frame.quit method is bound to a quit button. When I double click > the .py > file to run it, it closes when the quit button is pressed. But with > Ipython, > when the quit button is pressed, it unblocks the Ipython input but > doesn't > actually quit the window. I don't know what framework IPython uses but Tkinter is renowned for running in irregular ways from inside IDEs - even ones not written in Tkinter!. My recommendation for testing Tkinter (or indeed any GUI) programs is to always run them from an OS prompt. Alan G From kent37 at tds.net Tue Jan 27 00:45:20 2009 From: kent37 at tds.net (Kent Johnson) Date: Mon, 26 Jan 2009 18:45:20 -0500 Subject: [Tutor] using a for loop with feedparser In-Reply-To: <497E30EE.6080505@umn.edu> References: <497E2324.9080906@umn.edu> <497E29A1.4040704@umn.edu> <497E30EE.6080505@umn.edu> Message-ID: <1c2a2c590901261545m134573f7wbbcff4079b564e6a@mail.gmail.com> On Mon, Jan 26, 2009 at 4:53 PM, Tonu Mikk wrote: > I now have a new question related to the same project. I currently have a > code snippet like this: > > 1.for item in d.entries: > 2. link = Link(url=item.link) > 3. link.save() > 4. user = User.objects.get(id=1) > 5. link = Link.objects.get(id=1) > 6. bookmark = Bookmark ( > 7. title = item.title, > 8. desc = item.description, > 9. link = link, > 10. user = user, > 11. ) > 12. bookmark.save() > > I need to increment the link id (line 5) for each item in the d.entries. I > tried "link = Link.objects.get(id=id+1)" and "link = > Link.objects.get((id=1)+1)", but both of them generated errors. I am not > quite sure where to go from here. Are you trying to retrieve the Link you just saved in line 3? Why not just use the link variable you already have? Kent From kent37 at tds.net Tue Jan 27 00:50:54 2009 From: kent37 at tds.net (Kent Johnson) Date: Mon, 26 Jan 2009 18:50:54 -0500 Subject: [Tutor] Tk+Ipython unexpected behavior In-Reply-To: References: <333efb450901261243i5e596b59s89208644e62925fc@mail.gmail.com> Message-ID: <1c2a2c590901261550h18a7b77bg1ead16ec3fd61606@mail.gmail.com> On Mon, Jan 26, 2009 at 5:41 PM, Alan Gauld wrote: > I don't know what framework IPython uses None, it is an enhanced Python interactive shell, you should check it out! Kent From sander.sweers at gmail.com Tue Jan 27 01:01:09 2009 From: sander.sweers at gmail.com (Sander Sweers) Date: Tue, 27 Jan 2009 01:01:09 +0100 Subject: [Tutor] datetime year problem, default year available? Message-ID: Hello Tutors, I have some questions on setting the year in a datetime object via strptime. The issues is that in my date string I only have a day and a month ('11/27' for example). Now when I use datetime.strptime('11/27', ''%m/%d) I get a datetime object but the year is 1900. This makes sense as I did not provide one. Then I saw that a datetime object has a replace function so now I could replace a 1900 by 2008 (we can assume the year is 2008). Then we can do datetime.strptime('11/27', '%m/%d').replace(year=2008) and it works but... Is there a way to set a default year when none is provide to strptime? Or is there another way to handle this? Many thanks, Sander From alan.gauld at btinternet.com Tue Jan 27 02:17:25 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 27 Jan 2009 01:17:25 -0000 Subject: [Tutor] Tk+Ipython unexpected behavior References: <333efb450901261243i5e596b59s89208644e62925fc@mail.gmail.com> <1c2a2c590901261550h18a7b77bg1ead16ec3fd61606@mail.gmail.com> Message-ID: "Kent Johnson" wrote >> I don't know what framework IPython uses > > None, it is an enhanced Python interactive shell, you should check > it out! I've looked a couple of times at the web site but never bothered downloading it. I got the impression it was a GUI shell window like PyCrust but from your comment I assume I'm wrong in that idea and it runs in a normal console window? Alan G. From kent37 at tds.net Tue Jan 27 03:01:14 2009 From: kent37 at tds.net (Kent Johnson) Date: Mon, 26 Jan 2009 21:01:14 -0500 Subject: [Tutor] Tk+Ipython unexpected behavior In-Reply-To: References: <333efb450901261243i5e596b59s89208644e62925fc@mail.gmail.com> <1c2a2c590901261550h18a7b77bg1ead16ec3fd61606@mail.gmail.com> Message-ID: <1c2a2c590901261801r63a9f146i23072d1fa2f6bbe1@mail.gmail.com> On Mon, Jan 26, 2009 at 8:17 PM, Alan Gauld wrote: > > "Kent Johnson" wrote > >>> I don't know what framework IPython uses >> >> None, it is an enhanced Python interactive shell, you should check it out! > > I've looked a couple of times at the web site but never bothered > downloading it. I got the impression it was a GUI shell window > like PyCrust but from your comment I assume I'm wrong in that > idea and it runs in a normal console window? Yes, it is a text app that runs in a console window. It has many features; my favorites are listed here: http://personalpages.tds.net/~kent37/kk/00011.html Kent From lumbricus at gmx.net Tue Jan 27 05:29:03 2009 From: lumbricus at gmx.net (=?iso-8859-1?Q?=22J=F6rg_W=F6lke=22?=) Date: Tue, 27 Jan 2009 05:29:03 +0100 Subject: [Tutor] Tk+Ipython unexpected behavior Message-ID: <20090127042903.151880@gmx.net> * Kent Johnson [090127 03:39]: > Yes, it is a text app that runs in a console window. It has many > features; my favorites are listed here: > http://personalpages.tds.net/~kent37/kk/00011.html The links on your page are broken: See: http://ipython.scipy.org/doc/manual/html/ In fact Ipython is so feature rich, some people even use it as login shell. Short demo: % ipython Python 2.5.2 (r252:60911, Nov 14 2008, 19:46:32) Type "copyright", "credits" or "license" for more information. IPython 0.8.4 -- An enhanced Interactive Python. ? -> Introduction and overview of IPython's features. %quickref -> Quick reference. help -> Python's own help system. object? -> Details about 'object'. ?object also works, ?? prints more. In [2]: %magic IPython's 'magic' functions =========================== The magic function system provides a series of functions which allow you to control the behavior of IPython itself, plus a lot of system-type features. All these functions are prefixed with a % character, [ snip ] In [8]: ls -a .zshrc .zshrc* In [9]: _i Out[9]: u'_ip.system("ls -F -a .zshrc")\n' In [12]: s = !ls -altr .zshrc In [13]: s Out[13]: SList (.p, .n, .l, .s, .grep(), .fields() available). Value: 0: -rw------- 1 joe joe 12753 2009-01-02 01:32 .zshrc In [14]: for i in s: ....: print i ....: ....: -rw------- 1 joe joe 12753 2009-01-02 01:32 .zshrc In [18]: store s Stored 's' (SList) In [19]: store Stored variables and their in-db values: s -> ['-rw------- 1 joe joe 12753 2009-01-02 01:32 .zsh In [20]: a="/tmp" In [21]: ls $a jRs.tmp lost+found/ In [22]: %edit # opens Editor etc... -- Freedom, Freedom, Freedom, Oi! -- Zoidberg NUR NOCH BIS 31.01.! GMX FreeDSL - Telefonanschluss + DSL f?r nur 16,37 EURO/mtl.!* http://dsl.gmx.de/?ac=OM.AD.PD003K11308T4569a From alexei.vinidiktov at gmail.com Tue Jan 27 06:34:35 2009 From: alexei.vinidiktov at gmail.com (Alexei Vinidiktov) Date: Tue, 27 Jan 2009 12:34:35 +0700 Subject: [Tutor] import site failed (WinXP) Message-ID: <4ca041a00901262134g2d42890cx5478236c0b24d64f@mail.gmail.com> Hello, Since yesterday I've been having problems running Python. I've been getting the error "import site failed; use -v for traceback". IDLE won't start either. The traceback seems to sugget that Python "cannot import name aliases". I've tried uninstalling and reinstalling Python and also installing a newer version of Python, but the problem persists even if I try installing Python 2.6 instead of Python 2.5.2 which I had installed till yesterday. I'm on Windows XP SP3. Here's the traceback: C:\Documents and Settings\Alexei>c:\python25\python.exe -v # installing zipimport hook import zipimport # builtin # installed zipimport hook # c:\python25\lib\site.pyc matches c:\python25\lib\site.py import site # precompiled from c:\python25\lib\site.pyc # c:\python25\lib\os.pyc matches c:\python25\lib\os.py import os # precompiled from c:\python25\lib\os.pyc import errno # builtin import nt # builtin # c:\python25\lib\ntpath.pyc matches c:\python25\lib\ntpath.py import ntpath # precompiled from c:\python25\lib\ntpath.pyc # c:\python25\lib\stat.pyc matches c:\python25\lib\stat.py import stat # precompiled from c:\python25\lib\stat.pyc # c:\python25\lib\UserDict.pyc matches c:\python25\lib\UserDict.py import UserDict # precompiled from c:\python25\lib\UserDict.pyc # c:\python25\lib\copy_reg.pyc matches c:\python25\lib\copy_reg.py import copy_reg # precompiled from c:\python25\lib\copy_reg.pyc # c:\python25\lib\types.pyc matches c:\python25\lib\types.py import types # precompiled from c:\python25\lib\types.pyc import _types # builtin # c:\python25\lib\locale.pyc matches c:\python25\lib\locale.py import locale # precompiled from c:\python25\lib\locale.pyc import encodings # directory c:\python25\lib\encodings # c:\python25\lib\encodings\__init__.pyc matches c:\python25\lib\encodings\__ini t__.py import encodings # precompiled from c:\python25\lib\encodings\__init__.pyc # c:\python25\lib\codecs.pyc matches c:\python25\lib\codecs.py import codecs # precompiled from c:\python25\lib\codecs.pyc import _codecs # builtin 'import site' failed; traceback: Traceback (most recent call last): File "C:\Python25\lib\site.py", line 415, in main() File "C:\Python25\lib\site.py", line 406, in main aliasmbcs() File "C:\Python25\lib\site.py", line 356, in aliasmbcs import locale, codecs File "C:\Python25\lib\locale.py", line 14, in import sys, encodings, encodings.aliases File "C:\Python25\lib\encodings\__init__.py", line 32, in from encodings import aliases ImportError: cannot import name aliases # c:\python25\lib\warnings.pyc matches c:\python25\lib\warnings.py import warnings # precompiled from c:\python25\lib\warnings.pyc # c:\python25\lib\linecache.pyc matches c:\python25\lib\linecache.py import linecache # precompiled from c:\python25\lib\linecache.pyc Python 2.5.4 (r254:67916, Dec 23 2008, 15:10:54) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> -- Alexei Vinidiktov From sierra_mtnview at sbcglobal.net Tue Jan 27 07:19:00 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Mon, 26 Jan 2009 22:19:00 -0800 Subject: [Tutor] How Do I Put an Image on a Canvas and Display it? In-Reply-To: References: <497D3BE7.1030701@sbcglobal.net> <497DEACA.9080206@sbcglobal.net> <497DF57B.5050004@sbcglobal.net> <497E0493.6030501@sbcglobal.net> Message-ID: <497EA754.5020607@sbcglobal.net> An HTML attachment was scrubbed... URL: From denis.spir at free.fr Tue Jan 27 09:03:03 2009 From: denis.spir at free.fr (spir) Date: Tue, 27 Jan 2009 09:03:03 +0100 Subject: [Tutor] [Python-ideas] import imports In-Reply-To: References: <20090126194208.47f33aad@o> Message-ID: <20090127090303.4596bef5@o> Le Mon, 26 Jan 2009 22:38:24 -0000, "Alan Gauld" a ?crit : > "spir" wrote > > > Here are some ideas around import. I wish to receive comments > > > The module attribute __all__ allows defining names to be exported. > > I always use it for my own modules, and also sometimes define it in > > external modules, when absent, or adapt it to my needs. > > I've never defined it in any of my modules. It encourages people > to use from X import * which is nearly always a bad idea. > > > Then I'm happy with a secure "import *". > > I'm not sure what you mean by a secure import *. > The only danger is that of name collisions and limiting the > exported names only helps by a tiny amount. There is still > a good chance that another module will have the same > name exported. [...] > > "import *" is not recommanded for good reasons, as a > > blind and risky practice. Now, when this is done consciously, > > knowing that the imported module defines __all__, then > > the meaning is totally different, if not opposite. > > Not at all. Two modules could still have conflicting names. > I don;t see how you can avoid it. Thats why using import foo > is better. > "Secure import" means that I, as client of the imported module, know that this module defines __all__. I can then safely import all. I can even precisely know which names are defined simply by reading __all__. The common practice of defining __all__ on top of a module help in that, too. So that there is no name collision (or rather no more than may happen inside a module when not paying enough attention to naming.) "Opposite" here points to the difference between blind "import *" and conscious import relying on the existence of __all__. And/Or the difference between knowing or not which names will be imported. I also think distributed modules or packages should be encouraged to define __all__ and that their doc should explicitely list which names are defined there. Many actually do define __all__ if only for their own use: intra-package imports. Package/application developpers need to precisely specify the set of names that they import themselves from module to module, don't they? > import foo also has the advantage of forcing code to explicitly > flag where imported functions and classes are found. This > makes debugging and maintence far easier. > import * is a "bad idea" for all sorts of reasons. > Namespaces are powerful tools - lets use them. For sure. Either is good. > > === package module lookup === > > > > There is a similar issue at the package/application level: > > I do not know of any practice or feature that simply allows > > changing a filename, a directory name, or the organisation > > of the package's directory tree, without having then to > > correct all dependance information inside the concerned modules. > > This is a more valid issue although if you always import both > package and subpackages directly and especially if you use > aliases to protect your code references from change > > import foo as f > means even if foo changes name you only need to change > the import statement not all the references to f.x Here, I'm rather talking of package or application maintenance. (External import issues also come into account, they may be simplified with this proposal, they they are not the primary target. See below.) > > I would love a kind of import lookup to be based on the following > > assumption: > > "The main/startup module resides in the package's root dir." > > But most packages don;t have a startup or main module. They > are libraries that the application writer uses. Thus the app > writer provides the main or startup module not the package writer. I should have said application/package and more highlighted intra-package imports. Again, purely external, client imports are not the issue I'm talking about. Anyway, even purely toolbox packages are identified by an __init__.py file that is considered as a startup module that will be parsed and executed before any module or sub-package import. According to my proposal, the location of this file defines the package's root dir -- which is the practice with python packages anyway. Even if my developpment is rather small-scale, I like to split it into modules and organise these into a properly shaped local directory tree. At developpment time, at least, even if the final product happen to fit well in a single file. Now, I want to be free to move, rename, reorganise all of that stuff. What about you? This shouldn't be an issue! It's everyday job, isn't it? The proposal aims at letting this happen simply with either the developper or python itself, maintaining an up-to-date local module index for the application/package. Is it clearer? [...] ------ la vida e estranya From alan.gauld at btinternet.com Tue Jan 27 11:25:12 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 27 Jan 2009 10:25:12 -0000 Subject: [Tutor] [Python-ideas] import imports References: <20090126194208.47f33aad@o> <20090127090303.4596bef5@o> Message-ID: "spir" wrote > "Secure import" means that I, as client of the imported module, > know that this module defines __all__. I can then safely import all. I still don;t agree that simply defining __all__ means you can "safely" import all. all restricts what the module exposes it does nothing to prevent name clashes with other modules. > So that there is no name collision (or rather no more than may > happen inside a module when not paying enough attention to naming.) If you carefully read the __all__ of every module you import. Quite an onerous task that is completely unnecessaryy if you use import foo instead. > "Opposite" here points to the difference between blind "import *" > and conscious import relying on the existence of __all__. > And/Or the difference between knowing or not which names will be > imported. OK, I agree that __all__ reduces the likelihood of inadvertantly importing something you didn't expect (like a global variable say) > I also think distributed modules or packages should be encouraged > to define __all__ and that their doc should explicitely list which > names are defined there. Yes, if you are intending a package for distribution I would agree that it would be good practice - even just to give basic protection to foolhardy importers of all... > : intra-package imports. Package/application developpers > need to precisely specify the set of names that they import > themselves from module to module, don't they? Possibly, but if they too use import foo then again they will have no such problems. > Here, I'm rather talking of package or application maintenance. I don;t see that it makes a huge difference except.... >.... even purely toolbox packages are identified by an __init__.py > file that is considered as a startup module that will be parsed > and executed before any module or sub-package import. OK, Now I understand what you mean by startup. > Even if my developpment is rather small-scale, I like to split > it into modules and organise these into a properly shaped > local directory tree. I normally create a single folder and dump all my modules into that. It will be under my $PROJECT area which has an init.py file so is treated as a package and $PROJECT is in my $PYTHONPATH. I don;t normally construct subfolders for my modules, none of my Python projects have required more than 10-15 files which is fine in a single folder. But due to my use of Python I never develop packages specifically for distribution, I am primarily a consumer of packages not a producer. > Now, I want to be free to move, rename, reorganise all > of that stuff. What about you? I wouldn't see that as a problem since I use the import foo style almost exclusevely in production code Provided the top level folder is in Pythonpath and the package has init.py files my code will survive restructuring. Filename changes are covered by using aliases on imports > The proposal aims at letting this happen simply with > either the developper or python itself, maintaining an > up-to-date local module index for the application/package. > Is it clearer? Its clearer but still seems unnecessary to me unless you insist on using from x import *. But I'll leave it for those who are actually developing packages per se to comment further. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From a.t.hofkamp at tue.nl Tue Jan 27 12:23:13 2009 From: a.t.hofkamp at tue.nl (A.T.Hofkamp) Date: Tue, 27 Jan 2009 12:23:13 +0100 Subject: [Tutor] [Python-ideas] import imports In-Reply-To: <20090127090303.4596bef5@o> References: <20090126194208.47f33aad@o> <20090127090303.4596bef5@o> Message-ID: <497EEEA1.6040104@tue.nl> Hai Denis, spir wrote: > "Secure import" means that I, as client of the imported module, know that this module defines __all__. I can then safely import all. I can even precisely know which names are defined simply by reading __all__. The common practice of defining __all__ on top of a module help in that, too. So that there is no name collision (or rather no more than may happen inside a module when not paying enough attention to naming.) There is no such thing as 'secure import *' imho. The assumption that you make here is that you as client of a library have control over which version of the library is being used in your application. That assumption does not hold in the general case. Suppose you checked that __all__ of a library does not cause problems in your application. You do "import *", and distribute and use your application. It is a big hit, you get thousands of users. The library authors modify and extend their library, taking good care about backwards compability, and adding new names for theie new functionality to their __all__. Users blindly rely on package managers, or want to use bleeding edge libraries. They install the newest library (with enough users, you always get a set of library versions that users use with your application), which is by word of the author, backwards compatible. However, your import * pulls in the new __all__ names, which may cause new and unexpected name clashes, throwing your 'secure' out of the window in the process. I have started to believe that 'import *' should be removed from the language; it is way to easy to make fatal mistakes with it. Sincerely, Albert From kent37 at tds.net Tue Jan 27 13:04:50 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 27 Jan 2009 07:04:50 -0500 Subject: [Tutor] import site failed (WinXP) In-Reply-To: <4ca041a00901262134g2d42890cx5478236c0b24d64f@mail.gmail.com> References: <4ca041a00901262134g2d42890cx5478236c0b24d64f@mail.gmail.com> Message-ID: <1c2a2c590901270404v5b126a7ajffa0a1550437959c@mail.gmail.com> On Tue, Jan 27, 2009 at 12:34 AM, Alexei Vinidiktov wrote: > Hello, > > Since yesterday I've been having problems running Python. I've been > getting the error "import site failed; use -v for traceback". IDLE > won't start either. > > The traceback seems to sugget that Python "cannot import name aliases". > > I've tried uninstalling and reinstalling Python and also installing a > newer version of Python, but the problem persists even if I try > installing Python 2.6 instead of Python 2.5.2 which I had installed > till yesterday. > > I'm on Windows XP SP3. > > Here's the traceback: > > 'import site' failed; traceback: > Traceback (most recent call last): > File "C:\Python25\lib\site.py", line 415, in > main() > File "C:\Python25\lib\site.py", line 406, in main > aliasmbcs() > File "C:\Python25\lib\site.py", line 356, in aliasmbcs > import locale, codecs > File "C:\Python25\lib\locale.py", line 14, in > import sys, encodings, encodings.aliases > File "C:\Python25\lib\encodings\__init__.py", line 32, in > from encodings import aliases > ImportError: cannot import name aliases That's a puzzle. When you installed Python 2.6, does it show C:\Python26 in the paths when you try python2.6 -v ? My best guess is that somehow Python is finding the wrong encodings\aliases.py. Do you have a folder called encodings or a file called aliases.py anywhere on your PYTHONPATH? Does Python work if you start it from a different working directory? puzzled... Kent From tmikk at umn.edu Tue Jan 27 16:28:47 2009 From: tmikk at umn.edu (Tonu Mikk) Date: Tue, 27 Jan 2009 09:28:47 -0600 Subject: [Tutor] using a for loop with feedparser In-Reply-To: <1c2a2c590901261545m134573f7wbbcff4079b564e6a@mail.gmail.com> References: <497E2324.9080906@umn.edu> <497E29A1.4040704@umn.edu> <497E30EE.6080505@umn.edu> <1c2a2c590901261545m134573f7wbbcff4079b564e6a@mail.gmail.com> Message-ID: <497F282F.3040403@umn.edu> Kent, you are absolutely correct. I did not need the line number 5 at all. This was my first program that addressed a "real life" scenario. I am excited that it worked. Thank you, Tonu Kent Johnson wrote: > On Mon, Jan 26, 2009 at 4:53 PM, Tonu Mikk wrote: > >> I now have a new question related to the same project. I currently have a >> code snippet like this: >> >> 1.for item in d.entries: >> 2. link = Link(url=item.link) >> 3. link.save() >> 4. user = User.objects.get(id=1) >> 5. link = Link.objects.get(id=1) >> 6. bookmark = Bookmark ( >> 7. title = item.title, >> 8. desc = item.description, >> 9. link = link, >> 10. user = user, >> 11. ) >> 12. bookmark.save() >> >> I need to increment the link id (line 5) for each item in the d.entries. I >> tried "link = Link.objects.get(id=id+1)" and "link = >> Link.objects.get((id=1)+1)", but both of them generated errors. I am not >> quite sure where to go from here. >> > > Are you trying to retrieve the Link you just saved in line 3? Why not > just use the link variable you already have? > > Kent > -- Tonu Mikk Educational Technology Consultant Digital Media Center - dmc.umn.edu tmikk at umn.edu 612 625-9221 From kent37 at tds.net Tue Jan 27 17:38:03 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 27 Jan 2009 11:38:03 -0500 Subject: [Tutor] import site failed (WinXP) In-Reply-To: <4ca041a00901270824i5e225fcbnb11be31125d55fc@mail.gmail.com> References: <4ca041a00901262134g2d42890cx5478236c0b24d64f@mail.gmail.com> <1c2a2c590901270404v5b126a7ajffa0a1550437959c@mail.gmail.com> <4ca041a00901270824i5e225fcbnb11be31125d55fc@mail.gmail.com> Message-ID: <1c2a2c590901270838o641749c1h34f3113216348150@mail.gmail.com> On Tue, Jan 27, 2009 at 11:24 AM, Alexei Vinidiktov wrote: > 2009/1/27 Kent Johnson : >> My best guess is that somehow Python is finding the wrong >> encodings\aliases.py. > > I can't find an aliases.py file within the encodings folder. Should it be there? Yes, you should have a file C:\Python25\Lib\encodings\aliases.py and presumably if it is missing, it should be restored by re-installing. Kent PS, please use Reply All to reply to the list. From kent37 at tds.net Tue Jan 27 17:38:23 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 27 Jan 2009 11:38:23 -0500 Subject: [Tutor] Fwd: import site failed (WinXP) In-Reply-To: <4ca041a00901270824i5e225fcbnb11be31125d55fc@mail.gmail.com> References: <4ca041a00901262134g2d42890cx5478236c0b24d64f@mail.gmail.com> <1c2a2c590901270404v5b126a7ajffa0a1550437959c@mail.gmail.com> <4ca041a00901270824i5e225fcbnb11be31125d55fc@mail.gmail.com> Message-ID: <1c2a2c590901270838p18095ed4rf28d8902e94a219b@mail.gmail.com> Forwarding to the list ---------- Forwarded message ---------- From: Alexei Vinidiktov Date: Tue, Jan 27, 2009 at 11:24 AM Subject: Re: [Tutor] import site failed (WinXP) To: Kent Johnson 2009/1/27 Kent Johnson : > On Tue, Jan 27, 2009 at 12:34 AM, Alexei Vinidiktov > wrote: >> Hello, >> >> Since yesterday I've been having problems running Python. I've been >> getting the error "import site failed; use -v for traceback". IDLE >> won't start either. >> >> The traceback seems to sugget that Python "cannot import name aliases". >> >> I've tried uninstalling and reinstalling Python and also installing a >> newer version of Python, but the problem persists even if I try >> installing Python 2.6 instead of Python 2.5.2 which I had installed >> till yesterday. >> >> I'm on Windows XP SP3. >> >> Here's the traceback: >> > >> 'import site' failed; traceback: >> Traceback (most recent call last): >> File "C:\Python25\lib\site.py", line 415, in >> main() >> File "C:\Python25\lib\site.py", line 406, in main >> aliasmbcs() >> File "C:\Python25\lib\site.py", line 356, in aliasmbcs >> import locale, codecs >> File "C:\Python25\lib\locale.py", line 14, in >> import sys, encodings, encodings.aliases >> File "C:\Python25\lib\encodings\__init__.py", line 32, in >> from encodings import aliases >> ImportError: cannot import name aliases > > That's a puzzle. When you installed Python 2.6, does it show > C:\Python26 in the paths when you try python2.6 -v ? When I try C:\Python26\python.exe -v, it does show that. > > My best guess is that somehow Python is finding the wrong > encodings\aliases.py. I can't find an aliases.py file within the encodings folder. Should it be there? Do you have a folder called encodings or a file > called aliases.py anywhere on your PYTHONPATH? I don't have a PYTHONPATH environment variable defined. Does Python work if you > start it from a different working directory? No, it doesn't seem to work properly no matter what directory I run it from. -- Alexei Vinidiktov From alexei.vinidiktov at gmail.com Tue Jan 27 17:43:35 2009 From: alexei.vinidiktov at gmail.com (Alexei Vinidiktov) Date: Tue, 27 Jan 2009 23:43:35 +0700 Subject: [Tutor] import site failed (WinXP) In-Reply-To: <1c2a2c590901270838o641749c1h34f3113216348150@mail.gmail.com> References: <4ca041a00901262134g2d42890cx5478236c0b24d64f@mail.gmail.com> <1c2a2c590901270404v5b126a7ajffa0a1550437959c@mail.gmail.com> <4ca041a00901270824i5e225fcbnb11be31125d55fc@mail.gmail.com> <1c2a2c590901270838o641749c1h34f3113216348150@mail.gmail.com> Message-ID: <4ca041a00901270843t1f040b77y5f973a8e0eab98dd@mail.gmail.com> 2009/1/27 Kent Johnson : > On Tue, Jan 27, 2009 at 11:24 AM, Alexei Vinidiktov > wrote: >> 2009/1/27 Kent Johnson : > >>> My best guess is that somehow Python is finding the wrong >>> encodings\aliases.py. >> >> I can't find an aliases.py file within the encodings folder. Should it be there? > > Yes, you should have a file > C:\Python25\Lib\encodings\aliases.py > > and presumably if it is missing, it should be restored by re-installing. > That's the problem. Reinstalling Python or even installing a different version doesn't install ...\Lib\encodings\aliases.py > > PS, please use Reply All to reply to the list. Sorry, didn't know about that. -- Alexei Vinidiktov From kent37 at tds.net Tue Jan 27 18:03:50 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 27 Jan 2009 12:03:50 -0500 Subject: [Tutor] import site failed (WinXP) In-Reply-To: <4ca041a00901270843t1f040b77y5f973a8e0eab98dd@mail.gmail.com> References: <4ca041a00901262134g2d42890cx5478236c0b24d64f@mail.gmail.com> <1c2a2c590901270404v5b126a7ajffa0a1550437959c@mail.gmail.com> <4ca041a00901270824i5e225fcbnb11be31125d55fc@mail.gmail.com> <1c2a2c590901270838o641749c1h34f3113216348150@mail.gmail.com> <4ca041a00901270843t1f040b77y5f973a8e0eab98dd@mail.gmail.com> Message-ID: <1c2a2c590901270903u540a93f3n8d3e3cf28d9437be@mail.gmail.com> On Tue, Jan 27, 2009 at 11:43 AM, Alexei Vinidiktov wrote: > 2009/1/27 Kent Johnson : >> On Tue, Jan 27, 2009 at 11:24 AM, Alexei Vinidiktov >> wrote: >>> 2009/1/27 Kent Johnson : >> >>>> My best guess is that somehow Python is finding the wrong >>>> encodings\aliases.py. >>> >>> I can't find an aliases.py file within the encodings folder. Should it be there? >> >> Yes, you should have a file >> C:\Python25\Lib\encodings\aliases.py >> >> and presumably if it is missing, it should be restored by re-installing. >> > > That's the problem. Reinstalling Python or even installing a different > version doesn't install ...\Lib\encodings\aliases.py Very strange. What if you download it from here: http://svn.python.org/view/python/branches/release25-maint/Lib/encodings/aliases.py?rev=51333&view=auto and put it into C:\Python25\Lib\encodings\ ? Kent From bgailer at gmail.com Tue Jan 27 18:06:07 2009 From: bgailer at gmail.com (bob gailer) Date: Tue, 27 Jan 2009 12:06:07 -0500 Subject: [Tutor] Python Program: Newton's Method In-Reply-To: <85d27a00901262305r3d5fca8bi4a1fa7a629f53194@mail.gmail.com> References: <85d27a00901251511k40d709d2ie0bf87b04ce59b8c@mail.gmail.com> <497DF1FA.6050604@gmail.com> <85d27a00901262305r3d5fca8bi4a1fa7a629f53194@mail.gmail.com> Message-ID: <497F3EFF.2080906@gmail.com> I neglected to mention that we'd like you to always reply-all so a copy goes to the list. All of us participate and learn. Donna Ibarra wrote: > The numbers that are outputted are not exactly correct as they should > be for Newtons Method: OK - thanks - now please give us a few sample numbers, the results you want and the results you get. > > import math > > def main(): > x, loops = input("Please enter the value, and the number of times > to loop: ") > > for i in range(loops): > new_loops = float(loops + (x / loops)) / 2 > loops = new_loops > > print "The guess is", loops, "which is", loops - > math.sqrt(x),"away from", math.sqrt(x) > > > main() > > ^Do you have any suggestions as to what I should do? -- Bob Gailer Chapel Hill NC 919-636-4239 From alexei.vinidiktov at gmail.com Tue Jan 27 18:34:14 2009 From: alexei.vinidiktov at gmail.com (Alexei Vinidiktov) Date: Wed, 28 Jan 2009 00:34:14 +0700 Subject: [Tutor] import site failed (WinXP) In-Reply-To: <1c2a2c590901270903u540a93f3n8d3e3cf28d9437be@mail.gmail.com> References: <4ca041a00901262134g2d42890cx5478236c0b24d64f@mail.gmail.com> <1c2a2c590901270404v5b126a7ajffa0a1550437959c@mail.gmail.com> <4ca041a00901270824i5e225fcbnb11be31125d55fc@mail.gmail.com> <1c2a2c590901270838o641749c1h34f3113216348150@mail.gmail.com> <4ca041a00901270843t1f040b77y5f973a8e0eab98dd@mail.gmail.com> <1c2a2c590901270903u540a93f3n8d3e3cf28d9437be@mail.gmail.com> Message-ID: <4ca041a00901270934h241076fu178540d58cca875a@mail.gmail.com> 2009/1/28 Kent Johnson : > On Tue, Jan 27, 2009 at 11:43 AM, Alexei Vinidiktov > wrote: >> 2009/1/27 Kent Johnson : >>> On Tue, Jan 27, 2009 at 11:24 AM, Alexei Vinidiktov >>> wrote: >>>> 2009/1/27 Kent Johnson : >>> >>>>> My best guess is that somehow Python is finding the wrong >>>>> encodings\aliases.py. >>>> >>>> I can't find an aliases.py file within the encodings folder. Should it be there? >>> >>> Yes, you should have a file >>> C:\Python25\Lib\encodings\aliases.py >>> >>> and presumably if it is missing, it should be restored by re-installing. >>> >> >> That's the problem. Reinstalling Python or even installing a different >> version doesn't install ...\Lib\encodings\aliases.py > > Very strange. What if you download it from here: > http://svn.python.org/view/python/branches/release25-maint/Lib/encodings/aliases.py?rev=51333&view=auto > > and put it into C:\Python25\Lib\encodings\ ? Something very strange is happening on my system. After I downloaded the aliases.py file and saved it, I couldn't find it via the Explorer, but it was visible via an Open and Save dialog of some programs (such as Opera). I've conducted another experiment. I created several text files with a Notepad that contained text 'alia' in their names and none of them were visible after I had saved them to the disc. For example the files alia1.txt, alias.txt, aliases.txt, aliases2.txt, aliases.py.txt were all invisible in the Explorer, but the files ali.txt, ali1.txt were visible. I must add that I can see files that have an invisible attribute just fine in the Explorer. -- Alexei Vinidiktov From alan.gauld at btinternet.com Tue Jan 27 18:44:00 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 27 Jan 2009 17:44:00 -0000 Subject: [Tutor] import site failed (WinXP) References: <4ca041a00901262134g2d42890cx5478236c0b24d64f@mail.gmail.com><1c2a2c590901270404v5b126a7ajffa0a1550437959c@mail.gmail.com><4ca041a00901270824i5e225fcbnb11be31125d55fc@mail.gmail.com><1c2a2c590901270838o641749c1h34f3113216348150@mail.gmail.com><4ca041a00901270843t1f040b77y5f973a8e0eab98dd@mail.gmail.com><1c2a2c590901270903u540a93f3n8d3e3cf28d9437be@mail.gmail.com> <4ca041a00901270934h241076fu178540d58cca875a@mail.gmail.com> Message-ID: "Alexei Vinidiktov" wrote > I've conducted another experiment. I created several text files with > a > Notepad that contained text 'alia' in their names and none of them > were visible after I had saved them to the disc. Now that is strange! Does "alia" mean something in your local language (assuming its not English!)? I'm not aware of XP hiding files based on filename, it is certainly odd. Alan G. From alexei.vinidiktov at gmail.com Tue Jan 27 19:22:35 2009 From: alexei.vinidiktov at gmail.com (Alexei Vinidiktov) Date: Wed, 28 Jan 2009 01:22:35 +0700 Subject: [Tutor] import site failed (WinXP) In-Reply-To: References: <4ca041a00901262134g2d42890cx5478236c0b24d64f@mail.gmail.com> <1c2a2c590901270404v5b126a7ajffa0a1550437959c@mail.gmail.com> <4ca041a00901270824i5e225fcbnb11be31125d55fc@mail.gmail.com> <1c2a2c590901270838o641749c1h34f3113216348150@mail.gmail.com> <4ca041a00901270843t1f040b77y5f973a8e0eab98dd@mail.gmail.com> <1c2a2c590901270903u540a93f3n8d3e3cf28d9437be@mail.gmail.com> <4ca041a00901270934h241076fu178540d58cca875a@mail.gmail.com> Message-ID: <4ca041a00901271022nbb3b8c8x631e54574e33d18a@mail.gmail.com> 2009/1/28 Alan Gauld : > > "Alexei Vinidiktov" wrote > >> I've conducted another experiment. I created several text files with a >> Notepad that contained text 'alia' in their names and none of them >> were visible after I had saved them to the disc. > > Now that is strange! Does "alia" mean something in your local language > (assuming its not English!)? I'm not aware of XP hiding files based on > filename, it is certainly odd. > No, I'm afraid "alia" doesn't mean anything in Russian. I'm going to run a virus check of the system, and then check the disk for errors with CHKDSK, and then I'll let you know how it went off. -- Alexei Vinidiktov From sidewalking at gmail.com Tue Jan 27 20:34:38 2009 From: sidewalking at gmail.com (Scott Stueben) Date: Tue, 27 Jan 2009 12:34:38 -0700 Subject: [Tutor] Possible to search text file for multiple string values at once? In-Reply-To: <99004bb30901241943h14ece66dj60a30028cf22faa5@mail.gmail.com> References: <99004bb30901231025i6c04e338tcc373aa9469d0550@mail.gmail.com> <1c2a2c590901231052v5f40b318wfef45f0d437ce59a@mail.gmail.com> <99004bb30901231111x2e82b99v82b560e1a4da4a05@mail.gmail.com> <333efb450901231245j71608f48m48f9c6ab16f99398@mail.gmail.com> <20090124101651.3ff68667@o> <99004bb30901241943h14ece66dj60a30028cf22faa5@mail.gmail.com> Message-ID: <99004bb30901271134g9e3d374sd46800927019ddac@mail.gmail.com> As I think more about how to best do this, I wonder if/how python script would import File A with search values, File B to be searched, and write each full line containing any of those results to File C. The code could be set to look for the same input file (A, with the search values), and the same filename to write to (File C), thus leaving only the prompt for the file to be searched (File B). The user would be responsible for listing the search term variables into File A prior to running the script. Is this simple enough? Scott On Sat, Jan 24, 2009 at 8:43 PM, Scott Stueben wrote: > Excellent ideas...thanks to you all for the input. I will see what I > can work out in the next few days and report back. > > :) Scott > > On Sat, Jan 24, 2009 at 2:16 AM, spir wrote: >> Le Fri, 23 Jan 2009 14:45:32 -0600, >> W W a ?crit : >> >>> On Fri, Jan 23, 2009 at 1:11 PM, Scott Stueben wrote: >>> >>> > Thanks for the help so far - it seems easy enough. To clarify on the >>> > points you have asked me about: >>> > >>> > A sqlite3 database on my machine would be an excellent idea for >>> > personal use. I would like to be able to get a functional script for >>> > others on my team to use, so maybe a script or compiled program >>> > (Win32) eventually. >>> >>> >>> As long as everyone on your team has python installed (or as long as python >>> is installed on the machines they'll be using), a functional script would be >>> fairly easy to get rolling. Sqlite is (AFAIK) included with the newer >>> versions of python by default. Heck, it's on the version I have installed on >>> my phone! (Cingular 8525). Simply zipping up the directory should provide an >>> easy enough distribution method. Although, you *could* even write a python >>> script that does the "install" for them. >>> >>> >>> > As for output, I would probably like to return the entire lines that >>> > contain any search results of those strings. Maybe just output to a >>> > results.txt that would have the entire line of each line that contains >>> > 'Bob', 'John', 'Joe', 'Jim', and or 'Fred'. >>> >>> >>> The simplest method: >>> >>> In [5]: f = open('interculturalinterview2.txt', 'r') >>> >>> In [6]: searchstrings = ('holy', 'hand', 'grenade', 'potato') >>> >>> In [7]: for line in f.readlines(): >>> ...: for word in searchstrings: >>> ...: if word in line: >>> ...: print line >>> ...: >>> ...: >>> Hana: have a bonfire n candy apples n make potatoes on a car lol! >>> >>> Wayne: potatoes on a car? >>> >>> Hana .: yer lol its fun and they taste nicer lol, you wrap a potato in >>> tinfoil a >>> nd put in on the engine of a car and close the bonnet and have the engine >>> run an >>> d it cooks it in about 30 mins >>> >>> Speed isn't as important as ease of use, I suppose, since >>> > non-technical people should be able to use it, ideally. >> >> I guess the easiest for your team would be to: >> * let the script write the result lines into a text file >> * let the script open the result in an editor (using module called subprocess) >> * put a link to your script on the desk >> >> ### just an example >> # write to file >> target = open("target.txt",'w') >> for line in lines: >> target.write(line) >> target.close() >> >> # open in editor >> import subprocess >> subprocess.call(["gedit","target.txt"]) >> print "*** end ***" >> >> denis >> >> ------ >> la vida e estranya >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> > > > > -- > > "Shine on me baby, cause it's rainin' in my heart" > > --Elliott Smith > -- "Shine on me baby, cause it's rainin' in my heart" --Elliott Smith From alan.gauld at btinternet.com Tue Jan 27 23:38:00 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 27 Jan 2009 22:38:00 -0000 Subject: [Tutor] Possible to search text file for multiple string valuesat once? References: <99004bb30901231025i6c04e338tcc373aa9469d0550@mail.gmail.com><1c2a2c590901231052v5f40b318wfef45f0d437ce59a@mail.gmail.com><99004bb30901231111x2e82b99v82b560e1a4da4a05@mail.gmail.com><333efb450901231245j71608f48m48f9c6ab16f99398@mail.gmail.com><20090124101651.3ff68667@o><99004bb30901241943h14ece66dj60a30028cf22faa5@mail.gmail.com> <99004bb30901271134g9e3d374sd46800927019ddac@mail.gmail.com> Message-ID: "Scott Stueben" wrote > As I think more about how to best do this, I wonder if/how python > script would import File A with search values, File B to be > searched, > and write each full line containing any of those results to File C. > The code could be set to look for the same input file (A, with the > search values), and the same filename to write to (File C), thus > leaving only the prompt for the file to be searched (File B). Thats pretty straightforward to do. In pseudo code: fileB = open(raw_input("Filename to search: ")) searches = [s for s in open("FileA.txt")] results = Set() for line in fileB: for s in searches: if s in line: results.add(line+'\n') open("FileC.txt").writelines(results) Not the most efficient solution but that can be tweaked using some of the other suggestions from earlier. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From ajarncolin at gmail.com Wed Jan 28 02:07:19 2009 From: ajarncolin at gmail.com (col speed) Date: Wed, 28 Jan 2009 08:07:19 +0700 Subject: [Tutor] operator, mult Message-ID: <6a1b26420901271707i7f2dcd10t708b404ad4b17636@mail.gmail.com> Hello there, I got the following function while googling: def totient(n): """calculate Euler's totient function. If [[p_0,m_0], [p_1,m_1], ... ] is a prime factorization of 'n', then the totient function phi(n) is given by: (p_0 - 1)*p_0**(m_0-1) * (p_1 - 1)*p_1**(m_1-1) * ... >>> phi(1) 1 >>> phi(10) 4 """ from operator import mult if n == 1: return 1 return reduce(mult, [(p-1) * p**(m-1) for p,m in prime_factors_mult(n)]) I already have the "prime_factors" function. The problem is that I cannot find "mult". I tried using "mul" which is in "operator" but that is obviously not the same thing. Could there be a similar thing somewhere other than "operator"? Thanks a lot Colin -------------- next part -------------- An HTML attachment was scrubbed... URL: From john at fouhy.net Wed Jan 28 02:19:30 2009 From: john at fouhy.net (John Fouhy) Date: Wed, 28 Jan 2009 14:19:30 +1300 Subject: [Tutor] operator, mult In-Reply-To: <6a1b26420901271707i7f2dcd10t708b404ad4b17636@mail.gmail.com> References: <6a1b26420901271707i7f2dcd10t708b404ad4b17636@mail.gmail.com> Message-ID: <5e58f2e40901271719k226ddd2fv86d0c84c8d0ad244@mail.gmail.com> 2009/1/28 col speed : > Hello there, > I got the following function while googling: > > def totient(n): > """calculate Euler's totient function. > > If [[p_0,m_0], [p_1,m_1], ... ] is a prime factorization of 'n', > then the totient function phi(n) is given by: > > (p_0 - 1)*p_0**(m_0-1) * (p_1 - 1)*p_1**(m_1-1) * ... [...] > return reduce(mult, [(p-1) * p**(m-1) for p,m in prime_factors_mult(n)]) > > I already have the "prime_factors" function. The problem is that I cannot > find "mult". I tried using "mul" which is in "operator" but that is > obviously not the same thing. It seems pretty obvious that operator.mul is what they mean (based on what the reduce function does). Perhaps it's a typo? -- John. From ajarncolin at gmail.com Wed Jan 28 02:25:08 2009 From: ajarncolin at gmail.com (col speed) Date: Wed, 28 Jan 2009 08:25:08 +0700 Subject: [Tutor] operator, mult In-Reply-To: <5e58f2e40901271719k226ddd2fv86d0c84c8d0ad244@mail.gmail.com> References: <6a1b26420901271707i7f2dcd10t708b404ad4b17636@mail.gmail.com> <5e58f2e40901271719k226ddd2fv86d0c84c8d0ad244@mail.gmail.com> Message-ID: <6a1b26420901271725lc08677cv210382d68ee68dbe@mail.gmail.com> That's what I thought , but I tried it to no avail. Plus the syntax is wrong. Thanks anyway Colin 2009/1/28 John Fouhy > 2009/1/28 col speed : > > Hello there, > > I got the following function while googling: > > > > def totient(n): > > """calculate Euler's totient function. > > > > If [[p_0,m_0], [p_1,m_1], ... ] is a prime factorization of 'n', > > then the totient function phi(n) is given by: > > > > (p_0 - 1)*p_0**(m_0-1) * (p_1 - 1)*p_1**(m_1-1) * ... > [...] > > return reduce(mult, [(p-1) * p**(m-1) for p,m in > prime_factors_mult(n)]) > > > > I already have the "prime_factors" function. The problem is that I cannot > > find "mult". I tried using "mul" which is in "operator" but that is > > obviously not the same thing. > > It seems pretty obvious that operator.mul is what they mean (based on > what the reduce function does). Perhaps it's a typo? > > -- > John. > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alexei.vinidiktov at gmail.com Wed Jan 28 07:37:59 2009 From: alexei.vinidiktov at gmail.com (Alexei Vinidiktov) Date: Wed, 28 Jan 2009 13:37:59 +0700 Subject: [Tutor] import site failed (WinXP) (Solved) Message-ID: <4ca041a00901272237h1e514238g7617aef6c1b5a96f@mail.gmail.com> 2009/1/28 Alexei Vinidiktov : > 2009/1/28 Alan Gauld : >> >> "Alexei Vinidiktov" wrote >> >>> I've conducted another experiment. I created several text files with a >>> Notepad that contained text 'alia' in their names and none of them >>> were visible after I had saved them to the disc. >> >> Now that is strange! Does "alia" mean something in your local language >> (assuming its not English!)? I'm not aware of XP hiding files based on >> filename, it is certainly odd. >> > > No, I'm afraid "alia" doesn't mean anything in Russian. > > I'm going to run a virus check of the system, and then check the disk > for errors with CHKDSK, and then I'll let you know how it went off. > OK. I got it sorted out. I had a trojan on my system which hid all the files whose names started with 'ali'. Thanks for your help, Alan and Kent. -- Alexei Vinidiktov From alan.gauld at btinternet.com Wed Jan 28 09:29:09 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 28 Jan 2009 08:29:09 -0000 Subject: [Tutor] operator, mult References: <6a1b26420901271707i7f2dcd10t708b404ad4b17636@mail.gmail.com> Message-ID: "col speed" wrote > I got the following function while googling: > > def totient(n): > from operator import mult > if n == 1: return 1 > return reduce(mult, [(p-1) * p**(m-1) for p,m in > prime_factors_mult(n)]) > > I already have the "prime_factors" function. The problem is that I > cannot > find "mult". Given it says mult is in operators then it must be (or have been in a previous version) a standard Python operator that is intended. Did it menton which version of Python was used? Is it an old site? > I tried using "mul" which is in "operator" but that is > obviously not the same thing. How so? What did it do? >>> from operator import mul >>> reduce(mul,[1,2,3,4]) 24 Does what I would expect it to do... What do you think mult should do? Alan G From katcipis at inf.ufsc.br Wed Jan 28 11:53:21 2009 From: katcipis at inf.ufsc.br (Tiago Katcipis) Date: Wed, 28 Jan 2009 08:53:21 -0200 Subject: [Tutor] Handling post request Message-ID: <60a9403b0901280253n16987084wa60ae7dec1665435@mail.gmail.com> I am trying to make a small HTTP server on python just to handle some POST and GET requests. I never worked with http before and dont know if i am doing something completely stupid (probably yes). I read anything possible already and i just cant find how i access the information sent on the POST request, i need these because some parameters needed by the server must be sent on the POST request, my client test does this: f = urllib2.urlopen(url, urllib.urlencode('http://my_server_adress:port', {'Teste' : 'teste', 'Teste2' : 't2', 'Teste3' : 't3'})) f.close() The server runs ok and receives the POST request just fine, but im not finding where the data that i have sent on the post request is being held. Sorry if the question is extremely stupid, i really tried a lot of things already and read a lot, maybe i just have let something pass when i was reading or i am understanding something terribly wrong :-(. O already have take a look at: http://docs.python.org/library/simplehttpserver.html#module-SimpleHTTPServer http://docs.python.org/library/basehttpserver.html#BaseHTTPServer.BaseHTTPRequestHandler.handle_one_request http://effbot.org/librarybook/simplehttpserver.htm http://personalpages.tds.net/~kent37/kk/00010.html my server code is: def adcionar_tratador_server(endereco_servidor, tratador): BaseHTTPServer.HTTPServer(endereco_servidor, tratador).serve_forever() class TratadorRequisicaoHTTPIDLocutor(BaseHTTPServer.BaseHTTPRequestHandler): def do_HEAD(self): print self.command print self.path print self.headers print self.headers.getplist() print self.raw_requestline print urlparse.urlparse(self.path) return 'ok' def do_GET(self): print self.command print self.path print self.headers print self.headers.getplist() print self.raw_requestline print urlparse.urlparse(self.path) return 'ok' def do_POST(self): print self.command print self.path print self.headers print self.headers.getplist() print self.raw_requestline print urlparse.urlparse(self.path) return 'ok' adcionar_tratador_server(('', 8000) , TratadorRequisicaoHTTPIDLocutor) -- "it might be a profitable thing to learn Java, but it has no intellectual value whatsoever" Alexander Stepanov -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Wed Jan 28 12:03:34 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 28 Jan 2009 11:03:34 -0000 Subject: [Tutor] Handling post request References: <60a9403b0901280253n16987084wa60ae7dec1665435@mail.gmail.com> Message-ID: "Tiago Katcipis" wrote >I am trying to make a small HTTP server on python just to handle some >POST > and GET requests. I never worked with http before and dont know if i > am > doing something completely stupid (probably yes). Not stupid so much as overly complicated. The cgi module will do all the hard work for you including transparently handling POST and GET requests Read the web HOWTO document: http://docs.python.org/howto/webservers.html Then read the CGI module documentation which includes a very quick introduction to CGI programming. If you are intending expanding the web site to anything beyond trivial consider using a Framework such as Django, Turbo Gears or Pylons. Unless you are trying to do something very clever - which given your level of knowledge I'd guess is not the case - then the standard cgi module should do all you need! HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From katcipis at inf.ufsc.br Wed Jan 28 12:09:23 2009 From: katcipis at inf.ufsc.br (Tiago Katcipis) Date: Wed, 28 Jan 2009 09:09:23 -0200 Subject: [Tutor] Handling post request In-Reply-To: References: <60a9403b0901280253n16987084wa60ae7dec1665435@mail.gmail.com> Message-ID: <60a9403b0901280309re9d5e71yca71b52e5e7da004@mail.gmail.com> thanks for the help, im really not used on doing web stuff, ill try reading the how to. On Wed, Jan 28, 2009 at 9:03 AM, Alan Gauld wrote: > "Tiago Katcipis" wrote > > I am trying to make a small HTTP server on python just to handle some POST >> and GET requests. I never worked with http before and dont know if i am >> doing something completely stupid (probably yes). >> > > Not stupid so much as overly complicated. > > The cgi module will do all the hard work for you including transparently > handling POST and GET requests > > Read the web HOWTO document: > > http://docs.python.org/howto/webservers.html > > Then read the CGI module documentation which includes a very quick > introduction to CGI programming. If you are intending expanding the web > site to anything beyond trivial consider using a Framework such as > Django, Turbo Gears or Pylons. > > Unless you are trying to do something very clever - which given your > level of knowledge I'd guess is not the case - then the standard > cgi module should do all you need! > > HTH, > > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- "it might be a profitable thing to learn Java, but it has no intellectual value whatsoever" Alexander Stepanov -------------- next part -------------- An HTML attachment was scrubbed... URL: From katcipis at inf.ufsc.br Wed Jan 28 12:20:00 2009 From: katcipis at inf.ufsc.br (Tiago Katcipis) Date: Wed, 28 Jan 2009 09:20:00 -0200 Subject: [Tutor] Handling post request In-Reply-To: <60a9403b0901280309re9d5e71yca71b52e5e7da004@mail.gmail.com> References: <60a9403b0901280253n16987084wa60ae7dec1665435@mail.gmail.com> <60a9403b0901280309re9d5e71yca71b52e5e7da004@mail.gmail.com> Message-ID: <60a9403b0901280320u6bf34b11vb5058dcf5f0396cf@mail.gmail.com> actualy i have found what i wanted on the rfile attribute, i already tried before to read it but the application just freezes when i try to read() or readline() on it. But after i make the request, and both client and server sides freezes, if i kill the client side the server becomes able of reading the rfile. Does anyone know why i just cant read the rfile without killing the client side? it feels like the client side is waiting for something while the server is unable to read the rfile while the client side is waiting. On Wed, Jan 28, 2009 at 9:09 AM, Tiago Katcipis wrote: > thanks for the help, im really not used on doing web stuff, ill try reading > the how to. > > > On Wed, Jan 28, 2009 at 9:03 AM, Alan Gauld wrote: > >> "Tiago Katcipis" wrote >> >> I am trying to make a small HTTP server on python just to handle some >>> POST >>> and GET requests. I never worked with http before and dont know if i am >>> doing something completely stupid (probably yes). >>> >> >> Not stupid so much as overly complicated. >> >> The cgi module will do all the hard work for you including transparently >> handling POST and GET requests >> >> Read the web HOWTO document: >> >> http://docs.python.org/howto/webservers.html >> >> Then read the CGI module documentation which includes a very quick >> introduction to CGI programming. If you are intending expanding the web >> site to anything beyond trivial consider using a Framework such as >> Django, Turbo Gears or Pylons. >> >> Unless you are trying to do something very clever - which given your >> level of knowledge I'd guess is not the case - then the standard >> cgi module should do all you need! >> >> HTH, >> >> >> -- >> Alan Gauld >> Author of the Learn to Program web site >> http://www.alan-g.me.uk/ >> >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> > > > > -- > "it might be a profitable thing to learn Java, but it has no intellectual > value whatsoever" Alexander Stepanov > -- "it might be a profitable thing to learn Java, but it has no intellectual value whatsoever" Alexander Stepanov -------------- next part -------------- An HTML attachment was scrubbed... URL: From justin.mailinglists at gmail.com Wed Jan 28 12:20:06 2009 From: justin.mailinglists at gmail.com (Justin Ezequiel) Date: Wed, 28 Jan 2009 19:20:06 +0800 Subject: [Tutor] Handling post request Message-ID: <3c6718980901280320m3315a8b9m9de57e8da5a041a4@mail.gmail.com> > From: Tiago Katcipis > > I am trying to make a small HTTP server on python just to handle some POST > and GET requests. I never worked with http before and dont know if i am > doing something completely stupid (probably yes). I read anything possible > already and i just cant find how i access the information sent on the POST > request, i need these because some parameters needed by the server must be > sent on the POST request, my client test does this: > > > f = urllib2.urlopen(url, urllib.urlencode('http://my_server_adress:port', > {'Teste' : 'teste', 'Teste2' : 't2', 'Teste3' : 't3'})) > f.close() > > The server runs ok and receives the POST request just fine, but im not > finding where the data that i have sent on the post request is being held. > Sorry if the question is extremely stupid, i really tried a lot of things > already and read a lot, maybe i just have let something pass when i was > reading or i am understanding something terribly wrong :-(. Hello, I needed to do the same recently to test my scripts that do GET and POST to a web site. Found how to get at the posted data within CGIHTTPServer.py particularly the run_cgi method of the CGIHTTPRequestHandler class. At first I just ran an instance of the CGIHTTPServer and had a few CGI scripts until I read the code for the run_cgi method above. Now my test script runs an HTTP server in a daemon thread using my subclass of the CGIHTTPRequestHandler then the main thread then runs my GET and POST code. From katcipis at inf.ufsc.br Wed Jan 28 12:33:01 2009 From: katcipis at inf.ufsc.br (Tiago Katcipis) Date: Wed, 28 Jan 2009 09:33:01 -0200 Subject: [Tutor] Handling post request In-Reply-To: <3c6718980901280320m3315a8b9m9de57e8da5a041a4@mail.gmail.com> References: <3c6718980901280320m3315a8b9m9de57e8da5a041a4@mail.gmail.com> Message-ID: <60a9403b0901280333y4627382eg8ed34476868b49bc@mail.gmail.com> thank you all for the help but i have finnaly been able to do what i wanted. I will not use CGI scripts, its very simple what im doing and i just wanted the parameters sent on the POST like: * "name1=value1&name2=value2&name3=value3"* but reading about CGI i discovered that the size of these parameters are in content-lenght, when reading the rfile with the content-length as the number of bytes to read it has worked fine. best regards On Wed, Jan 28, 2009 at 9:20 AM, Justin Ezequiel < justin.mailinglists at gmail.com> wrote: > > From: Tiago Katcipis > > > > I am trying to make a small HTTP server on python just to handle some > POST > > and GET requests. I never worked with http before and dont know if i am > > doing something completely stupid (probably yes). I read anything > possible > > already and i just cant find how i access the information sent on the > POST > > request, i need these because some parameters needed by the server must > be > > sent on the POST request, my client test does this: > > > > > > f = urllib2.urlopen(url, urllib.urlencode('http://my_server_adress:port > ', > > {'Teste' : 'teste', 'Teste2' : 't2', 'Teste3' : 't3'})) > > f.close() > > > > The server runs ok and receives the POST request just fine, but im not > > finding where the data that i have sent on the post request is being > held. > > Sorry if the question is extremely stupid, i really tried a lot of things > > already and read a lot, maybe i just have let something pass when i was > > reading or i am understanding something terribly wrong :-(. > > Hello, I needed to do the same recently to test my scripts that do GET > and POST to a web site. > Found how to get at the posted data within CGIHTTPServer.py > particularly the run_cgi method of the CGIHTTPRequestHandler class. > > At first I just ran an instance of the CGIHTTPServer and had a few CGI > scripts until I read the code for the run_cgi method above. > Now my test script runs an HTTP server in a daemon thread using my > subclass of the CGIHTTPRequestHandler then the main thread then runs > my GET and POST code. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- "it might be a profitable thing to learn Java, but it has no intellectual value whatsoever" Alexander Stepanov -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Wed Jan 28 13:04:04 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 28 Jan 2009 07:04:04 -0500 Subject: [Tutor] Python grep Message-ID: <1c2a2c590901280404m4d64bec7qebe9801f72932209@mail.gmail.com> Since there have been a couple of threads about searching recently, I thought this might be of interest: http://www.redmountainsw.com/wordpress/archives/python-grep Kent From alan.gauld at btinternet.com Wed Jan 28 13:42:06 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 28 Jan 2009 12:42:06 -0000 Subject: [Tutor] Handling post request References: <3c6718980901280320m3315a8b9m9de57e8da5a041a4@mail.gmail.com> <60a9403b0901280333y4627382eg8ed34476868b49bc@mail.gmail.com> Message-ID: "Tiago Katcipis" wrote > thank you all for the help but i have finnaly been able to do what i > wanted. > I will not use CGI scripts, its very simple what im doing and i just > wanted > the parameters sent on the POST like: > * > "name1=value1&name2=value2&name3=value3"* The cgi module would have given you that in about 5 lines of code, so you did an awful lot of work that you didn't need to! But at least you will have learned a lot about http servers that might be useful in the future. :-) Alan G. From sierra_mtnview at sbcglobal.net Wed Jan 28 14:19:22 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Wed, 28 Jan 2009 05:19:22 -0800 Subject: [Tutor] How Do I Put an Image on a Canvas and Display it? In-Reply-To: <497E0536.4090106@sbcglobal.net> References: <497D3BE7.1030701@sbcglobal.net> <497DEACA.9080206@sbcglobal.net> <497DF57B.5050004@sbcglobal.net> <566057.76018.qm@web86710.mail.ird.yahoo.com> <497E0536.4090106@sbcglobal.net> Message-ID: <49805B5A.8050801@sbcglobal.net> An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Wed Jan 28 14:21:41 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Wed, 28 Jan 2009 05:21:41 -0800 Subject: [Tutor] Find a Word in *.py (Win XP) In-Reply-To: <1c2a2c590901250824r2b295608s4c466c5977350a21@mail.gmail.com> References: <497C85D8.8010702@sbcglobal.net> <1c2a2c590901250824r2b295608s4c466c5977350a21@mail.gmail.com> Message-ID: <49805BE5.6030309@sbcglobal.net> An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Wed Jan 28 14:25:21 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Wed, 28 Jan 2009 05:25:21 -0800 Subject: [Tutor] To Arc (PIL) or Not to Arc (Tkinter) In-Reply-To: References: <497CF1CB.7090908@sbcglobal.net> Message-ID: <49805CC1.3080501@sbcglobal.net> An HTML attachment was scrubbed... URL: From kent37 at tds.net Wed Jan 28 15:15:42 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 28 Jan 2009 09:15:42 -0500 Subject: [Tutor] To Arc (PIL) or Not to Arc (Tkinter) In-Reply-To: <49805CC1.3080501@sbcglobal.net> References: <497CF1CB.7090908@sbcglobal.net> <49805CC1.3080501@sbcglobal.net> Message-ID: <1c2a2c590901280615m7269a4a4u1d07b8ef215e0369@mail.gmail.com> On Wed, Jan 28, 2009 at 8:25 AM, Wayne Watson wrote: > I've been playing with PIL and Tkinter a bit, and see that PIL does not have > any facility to view the image file I draw on. I open a file from my folder > with a py program as an Image. The only way, without using some other > module, is to save the changed file, then display it with a paint or photo > program. Is that correct, or did I miss something in PIL? The ImageTk module integrates PIL with Tkinter: http://effbot.org/imagingbook/imagetk.htm Here is a simple image viewer library, just call showImage() with your loaded Image object: # an image viewer import ImageTk from Tkinter import Tk, Label class UI(Label): def __init__(self, master, im): if im.mode == "1": # bitmap image self.image = ImageTk.BitmapImage(im, foreground="white") Label.__init__(self, master, image=self.image, bg="black", bd=0) else: # photo image self.image = ImageTk.PhotoImage(im) Label.__init__(self, master, image=self.image, bd=0) def showImage(im): root = Tk() UI(root, im).pack() root.mainloop() Kent From alan.gauld at btinternet.com Wed Jan 28 15:59:17 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 28 Jan 2009 14:59:17 -0000 Subject: [Tutor] Find a Word in *.py (Win XP) References: <497C85D8.8010702@sbcglobal.net><1c2a2c590901250824r2b295608s4c466c5977350a21@mail.gmail.com> <49805BE5.6030309@sbcglobal.net> Message-ID: "Wayne Watson" wrote > Just using the standard Win XP Pro folder search. > I target the folder with my py programs, use *.py to > search, and specify I'm looking for angle in the files it finds. Yes, I get the same behaviour! I tried searching for 'import' which should be almost every file! It came up blank. When I tried tkinter it found one file with Tkinter in the file name. It seems it is not looking inside the file! Weird. However the DOS command findstr works as expected! Alan G From mail at timgolden.me.uk Wed Jan 28 16:12:36 2009 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 28 Jan 2009 15:12:36 +0000 Subject: [Tutor] Find a Word in *.py (Win XP) In-Reply-To: References: <497C85D8.8010702@sbcglobal.net><1c2a2c590901250824r2b295608s4c466c5977350a21@mail.gmail.com> <49805BE5.6030309@sbcglobal.net> Message-ID: <498075E4.9000405@timgolden.me.uk> Alan Gauld wrote: > > "Wayne Watson" wrote >> Just using the standard Win XP Pro folder search. >> I target the folder with my py programs, use *.py to >> search, and specify I'm looking for angle in the files it finds. > > Yes, I get the same behaviour! > I tried searching for 'import' which should be almost every file! > It came up blank. When I tried tkinter it found one file with Tkinter > in the file name. It seems it is not looking inside the file! > > Weird. It's because of XP search treating what it thinks of as text files differently from what it doesn't think of as text files. It does the same for .sql. Immensely irritating. There is some registry fudge which will work around it, but I gave up on using Windows search years ago. (FWIW, I use the pay-for xplorer2 everywhere I go which has been invaluable to me, but YMMV). TJG From sierra_mtnview at sbcglobal.net Wed Jan 28 16:30:34 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Wed, 28 Jan 2009 07:30:34 -0800 Subject: [Tutor] To Arc (PIL) or Not to Arc (Tkinter) In-Reply-To: <1c2a2c590901280615m7269a4a4u1d07b8ef215e0369@mail.gmail.com> References: <497CF1CB.7090908@sbcglobal.net> <49805CC1.3080501@sbcglobal.net> <1c2a2c590901280615m7269a4a4u1d07b8ef215e0369@mail.gmail.com> Message-ID: <49807A1A.1050209@sbcglobal.net> An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Wed Jan 28 16:30:57 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Wed, 28 Jan 2009 07:30:57 -0800 Subject: [Tutor] Find a Word in *.py (Win XP) In-Reply-To: References: <497C85D8.8010702@sbcglobal.net><1c2a2c590901250824r2b295608s4c466c5977350a21@mail.gmail.com> <49805BE5.6030309@sbcglobal.net> Message-ID: <49807A31.4060203@sbcglobal.net> An HTML attachment was scrubbed... URL: From kent37 at tds.net Wed Jan 28 16:51:45 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 28 Jan 2009 10:51:45 -0500 Subject: [Tutor] To Arc (PIL) or Not to Arc (Tkinter) In-Reply-To: <49807A1A.1050209@sbcglobal.net> References: <497CF1CB.7090908@sbcglobal.net> <49805CC1.3080501@sbcglobal.net> <1c2a2c590901280615m7269a4a4u1d07b8ef215e0369@mail.gmail.com> <49807A1A.1050209@sbcglobal.net> Message-ID: <1c2a2c590901280751y1824f9dar4155b8c1898020a3@mail.gmail.com> On Wed, Jan 28, 2009 at 10:30 AM, Wayne Watson wrote: > Thanks. I was beginning to think the only way to get this done is via > Tkinter's canvas. > > I guess I can see why PIL later became amended with libraries like Tkinter. > I think PIL came first, and apparently depended upon some then present > elements of Python for displaying images. I don't know the history but Tkinter and PIL really are focused on separate jobs; Tkinter is a general-purpose GUI framework, PIL is for image manipulation. > UI == Utility Imager? User Interface. This is just a quick hack I wrote to help solve problems in the Python Challenge. Many of them involve image manipulation and display. http://www.pythonchallenge.com/ Kent From srilyk at gmail.com Wed Jan 28 16:56:22 2009 From: srilyk at gmail.com (W W) Date: Wed, 28 Jan 2009 09:56:22 -0600 Subject: [Tutor] Find a Word in *.py (Win XP) In-Reply-To: <49807A31.4060203@sbcglobal.net> References: <497C85D8.8010702@sbcglobal.net> <1c2a2c590901250824r2b295608s4c466c5977350a21@mail.gmail.com> <49805BE5.6030309@sbcglobal.net> <49807A31.4060203@sbcglobal.net> Message-ID: <333efb450901280756h2491f4b3sccf8207077924910@mail.gmail.com> You know, it probably wouldn't be terribly difficult to write the search in python. Then you *could* find strings inside rather easily. HTH, Wayne On Wed, Jan 28, 2009 at 9:30 AM, Wayne Watson wrote: > Thanks. I'll post a msg to a XP group about this. I suspect Python hashes > the code somehow. > > Findstr? Wow, that's got to be old. Where did you find that? > > > Alan Gauld wrote: > > > "Wayne Watson" wrote > > Just using the standard Win XP Pro folder search. > I target the folder with my py programs, use *.py to > search, and specify I'm looking for angle in the files it finds. > > > Yes, I get the same behaviour! > I tried searching for 'import' which should be almost every file! > It came up blank. When I tried tkinter it found one file with Tkinter > in the file name. It seems it is not looking inside the file! > > Weird. > > However the DOS command findstr works as expected! > > Alan G > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > -- > > Wayne Watson (Watson Adventures, Prop., Nevada City, CA) > > (121.01 Deg. W, 39.26 Deg. N) GMT-8 hr std. time) * Copper and its alloys have been found effective in hospital > sinks, hand rails, beds, ... in significantly reducing > bacteria. Estimates are 1/20 people admitted to a hospital > become infected, and 1/20 die from the infection. > -- NPR Science Friday, 01/16/2009 ***** Web Page: > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn't. - Primo Levi -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Wed Jan 28 17:38:19 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 28 Jan 2009 11:38:19 -0500 Subject: [Tutor] Find a Word in *.py (Win XP) In-Reply-To: <333efb450901280756h2491f4b3sccf8207077924910@mail.gmail.com> References: <497C85D8.8010702@sbcglobal.net> <1c2a2c590901250824r2b295608s4c466c5977350a21@mail.gmail.com> <49805BE5.6030309@sbcglobal.net> <49807A31.4060203@sbcglobal.net> <333efb450901280756h2491f4b3sccf8207077924910@mail.gmail.com> Message-ID: <1c2a2c590901280838y4214dcffn3282be683fb78514@mail.gmail.com> On Wed, Jan 28, 2009 at 10:56 AM, W W wrote: > You know, it probably wouldn't be terribly difficult to write the search in > python. Then you *could* find strings inside rather easily. Other than being written in Perl ;-) ack is a nice command-line search tool: http://petdance.com/ack/ or the Python equivalent: http://pypi.python.org/pypi/grin Kent From kent37 at tds.net Wed Jan 28 20:04:34 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 28 Jan 2009 14:04:34 -0500 Subject: [Tutor] Find a Word in *.py (Win XP) In-Reply-To: <4980A401.1010608@sbcglobal.net> References: <497C85D8.8010702@sbcglobal.net> <1c2a2c590901250824r2b295608s4c466c5977350a21@mail.gmail.com> <49805BE5.6030309@sbcglobal.net> <49807A31.4060203@sbcglobal.net> <333efb450901280756h2491f4b3sccf8207077924910@mail.gmail.com> <1c2a2c590901280838y4214dcffn3282be683fb78514@mail.gmail.com> <4980A401.1010608@sbcglobal.net> Message-ID: <1c2a2c590901281104y544f5444j36e9ce2542d28269@mail.gmail.com> On Wed, Jan 28, 2009 at 1:29 PM, Wayne Watson wrote: > These look Linux based. > > Kent Johnson wrote: > Other than being written in Perl ;-) ack is a nice command-line search tool: > http://petdance.com/ack/ > > or the Python equivalent: > http://pypi.python.org/pypi/grin No, they are Perl and Python based command-line programs. I know that ack runs fine on Mac OSX and Windows; AFAIK grin is plain Python so it probably does too. Kent From ricaraoz at gmail.com Tue Jan 27 14:26:06 2009 From: ricaraoz at gmail.com (=?windows-1252?Q?Ricardo_Ar=E1oz?=) Date: Tue, 27 Jan 2009 11:26:06 -0200 Subject: [Tutor] Defining "bit" type In-Reply-To: References: <50ed08f40901240625vd1b4980ta751326038adcc6c@mail.gmail.com> Message-ID: <497F0B6E.1010209@gmail.com> > "Vicent" wrote > >> Anyway, I am working with Python 2.5.4, and I am interested in >> defining a >> new type called "bit" (if possible), which represents a number that >> can only >> take values 0 or 1 ?that's what we would call a "binary variable", in a >> Mathematical Programming context. The python manual is usually a good thing to read : 3.4.1 Bit-string Operations on Integer Types Plain and long integer types support additional operations that make sense only for bit-strings. Negative numbers are treated as their 2's complement value (for long integers, this assumes a sufficiently large number of bits that no overflow occurs during the operation). The priorities of the binary bit-wise operations are all lower than the numeric operations and higher than the comparisons; the unary operation "~" has the same priority as the other unary numeric operations ("+" and "-"). This table lists the bit-string operations sorted in ascending priority (operations in the same box have the same priority): Operation Result Notes |x | y| bitwise /or/ of x and y |x ^ y| bitwise /exclusive or/ of x and y |x & y| bitwise /and/ of x and y |x << n| x shifted left by n bits (1), (2) |x >> n| x shifted right by n bits (1), (3) |~x| the bits of x inverted Notes: *(1)* Negative shift counts are illegal and cause a ValueError to be raised. *(2)* A left shift by n bits is equivalent to multiplication by |pow(2, n)| without overflow check. *(3)* A right shift by n bits is equivalent to division by |pow(2, n)| without overflow check. -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Jan 29 01:47:47 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 29 Jan 2009 00:47:47 -0000 Subject: [Tutor] Find a Word in *.py (Win XP) References: <497C85D8.8010702@sbcglobal.net><1c2a2c590901250824r2b295608s4c466c5977350a21@mail.gmail.com><49805BE5.6030309@sbcglobal.net> <49807A31.4060203@sbcglobal.net> <333efb450901280756h2491f4b3sccf8207077924910@mail.gmail.com> Message-ID: "W W" wrote > You know, it probably wouldn't be terribly difficult to write the > search in > python. Then you *could* find strings inside rather easily. Given that there's findstr in DOS and grep in *nix(and for DOS too!) it hardly seems worthwhile reinventing that particular wheel! :-) But the Explorer based search does have advantages in that you can manipulate the found files using the windows GUI where as with the command line tools you either have to construct some kind of pipeline or take a note of the found files. How insane that XP doesn't search the text in "non text" files! -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From sierra_mtnview at sbcglobal.net Thu Jan 29 01:53:35 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Wed, 28 Jan 2009 16:53:35 -0800 Subject: [Tutor] Finding the End of a Def? In-Reply-To: <497F07F9.2050503@gmail.com> References: <497AB441.1050102@sbcglobal.net> <20090124105324.6780b0df@o> <497B124F.3080501@sbcglobal.net> <333efb450901240537j5f2bf80axbcca54168fe6ffd7@mail.gmail.com> <497B29AE.9030008@sbcglobal.net> <497F07F9.2050503@gmail.com> Message-ID: <4980FE0F.3080604@sbcglobal.net> An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Jan 29 02:01:37 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 29 Jan 2009 01:01:37 -0000 Subject: [Tutor] To Arc (PIL) or Not to Arc (Tkinter) References: <497CF1CB.7090908@sbcglobal.net> <49805CC1.3080501@sbcglobal.net><1c2a2c590901280615m7269a4a4u1d07b8ef215e0369@mail.gmail.com><49807A1A.1050209@sbcglobal.net> <1c2a2c590901280751y1824f9dar4155b8c1898020a3@mail.gmail.com> Message-ID: >> I think PIL came first, and apparently depended upon some then >> present >> elements of Python for displaying images. I'm pretty sure Tkinter came before PIL. Tkinter has been around since at least Python 1.3, and I think maybe even 1.2.X! I don't think PIL appeared till about v2.0 But PIL is not, and never has been a display tool, it is about maniplulating images in memory. How you display them is another issue entirely. Tkinter is a wrapper around Tk which was designed (in 1988) as a way of building simple GUIs around command line tools. Specifically tools intended to control bespoke bits of electronic hardware. So its graphical requirements were very limited. Conciseness, small footprint and ease of use were its primary goals. And all that is as it should be - separation of concerns is a very good design pattern. Its a tetament to PIL that the latest version is 1.1.6 which was developed for Python 1.5.2 and still works fine with Python 2.6! I suspect changes will be needed for v3 though... -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk From alan.gauld at btinternet.com Thu Jan 29 02:14:47 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 29 Jan 2009 01:14:47 -0000 Subject: [Tutor] Python grep References: <1c2a2c590901280404m4d64bec7qebe9801f72932209@mail.gmail.com> Message-ID: "Kent Johnson" wrote > Since there have been a couple of threads about searching recently, > I > thought this might be of interest: > http://www.redmountainsw.com/wordpress/archives/python-grep I'll throw in PowerGrep which is a grep like tool that knows about multiple file formats such as MS Office filers. Its commercial, not very cheap but does what it says on the tin and I don't know of any other equivalent. http://www.powergrep.com/ But you need to be a pretty determined searcher to need it! Alan G. From sierra_mtnview at sbcglobal.net Thu Jan 29 02:41:25 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Wed, 28 Jan 2009 17:41:25 -0800 Subject: [Tutor] IDLE vs PythonWin Message-ID: <49810945.8050402@sbcglobal.net> An HTML attachment was scrubbed... URL: From justin.mailinglists at gmail.com Thu Jan 29 03:25:59 2009 From: justin.mailinglists at gmail.com (Justin Ezequiel) Date: Thu, 29 Jan 2009 10:25:59 +0800 Subject: [Tutor] Find a Word in *.py (Win XP) Message-ID: <3c6718980901281825p1888b923se3284538d91d626f@mail.gmail.com> > How insane that XP doesn't search the text in "non text" files! > > -- > Alan Gauld http://support.microsoft.com/default.aspx?scid=KB;EN-US;q309173 I used Method 2 under Resolution recently when I reinstalled XP on a new harddisk. HTH From bmoll70 at att.net Thu Jan 29 02:31:03 2009 From: bmoll70 at att.net (bmoll70 at att.net) Date: Wed, 28 Jan 2009 20:31:03 -0500 Subject: [Tutor] configuring web browser PP3E Message-ID: hi. i'm reading 'Programming Python' and having some trouble with adding a web interface in chapter one. (page 72) basically, i open the cgi101.html file in Firefox. i enter a name and hit Submit Query: but instead of getting the Hello "name"! page returned to me.... I get the error page. #!/usr/bin/python import cgi form = cgi.FieldStorage() # parse form data print "Content-type: text/html\n" # hdr plus blank line print "Reply Page" # html reply page if not form.has_key('user'): print "

Who are you?

" else: print "

Hello %s!

" % cgi.escape(form['user'].value) the book says i might have to modify the path to my Python in the #! line at the top of the script file and make it executable with a chmod command. i've tried many things to get this working. also, i'm not getting anywhere with the webserver.py file either. here is the error message: Traceback (most recent call last): File "webserver.py", line 22, in ? srvrobj = HTTPServer(srvraddr, CGIHTTPRequestHandler) File "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/ python2.3/SocketServer.py", line 330, in __init__ File "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/ python2.3/BaseHTTPServer.py", line 100, in server_bind File "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/ python2.3/SocketServer.py", line 341, in server_bind File "", line 1, in bind socket.error: (13, 'Permission denied') can anyone help? From prologic at shortcircuit.net.au Thu Jan 29 03:50:06 2009 From: prologic at shortcircuit.net.au (James Mills) Date: Thu, 29 Jan 2009 12:50:06 +1000 Subject: [Tutor] configuring web browser PP3E In-Reply-To: References: Message-ID: On Thu, Jan 29, 2009 at 11:31 AM, bmoll70 at att.net wrote: > Traceback (most recent call last): > File "webserver.py", line 22, in ? > srvrobj = HTTPServer(srvraddr, CGIHTTPRequestHandler) > File > "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/SocketServer.py", > line 330, in __init__ > File > "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/BaseHTTPServer.py", > line 100, in server_bind > File > "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/SocketServer.py", > line 341, in server_bind > File "", line 1, in bind > socket.error: (13, 'Permission denied') srvraddr is being passed a port of 80. I suspect that you're running on a Mac and that Mac's being UNIX systems, do not allow you as a normal user to listen on ports < 1000 without root privileges. Solution 1: Run this under sudo Solution 2: Change the port to 8000 cheers James From berankin99 at yahoo.com Thu Jan 29 04:01:24 2009 From: berankin99 at yahoo.com (Bernard Rankin) Date: Wed, 28 Jan 2009 19:01:24 -0800 (PST) Subject: [Tutor] building Python 2.6? Message-ID: <74094.90479.qm@web112219.mail.gq1.yahoo.com> Hello, I am trying to build python 2.6 on a machine (web server) that I do not have root access to. (has 2.4 installed) Python 2.5 builds fine, but I am getting an error when I run "make" for 2.6.1 Here is the command line I am using: ../configure -prefix=/home/username/local-python/ --enable-unicode=ucs4 (I don't know what the ucs4 thing is, but all the HOWTOs I saw say to use it. ) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Here is what the local python reports itself as: ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Python 2.4.3 (#1, Jul 29 2007, 14:09:31) [GCC 3.4.6 20060404 (Red Hat 3.4.6-8)] on linux2 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Here is the error after I run "make": ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ [SNIP] /home/username/local-src/Python-2.6.1/Modules/_ctypes/_ctypes.c:3941: error: syntax error before '*' token /home/username/local-src/Python-2.6.1/Modules/_ctypes/_ctypes.c:3942: warning: function declaration isn't a prototype /home/username/local-src/Python-2.6.1/Modules/_ctypes/_ctypes.c: In function `CFuncPtr_nonzero': /home/username/local-src/Python-2.6.1/Modules/_ctypes/_ctypes.c:3943: error: `self' undeclared (first use in this function) Failed to find the necessary bits to build these modules: _tkinter bsddb185 sunaudiodev To find the necessary bits, look in setup.py in detect_modules() for the module's name. Failed to build these modules: _ctypes running build_script ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ From prologic at shortcircuit.net.au Thu Jan 29 04:21:33 2009 From: prologic at shortcircuit.net.au (James Mills) Date: Thu, 29 Jan 2009 13:21:33 +1000 Subject: [Tutor] configuring web browser PP3E In-Reply-To: References: Message-ID: On Thu, Jan 29, 2009 at 12:17 PM, bmoll70 at att.net wrote: > yes, i'm running on Mac OS X / Unix, but i'm afraid i don't know "where" to > change the port to 80. i'm working with the following files straight from > the book 'Programming Python': You're not blind are you ? Because I am. > cgi101.py (here it is...) > #!/usr/bin/python > import cgi > form = cgi.FieldStorage() # parse form data > print "Content-type: text/html\n" # hdr plus blank line > print "Reply Page" # html reply page > if not form.has_key('user'): > print "

Who are you?

" > else: > print "

Hello %s!

" % cgi.escape(form['user'].value) > cgi101.html (here it is...) > > Interactive Page > >
>

Enter your name: >

>

>

> > and webserver.py (here it is...) > ###################################################################### > # implement HTTP web server in Python which knows how to run server > # side CGI scripts; serves files/scripts from current working dir; > # python scripts must be stored in webdir\cgi-bin or webdir\htbin; > ###################################################################### > webdir = '.' # where your html files and cgi-bin script directory live > port = 80 # default http://localhost/, else use http://localhost:xxxx/ Chat the above line. [...] cheers James From ajarncolin at gmail.com Thu Jan 29 05:30:35 2009 From: ajarncolin at gmail.com (col speed) Date: Thu, 29 Jan 2009 11:30:35 +0700 Subject: [Tutor] operator, mult In-Reply-To: <6a1b26420901271725lc08677cv210382d68ee68dbe@mail.gmail.com> References: <6a1b26420901271707i7f2dcd10t708b404ad4b17636@mail.gmail.com> <5e58f2e40901271719k226ddd2fv86d0c84c8d0ad244@mail.gmail.com> <6a1b26420901271725lc08677cv210382d68ee68dbe@mail.gmail.com> Message-ID: <6a1b26420901282030x5435f12akf2c7970ce6bb2663@mail.gmail.com> This is a way of finding how many coprimes there are for a number - eg 144 How many positive numbers less than or equal to 144 are relatively prime to 144? Factor 144 = 2 4 ? 3 2 . Use the formula for each prime: >From 2 4 , we get 2 - 1 = 1 and 2 4 - 1 = 2 3 = 8. >From 3 2 , we get 3 - 1 = 2 and 3 2 - 1 = 3 1 = 3. Multiply these numbers together to get the answer. 1 ? 8 ? 2 ? 3 = 48. What I expected "mult" to do was (somehow)to work out what the *powers* of the prime factors would be. Another reason I didn't think it was "mul" is the part that says " prime_factors_mult(n)" as the prime_factors function is just "prime_factors(n)" - without the "_mult". The website is http://wiki.python.org/moin/ProblemSets/99%20Prolog%20Problems%20Solutions#Problem33.3ADetermineiftwonumbersarecoprime I've attached a script that *should *work out the number of coprimes of 144 *Please don't bother too much about this. I've included it for your information as syou have replied, but I think I'll leave it until I understand a bit more - I'm biting off more than I can chew.* Message: 6 Date: Wed, 28 Jan 2009 08:29:09 -0000 From: "Alan Gauld" Subject: Re: [Tutor] operator, mult To: tutor at python.org Message-ID: Content-Type: text/plain; format=flowed; charset="iso-8859-1"; reply-type=original "col speed" wrote > I got the following function while googling: > > def totient(n): > from operator import mult > if n == 1: return 1 > return reduce(mult, [(p-1) * p**(m-1) for p,m in > prime_factors_mult(n)]) > > I already have the "prime_factors" function. The problem is that I > cannot > find "mult". Given it says mult is in operators then it must be (or have been in a previous version) a standard Python operator that is intended. Did it menton which version of Python was used? Is it an old site? > I tried using "mul" which is in "operator" but that is > obviously not the same thing. How so? What did it do? >>> from operator import mul >>> reduce(mul,[1,2,3,4]) 24 Does what I would expect it to do... What do you think mult should do? Alan G -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: totientmult.py Type: text/x-python Size: 862 bytes Desc: not available URL: From john at fouhy.net Thu Jan 29 05:38:50 2009 From: john at fouhy.net (John Fouhy) Date: Thu, 29 Jan 2009 17:38:50 +1300 Subject: [Tutor] operator, mult In-Reply-To: <6a1b26420901282030x5435f12akf2c7970ce6bb2663@mail.gmail.com> References: <6a1b26420901271707i7f2dcd10t708b404ad4b17636@mail.gmail.com> <5e58f2e40901271719k226ddd2fv86d0c84c8d0ad244@mail.gmail.com> <6a1b26420901271725lc08677cv210382d68ee68dbe@mail.gmail.com> <6a1b26420901282030x5435f12akf2c7970ce6bb2663@mail.gmail.com> Message-ID: <5e58f2e40901282038k7e3c9c32jc9435ffe5fc437b@mail.gmail.com> 2009/1/29 col speed : [...] > What I expected "mult" to do was (somehow)to work out what the powers of > the prime factors would be. Another reason I didn't think it was "mul" is > the part that says " prime_factors_mult(n)" as the prime_factors function > is just "prime_factors(n)" - without the "_mult". Well, it's been a while since my number theory course, so I was just going from the code comments: def totient(n): """calculate Euler's totient function. If [[p_0,m_0], [p_1,m_1], ... ] is a prime factorization of 'n', then the totient function phi(n) is given by: (p_0 - 1)*p_0**(m_0-1) * (p_1 - 1)*p_1**(m_1-1) * ... >>> phi(1) 1 >>> phi(10) 4 """ from operator import mult if n == 1: return 1 return reduce(mult, [(p-1) * p**(m-1) for p,m in prime_factors_mult(n)]) If we imagine for a moment that we have: prime_facs = [(p_0, m_0), (p_1, m_1), (p_2, m_2), (p_3, m_3)] then reduce(operator.mul, [(p-1) * p**(m-1) for p,m in prime_facs]) translates exactly to (p_0-1)*p_0**(m_0-1) * (p_1-1)*p_1**(m_1-1) * (p_2-1)*p_2**(m_2-1) * (p_3-1)*p_3**(m_3-1) which seems to match the description in the comment. -- John. From ajarncolin at gmail.com Thu Jan 29 07:59:35 2009 From: ajarncolin at gmail.com (col speed) Date: Thu, 29 Jan 2009 13:59:35 +0700 Subject: [Tutor] operator, mult In-Reply-To: <5e58f2e40901282038k7e3c9c32jc9435ffe5fc437b@mail.gmail.com> References: <6a1b26420901271707i7f2dcd10t708b404ad4b17636@mail.gmail.com> <5e58f2e40901271719k226ddd2fv86d0c84c8d0ad244@mail.gmail.com> <6a1b26420901271725lc08677cv210382d68ee68dbe@mail.gmail.com> <6a1b26420901282030x5435f12akf2c7970ce6bb2663@mail.gmail.com> <5e58f2e40901282038k7e3c9c32jc9435ffe5fc437b@mail.gmail.com> Message-ID: <6a1b26420901282259v4577f63x4a7bea848a9c4bdb@mail.gmail.com> Thanks John, That sorted me out, sometimes I just can't get things worked out in my head, then get a sense of "instant enlightenment", which your comments did for me. I am ashamed to say I was using the wrong prime factors function, then changing the mult to mul all started to make sense. Thanks again Colin 2009/1/29 John Fouhy > 2009/1/29 col speed : > [...] > > What I expected "mult" to do was (somehow)to work out what the powers > of > > the prime factors would be. Another reason I didn't think it was "mul" is > > the part that says " prime_factors_mult(n)" as the prime_factors > function > > is just "prime_factors(n)" - without the "_mult". > > Well, it's been a while since my number theory course, so I was just > going from the code comments: > > def totient(n): > """calculate Euler's totient function. > > If [[p_0,m_0], [p_1,m_1], ... ] is a prime factorization of 'n', > then the totient function phi(n) is given by: > > (p_0 - 1)*p_0**(m_0-1) * (p_1 - 1)*p_1**(m_1-1) * ... > > >>> phi(1) > 1 > >>> phi(10) > 4 > """ > from operator import mult > > if n == 1: return 1 > > return reduce(mult, [(p-1) * p**(m-1) for p,m in prime_factors_mult(n)]) > > If we imagine for a moment that we have: > > prime_facs = [(p_0, m_0), (p_1, m_1), (p_2, m_2), (p_3, m_3)] > > then > > reduce(operator.mul, [(p-1) * p**(m-1) for p,m in prime_facs]) > > translates exactly to > > (p_0-1)*p_0**(m_0-1) * (p_1-1)*p_1**(m_1-1) * (p_2-1)*p_2**(m_2-1) > * (p_3-1)*p_3**(m_3-1) > > which seems to match the description in the comment. > > -- > John. > -------------- next part -------------- An HTML attachment was scrubbed... URL: From vginer at gmail.com Thu Jan 29 08:01:00 2009 From: vginer at gmail.com (Vicent) Date: Thu, 29 Jan 2009 08:01:00 +0100 Subject: [Tutor] Defining "bit" type In-Reply-To: <497F0B6E.1010209@gmail.com> References: <50ed08f40901240625vd1b4980ta751326038adcc6c@mail.gmail.com> <497F0B6E.1010209@gmail.com> Message-ID: <50ed08f40901282301w33a0f739g900439864d584789@mail.gmail.com> On Tue, Jan 27, 2009 at 14:26, Ricardo Ar?oz wrote: > > "Vicent" wrote > > Anyway, I am working with Python 2.5.4, and I am interested in defining a > new type called "bit" (if possible), which represents a number that can > only > take values 0 or 1 ?that's what we would call a "binary variable", in a > Mathematical Programming context. > > The python manual is usually a good thing to read : > > > 3.4.1 Bit-string Operations on Integer Types > > Plain and long integer types support additional operations that make sense > only for bit-strings. Negative numbers are treated as their 2's complement > value (for long integers, this assumes a sufficiently large number of bits > that no overflow occurs during the operation). > > The priorities of the binary bit-wise operations are all lower than the > numeric operations and higher than the comparisons; the unary operation "~" > has the same priority as the other unary numeric operations ("+" and "-"). > > > This table lists the bit-string operations sorted in ascending priority > (operations in the same box have the same priority): > > Operation Result Notes x | y bitwise *or* of x and y > x ^ y bitwise *exclusive or* of x and y > x & y bitwise *and* of x and y > x << n x shifted left by n bits (1), (2) x >> n x shifted right by nbits (1), > (3) ~x the bits of x inverted > > Notes: > *(1)* Negative shift counts are illegal and cause a ValueError to be > raised. *(2)* A left shift by n bits is equivalent to multiplication by pow(2, > n) without overflow check. *(3)* A right shift by n bits is equivalent to > division by pow(2, n) without overflow check. > Ricardo, Thank you. I think I already read this, but I didn't realize that it could be useful for me. I mean, I was looking for a class that stores only 0-1 values and that is 1-bit-sized, in order to save memory and/or disk space. That's why I thought that "bool" type would be OK for me, but maybe I could also consider integers (or translating those data into integers), because of those operations that are already implemented and that you have just showed me. Anyway, I think similar operators already exist for single "bool" data. That approach you suggest would be useful in case I wanted to manage with strings of 0's and 1's (which could be possible). Thank you! -- Vicent -------------- next part -------------- An HTML attachment was scrubbed... URL: From denis.spir at free.fr Thu Jan 29 10:19:57 2009 From: denis.spir at free.fr (spir) Date: Thu, 29 Jan 2009 10:19:57 +0100 Subject: [Tutor] Defining "bit" type -- why not '!' ? In-Reply-To: <497F0B6E.1010209@gmail.com> References: <50ed08f40901240625vd1b4980ta751326038adcc6c@mail.gmail.com> <497F0B6E.1010209@gmail.com> Message-ID: <20090129101957.186f422b@o> Le Tue, 27 Jan 2009 11:26:06 -0200, Ricardo Ar?oz a ?crit : > > > "Vicent" wrote > > > >> Anyway, I am working with Python 2.5.4, and I am interested in > >> defining a > >> new type called "bit" (if possible), which represents a number that > >> can only > >> take values 0 or 1 ?that's what we would call a "binary variable", in a > >> Mathematical Programming context. > The python manual is usually a good thing to read : > > > > 3.4.1 Bit-string Operations on Integer Types > > Plain and long integer types support additional operations that make > sense only for bit-strings. Negative numbers are treated as their 2's > complement value (for long integers, this assumes a sufficiently large > number of bits that no overflow occurs during the operation). > > The priorities of the binary bit-wise operations are all lower than the > numeric operations and higher than the comparisons; the unary operation > "~" has the same priority as the other unary numeric operations ("+" and > "-"). > > This table lists the bit-string operations sorted in ascending priority > (operations in the same box have the same priority): > > Operation Result Notes > |x | y| bitwise /or/ of x and y > |x ^ y| bitwise /exclusive or/ of x and y > |x & y| bitwise /and/ of x and y > |x << n| x shifted left by n bits (1), (2) > |x >> n| x shifted right by n bits (1), (3) > |~x| the bits of x inverted Why not '!' for not, instead of '~'? I mean, '!' is used in logic, in many languages and even in python (!=). On the other hand, I had never encountered '~' meaning not. Denis ------ la vida e estranya From andreengels at gmail.com Thu Jan 29 10:26:32 2009 From: andreengels at gmail.com (Andre Engels) Date: Thu, 29 Jan 2009 10:26:32 +0100 Subject: [Tutor] Defining "bit" type -- why not '!' ? In-Reply-To: <20090129101957.186f422b@o> References: <50ed08f40901240625vd1b4980ta751326038adcc6c@mail.gmail.com> <497F0B6E.1010209@gmail.com> <20090129101957.186f422b@o> Message-ID: <6faf39c90901290126k5f289911tb237fcd025acfdad@mail.gmail.com> On Thu, Jan 29, 2009 at 10:19 AM, spir wrote: > Why not '!' for not, instead of '~'? I mean, '!' is used in logic, in many languages and even in python (!=). On the other hand, I had never encountered '~' meaning not. Although ! is indeed usual in computer languages, I disagree when you say it is used in logic. There to my knowledge the standard is ?, with ~ being used if one wants to remain within easily-accessible character sets. -- Andr? Engels, andreengels at gmail.com From denis.spir at free.fr Thu Jan 29 10:40:11 2009 From: denis.spir at free.fr (spir) Date: Thu, 29 Jan 2009 10:40:11 +0100 Subject: [Tutor] building Python 2.6? In-Reply-To: <74094.90479.qm@web112219.mail.gq1.yahoo.com> References: <74094.90479.qm@web112219.mail.gq1.yahoo.com> Message-ID: <20090129104011.613b15d3@o> Le Wed, 28 Jan 2009 19:01:24 -0800 (PST), Bernard Rankin a ?crit : > Hello, > > I am trying to build python 2.6 on a machine (web server) that I do not have root access to. (has 2.4 installed) > > Python 2.5 builds fine, but I am getting an error when I run "make" for 2.6.1 > > Here is the command line I am using: > ../configure -prefix=/home/username/local-python/ --enable-unicode=ucs4 > > (I don't know what the ucs4 thing is, but all the HOWTOs I saw say to use it. ) UCS (universal character set) is the name of the ISO norm that is +/- equivalent to unicode. ucs-4 is an encoding equivalent to utf-16, if I remenber well. > ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ > Here is what the local python reports itself as: > ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ > > Python 2.4.3 (#1, Jul 29 2007, 14:09:31) > [GCC 3.4.6 20060404 (Red Hat 3.4.6-8)] on linux2 > > ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ > Here is the error after I run "make": > ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ > [SNIP] > /home/username/local-src/Python-2.6.1/Modules/_ctypes/_ctypes.c:3941: error: syntax error before '*' token > /home/username/local-src/Python-2.6.1/Modules/_ctypes/_ctypes.c:3942: warning: function declaration isn't a prototype > /home/username/local-src/Python-2.6.1/Modules/_ctypes/_ctypes.c: In function `CFuncPtr_nonzero': > /home/username/local-src/Python-2.6.1/Modules/_ctypes/_ctypes.c:3943: error: `self' undeclared (first use in this function) > > Failed to find the necessary bits to build these modules: > _tkinter bsddb185 sunaudiodev > To find the necessary bits, look in setup.py in detect_modules() for the module's name. > > > Failed to build these modules: > _ctypes > > running build_script > ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Saw the same kind of error report for buiding ctypes, precisely, on another list. It seemed that this module's buiding is platform dependant. Well informed people said that it's not needed anyway (it allows using native C value types in python code). Don't know more myself. Denis ______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > ------ la vida e estranya From a.t.hofkamp at tue.nl Thu Jan 29 10:45:12 2009 From: a.t.hofkamp at tue.nl (A.T.Hofkamp) Date: Thu, 29 Jan 2009 10:45:12 +0100 Subject: [Tutor] Defining "bit" type -- why not '!' ? In-Reply-To: <20090129101957.186f422b@o> References: <50ed08f40901240625vd1b4980ta751326038adcc6c@mail.gmail.com> <497F0B6E.1010209@gmail.com> <20090129101957.186f422b@o> Message-ID: <49817AA8.4030603@tue.nl> spir wrote: > Le Tue, 27 Jan 2009 11:26:06 -0200, > Ricardo Ar?oz a ?crit : >> Operation Result Notes >> |x | y| bitwise /or/ of x and y >> |x ^ y| bitwise /exclusive or/ of x and y >> |x & y| bitwise /and/ of x and y >> |x << n| x shifted left by n bits (1), (2) >> |x >> n| x shifted right by n bits (1), (3) >> |~x| the bits of x inverted > > Why not '!' for not, instead of '~'? I mean, '!' is used in logic, in many languages and even in python (!=). On the other hand, I had never encountered '~' meaning not. Watch out here, the above operations work on integer values, not on single bits. In that context, 'not' and '~' are two different operations. 'not v' inverts the logical value of v (that is, it computes 'not (v != 0)'). '~v' on the other hand, swaps all bits of the integer value. print ~1 # gives '-2' as result print not 1 # gives 'False' as result Sincerely, Albert From alan.gauld at btinternet.com Thu Jan 29 10:47:22 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 29 Jan 2009 09:47:22 -0000 Subject: [Tutor] Defining "bit" type -- why not '!' ? References: <50ed08f40901240625vd1b4980ta751326038adcc6c@mail.gmail.com> <497F0B6E.1010209@gmail.com><20090129101957.186f422b@o> <6faf39c90901290126k5f289911tb237fcd025acfdad@mail.gmail.com> Message-ID: "Andre Engels" wrote >> Why not '!' for not, instead of '~'? I mean, '!' is used in logic, > in many languages and even in python (!=). On the other hand, > I had never encountered '~' meaning not. > > Although ! is indeed usual in computer languages, I disagree when > you > say it is used in logic. There to my knowledge the standard is ?, > with > ~ being used if one wants to remain within easily-accessible > character > sets. And both statements are correct. The symbols directly trace back to C where ! meant logical not and ~ meant bitwise not. The latter symbol being chosen because it was sometimes used in maths for not... (Why they chose ! for logical not I don't know!) Python (and many other languages since) simply passes on its C heritage -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Thu Jan 29 10:50:59 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 29 Jan 2009 09:50:59 -0000 Subject: [Tutor] Find a Word in *.py (Win XP) References: <3c6718980901281825p1888b923se3284538d91d626f@mail.gmail.com> Message-ID: "Justin Ezequiel" wrote >> How insane that XP doesn't search the text in "non text" files! >> > > http://support.microsoft.com/default.aspx?scid=KB;EN-US;q309173 > > I used Method 2 under Resolution recently when I reinstalled XP on a > new harddisk. Yes that looks like it should fix it. I'll try that later, Thanks, Alan G From alan.gauld at btinternet.com Thu Jan 29 10:59:28 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 29 Jan 2009 09:59:28 -0000 Subject: [Tutor] IDLE vs PythonWin References: <49810945.8050402@sbcglobal.net> Message-ID: "Wayne Watson" wrote > About three weeks ago I decided to give PythonWin a whirl. > I believe I've noticed about as many code "wrecks" as with IDLE. Really? I haven't had many problems. > That is, while working repeatedly on a program, > the editor got confused about what it had available, > usually remnants of previous code. The editor or the interactive shell? The editor doesn't really display much knowlege of the code. How are you using Pythonwin to get that error? Are you importing your module into the shell? Or are you using Run with F5? > I just tried to print a very small program in PWin and it printed > five blank pages with a small title on each. I've never seen that. Are you sure you didn't have a lot of white space under the code or something? > interactive window being part of the larger window with the > program windows, I'm not much in favor of it any more. MDI used to be the official Windows style but since XP came out SDI has taken over. Pythonwin is still firmly in the MDI camp. Its very much a matter of taste, although I'm fairly ambivalent. The Window menu is your friend :-) > It may be time to move on to another editor or return to IDLE. There are so many to choose from, One is sure to suit you :-) Personally I still prefer 3 separate windows for intensive coding. 1) running vim(or increasingly Scite) for editing 2) running a standard python shell (sometimes PyCrust) 3) an OS prompt for testing. Alt-Tab and up-arrow for navigating between windows/commands works for me :-) -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From denis.spir at free.fr Thu Jan 29 11:32:36 2009 From: denis.spir at free.fr (spir) Date: Thu, 29 Jan 2009 11:32:36 +0100 Subject: [Tutor] Defining "bit" type -- why not '!' ? In-Reply-To: References: <50ed08f40901240625vd1b4980ta751326038adcc6c@mail.gmail.com> <497F0B6E.1010209@gmail.com> <20090129101957.186f422b@o> <6faf39c90901290126k5f289911tb237fcd025acfdad@mail.gmail.com> Message-ID: <20090129113236.2465f5ef@o> Le Thu, 29 Jan 2009 09:47:22 -0000, "Alan Gauld" a ?crit : > > "Andre Engels" wrote > > >> Why not '!' for not, instead of '~'? I mean, '!' is used in logic, > > in many languages and even in python (!=). On the other hand, > > I had never encountered '~' meaning not. > > > > Although ! is indeed usual in computer languages, I disagree when > > you > > say it is used in logic. There to my knowledge the standard is ?, > > with > > ~ being used if one wants to remain within easily-accessible > > character > > sets. Thank you for all your answers Albert, Andre, Alan (the 3A gang ;-}). Here is an overal and a trial to introduce my view on this topic. I'm aware that "not 1" is not the same as "~1" in python. And I agree with that, while I disagree on how it is different. As I see it, both operators have a close meaning, so that using the same sign (and the same underlying method name, e.g. __not__) should be allright. This is a common practice in python and many languages that support OOP. The flaw here in python is to treat integers as logical values, like if they were bools. This is for me a conceptual error. So that: * If 'not' is only a plain logical operator, then "not 1" must raise TypeError. * On the hand hand, "extended logic", meaning apply logic operators to non-logic values (e.g. "if not s" instead of "if s==''" or "isEmpty(s)"), is seen by many as a useful feature. * If 'not' (or '!', or '~') has an extended meaning, and integers are additionally considered as byte sequences, then it is sensible to give "not 1" a semantics of bitwise not. So we don't need both "not 1" and "~1". * In the latter case, if I understand correctly the new 'byte' type, then bitwise logical operations should rather be applied to byte, than to integers. * The mix of "extended logic" on non-logical types and treating integers as bit sequences provakes a kind of conceptual collision. * As a solution, bitwise operations may apply only to a type (byte or int) on which "extended logic" raises an TypeError. Denis ------ la vida e estranya From emmanuel.delaborde at cimex.com Thu Jan 29 12:06:57 2009 From: emmanuel.delaborde at cimex.com (emmanuel.delaborde) Date: Thu, 29 Jan 2009 11:06:57 +0000 Subject: [Tutor] Problem with nested for-in Message-ID: <80B644F1-D6C0-4B79-BB9C-5D9EC9E7ABCE@cimex.com> Hello, I have the following snippet : lines = csv.reader(open("CATEGORY.csv","r")) lines2 = csv.reader(open("CATEGORYLIST.csv","r")) old_cats = [] for line in lines: stories = [] for line2 in lines2: if line2[1] == line[0]: stories.append(line2[0]) old_cats.append((line[0],line[2], stories)) what happens is that for the first elt of lines, the nested for in runs fine but then never seem to run again while the top level loop iterates through the rest of lines consequently stories accumulate nothing... Can someone explain please ? Thanks E ----------------------------------------------------------------------------------------------- This e-mail (and any attachments) is confidential and may contain personal views which are not the views of Cimex Media Ltd and any affiliated companies, unless specifically stated. It is intended for the use of the individual or group to whom it is addressed. If you have received it in error, please delete it from your system, do not use, copy or disclose the information in any way nor act in reliance on it and please notify postmaster at cimex.com A company registered in England Wales. Company Number 03765711 Registered Office : The Olde Bakehouse, 156 Watling Street East, Towcester, Northants NN12 6DB This email was scanned by Postini, the leading provider in Managed Email Security. From srilyk at gmail.com Thu Jan 29 12:43:37 2009 From: srilyk at gmail.com (W W) Date: Thu, 29 Jan 2009 05:43:37 -0600 Subject: [Tutor] Problem with nested for-in In-Reply-To: <80B644F1-D6C0-4B79-BB9C-5D9EC9E7ABCE@cimex.com> References: <80B644F1-D6C0-4B79-BB9C-5D9EC9E7ABCE@cimex.com> Message-ID: <333efb450901290343t287419bfq3757a7e9590630@mail.gmail.com> On Thu, Jan 29, 2009 at 5:06 AM, emmanuel.delaborde < emmanuel.delaborde at cimex.com> wrote: > Hello, > > I have the following snippet : > > lines = csv.reader(open("CATEGORY.csv","r")) > lines2 = csv.reader(open("CATEGORYLIST.csv","r")) > > old_cats = [] > for line in lines: print line > > stories = [] > for line2 in lines2: print line2 > > if line2[1] == line[0]: > stories.append(line2[0]) > old_cats.append((line[0],line[2], stories)) > > > what happens is that > > for the first elt of lines, the nested for in runs fine > but then never seem to run again while the top level loop iterates through > the rest of lines > > consequently stories accumulate nothing... > > Can someone explain please ? > I would try adding the two print statements above to your code. It might give you an idea about what's going on. It would also be helpful to provide us with some of your original data and the data you get once you've run the program. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Jan 29 13:17:24 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 29 Jan 2009 12:17:24 -0000 Subject: [Tutor] Problem with nested for-in References: <80B644F1-D6C0-4B79-BB9C-5D9EC9E7ABCE@cimex.com> Message-ID: "emmanuel.delaborde" wrote > I have the following snippet : > > lines = csv.reader(open("CATEGORY.csv","r")) > lines2 = csv.reader(open("CATEGORYLIST.csv","r")) > > old_cats = [] > for line in lines: > stories = [] > for line2 in lines2: > if line2[1] == line[0]: > stories.append(line2[0]) > old_cats.append((line[0],line[2], stories)) > > > what happens is that > > for the first elt of lines, the nested for in runs fine > but then never seem to run again while the top level loop iterates > through the rest of lines I suspect that you need to reset the reader iterator to the start. I'm sure there will be something in the iterator protocol to do that but failing that you would need to change the inner loop to: for line2 in csv.reader(open("CATEGORYLIST.csv","r")) which will re-read the file and create a new iterator each time... resetting the iterator would be faster I suspect. Alan G. From alan.gauld at btinternet.com Thu Jan 29 13:22:29 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 29 Jan 2009 12:22:29 -0000 Subject: [Tutor] Defining "bit" type -- why not '!' ? References: <50ed08f40901240625vd1b4980ta751326038adcc6c@mail.gmail.com> <497F0B6E.1010209@gmail.com><20090129101957.186f422b@o><6faf39c90901290126k5f289911tb237fcd025acfdad@mail.gmail.com> <20090129113236.2465f5ef@o> Message-ID: "spir" wrote > Here is an overal and a trial to introduce my view on this topic. ... > * The mix of "extended logic" on non-logical types and treating > integers > as bit sequences provakes a kind of conceptual collision. > * As a solution, bitwise operations may apply only to a type (byte > or int) > on which "extended logic" raises an TypeError. You are probably correct but it would break a ton of working code! Especially when you recall that bool types were only introduced relatively recently so a lot of old code relies on the fact that True/False were until then literally 1/0. Maybe it is "improved" in Python 3. As you say the ~ operator makes most sense if applied to bytes only. But for compatibility reasons I suspect they have kept it as-is... Alan G From emmanuel.delaborde at cimex.com Thu Jan 29 14:38:31 2009 From: emmanuel.delaborde at cimex.com (emmanuel.delaborde) Date: Thu, 29 Jan 2009 13:38:31 +0000 Subject: [Tutor] Fwd: Problem with nested for-in References: <333efb450901290343t287419bfq3757a7e9590630@mail.gmail.com> Message-ID: <611FF21D-F948-4427-925F-9BD7D38D1C73@cimex.com> Hello I hope this will be clearer here is the script : #################################### # -*- coding: utf-8 -*- import csv lines = csv.reader(open("CATEGORY.csv","r")) lines2 = csv.reader(open("CATEGORYLIST.csv","r")) old_cats = [] for line in lines: print line stories = [] for line2 in lines2: print "\t%s == %s ? %s" % (line2[1], line[0], line2[1] == line[0]) if line2[1] == line[0]: stories.append(line2[0]) old_cats.append((line[0],line[2], stories)) #################################### here's the output : ['100701', '22', 'Water softeners', '2', '0', '100401'] 21092 == 100701 ? False 100418 == 100701 ? False 100440 == 100701 ? False 100405 == 100701 ? False 100704 == 100701 ? False 21079 == 100701 ? False 21081 == 100701 ? False 21075 == 100701 ? False 21085 == 100701 ? False 21076 == 100701 ? False 21082 == 100701 ? False 21085 == 100701 ? False 21092 == 100701 ? False 100396 == 100701 ? False 100700 == 100701 ? False 100335 == 100701 ? False 100335 == 100701 ? False 100420 == 100701 ? False 100421 == 100701 ? False 100335 == 100701 ? False 100337 == 100701 ? False ['100702', '22', 'Garment processing', '2', '0', '100491'] ['100703', '22', 'Fume hoods', '2', '0', '100441'] ['100704', '22', 'Tank vent breathers', '2', '0', '100405'] ['100705', '22', 'Absorbent paper', '2', '0', '100438'] ['100706', '22', 'Packaging machinery & equipment', '2', '0', '100403'] ['100707', '22', 'Copper', '2', '0', '100428'] ['100708', '22', 'Silver', '2', '0', '100428'] ['100709', '22', 'Clinical waste disposal', '2', '0', '100418'] ['100710', '22', 'Air decontamination systems', '2', '0', '100342'] ['100711', '22', 'Instrument cleaner-processors', '2', '0', '100438'] ['100712', '22', 'Pathogen identification', '2', '0', '100404'] ['100713', '22', 'Biocidal wipes', '2', '0', '100517'] ['100714', '22', 'Medical devices', '2', '0', '100418'] ['100715', '22', 'Testing', '2', '0', '100491'] when can see that the inner loop is only executed for the first item of the top-level loop... I've attached the 2 CSV files. Thanks Begin forwarded message: > From: W W > Date: 29 January 2009 11:43:37 GMT > To: "emmanuel.delaborde" > Cc: tutor at python.org > Subject: Re: [Tutor] Problem with nested for-in > > On Thu, Jan 29, 2009 at 5:06 AM, emmanuel.delaborde > wrote: > Hello, > > I have the following snippet : > > lines = csv.reader(open("CATEGORY.csv","r")) > lines2 = csv.reader(open("CATEGORYLIST.csv","r")) > > old_cats = [] > for line in lines: > print line > > stories = [] > for line2 in lines2: > print line2 > > if line2[1] == line[0]: > stories.append(line2[0]) > old_cats.append((line[0],line[2], stories)) > > > what happens is that > > for the first elt of lines, the nested for in runs fine > but then never seem to run again while the top level loop iterates > through the rest of lines > > consequently stories accumulate nothing... > > Can someone explain please ? > > I would try adding the two print statements above to your code. It > might give you an idea about what's going on. It would also be > helpful to provide us with some of your original data and the data > you get once you've run the program. > > HTH, > Wayne ----------------------------------------------------------------------------------------------- This e-mail (and any attachments) is confidential and may contain personal views which are not the views of Cimex Media Ltd and any affiliated companies, unless specifically stated. It is intended for the use of the individual or group to whom it is addressed. If you have received it in error, please delete it from your system, do not use, copy or disclose the information in any way nor act in reliance on it and please notify postmaster at cimex.com A company registered in England Wales. Company Number 03765711 Registered Office : The Olde Bakehouse, 156 Watling Street East, Towcester, Northants NN12 6DB This email was scanned by Postini, the leading provider in Managed Email Security. -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: CATEGORYLIST.csv Type: application/octet-stream Size: 283 bytes Desc: not available URL: -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: CATEGORY.csv Type: application/octet-stream Size: 633 bytes Desc: not available URL: -------------- next part -------------- An HTML attachment was scrubbed... URL: From emmanuel.delaborde at cimex.com Thu Jan 29 14:55:13 2009 From: emmanuel.delaborde at cimex.com (emmanuel.delaborde) Date: Thu, 29 Jan 2009 13:55:13 +0000 Subject: [Tutor] Problem with nested for-in (Alan Gauld) In-Reply-To: References: Message-ID: <0CCFE497-38FE-469D-A89A-49B3ED9D0FE8@cimex.com> > > I suspect that you need to reset the reader iterator to the start. > I'm sure there will be something in the iterator protocol to do > that but failing that you would need to change the inner loop to: > > for line2 in csv.reader(open("CATEGORYLIST.csv","r")) > > which will re-read the file and create a new iterator each time... > resetting the iterator would be faster I suspect. > > Alan G. > > You are right, of course! It did the trick Thank you E. ----------------------------------------------------------------------------------------------- This e-mail (and any attachments) is confidential and may contain personal views which are not the views of Cimex Media Ltd and any affiliated companies, unless specifically stated. It is intended for the use of the individual or group to whom it is addressed. If you have received it in error, please delete it from your system, do not use, copy or disclose the information in any way nor act in reliance on it and please notify postmaster at cimex.com A company registered in England Wales. Company Number 03765711 Registered Office : The Olde Bakehouse, 156 Watling Street East, Towcester, Northants NN12 6DB This email was scanned by Postini, the leading provider in Managed Email Security. From kent37 at tds.net Thu Jan 29 16:22:02 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 29 Jan 2009 10:22:02 -0500 Subject: [Tutor] Defining "bit" type -- why not '!' ? In-Reply-To: <20090129113236.2465f5ef@o> References: <50ed08f40901240625vd1b4980ta751326038adcc6c@mail.gmail.com> <497F0B6E.1010209@gmail.com> <20090129101957.186f422b@o> <6faf39c90901290126k5f289911tb237fcd025acfdad@mail.gmail.com> <20090129113236.2465f5ef@o> Message-ID: <1c2a2c590901290722m675e2f09wb5c8cda1220e54ad@mail.gmail.com> On Thu, Jan 29, 2009 at 5:32 AM, spir wrote: > I'm aware that "not 1" is not the same as "~1" in python. And I agree with that, while I disagree on how it is different. As I see it, both operators have a close meaning, so that using the same sign (and the same underlying method name, e.g. __not__) should be allright. This is a common practice in python and many languages that support OOP. > The flaw here in python is to treat integers as logical values, like if they were bools. This is for me a conceptual error. So that: > > * If 'not' is only a plain logical operator, then "not 1" must raise TypeError. > * On the hand hand, "extended logic", meaning apply logic operators to non-logic values (e.g. "if not s" instead of "if s==''" or "isEmpty(s)"), is seen by many as a useful feature. > * If 'not' (or '!', or '~') has an extended meaning, and integers are additionally considered as byte sequences, then it is sensible to give "not 1" a semantics of bitwise not. So we don't need both "not 1" and "~1". That way lies madness, you would have a situation where both these expressions would be True for any non-zero integer: not(bool(x)) != bool(not(x)) (x or not x) == False Kent From kent37 at tds.net Thu Jan 29 16:26:14 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 29 Jan 2009 10:26:14 -0500 Subject: [Tutor] Problem with nested for-in (Alan Gauld) In-Reply-To: <0CCFE497-38FE-469D-A89A-49B3ED9D0FE8@cimex.com> References: <0CCFE497-38FE-469D-A89A-49B3ED9D0FE8@cimex.com> Message-ID: <1c2a2c590901290726x229c1b39gd0c9aa4c44ead4c7@mail.gmail.com> On Thu, Jan 29, 2009 at 8:55 AM, emmanuel.delaborde wrote: >> >> I suspect that you need to reset the reader iterator to the start. >> I'm sure there will be something in the iterator protocol to do >> that No, in general iterators cannot be reset. >> but failing that you would need to change the inner loop to: >> >> for line2 in csv.reader(open("CATEGORYLIST.csv","r")) >> >> which will re-read the file and create a new iterator each time... >> resetting the iterator would be faster I suspect. Better would be to read the lines into a list before the first loop: lines2 = list(csv.reader(("CATEGORYLIST.csv","r")) Then lines2 can be iterated as many times as you like. What are you trying to do? Generally problems of the form for item in list1: if item in list2: # do something with item have better solutions using sets or dicts in place of list2. Kent From denis.spir at free.fr Thu Jan 29 16:29:05 2009 From: denis.spir at free.fr (spir) Date: Thu, 29 Jan 2009 16:29:05 +0100 Subject: [Tutor] Problem with nested for-in In-Reply-To: <80B644F1-D6C0-4B79-BB9C-5D9EC9E7ABCE@cimex.com> References: <80B644F1-D6C0-4B79-BB9C-5D9EC9E7ABCE@cimex.com> Message-ID: <20090129162905.6ca17f6b@o> Le Thu, 29 Jan 2009 11:06:57 +0000, "emmanuel.delaborde" a ?crit : > Hello, > > I have the following snippet : > > lines = csv.reader(open("CATEGORY.csv","r")) > lines2 = csv.reader(open("CATEGORYLIST.csv","r")) > > old_cats = [] > for line in lines: > stories = [] > for line2 in lines2: > if line2[1] == line[0]: > stories.append(line2[0]) > old_cats.append((line[0],line[2], stories)) > > > what happens is that > > for the first elt of lines, the nested for in runs fine > but then never seem to run again while the top level loop iterates > through the rest of lines > > consequently stories accumulate nothing... > > Can someone explain please ? > > Thanks > > E I rewrote you nested loop only to have it clearer to my eyes: for line in lines: word0 = line[0] stories = [line2[0] for line2 in lines2 if line2[1] == word0] old_cats.append((line[0],line[2], stories)) (word0 is here only to avoid computing it for each line2) Only a guess: if ever cvs.reader returns an iterator, instead of a list, then once it has reached last line it is "like empty" (raises StopIterator). So that the internal loop can be walked thru only once -- like if lines2 was empty. To check that, simply to outputing twice all items in lines1 or lines 2. Or output lines2's type. If this is the issue, remedies can be: * rebuild lines2 for each iteration inside the outer loop * cast lines2 into a list (I don't have any csv file to test) Denis ------ la vida e estranya From sierra_mtnview at sbcglobal.net Thu Jan 29 16:39:33 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Thu, 29 Jan 2009 07:39:33 -0800 Subject: [Tutor] IDLE vs PythonWin In-Reply-To: References: <49810945.8050402@sbcglobal.net> Message-ID: <4981CDB5.9080808@sbcglobal.net> An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Thu Jan 29 17:38:37 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Thu, 29 Jan 2009 08:38:37 -0800 Subject: [Tutor] IDLE vs PythonWin In-Reply-To: <589697.85007.qm@web86706.mail.ird.yahoo.com> References: <49810945.8050402@sbcglobal.net> <49819EBA.3030208@sbcglobal.net> <589697.85007.qm@web86706.mail.ird.yahoo.com> Message-ID: <4981DB8D.5050108@sbcglobal.net> An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: moz-screenshot-165.jpg Type: image/jpeg Size: 25184 bytes Desc: not available URL: From berankin99 at yahoo.com Thu Jan 29 18:01:16 2009 From: berankin99 at yahoo.com (Bernard Rankin) Date: Thu, 29 Jan 2009 09:01:16 -0800 (PST) Subject: [Tutor] building Python 2.6? References: <74094.90479.qm@web112219.mail.gq1.yahoo.com> <20090129104011.613b15d3@o> Message-ID: <207556.39783.qm@web112213.mail.gq1.yahoo.com> > > Python 2.5 builds fine, but I am getting an error when I run "make" for 2.6.1 > > > > Here is the command line I am using: > > ../configure -prefix=/home/username/local-python/ --enable-unicode=ucs4 > > > > (I don't know what the ucs4 thing is, but all the HOWTOs I saw say to use it. > ) > > UCS (universal character set) is the name of the ISO norm that is +/- equivalent > to unicode. ucs-4 is an encoding equivalent to utf-16, if I remenber well. > Is this something I need? Do it hurt to use it? > > ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ > > Here is what the local python reports itself as: > > ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ > > > > Python 2.4.3 (#1, Jul 29 2007, 14:09:31) > > [GCC 3.4.6 20060404 (Red Hat 3.4.6-8)] on linux2 > > > > ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ > > Here is the error after I run "make": > > ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ > > [SNIP] > > /home/username/local-src/Python-2.6.1/Modules/_ctypes/_ctypes.c:3941: error: > syntax error before '*' token > > /home/username/local-src/Python-2.6.1/Modules/_ctypes/_ctypes.c:3942: warning: > function declaration isn't a prototype > > /home/username/local-src/Python-2.6.1/Modules/_ctypes/_ctypes.c: In function > `CFuncPtr_nonzero': > > /home/username/local-src/Python-2.6.1/Modules/_ctypes/_ctypes.c:3943: error: > `self' undeclared (first use in this function) > > > > Failed to find the necessary bits to build these modules: > > _tkinter bsddb185 sunaudiodev > > To find the necessary bits, look in setup.py in detect_modules() for the > module's name. > > > > > > Failed to build these modules: > > _ctypes > > > > running build_script > > ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ > > Saw the same kind of error report for buiding ctypes, precisely, on another > list. It seemed that this module's buiding is platform dependant. Well informed > people said that it's not needed anyway (it allows using native C value types in > python code). > Don't know more myself. > Hmm.... Do I need ctypes to use TurboGears/Pylons/etc? Is the problem fixable? If I chose to not use ctypes, how do I correctly build 2.6 without it? Thank you :) From bgailer at gmail.com Thu Jan 29 18:52:21 2009 From: bgailer at gmail.com (bob gailer) Date: Thu, 29 Jan 2009 12:52:21 -0500 Subject: [Tutor] Find a Word in *.py (Win XP) In-Reply-To: <3c6718980901281825p1888b923se3284538d91d626f@mail.gmail.com> References: <3c6718980901281825p1888b923se3284538d91d626f@mail.gmail.com> Message-ID: <4981ECD5.1000804@gmail.com> Justin Ezequiel wrote: >> How insane that XP doesn't search the text in "non text" files! >> >> -- >> Alan Gauld >> > > http://support.microsoft.com/default.aspx?scid=KB;EN-US;q309173 > > I used Method 2 under Resolution recently when I reinstalled XP on a > new harddisk. Thanks for that. Also works with 2003 Server. -- Bob Gailer Chapel Hill NC 919-636-4239 From kent37 at tds.net Thu Jan 29 19:27:23 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 29 Jan 2009 13:27:23 -0500 Subject: [Tutor] Problem with nested for-in (Alan Gauld) In-Reply-To: <1E608955-1443-4647-B542-536F26B65CC0@cimex.com> References: <0CCFE497-38FE-469D-A89A-49B3ED9D0FE8@cimex.com> <1c2a2c590901290726x229c1b39gd0c9aa4c44ead4c7@mail.gmail.com> <1E608955-1443-4647-B542-536F26B65CC0@cimex.com> Message-ID: <1c2a2c590901291027v4a5a6753o8df12efaccd0d262@mail.gmail.com> On Thu, Jan 29, 2009 at 12:21 PM, emmanuel.delaborde wrote: > On 29 Jan 2009, at 15:26, Kent Johnson wrote: >> What are you trying to do? Generally problems of the form >> for item in list1: >> if item in list2: >> # do something with item >> > > the first csv file is a list of rows like this : cat_code, ... other > irrelevent fields here ... > > the second csv file is a list of rows like this : story_code, cat_code > (there can be many story_code for each cat_code) > > I am trying to build the list of story_code for each cat_code in the first > file > > (it really is similar to a SQL join, funny things is these CSV files ARE > table dumps...) OK, so make a dict that maps cat_code to a list of story_code and look up the cat_codes in the dict. For example (untested, not explained much either), # Build a dict mapping cat_codes to a list of story_codes from collections import defaultdict cat_to_story = defaultdict(list) lines2 = csv.reader(open("CATEGORYLIST.csv","r")) for line2 in lines2: cat_to_story[line2[1]].append(line2[0]) # Now you can build old_cats easily, using dictionary lookup instead of search # (this assumes every cat_code in lines is in the dict lines = csv.reader(open("CATEGORY.csv","r")) old_cats = [(line[0],line[2], cat_to_story[line[0])] > building the dictionnary would lead to a similar iterator reset problem > though... No, because you build the dict once. > I am not very familiar with the set data type, are you talking about its > specific set operations like intersection, union etc... ? Yes; or testing for membership. Kent From vginer at gmail.com Thu Jan 29 19:59:09 2009 From: vginer at gmail.com (Vicent) Date: Thu, 29 Jan 2009 19:59:09 +0100 Subject: [Tutor] Properties of an object Message-ID: <50ed08f40901291059i50f11a17v2f21f9ada66ed463@mail.gmail.com> This is an easy question, I guess, but I am not able to find out the answer. In fact, it is both a Python question and a general programming "style" question. I want to define a class that contains a list (or a NumPy array) of elements of a certain type, and an integer: class ExampleList : def __init__(self, list, position) : self.list = list self.position = position This is clear to me. My first question, which is Python related: (1) Where are the right places to define PROPERTIES for my class, and how (I mean, which is the right syntax) must I define them? As far as I know, the usual place where properties are "declared" and assigned is in the __init__ function. Can I define properties in other parts of the "Class" code? I am not able to deduce it from the things I've read. I've also seen sometimes something like this: class ExampleFoo : _property1 = 0 [...] And I think that later I found "self._property1" or "self.property1", but I am not sure of that. Anyway, why the prefix "_", and what does that definition "_property = 0" mean and imply? Coming back to my ExampleList, I have another "philosophic" question. Suppose I'm interested (many times within my "main" program) to recover a part of the list contained by an ExampleList object. To be more clear: >>> a = ExampleList([1,2,3,4], 2) >>> a.list [1, 2, 3, 4] >>> a.position 2 I want to get the second part of the list, I mean, the part of list a.list that goes from position a.position until the last element in the list. I know I can do it like this: >>> a.list[a.position:] [3, 4] Or, if I want the first part of the list: >>> a.list[:a.position] [1, 2] My problem/question/dilemma: I want to define it as a property or as a method in the class definition, because I am going to need many times "the first part of te list" or "the second part of the list". For me, I see it as a property of the object, I mean: "tell me which is your first part". It is not like an action over the object or to/from/related to the object (that would be a method, then). So, this kind of "derived" properties (because they are based on two other previously defined "primary" properties) are better to be defined as methods, or it is the same? I mean, what I would like to do is this: class ExampleList : def __init__(self, list, position) : self.list = list self.position = position self.list_1stpart = self.list[:self.position] self.list_2ndpart = self.list[self.position:] Is that right? Is that good practice? If I want to define self.list_1stpart as a property, is the __init__ function the only and the best place to do it? If not, I suppose I'll have to define it as a method, and then it will look like something like this: [... within the class definition ...] def list_1stpart(self) : return self.list[:self.position] Then I'll call the method like this: >>> a.list_1stpart() [1, 2] For me, the "()" look like artificial, not necessary. I would prefer just to type "a.list_1stpart" , a property. The general case is (the second question): (2) properties which can be derived from other "primary" properties, are they just methods?? I don't know which approach is more correct, from any point of view... By the way, does the "property" approach consume much memory or space than the "method" approach?? Thank you very much for your patience... -- Vicent -------------- next part -------------- An HTML attachment was scrubbed... URL: From andreengels at gmail.com Thu Jan 29 22:27:07 2009 From: andreengels at gmail.com (Andre Engels) Date: Thu, 29 Jan 2009 22:27:07 +0100 Subject: [Tutor] Properties of an object In-Reply-To: <50ed08f40901291059i50f11a17v2f21f9ada66ed463@mail.gmail.com> References: <50ed08f40901291059i50f11a17v2f21f9ada66ed463@mail.gmail.com> Message-ID: <6faf39c90901291327n5e46cc97g31842480b5527c52@mail.gmail.com> On Thu, Jan 29, 2009 at 7:59 PM, Vicent wrote: > This is an easy question, I guess, but I am not able to find out the answer. > > In fact, it is both a Python question and a general programming "style" > question. > > I want to define a class that contains a list (or a NumPy array) of elements > of a certain type, and an integer: > > class ExampleList : > def __init__(self, list, position) : > self.list = list > self.position = position > > > This is clear to me. > > My first question, which is Python related: > > (1) Where are the right places to define PROPERTIES for my class, and how (I > mean, which is the right syntax) must I define them? > > As far as I know, the usual place where properties are "declared" and > assigned is in the __init__ function. > > Can I define properties in other parts of the "Class" code? I am not able to > deduce it from the things I've read. Yes, you can do it wherever you like. Even outside the class code (although it makes your code resemble a board of badly boiled spaghetti). However, the __init__ method is in most cases the 'best' place to do it - that ensures that every member of the class has their properties set. If you do it in another method, or outside the class, you have problems in ensuring that the property is not used before it comes into existence. > I've also seen sometimes something like this: > > > class ExampleFoo : > _property1 = 0 > > [...] > > And I think that later I found "self._property1" or "self.property1", but I > am not sure of that. Anyway, why the prefix "_", and what does that > definition "_property = 0" mean and imply? The definition says tat the property gets the value for all members of the class. I have only seen it done this way when it is not changed later, except in the definition of subclasses. The prefix "_" means that the property is supposed to be private, that is, it should not be accessed from outside the class. This may be because it doesn't really have any meaning for te outside, or because you want to keep the option of defining your class differently, having the property get a somewhat different meaning or even be completely removed. However, Python is very flexible at this point. Many languages allow you to declare a variable to be 'private', which means it is not visible at all from the outside. Python uses the "consenting adults" philosophy here - if, despite the starting _ you still try to access the variable from the outside, Python assumes that you know what you are doing, and will let you do it without any objection. In fact, the _ is not even an official part of the language; rather, it is more a coding style that many Python programmers use. > Coming back to my ExampleList, I have another "philosophic" question. > > Suppose I'm interested (many times within my "main" program) to recover a > part of the list contained by an ExampleList object. To be more clear: > >>>> a = ExampleList([1,2,3,4], 2) >>>> a.list > [1, 2, 3, 4] >>>> a.position > 2 > > I want to get the second part of the list, I mean, the part of list > a.list that goes from position a.position until the last element in > the list. > > I know I can do it like this: > >>>> a.list[a.position:] > [3, 4] > > Or, if I want the first part of the list: > >>>> a.list[:a.position] > [1, 2] > > > My problem/question/dilemma: I want to define it as a property or as a > method in the class definition, because I am going to need many times "the > first part of te list" or "the second part of the list". > > For me, I see it as a property of the object, I mean: "tell me which is your > first part". It is not like an action over the object or to/from/related to > the object (that would be a method, then). > > So, this kind of "derived" properties (because they are based on two other > previously defined "primary" properties) are better to be defined as > methods, or it is the same? > > I mean, what I would like to do is this: > > class ExampleList : > def __init__(self, list, position) : > self.list = list > self.position = position > self.list_1stpart = self.list[:self.position] > self.list_2ndpart = self.list[self.position:] > > > Is that right? Is that good practice? If I want to define > self.list_1stpart as a property, is the __init__ function the only and > the best place to do it? > > If not, I suppose I'll have to define it as a method, and then it will look > like something like this: > > [... within the class definition ...] > > def list_1stpart(self) : > return self.list[:self.position] > > > Then I'll call the method like this: > >>>> a.list_1stpart() > [1, 2] > > For me, the "()" look like artificial, not necessary. I would prefer just to > type "a.list_1stpart" , a property. > > The general case is (the second question): > > (2) properties which can be derived from other "primary" properties, are > they just methods?? > > I don't know which approach is more correct, from any point of view... By > the way, does the "property" approach consume much memory or space than the > "method" approach?? The amount of extra memory is negligible, and also counteracted by a (just as negligible) gain in speed. However, your method has a disadvantage in making it harder to keep the code correct if you extend it. Suppose in the future you want to make it so that after the object has been created, its list can be changed. In your method, there are 4 properties that you have to keep an eye on rather than 2, increasing the chance of errors. Also, if you always write a.getList() and a.getListFirstPart() rather than a.list and a.listFirstPart, you or someone else writing your code will be much less tempted to try to change it through "a.list = foobar" or "a.listFirstPart = foobar" (which will cause a 'wrong' state), rather than through "a.setList(foobar)" or "a.setListFirstPart(foobar)", the effect of which is completely under your control. Because of this, I prefer to do _everything_ through methods rather than outside usage of variables. -- Andr? Engels, andreengels at gmail.com From denis.spir at free.fr Thu Jan 29 23:04:40 2009 From: denis.spir at free.fr (spir) Date: Thu, 29 Jan 2009 23:04:40 +0100 Subject: [Tutor] Properties of an object In-Reply-To: <50ed08f40901291059i50f11a17v2f21f9ada66ed463@mail.gmail.com> References: <50ed08f40901291059i50f11a17v2f21f9ada66ed463@mail.gmail.com> Message-ID: <20090129230440.61f2102f@o> Le Thu, 29 Jan 2009 19:59:09 +0100, Vicent a ?crit : > This is an easy question, I guess, but I am not able to find out the answer. > > In fact, it is both a Python question and a general programming "style" > question. > > I want to define a class that contains a list (or a NumPy array) of elements > of a certain type, and an integer: > > class ExampleList : > def __init__(self, list, position) : > self.list = list > self.position = position > > > This is clear to me. > > My first question, which is Python related: > > (1) Where are the right places to define PROPERTIES for my class, and how (I > mean, which is the right syntax) must I define them? > > As far as I know, the usual place where properties are "declared" and > assigned is in the __init__ function. > > Can I define properties in other parts of the "Class" code? I am not able to > deduce it from the things I've read. > > I've also seen sometimes something like this: > > > class ExampleFoo : > _property1 = 0 > > [...] > > And I think that later I found "self._property1" or "self.property1", but I > am not sure of that. Anyway, why the prefix "_", and what does that > definition "_property = 0" mean and imply? Rather pleased to read such a question here, because when I speak like that the reactions let me feel like if I were a martian ;-} [I think I get why you are trouble, why the "python way" seems strange, so I will try to answer. But my words are to be read strictly as a personal view. They probably do not reflect the views of the majority.] There is no real native support for ordinary OOP in python, meaning as is done in most other languages, or according to the theory. There is instead a POOP, where the first P stands for 'python'. The python way lacks for constraints which are considered basic things elsewhere, such as defining a strict list of properties. You wont find e.g.: class MyCLass # list of visible properties ... # list of private things ... On the contrary, python is much more flexible. It lets you bind anything to an object, at anytime and from anywhere (inside/outside): obj = MyClass("prop1") obj.quality = "prop2" obj.method() # list obj's bound attributes, # stored in "magic" attr '__dict__' for attr in obj.__dict__.items(): print attr ==> I'm doing something. I got a result. ('quality', 'prop2') ('result', 'present result') ('start_prop', 'prop1') This way has huge advantages. It lets doing many things in a light, easy and straighforward manner, compared to many languages where simple things rapidly get heavy. On the other hand, there is a 'heavy' ;-) lack of structure, of frame, of standard, that easily lets code get chaotic -- especially because anything can be influenced by anything else "in the background". Good practice, clear code, sensible structure only depend on the developper's discipline. There are also (more & more) special features (somewhat abstract and complicated for my taste), that allow a programmer forcing constraints and structure. But they hardly fit the python way. It's forced, indeed. For instance, there are several ways to forbid adding or changing properties -- so that the client willget an error (that may let the old pythonist stuck). > Coming back to my ExampleList, I have another "philosophic" question. > > Suppose I'm interested (many times within my "main" program) to recover a > part of the list contained by an ExampleList object. To be more clear: > > >>> a = ExampleList([1,2,3,4], 2) > >>> a.list > [1, 2, 3, 4] > >>> a.position > 2 > > I want to get the second part of the list, I mean, the part of list > a.list that goes from position a.position until the last element in > the list. > > I know I can do it like this: > > >>> a.list[a.position:] > [3, 4] > > Or, if I want the first part of the list: > > >>> a.list[:a.position] > [1, 2] > > > My problem/question/dilemma: I want to define it as a property or as a > method in the class definition, because I am going to need many times "the > first part of te list" or "the second part of the list". > > For me, I see it as a property of the object, I mean: "tell me which is your > first part". It is not like an action over the object or to/from/related to > the object (that would be a method, then). > > So, this kind of "derived" properties (because they are based on two other > previously defined "primary" properties) are better to be defined as > methods, or it is the same? > > I mean, what I would like to do is this: > > class ExampleList : > def __init__(self, list, position) : > self.list = list > self.position = position > self.list_1stpart = self.list[:self.position] > self.list_2ndpart = self.list[self.position:] > > > Is that right? Is that good practice? If I want to define > self.list_1stpart as a property, is the __init__ function the only and > the best place to do it? > > If not, I suppose I'll have to define it as a method, and then it will look > like something like this: > > [... within the class definition ...] > > def list_1stpart(self) : > return self.list[:self.position] > > > Then I'll call the method like this: > > >>> a.list_1stpart() > [1, 2] > > For me, the "()" look like artificial, not necessary. I would prefer just to > type "a.list_1stpart" , a property. > > The general case is (the second question): > > (2) properties which can be derived from other "primary" properties, are > they just methods?? > > I don't know which approach is more correct, from any point of view... By > the way, does the "property" approach consume much memory or space than the > "method" approach?? > > Thank you very much for your patience... > > This is not directly related to python, as you said -- if I well understand what you mean. For any property, you always have the choice between giving the client direct access to the data, or writing a method that returns it. It may be a question of style. When a property is dependant on others, such as a sum of 2 values, or the 2 parts of your list, then the choice becomes: -1- Either, compute the prop each time the other values change, then let the result available as a simple data attribute. -2- Or write a function that computes & returns the result on demand only. Well, my opinion is: if the base data change much, and the result is not often required, choose -2- If the source data change few, and the result is often required, choose -1-. If you want -1-, then you simply transfer the charge to the base properties -- or rather to methods the client will have to use for setting the properties: def set_list(new_list): self.list = new_list # compute parts 1 & 2 def set_pos(new_pos): self.pos = new_pos # compute parts 1 & 2 Denis ------ la vida e estranya From alan.gauld at btinternet.com Thu Jan 29 23:07:55 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 29 Jan 2009 22:07:55 -0000 Subject: [Tutor] Properties of an object References: <50ed08f40901291059i50f11a17v2f21f9ada66ed463@mail.gmail.com> Message-ID: "Vicent" wrote > This is an easy question, I guess, but I am not able to find out the > answer. Or in fact a series of not so easy questions! :-) Andre has already answered most of them but I'll add a few extras. > (1) Where are the right places to define PROPERTIES for my class, > and how (I > mean, which is the right syntax) must I define them? > > As far as I know, the usual place where properties are "declared" > and > assigned is in the __init__ function. > > Can I define properties in other parts of the "Class" code? I am not > able to > deduce it from the things I've read. Yes but its generally best not to. It makes for easier to maintain code to keep all definitions in the init method - even if the deefinition is just to None initially! However that is for instance variables, that is ones that are unique to each instance of your class. You can also have class variables which are shared by all instances (and in fact exist even if no instances exist - they are owned by the class which is itself an object! These are defined outside of a method. > class ExampleFoo : > _property1 = 0 Thats a class variable as I've just described. > And I think that later I found "self._property1" or "self.property1" These will work as will ExampleFoo._property1 They will, all three, return the same object. > am not sure of that. Anyway, why the prefix "_", and what does that > definition "_property = 0" mean and imply? The assignment simply creates the class variable with an initial value of zero. The underscore is a Python convention to suggest that users of the class should not directly access this variable. It is intended for use internally by the class's methods. You will see self._foo as a naming convention inside methods too. > I want to get the second part of the list, I mean, the part of list >>>> a.list[a.position:] > [3, 4] > > Or, if I want the first part of the list: > >>>> a.list[:a.position] > [1, 2] A common naming convention to do this is first and butfirst or first and rest. However those are usually applied where first means the first element. In your case we might adapt the convention to be methods called firstpart() lastpart() > For me, I see it as a property of the object, I mean: "tell me which > is your > first part". It is not like an action over the object or > to/from/related to > the object (that would be a method, then). The way I think of objects is as actors on a stage receiving messages and responding with actions or results. So a method is the function carried out in response to a message. Thus you send the message firstpart() and the object gives you back what you asked for. It also removes the temptation to access the attributes directly. Although in Python thats not considered such a heinous crime as in other OO languages. > So, this kind of "derived" properties (because they are based on two > other > previously defined "primary" properties) are better to be defined as > methods, or it is the same? Now we come to an important terminology point. You are using the term properties to refer to the internal data items. But in Python a "property" is a little bit special. It is a variable within a class which can be accessed as if it were a normal variable but in fact the access will be via two methods (one for getting and one for setting the value) This is described in the documentation and is not used all that often in my experience but it can cause confusion if you use the term property loosely in Python circles. (Actually having worked through the rest of the mail you might actually be aware of that and are intending the Pythonic use of property?) > class ExampleList : > def __init__(self, list, position) : > self.list = list > self.position = position > self.list_1stpart = self.list[:self.position] > self.list_2ndpart = self.list[self.position:] You can't do it quite like that or the 1stpart etc will be fixed as reflections of how it was when you created it - which I assume is not what you want! You either have to use metthods or create properties - which will make things look like I think you would prefer but at the expense of more work. Also please don't name methods with the object type in the name it leads to really ugly code. Use firstpart, secondpart or similar, ie. lose the list_ bit > Is that right? Is that good practice? If I want to define > self.list_1stpart as a property, is the __init__ function the > only and > the best place to do it? init is the best place to define your instance variables but defining properties requires you to define methods too. But if you want the access to firstpart/second part to reflect changes in position you need metods anyway and I'd recommend using methods called firstpart) and secondpart() > If not, I suppose I'll have to define it as a method, and then it > will look > like something like this: > > [... within the class definition ...] > > def list_1stpart(self) : > return self.list[:self.position] Yes but please not with the list_ bit. We are trying to hide the internal data not expose it. And you wind up with something like: mylist = ExampleList([1,2,3,4,5,6], 3) mylist.list_1stpart() Do you see how that then gives a double list in the method call? The user doesn't need to know you use a list inside! After all you might change it to a generator someday! > For me, the "()" look like artificial, not necessary. I would prefer > just to > type "a.list_1stpart" , a property. You can do that by writing a property but to me the () signifies that I'm sending a message to an object :-) > (2) properties which can be derived from other "primary" properties, > are > they just methods?? Nope. But I'm not sure exactly what you mean here. In what sense derived? And how primary? And do you mean real "Python properties" or just attributes? > the way, does the "property" approach consume much memory or space > than the > "method" approach?? Not much more memory because the methods used to access the property are stored once only in the class. Instances access methods via the class. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From jervisau at gmail.com Fri Jan 30 00:50:29 2009 From: jervisau at gmail.com (Jervis Whitley) Date: Fri, 30 Jan 2009 10:50:29 +1100 Subject: [Tutor] Properties of an object In-Reply-To: <50ed08f40901291059i50f11a17v2f21f9ada66ed463@mail.gmail.com> References: <50ed08f40901291059i50f11a17v2f21f9ada66ed463@mail.gmail.com> Message-ID: <8e63a5ce0901291550p4183bab3je36fcae405fffcc9@mail.gmail.com> > > > > For me, the "()" look like artificial, not necessary. I would prefer just > to type "a.list_1stpart" , a property. > > > > -- > > Others have explained their preference for using get methods for accessing internal data structures, However it does look like you have specifically mentioned a preference for attribute like access: e = ExampleList([1,2,3,4], 2) >>> e.firstpart [1,2] rather than >>> e.firstpart() [1,2] We can implement this using properties, and I will refer you to some of the documentation http://docs.python.org/library/functions.html#property Here is just one way that you could simply implement a property in your case: class ExampleList(object): """Note that this is a new style class.""" def __init__(self, sequence, position): self._sequence = sequence self._position = position @property def firstpart(self): """This method will be called on inst.firstpart rather than inst.firstpart().""" return self._sequence[:self._position] Here I have used property as a decorator (described in the link), now you can get your firstpart through attribute access (not that you cannot 'set' to it): e.firstpart Cheers, -------------- next part -------------- An HTML attachment was scrubbed... URL: From lie.1296 at gmail.com Fri Jan 30 07:09:08 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Fri, 30 Jan 2009 06:09:08 +0000 (UTC) Subject: [Tutor] Defining "bit" type -- why not '!' ? References: <50ed08f40901240625vd1b4980ta751326038adcc6c@mail.gmail.com> <497F0B6E.1010209@gmail.com> <20090129101957.186f422b@o> <6faf39c90901290126k5f289911tb237fcd025acfdad@mail.gmail.com> <20090129113236.2465f5ef@o> Message-ID: On Thu, 29 Jan 2009 12:22:29 +0000, Alan Gauld wrote: > "spir" wrote > >> Here is an overal and a trial to introduce my view on this topic. > ... >> * The mix of "extended logic" on non-logical types and treating >> integers >> as bit sequences provakes a kind of conceptual collision. >> * As a solution, bitwise operations may apply only to a type (byte or >> int) >> on which "extended logic" raises an TypeError. > > You are probably correct but it would break a ton of working code! > Especially when you recall that bool types were only introduced > relatively recently so a lot of old code relies on the fact that > True/False were until then literally 1/0. > > Maybe it is "improved" in Python 3. As you say the ~ operator makes most > sense if applied to bytes only. But for compatibility reasons I suspect > they have kept it as-is... I think it's an unnecessary complication. In programming we have to remember that the decimal numbers we see are really just a user-friendly view of the bit patterns used in the CPU. These bit patterns are used in arithmetic and bit-wise operations (logical operation is a much higher concept, AFAIK no CPU implements hardware logical operation). From vginer at gmail.com Fri Jan 30 12:22:10 2009 From: vginer at gmail.com (Vicent) Date: Fri, 30 Jan 2009 12:22:10 +0100 Subject: [Tutor] Properties of an object In-Reply-To: <8e63a5ce0901291550p4183bab3je36fcae405fffcc9@mail.gmail.com> References: <50ed08f40901291059i50f11a17v2f21f9ada66ed463@mail.gmail.com> <8e63a5ce0901291550p4183bab3je36fcae405fffcc9@mail.gmail.com> Message-ID: <50ed08f40901300322o12272039i1e9dfa9ca0fbbbc5@mail.gmail.com> Thanks to all for your clear answers. I learned a lot about the way Python manages properties or attributes. In my particular case, I think, as Spir said, that the best implementation depends on wether I am going to update the "base" properties very often or not, and wether I am going to access "the secondary properties" many times or not. I didn't realized that, in case I define "firstpart" as a property, I have to update it every time the "list" property is updated/changed. Thank you for that obvius detail! And thank you also for the advice about the name of properties. I agree with getting the "list_" prefix out. Thank you!! -- Vicent -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Fri Jan 30 12:43:16 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 30 Jan 2009 06:43:16 -0500 Subject: [Tutor] Properties of an object In-Reply-To: <50ed08f40901291059i50f11a17v2f21f9ada66ed463@mail.gmail.com> References: <50ed08f40901291059i50f11a17v2f21f9ada66ed463@mail.gmail.com> Message-ID: <1c2a2c590901300343g5bc67819g52672360b2687281@mail.gmail.com> On Thu, Jan 29, 2009 at 1:59 PM, Vicent wrote: > This is an easy question, I guess, but I am not able to find out the answer. > > In fact, it is both a Python question and a general programming "style" > question. > > I want to define a class that contains a list (or a NumPy array) of elements > of a certain type, and an integer: > > class ExampleList : > def __init__(self, list, position) : > self.list = list > self.position = position > > > This is clear to me. > > My first question, which is Python related: > > (1) Where are the right places to define PROPERTIES for my class, and how (I > mean, which is the right syntax) must I define them? A note on terminology: In Python, what you are describing is called an attribute. 'property' has a very specific meaning, it is a way to associate a value with an instance that uses attribute notation for access, i.e. a.b, but actually uses a method call to get and set the value. In other words, it provides the flexibility of getters and setters with the notation of a plain attribute. Moreover, you can change a value from an attribute to a property without changing client code at all. This might be appropriate for your 1stpart and 2ndpart values. See http://personalpages.tds.net/~kent37/kk/00008.html http://docs.python.org/library/functions.html#property Kent From denis.spir at free.fr Fri Jan 30 12:47:59 2009 From: denis.spir at free.fr (spir) Date: Fri, 30 Jan 2009 12:47:59 +0100 Subject: [Tutor] non-greedy matching Message-ID: <20090130124759.1b06262f@o> Hello, imagine you need to match such a pattern: pat : (@@ [charset]* @@) | [charset]* ... where [charset] has to include '@' My questions are: * Is there any other way than using a non-greedy form of [charset]* ? * How, actually, is non-greedy character string matching performed? Thank you, denis ------ la vida e estranya From denis.spir at free.fr Fri Jan 30 13:02:23 2009 From: denis.spir at free.fr (spir) Date: Fri, 30 Jan 2009 13:02:23 +0100 Subject: [Tutor] Properties of an object In-Reply-To: <50ed08f40901300322o12272039i1e9dfa9ca0fbbbc5@mail.gmail.com> References: <50ed08f40901291059i50f11a17v2f21f9ada66ed463@mail.gmail.com> <8e63a5ce0901291550p4183bab3je36fcae405fffcc9@mail.gmail.com> <50ed08f40901300322o12272039i1e9dfa9ca0fbbbc5@mail.gmail.com> Message-ID: <20090130130223.310491a6@o> Le Fri, 30 Jan 2009 12:22:10 +0100, Vicent a ?crit : > Thanks to all for your clear answers. I learned a lot about the way Python > manages properties or attributes. > > In my particular case, I think, as Spir said, that the best implementation > depends on wether I am going to update the "base" properties very often or > not, and wether I am going to access "the secondary properties" many times > or not. > > I didn't realized that, in case I define "firstpart" as a property, I have > to update it every time the "list" property is updated/changed. Thank you > for that obvius detail! Do not forget that, as someone said, if you let firstpart and lastpart available as "data attributes" (rather avoid 'properties'), then the client code is implicitely allowed to set/change it. Which would obviously lead to inconsistent status. So that it may be better, if only for clarity, to write them as methods, even if there are automatically updated each time primary data are changed. Or else, use the "_prop" convention to remove ambiguity. The actual semantics are "information attribute", that is read-only, a distinction which is not native to python: you have to maintain it. Finally, you could use "properties", in the sense of python, as suggested in a previous message: if you simply define a 'getter" without any 'setter', the data won't be 'settable' from outside. (It may be nevertheless better to define a "setter" that raises an error with a sensible message...) Denis ------ la vida e estranya From vginer at gmail.com Fri Jan 30 13:08:17 2009 From: vginer at gmail.com (Vicent) Date: Fri, 30 Jan 2009 13:08:17 +0100 Subject: [Tutor] Properties of an object In-Reply-To: <1c2a2c590901300343g5bc67819g52672360b2687281@mail.gmail.com> References: <50ed08f40901291059i50f11a17v2f21f9ada66ed463@mail.gmail.com> <1c2a2c590901300343g5bc67819g52672360b2687281@mail.gmail.com> Message-ID: <50ed08f40901300408x74544057lc044a40526254e7b@mail.gmail.com> On Fri, Jan 30, 2009 at 12:43, Kent Johnson wrote: > > A note on terminology: In Python, what you are describing is called an > attribute. 'property' has a very specific meaning, it is a way to > associate a value with an instance that uses attribute notation for > access, i.e. a.b, but actually uses a method call to get and set the > value. In other words, it provides the flexibility of getters and > setters with the notation of a plain attribute. Moreover, you can > change a value from an attribute to a property without changing client > code at all. This might be appropriate for your 1stpart and 2ndpart > values. See > http://personalpages.tds.net/~kent37/kk/00008.html > http://docs.python.org/library/functions.html#property > > OK... Now I see. Thank you, and also to Spir again! -- Vicent -------------- next part -------------- An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Fri Jan 30 13:40:06 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Fri, 30 Jan 2009 04:40:06 -0800 Subject: [Tutor] Writing a Configuration Facility for an Application Message-ID: <4982F526.80305@sbcglobal.net> An HTML attachment was scrubbed... URL: From a.t.hofkamp at tue.nl Fri Jan 30 13:44:42 2009 From: a.t.hofkamp at tue.nl (A.T.Hofkamp) Date: Fri, 30 Jan 2009 13:44:42 +0100 Subject: [Tutor] non-greedy matching In-Reply-To: <20090130124759.1b06262f@o> References: <20090130124759.1b06262f@o> Message-ID: <4982F63A.1020402@tue.nl> spir wrote: > Hello, > > imagine you need to match such a pattern: > > pat : (@@ [charset]* @@) | [charset]* > ... where [charset] has to include '@' > > My questions are: > * Is there any other way than using a non-greedy form of [charset]* ? Something like this? (in pseudo-RE syntax) "(@@" ( [^@]* "@" [^@] | [^@]* "@" "@"+ [^@)] )* [^@]* "@" "@"+ ")" to understand, break the above down in pieces: "(@@" ( A | B )* C with A: [^@]* "@" [^@] # lots of chars, then a @, and a non-@ B: [^@]* "@" "@"+ [^@)] # lots of chars then at least two @, and a non-closing bracket # (the non-@ at the end is for forcing all @ to be matched in "@"+) C: [^@]* "@" "@"+ ")" # lots of chars, then at least two @, and finally a closing bracket > * How, actually, is non-greedy character string matching performed? That's what I'd like to know too. (and while we are at it, what about the \b )? Sincerely, Albert From a.t.hofkamp at tue.nl Fri Jan 30 13:47:57 2009 From: a.t.hofkamp at tue.nl (A.T.Hofkamp) Date: Fri, 30 Jan 2009 13:47:57 +0100 Subject: [Tutor] Writing a Configuration Facility for an Application In-Reply-To: <4982F526.80305@sbcglobal.net> References: <4982F526.80305@sbcglobal.net> Message-ID: <4982F6FD.4090001@tue.nl> Wayne Watson wrote: > mask file: c:\operation/horizon.jpg > latitutde: -140.22 > longitude 38.22 > start time: 18:25:00 > stop time: 06:30:00 > event directory: d:\events_2009 > grey scale: yes > autoexpose format: gif > I suspect there may be a standard way of doing this in Python that relies on > more complex operations that simplify matters than just reading the file one > line at a time. Dictionaries? Comments? The ConfigParser module in the standard library can do this for you. (Which is written in pure Python BTW in case you want to find out how they do it.) Sincerely, Albert From kent37 at tds.net Fri Jan 30 13:53:08 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 30 Jan 2009 07:53:08 -0500 Subject: [Tutor] Writing a Configuration Facility for an Application In-Reply-To: <4982F526.80305@sbcglobal.net> References: <4982F526.80305@sbcglobal.net> Message-ID: <1c2a2c590901300453r4b77166ehc004548fddf1c957@mail.gmail.com> On Fri, Jan 30, 2009 at 7:40 AM, Wayne Watson wrote: > I'm about to provide a config file for an application I've been working > with. > I suspect there may be a standard way of doing this in Python that relies on > more complex operations that simplify matters than just reading the file one > line at a time. Dictionaries? Comments? One possibility is to put the settings in a dictionary and use the pickle module to save and restore the dict. This is pretty simple. The pickled file is not particularly readable, though. http://docs.python.org/library/pickle.html Another way is to use a .ini file. The ConfigParser module can read ini files but not write them. http://docs.python.org/library/configparser.html There are add-on modules that implement read-write ini files, for example http://www.voidspace.org.uk/python/configobj.html Kent From w.richert at gmx.net Fri Jan 30 13:56:45 2009 From: w.richert at gmx.net (Willi Richert) Date: Fri, 30 Jan 2009 13:56:45 +0100 Subject: [Tutor] non-greedy matching In-Reply-To: <4982F63A.1020402@tue.nl> References: <20090130124759.1b06262f@o> <4982F63A.1020402@tue.nl> Message-ID: <200901301356.45705.w.richert@gmx.net> Hi, you make it non-greedy with "?": import re text="axa axa" greedy_x, greedy_y = re.match("a.*a", text).span() print text[greedy_x:greedy_y] non_greedy_x, non_greedy_y = re.match("a.*?a", text).span() print text[non_greedy_x:non_greedy_y] Will print out: axa axa axa Regards, wr On Freitag, 30. Januar 2009 13:44:42 A.T.Hofkamp wrote: > spir wrote: > > Hello, > > > > imagine you need to match such a pattern: > > > > pat : (@@ [charset]* @@) | [charset]* > > ... where [charset] has to include '@' > > > > My questions are: > > * Is there any other way than using a non-greedy form of [charset]* ? > > Something like this? > (in pseudo-RE syntax) > > "(@@" ( [^@]* "@" [^@] | [^@]* "@" "@"+ [^@)] )* [^@]* "@" "@"+ ")" > > to understand, break the above down in pieces: > > "(@@" ( A | B )* C > > with A: [^@]* "@" [^@] > # lots of chars, then a @, and a non-@ > > B: [^@]* "@" "@"+ [^@)] > # lots of chars then at least two @, and a non-closing bracket > # (the non-@ at the end is for forcing all @ to be matched in > "@"+) > > C: [^@]* "@" "@"+ ")" > # lots of chars, then at least two @, and finally a closing > bracket > > > * How, actually, is non-greedy character string matching performed? > > That's what I'd like to know too. > (and while we are at it, what about the \b )? > > > Sincerely, > Albert > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From w.richert at gmx.net Fri Jan 30 14:17:34 2009 From: w.richert at gmx.net (Willi Richert) Date: Fri, 30 Jan 2009 14:17:34 +0100 Subject: [Tutor] Writing a Configuration Facility for an Application In-Reply-To: <1c2a2c590901300453r4b77166ehc004548fddf1c957@mail.gmail.com> References: <4982F526.80305@sbcglobal.net> <1c2a2c590901300453r4b77166ehc004548fddf1c957@mail.gmail.com> Message-ID: <200901301417.34763.w.richert@gmx.net> Hi, I have often found that just initializing all the necessary stuff in one Configuration.py module. You just import it and it works. If you like the Windows .ini format, ConfigParser is your friend (http://docs.python.org/library/configparser.html). Regards, wr On Freitag, 30. Januar 2009 13:53:08 Kent Johnson wrote: > On Fri, Jan 30, 2009 at 7:40 AM, Wayne Watson > > wrote: > > I'm about to provide a config file for an application I've been working > > with. > > > > I suspect there may be a standard way of doing this in Python that relies > > on more complex operations that simplify matters than just reading the > > file one line at a time. Dictionaries? Comments? > > One possibility is to put the settings in a dictionary and use the > pickle module to save and restore the dict. This is pretty simple. The > pickled file is not particularly readable, though. > http://docs.python.org/library/pickle.html > > Another way is to use a .ini file. The ConfigParser module can read > ini files but not write them. > http://docs.python.org/library/configparser.html > > There are add-on modules that implement read-write ini files, for example > http://www.voidspace.org.uk/python/configobj.html > > Kent > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From a.t.hofkamp at tue.nl Fri Jan 30 14:57:13 2009 From: a.t.hofkamp at tue.nl (A.T.Hofkamp) Date: Fri, 30 Jan 2009 14:57:13 +0100 Subject: [Tutor] Writing a Configuration Facility for an Application In-Reply-To: <1c2a2c590901300453r4b77166ehc004548fddf1c957@mail.gmail.com> References: <4982F526.80305@sbcglobal.net> <1c2a2c590901300453r4b77166ehc004548fddf1c957@mail.gmail.com> Message-ID: <49830739.7080408@tue.nl> Kent Johnson wrote: > Another way is to use a .ini file. The ConfigParser module can read > ini files but not write them. > http://docs.python.org/library/configparser.html What do you mean 'not write them'? from the Python docs: RawConfigParser.write(fileobject) Write a representation of the configuration to the specified file object. This representation can be parsed by a future read() call. Sincerely, Albert From denis.spir at free.fr Fri Jan 30 15:48:49 2009 From: denis.spir at free.fr (spir) Date: Fri, 30 Jan 2009 15:48:49 +0100 Subject: [Tutor] Writing a Configuration Facility for an Application In-Reply-To: <200901301417.34763.w.richert@gmx.net> References: <4982F526.80305@sbcglobal.net> <1c2a2c590901300453r4b77166ehc004548fddf1c957@mail.gmail.com> <200901301417.34763.w.richert@gmx.net> Message-ID: <20090130154849.150a6eab@o> Le Fri, 30 Jan 2009 14:17:34 +0100, Willi Richert a ?crit : > Hi, > > I have often found that just initializing all the necessary stuff in one > Configuration.py module. You just import it and it works. I support this as it's far the most straightforward way! Now, depending on the actual use, some may see that as a security issue as the module is executed. You can prevent (all?most?) problems by checking that it matches a sequence of assignments. Far easier than a real parsing... and interpreting... Another advantage is that you a config object for free: if your module is called config.py, then you will have config.mask_file, config.latitude... [I personly like structuring the config data into records (just named data containers): location = Record() location.latitude = ... location.longitude = ... wil give config.location config.location.latitude config.location.longitude] Denis > Regards, > wr ------ la vida e estranya From kent37 at tds.net Fri Jan 30 16:05:35 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 30 Jan 2009 10:05:35 -0500 Subject: [Tutor] Writing a Configuration Facility for an Application In-Reply-To: <49830739.7080408@tue.nl> References: <4982F526.80305@sbcglobal.net> <1c2a2c590901300453r4b77166ehc004548fddf1c957@mail.gmail.com> <49830739.7080408@tue.nl> Message-ID: <1c2a2c590901300705t294a38e1yb25d3359c01dbb50@mail.gmail.com> On Fri, Jan 30, 2009 at 8:57 AM, A.T.Hofkamp wrote: > Kent Johnson wrote: >> >> Another way is to use a .ini file. The ConfigParser module can read >> ini files but not write them. >> http://docs.python.org/library/configparser.html > > What do you mean 'not write them'? > > > from the Python docs: > > RawConfigParser.write(fileobject) > > Write a representation of the configuration to the specified file object. > This representation can be parsed by a future read() call. Oops. Thanks for the correction! Kent From ldl08 at gmx.net Fri Jan 30 17:30:18 2009 From: ldl08 at gmx.net (David) Date: Sat, 31 Jan 2009 00:30:18 +0800 Subject: [Tutor] jumping from function to function Message-ID: <49832B1A.6010604@gmx.net> Dear List, the following comes from Harrington's "Hands-on Python" (section 1.11.8): http://www.cs.luc.edu/~anh/python/hands-on/ '''Avoiding any error by passing a parameter''' def main(): x = 3 f(x) def f(whatever): print whatever main() I am not quite sure what is going on here. Could you please correct my line of thought? 1) main() calls the function def main(): 2) in function def main(): the actual parameter 3 is given to the function call f(). 3) f() then "jumps" out of function def main(): to call function def f(whatever):, whose new value, 3, gets printed. Is this what is going on? I find it difficult to get my head around this one. Also: does Python go back to the function call main()'s position after step 3)? How does that work? Again via def main():??? Cheers for any clarifications, David From denis.spir at free.fr Fri Jan 30 18:21:49 2009 From: denis.spir at free.fr (spir) Date: Fri, 30 Jan 2009 18:21:49 +0100 Subject: [Tutor] jumping from function to function In-Reply-To: <49832B1A.6010604@gmx.net> References: <49832B1A.6010604@gmx.net> Message-ID: <20090130182149.120367a6@o> Le Sat, 31 Jan 2009 00:30:18 +0800, David a ?crit : > Dear List, > > the following comes from Harrington's "Hands-on Python" (section > 1.11.8): http://www.cs.luc.edu/~anh/python/hands-on/ > > > > > '''Avoiding any error by passing a parameter''' > > def main(): > x = 3 > f(x) > > def f(whatever): > print whatever > > main() > > > > I am not quite sure what is going on here. Could you please correct my > line of thought? > > 1) main() calls the function def main(): > > 2) in function def main(): the actual parameter 3 is given to the > function call f(). > > 3) f() then "jumps" out of function def main(): to call function > def f(whatever):, whose new value, 3, gets printed. > > Is this what is going on? I find it difficult to get my head around this > one. > Also: does Python go back to the function call main()'s position after > step 3)? How does that work? Again via def main():??? Your interpretation is correct. I guess what may trouble here is a question of order. main is defined before f, while its own definition uses f's definition. This is a bit weird, indeed, and does not help reading. But python doesn't mind. Instead, if ever main would actually be called/executed before f's definition, then you would get an error (try it). denis ------ la vida e estranya From bgailer at gmail.com Fri Jan 30 18:48:14 2009 From: bgailer at gmail.com (bob gailer) Date: Fri, 30 Jan 2009 12:48:14 -0500 Subject: [Tutor] Defining "bit" type -- why not '!' ? In-Reply-To: References: <50ed08f40901240625vd1b4980ta751326038adcc6c@mail.gmail.com> <497F0B6E.1010209@gmail.com> <20090129101957.186f422b@o> <6faf39c90901290126k5f289911tb237fcd025acfdad@mail.gmail.com> <20090129113236.2465f5ef@o> Message-ID: <49833D5E.8090409@gmail.com> Lie Ryan wrote: [snip] > > AFAIK no CPU implements hardware logical operation). > > I disagree. But perhaps logical operation means different things to you. Please expand. -- Bob Gailer Chapel Hill NC 919-636-4239 From bgailer at gmail.com Fri Jan 30 18:56:12 2009 From: bgailer at gmail.com (bob gailer) Date: Fri, 30 Jan 2009 12:56:12 -0500 Subject: [Tutor] jumping from function to function In-Reply-To: <49832B1A.6010604@gmx.net> References: <49832B1A.6010604@gmx.net> Message-ID: <49833F3C.9020104@gmail.com> David wrote: > Dear List, > > the following comes from Harrington's "Hands-on Python" (section > 1.11.8): http://www.cs.luc.edu/~anh/python/hands-on/ > > > > > '''Avoiding any error by passing a parameter''' > > def main(): > x = 3 > f(x) > > def f(whatever): > print whatever > > main() > > > > I am not quite sure what is going on here. Could you please correct my > line of thought? > > 1) main() calls the function def main(): > > 2) in function def main(): the actual parameter 3 is given to the > function call f(). > > 3) f() then "jumps" out of function def main(): to call function > def f(whatever):, whose new value, 3, gets printed. 1) It is customary to refer to a function by it's name e.g. main() rather than def main(). 2) Distinguish where the function is defined from where it is executed. The definition of f() is at the same "level" as that of main(), but the call to f() is nested in main(); it does not "jump out". > > Also: does Python go back to the function call main()'s position after > step 3)? Yes. when f() is called the position in main() is placed on a "stack". When f() returns, the position of main is retrieved from the stack and its execution continues. -- Bob Gailer
Chapel Hill NC
919-636-4239 From alan.gauld at btinternet.com Fri Jan 30 19:40:55 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 30 Jan 2009 18:40:55 -0000 Subject: [Tutor] jumping from function to function References: <49832B1A.6010604@gmx.net> Message-ID: "David" wrote > def main(): > x = 3 > f(x) > > def f(whatever): > print whatever > > main() > I am not quite sure what is going on here. Could you please correct > my line of thought? As others have said you are pretty much correct apart from some terminology. However one of the insanely great things about Python is that it is very easy to test these kinds of assumptions by writing code at the >>> prompt: >>> def main(): ... f(1) ... g(2) ... f(3) ... >>> def f(v): print "This is f with parameter: ", v ... >>> def g(v): print "This is g with parameter: ", v ... >>> main() This is f with parameter: 1 This is g with parameter: 2 This is f with parameter: 3 >>> Here you can see quite clearly that main() executed the main function which in turn main called f followed by g followed by f again passing in different values each time. You can see the printout showing that the functions f and g used the values passed in by main as substitutes for v. This kind of experimental learning is a very powerful tool when you come up with questions like this. Don't be afraid to tamper with the example code and see if it does what you expect. If it doesn't try to figure out why not. If you can't then come back here and ask! :-) HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Fri Jan 30 20:05:40 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 30 Jan 2009 19:05:40 -0000 Subject: [Tutor] Properties of an object References: <50ed08f40901291059i50f11a17v2f21f9ada66ed463@mail.gmail.com> <20090129230440.61f2102f@o> Message-ID: "spir" wrote > There is no real native support for ordinary OOP in python, meaning > as is done in most other languages, or according to the theory. I have to disagree. I think you are confusing OOP with C++ and Java. The early OOP languages had a variety of approaches to this. Several took the same approach as Python and ignored visibility of attributes (Lisp & Object Pascal being obvious examples), others took the other extreme of making all data "private" with no way to access it other than via methods (Smalltalk being the prime example here) The common terms for controlling access (private/public, and later protected) didn't come along until C++ showed up in the mid 80's And the theory of OOP is much less concerned about data hiding (a technique championed by David Parnas at around the same time OOP was being developed) than it is about the idea of independant objects encapsulating data and functions within a single entity or capsule. The most common theoretical models were of each object being a separate process communicating over message streams. Polymorphism was identified as a key feature early on but even the idea of inheritance was later. Data hiding was an orthogonaslconcept that happened to fit quite well with the ideas of OOP but was not intrinisic to it. So Python fits very well with basic OOP theory and practice, its just quite different to C== and Java practice. But I would strongly argue that neither C++ nor Java are particularly good OOP languages - they have been compromised to facilitate familiarity for most developers. Thats a very pragmatic approach if you want to get a language adopted and has worked well for both, but it doesn't mean they are very pure from an OOP standpoint! > On the contrary, python is much more flexible. It lets you bind > anything to an object, at anytime and from anywhere > (inside/outside): And again is far from being alone in tyhe OOP world indoing that. Languages like Lisp, Objective C and (I believe?) Actor all allow that too. > On the other hand, there is a 'heavy' ;-) lack of structure, > of frame, of standard, that easily lets code get chaotic I've heard this claim many times but I have to say I haven't seen it justified in practice. Of course you can write chaotic code but in practice most developers just don't - its in their own interest to play be the "rules". > clear code, sensible structure only depend on the developer's > discipline. This is true in C++ too. Have you ever tried # define private public # include I've actually seen that in production code... Python takes the consenting adults approach to these things, but that doesn't mean its somehow ducking from the theory. In fact, Guido has produced a language that is very close to a Computer Scientist's vision of a pure imperative language while still being practical enough to use in real world projects! (Sorry for the rant but I get very frustrated when I see how the C++/Java axis is polluting programmer's views of what is/isn't real OOP! OOP is a very broad church :-) -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From denis.spir at free.fr Fri Jan 30 21:10:13 2009 From: denis.spir at free.fr (spir) Date: Fri, 30 Jan 2009 21:10:13 +0100 Subject: [Tutor] Properties of an object In-Reply-To: References: <50ed08f40901291059i50f11a17v2f21f9ada66ed463@mail.gmail.com> <20090129230440.61f2102f@o> Message-ID: <20090130211013.3793c6b4@o> Le Fri, 30 Jan 2009 19:05:40 -0000, "Alan Gauld" a ?crit : > "spir" wrote > > > There is no real native support for ordinary OOP in python, meaning > > as is done in most other languages, or according to the theory. > > I have to disagree. I think you are confusing OOP with C++ and Java. > The early OOP languages had a variety of approaches to this. Several > took the same approach as Python and ignored visibility of attributes > (Lisp & Object Pascal being obvious examples), others took the > other extreme of making all data "private" with no way to access > it other than via methods (Smalltalk being the prime example here) > > The common terms for controlling access (private/public, and later > protected) didn't come along until C++ showed up in the mid 80's > > And the theory of OOP is much less concerned about data hiding > (a technique championed by David Parnas at around the same > time OOP was being developed) than it is about the idea of > independant objects encapsulating data and functions within > a single entity or capsule. The most common theoretical models > were of each object being a separate process communicating > over message streams. Polymorphism was identified as a key > feature early on but even the idea of inheritance was later. Data > hiding was an orthogonaslconcept that happened to fit quite well > with the ideas of OOP but was not intrinisic to it. > > So Python fits very well with basic OOP theory and practice, > its just quite different to C== and Java practice. But I would > strongly argue that neither C++ nor Java are particularly good > OOP languages - they have been compromised to facilitate > familiarity for most developers. Thats a very pragmatic approach > if you want to get a language adopted and has worked well for > both, but it doesn't mean they are very pure from an OOP standpoint! [...more...] I agree with you, Alan (including what you have written in the part I cut). I also share your point of view about C++ and Java. And I was *not* speaking from their standpoint (correct?), nore from any other specific language -- except maybe unconsciously from objective Pascal variants. I should have been more precise in the lines you quote above. [Also, if ever I criticise some point, it's always due a need of understanding. Sometimes it's hard to get a useful reply, and I may take the devil's advocate position in order to learn what actually hides where my eyes do not yet see.] I was not thinking at data hiding or protection, rather at object structure (or behaviour) specification. First, to the human -- and alse to the machine. What I mean is that, as it is possible to remove/change/add any feature of an object, at any time and from any place, there is no real object specification; not even by class: not only an object (rather: an instance) can evolve independently, but a class itself, beeing an object, can change too. I do *not* mean that this is bad in any sense. Rather I do mean that this can trouble, as it has long troubled me when I first discovered python, especially combined with next point. In a rather consistent approach, Python does not provide any standard way to simply define/describe/structure an object -- or a class. This would be +/- absurd, as anything can change at any time. This participates to trouble; after all, OO is well about defining objects that represent model components, aspects, agents, their behaviour, their relationships. No? I may be wrong, still for me *this* is OO fondamental. Note that this is different from gentleman's agreement on not misusing a provided object structure or interface. This is information. Think kind of definition still seems to be needed, so that several formal or informal ways live in the python community to remedy that, from doc/comment practices to attribute "introduction" in __init__, etc... All of these carry no real language semantics, instead for me they fulfill a human relevant semantic need -- that I was missing, and still miss. denis ------ la vida e estranya From alan.gauld at btinternet.com Fri Jan 30 21:50:33 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 30 Jan 2009 20:50:33 -0000 Subject: [Tutor] Properties of an object References: <50ed08f40901291059i50f11a17v2f21f9ada66ed463@mail.gmail.com><20090129230440.61f2102f@o> <20090130211013.3793c6b4@o> Message-ID: "spir" wrote > I was not thinking at data hiding or protection, rather at object > structure > (or behaviour) specification. First, to the human -- and alse to the > machine. Ah, OK, then in that case I am happier to agree that Python is unusual (although not unique - Lisp can do the same) in its ability to add new attributes - and even methods in V3 I believe - to an existing class/instance. Indeed it's perfectly valid to do: class Data: pass ## no attributes or methods! d1 = Data() d2 = Data() d1.foo = 'something' d2.bar = 66 So that although d1 and d2 are both instances of Data their internal attributes are very different both in name and content!. BUT they both still adhere to the Data interface, they have merely enhanced it. So: dataset = [d1,d2] is still perfectly valid as a homogenous collection. Actually Lisp goes further than Python and allows us to switch inherited classes around in the method resolution lookup etc at run time, so (foo myMethod) might call different methods at different places in the same program (don't do this kiddies, it will make your brain hurt!) (I suspect this is possible in Python too using metaclasses, but they make your brain hurt too so don't do it! :-) > there is no real object specification; not even by class: The specification is there but its a minimal specification (lowest common denominator) rather than a comlete specification for any given instance. Again its a difference in perspective. > In a rather consistent approach, Python does not provide > any standard way to simply define/describe/structure an > object -- or a class. It does but not completely. You can be fairly sure that anything defined in the class definition will be there, but there might be other extras added is all. (although you can of course delete attributes as well which does I admit kind of mess things up - I don't like that feature although it is admittedly consistent with the rest of the language) > OO is well about defining objects that represent model > components, aspects, agents, their behaviour, their relationships. Yes, mostly although a broader view takes us back to the early model of OOP as being about independent communicating proceses. So in that model processes(objects) can acquire/lose attributes during their lifetime without problem. The idea that OOP was all about controllling interfaces was a later notion. But I would agree that it is one that has become fairly well established as a prime objectives of OOP. > ... to remedy that, from doc/comment practices to attribute > "introduction" in __init__, etc... All of these carry no real > language semantics, instead for me they fulfill a human > relevant semantic need -- that I was missing, and still miss. I wouldn't argue with that. I've never found the ability to add/delete attributes defined by the class to be useful, although I'm sure somebiody can find a use case. But the ability to dynamically augment an object is useful in a language like Python. But I would like the assurance that what was originally defined in the class was at least guaranteed! My apologies for the misunderstanding. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Fri Jan 30 23:16:27 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 30 Jan 2009 17:16:27 -0500 Subject: [Tutor] Properties of an object In-Reply-To: References: <50ed08f40901291059i50f11a17v2f21f9ada66ed463@mail.gmail.com> <20090129230440.61f2102f@o> <20090130211013.3793c6b4@o> Message-ID: <1c2a2c590901301416y31a7524cm870f72eb283fb944@mail.gmail.com> On Fri, Jan 30, 2009 at 3:50 PM, Alan Gauld wrote: > "spir" wrote > >> I was not thinking at data hiding or protection, rather at object >> structure >> (or behaviour) specification. First, to the human -- and alse to the >> machine. > > Ah, OK, then in that case I am happier to agree that Python is unusual > (although not unique - Lisp can do the same) in its ability to add new > attributes - and even methods in V3 I believe - to an existing > class/instance. Python 2.x can add new methods to a user-defined class or instance or redefine existing methods. Ruby and Objective-C also allow adding methods to existing classes. In Python this is called "monkey-patching" and considered a bad idea. In Ruby it is considered a powerful feature and IIUC it is widely used. > Indeed it's perfectly valid to do: > > class Data: pass ## no attributes or methods! > > d1 = Data() > d2 = Data() > > d1.foo = 'something' > d2.bar = 66 Also this: In [6]: def sayFoo(self): print 'foo' In [7]: Data.sayFoo = sayFoo In [8]: d1.sayFoo() foo > Actually Lisp goes further than Python and allows us to switch > inherited classes around in the method resolution lookup etc > at run time, so > > (foo myMethod) > > might call different methods at different places in the same > program (don't do this kiddies, it will make your brain hurt!) With old-style classes, you can assign directly to __bases__. This seems to have been removed for new-style classes. >> there is no real object specification; not even by class: The introduction of Abstract Base Classes in Python 2.6 and 3.0 seems intended to remedy this, giving you a way to specify an interface in the language: http://docs.python.org/whatsnew/2.6.html#pep-3119-abstract-base-classes Kent From eike.welk at gmx.net Sat Jan 31 00:17:06 2009 From: eike.welk at gmx.net (Eike Welk) Date: Sat, 31 Jan 2009 00:17:06 +0100 Subject: [Tutor] Properties of an object In-Reply-To: <20090130211013.3793c6b4@o> References: <50ed08f40901291059i50f11a17v2f21f9ada66ed463@mail.gmail.com> <20090130211013.3793c6b4@o> Message-ID: <200901310017.06328.eike.welk@gmx.net> Hello Spir! On Friday 30 January 2009, spir wrote: > In a rather consistent approach, Python does not provide any > standard way to simply define/describe/structure an object -- or a > class. The added flexibility of Python gives great powers to the programmers of libraries. There is for example a library for Java/C++ style data attributes in Python; Traits: http://code.enthought.com/projects/traits/docs/html/traits_user_manual/intro.html Also pretty cool is the possibility to change what happens when you type the 'class' statement. You only have to define the global variable '__metaclass__', which must point to an alternative implementation of the class definition algorithm. It seems to be possible to write this algorithm in pure Python. Some documentation is here: http://www.python.org/download/releases/2.2/descrintro/#metaclasses http://www.python.org/doc/essays/metaclasses/ This is a class definition algorithm (a metaclass) written in Python: http://www.python.org/doc/essays/metaclasses/Meta.py You can even change the type of an object at runtime: ---- In [1]:class A(object): .1.: def f(self): .1.: print 'A.f; self:', id(self) .1.: In [2]:class B(object): .2.: def f(self): .2.: print 'B.f; self:', id(self) .2.: In [3]:a = A() In [4]:a.f() A.f; self: 26272592 In [7]:a.__class__ = B In [8]:a.f() B.f; self: 26272592 ----- Kind regards, Eike. From alan.gauld at btinternet.com Sat Jan 31 00:25:09 2009 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Fri, 30 Jan 2009 23:25:09 +0000 (GMT) Subject: [Tutor] Properties of an object References: <50ed08f40901291059i50f11a17v2f21f9ada66ed463@mail.gmail.com> <20090129230440.61f2102f@o> <20090130211013.3793c6b4@o> <1c2a2c590901301416y31a7524cm870f72eb283fb944@mail.gmail.com> Message-ID: <823194.70118.qm@web86710.mail.ird.yahoo.com> > Python 2.x can add new methods to a user-defined class or instance or > redefine existing methods. > In [6]: def sayFoo(self): print 'foo' > > In [7]: Data.sayFoo = sayFoo > > In [8]: d1.sayFoo() > foo > Now for some reason I was sure that didn't work. So sure I never even tried! (despite my comments in another thread about experimenting with the >>> prompt!) > The introduction of Abstract Base Classes in Python 2.6 and 3.0 seems > intended to remedy this, giving you a way to specify an interface in > the language: I only downloaded v 3 a week or so ago and just spotted the ABC reference last week. I haven't looked at it yet so it will be interesting to see if you can do that. Alan G. From alan.gauld at btinternet.com Sat Jan 31 00:48:03 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 30 Jan 2009 23:48:03 -0000 Subject: [Tutor] Properties of an object References: <50ed08f40901291059i50f11a17v2f21f9ada66ed463@mail.gmail.com> <20090130211013.3793c6b4@o> <200901310017.06328.eike.welk@gmx.net> Message-ID: "Eike Welk" wrote >> In a rather consistent approach, Python does not provide any >> standard way to simply define/describe/structure an object -- or a >> class. > The added flexibility of Python gives great powers to the > programmers > of libraries. It goves a lot of flexibility, whether that really is power I'm not sure. Power is only good if used well and I've yet to see a convincing case for that kind of power applied to objects in either Python or Lisp (which also has that kind of ability). Its a bit like C++ templates. Strousdtrup spends a couple of chapters in his book on the evolution of C++ discussing clever tricks you can do with templates, including writing a class that inherits from itself! But that doesn't mean templates should be used that way! > There is for example a library for Java/C++ style data attributes in > Python; Traits: > http://code.enthought.com/projects/traits/docs/html/traits_user_manual/intro.html I'll check that one out, I haven't noticed it before. > Also pretty cool is the possibility to change what happens when you > type the 'class' statement. You only have to define the global > variable '__metaclass__', which must point to an alternative > implementation of the class definition algorithm. As I said beforer, be very careful with metacvlasses, they are powerful and have valid uses but they make your head hurt! (I have actually used metaclasses in real world code and they are useful, but complex and therefore dangerous) > You can even change the type of an object at runtime: Again I've never really found a valid need for this (especially in Python) but in some respects its like C++'s dynamic casts. Its most useful if changing between objects within the same heirarchy. For example a banking system with multiple types of Bank account. You might want to convert a savings account to a checking account. This could be done using class type changes (But its usually done through more conventional measures!) I rather suspect the OP has run from the room screaming by now! :-) For anyone else still reading this and getting jumpy, don't panic it's all extremely esoteric capability that in practice is hardly ever used by normal programmers. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From sierra_mtnview at sbcglobal.net Sat Jan 31 00:54:17 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Fri, 30 Jan 2009 15:54:17 -0800 Subject: [Tutor] Writing a Configuration Facility for an Application In-Reply-To: <1c2a2c590901300705t294a38e1yb25d3359c01dbb50@mail.gmail.com> References: <4982F526.80305@sbcglobal.net> <1c2a2c590901300453r4b77166ehc004548fddf1c957@mail.gmail.com> <49830739.7080408@tue.nl> <1c2a2c590901300705t294a38e1yb25d3359c01dbb50@mail.gmail.com> Message-ID: <49839329.6030604@sbcglobal.net> An HTML attachment was scrubbed... URL: From jandmstull at gmail.com Sat Jan 31 01:45:47 2009 From: jandmstull at gmail.com (jims) Date: Fri, 30 Jan 2009 19:45:47 -0500 Subject: [Tutor] Print question in IDLE Message-ID: <49839F3B.9020408@gmail.com> I apologize for asking such a dumb question but I have no prior programming experience and am trying to learn by following examples from a book. And also from the web. Simply put here is where I am stuck. (Python version 3.0) I type in the example using the comment command: (example) *>>> "food is very nice" #lets eat *(I am supposed to get) *food is very nice (*What I do get is) SyntaxError: invalid syntax (, line 1) I understand the comment part, no problem but no way can I get past what ever else I am doing wrong. I assume it's something fundamental but I can't get past this. Thanks for any help. Jim From dorseye at gmail.com Sat Jan 31 02:01:48 2009 From: dorseye at gmail.com (Eric Dorsey) Date: Fri, 30 Jan 2009 18:01:48 -0700 Subject: [Tutor] Print question in IDLE In-Reply-To: <49839F3B.9020408@gmail.com> References: <49839F3B.9020408@gmail.com> Message-ID: At the >>> prompt (which is the interactive) interpreter, try: print('food is very nice') #lets eat On Fri, Jan 30, 2009 at 5:45 PM, jims wrote: > I apologize for asking such a dumb question but I have no prior programming > experience and am trying to learn by following examples from a book. And > also from the web. > > Simply put here is where I am stuck. (Python version 3.0) > > I type in the example using the comment command: > > (example) *>>> "food is very nice" #lets eat > > *(I am supposed to get) *food is very nice > > (*What I do get is) SyntaxError: invalid syntax (, line 1) > > I understand the comment part, no problem but no way can I get past what > ever else I am doing wrong. I assume it's something fundamental but I can't > get past this. > Thanks for any help. > Jim > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- eric dorsey | www.perfecteyedesign.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sat Jan 31 02:05:50 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 31 Jan 2009 01:05:50 -0000 Subject: [Tutor] Print question in IDLE References: <49839F3B.9020408@gmail.com> Message-ID: "jims" wrote >I apologize for asking such a dumb question The only dumb questions are the ones you don;t ask. Its how to learn! > Simply put here is where I am stuck. (Python version 3.0) > > I type in the example using the comment command: > > (example) *>>> "food is very nice" #lets eat The >>> prompt is produced by Python so you don;t type it. ie you need to be in the intreractive shell window of IDLE for this to work. > (*What I do get is) SyntaxError: invalid syntax (, line > 1) If you are typing the >>> then thats what you will get. You don't type the >>> BTW YOu are using Python 3 - that has some inconsistencies with older versions which might catch you out. The biggest is probably that where older tutorials (including mine currently) will show >>> print "foo" In Python 3 you need to use >>> print ("foo") ie use parens around the stuff to be printed. There are a few other changes to print as well so if you do find wierd things happening ask here for advice. I am currently updating my tutorial to v3 but it will be a slow process. The v3 version will be on the URL below... HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/l2p/ From vceder at canterburyschool.org Sat Jan 31 02:16:38 2009 From: vceder at canterburyschool.org (Vern Ceder) Date: Fri, 30 Jan 2009 20:16:38 -0500 Subject: [Tutor] Print question in IDLE In-Reply-To: <49839F3B.9020408@gmail.com> References: <49839F3B.9020408@gmail.com> Message-ID: <4983A676.6060103@canterburyschool.org> I just tried it in Python 3 (both at the interactive prompt and in idle) and both places I get: >>> "food is very nice" #lets eat 'food is very nice' >>> So it looks like it *should* work. You might copy and paste exactly what you get into a post, including the full error traceso that we can see if there is some other problem. From the error message I (like Alan) wonder if you are typing in the ">>>" or something like that. Cheers, Vern jims wrote: > I apologize for asking such a dumb question but I have no prior > programming experience and am trying to learn by following examples from > a book. And also from the web. > > Simply put here is where I am stuck. (Python version 3.0) > > I type in the example using the comment command: > > (example) *>>> "food is very nice" #lets eat > > *(I am supposed to get) *food is very nice > > (*What I do get is) SyntaxError: invalid syntax (, line 1) > > I understand the comment part, no problem but no way can I get past what > ever else I am doing wrong. I assume it's something fundamental but I > can't get past this. > Thanks for any help. > Jim > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- This time for sure! -Bullwinkle J. Moose ----------------------------- Vern Ceder, Director of Technology Canterbury School, 3210 Smith Road, Ft Wayne, IN 46804 vceder at canterburyschool.org; 260-436-0746; FAX: 260-436-5137 From prasadaraon50 at gmail.com Sat Jan 31 10:51:59 2009 From: prasadaraon50 at gmail.com (prasad rao) Date: Sat, 31 Jan 2009 15:21:59 +0530 Subject: [Tutor] set key to sort Message-ID: <9e3fac840901310151h5df7056fm987fbc572f0df941@mail.gmail.com> hellI got a problem sorting a list of lists. ml= [[112, 'p'], [114, 'r'], [97, 'a'], [115, 's'], [97, 'a'], [100, 'd'], [97, 'a'], [114, 'r'], [97, 'a'], [111, 'o']] sorted(ml,key=?) How can I formulate a key to sort based on the first element of each list. sorting list of lists might have been discussed in the resent past. Is there a repository of all threads of this list on the web. thank you prasad -------------- next part -------------- An HTML attachment was scrubbed... URL: From sander.sweers at gmail.com Sat Jan 31 11:23:56 2009 From: sander.sweers at gmail.com (Sander Sweers) Date: Sat, 31 Jan 2009 11:23:56 +0100 Subject: [Tutor] set key to sort In-Reply-To: <9e3fac840901310151h5df7056fm987fbc572f0df941@mail.gmail.com> References: <9e3fac840901310151h5df7056fm987fbc572f0df941@mail.gmail.com> Message-ID: On Sat, Jan 31, 2009 at 10:51, prasad rao wrote: > I got a problem sorting a list of lists. > ml= > [[112, 'p'], [114, 'r'], [97, 'a'], [115, 's'], [97, 'a'], [100, 'd'], [97, > 'a'], [114, 'r'], [97, 'a'], [111, 'o']] > sorted(ml,key=?) > How can I formulate a key to sort based on the first element of each list. > sorting list of lists might have been discussed in the resent past. By default sort() will use the first value to sort so no key would be needed. Greets Sander From mydomdom at gmail.com Sat Jan 31 10:13:52 2009 From: mydomdom at gmail.com (Dominique) Date: Sat, 31 Jan 2009 09:13:52 +0000 (UTC) Subject: [Tutor] Recycle bin Windows XP - List or empty the bin Message-ID: Hello, I would like to access the recycle bin on windows xp and eventually empty its content. Googling around this led me to try the following (to empty the bin): from win32com.shell import shell shell.SHEmptyRecycleBin() Unfortunately, this doesn't work. The traceback gives me : TypeError: SHEmptyRecycleBin() takes exactly 3 arguments (0 given) So, I tried something I found somewhere: from win32com.shell import shell shell.SHEmptyRecycleBin( #No confirmation dialog when emptying the recycle bin SHERB_NOCONFIRMATION = 0x00000001, #No progress tracking window during the emptying of the recycle bin SHERB_NOPROGRESSUI = 0x00000001), #No sound whent the emptying of the recycle bin is complete SHERB_NOSOUND = 0x00000004 ) This doesn't work either, giving me the following traceback: TypeError: SHEmptyRecycleBin() takes no keyword arguments Ooops! The 2 tracebacks are contradictory. Can anybody help me on this, please. read and empty the bin and possibly send a file to it. Thanks in advance Dominique From mail at timgolden.me.uk Sat Jan 31 12:27:09 2009 From: mail at timgolden.me.uk (Tim Golden) Date: Sat, 31 Jan 2009 11:27:09 +0000 Subject: [Tutor] Recycle bin Windows XP - List or empty the bin In-Reply-To: References: Message-ID: <4984358D.7070400@timgolden.me.uk> Dominique wrote: > Googling around this led me to try the following (to empty the bin): > > from win32com.shell import shell > shell.SHEmptyRecycleBin() > > Unfortunately, this doesn't work. > The traceback gives me : > TypeError: SHEmptyRecycleBin() takes exactly 3 arguments (0 given) > > So, I tried something I found somewhere: > > from win32com.shell import shell > shell.SHEmptyRecycleBin( > #No confirmation dialog when emptying the recycle bin > SHERB_NOCONFIRMATION = 0x00000001, > #No progress tracking window during the emptying of the recycle bin > SHERB_NOPROGRESSUI = 0x00000001), > #No sound whent the emptying of the recycle bin is complete > SHERB_NOSOUND = 0x00000004 > ) > > This doesn't work either, giving me the following traceback: > TypeError: SHEmptyRecycleBin() takes no keyword arguments > > Ooops! The 2 tracebacks are contradictory. Well, not contradictory; more complementary. The help for shell.SHEmptyRecycleBin gives us 3 params: hwnd - parent window (or None) path - null-terminated root path or None for all recycle bins flags - some combination of SHERB constants Since it seems the args can't be keyword args (and since your example above seems to be more of a list of constants than a list of args), try this to empty the c-drive bin. Obviously you can play around with the constants by or-ing them together to give you that final arg: from win32com.shell import shell, shellcon # flags = shellcon.SHERB_NOSOUND | shellcon.SHERB_NOCONFIRMATION flags = 0 shell.SHEmptyRecycleBin (None, "c:\\", flags) You might want to look at my winshell module which wraps some of the shell module funcs in a slightly more Pythonic wrapper. At the very least, you can see some working source code: http://timgolden.me.uk/python/winshell.html TJG From hongyi.zhao at gmail.com Sat Jan 31 13:11:41 2009 From: hongyi.zhao at gmail.com (hongyi.zhao at gmail.com) Date: Sat, 31 Jan 2009 20:11:41 +0800 Subject: [Tutor] Want to write a Perl based IP to Domain Name converter. Message-ID: <6410451598.20090131201141@gmail.com> Hi all, The script in the following can do the batch conversion from domain name to IP: ------------------ #!/usr/bin/perl use warnings; use strict; use Socket; while ( <> ) { chomp; my ( $address, $port ) = split /:/ or next; my $number = inet_aton $address; my $ip = inet_ntoa $number; print "$address:$port -> $ip:$port\n"; } __END__ ------------------ If I want to do the opposite thing, i.e., conversion from IP to domain name, what should I revise this script to do the trick. Regards, -- Hongyi Zhao Xinjiang Technical Institute of Physics and Chemistry Chinese Academy of Sciences GnuPG DSA: 0xD108493 2009-1-31 From kent37 at tds.net Sat Jan 31 14:14:26 2009 From: kent37 at tds.net (Kent Johnson) Date: Sat, 31 Jan 2009 08:14:26 -0500 Subject: [Tutor] set key to sort In-Reply-To: <9e3fac840901310151h5df7056fm987fbc572f0df941@mail.gmail.com> References: <9e3fac840901310151h5df7056fm987fbc572f0df941@mail.gmail.com> Message-ID: <1c2a2c590901310514p1efc72dh50aa91f8a943022e@mail.gmail.com> On Sat, Jan 31, 2009 at 4:51 AM, prasad rao wrote: > hell > I got a problem sorting a list of lists. > ml= > [[112, 'p'], [114, 'r'], [97, 'a'], [115, 's'], [97, 'a'], [100, 'd'], [97, > 'a'], [114, 'r'], [97, 'a'], [111, 'o']] > sorted(ml,key=?) > How can I formulate a key to sort based on the first element of each list. Sorting is by default a lexicographic sort, it will sort on the first element using the second to break ties in the first, etc. If you really want to sort *only* on the first item (perhaps the second items are not comparable) then use key=operator.itemgetter(0). More explanation here: http://personalpages.tds.net/~kent37/kk/00007.html http://wiki.python.org/moin/HowTo/Sorting > sorting list of lists might have been discussed in the resent past. > Is there a repository of all threads of this list on the web. Click the link at the bottom of each email to get to the tutor list home page. From there you can click to the archives. Kent > thank you > prasad > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From sander.sweers at gmail.com Sat Jan 31 14:28:03 2009 From: sander.sweers at gmail.com (Sander Sweers) Date: Sat, 31 Jan 2009 14:28:03 +0100 Subject: [Tutor] datetime year problem, default year available? In-Reply-To: References: Message-ID: On Tue, Jan 27, 2009 at 01:01, Sander Sweers wrote: > month ('11/27' for example). Now when I use datetime.strptime('11/27', > ''%m/%d) I get a datetime object but the year is 1900. This makes > sense as I did not provide one. > > Then I saw that a datetime object has a replace function so now I > could replace a 1900 by 2008 (we can assume the year is 2008). Then we > can do datetime.strptime('11/27', '%m/%d').replace(year=2008). I could also do do datetime.strptime('11/27' + '/09', '%m/%d/%y'). Which solution would be recommended to use? Thanks Sander From kent37 at tds.net Sat Jan 31 14:44:58 2009 From: kent37 at tds.net (Kent Johnson) Date: Sat, 31 Jan 2009 08:44:58 -0500 Subject: [Tutor] Want to write a Perl based IP to Domain Name converter. In-Reply-To: <6410451598.20090131201141@gmail.com> References: <6410451598.20090131201141@gmail.com> Message-ID: <1c2a2c590901310544l7f261ef3xeceb2633030b7e05@mail.gmail.com> On Sat, Jan 31, 2009 at 7:11 AM, wrote: > Hi all, > > The script in the following can do the batch conversion from domain name to IP: ?? This is a Python list, not Perl! Kent > > ------------------ > > #!/usr/bin/perl > use warnings; > use strict; > use Socket; > > while ( <> ) { > chomp; > my ( $address, $port ) = split /:/ or next; > my $number = inet_aton $address; > my $ip = inet_ntoa $number; > print "$address:$port -> $ip:$port\n"; > } > > __END__ > > ------------------ > > > If I want to do the opposite thing, i.e., conversion from IP to domain > name, what should I revise this script to do the trick. > > Regards, > -- > Hongyi Zhao > Xinjiang Technical Institute of Physics and Chemistry > Chinese Academy of Sciences > GnuPG DSA: 0xD108493 > 2009-1-31 > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From mydomdom at gmail.com Sat Jan 31 15:01:35 2009 From: mydomdom at gmail.com (Dominique) Date: Sat, 31 Jan 2009 14:01:35 +0000 (UTC) Subject: [Tutor] Recycle bin Windows XP - List or empty the bin Message-ID: Tim, Thank you very much for your help. That works fine. Dominique From hongyi.zhao at gmail.com Sat Jan 31 15:11:28 2009 From: hongyi.zhao at gmail.com (hongyi.zhao at gmail.com) Date: Sat, 31 Jan 2009 22:11:28 +0800 Subject: [Tutor] Want to write a Perl based IP to Domain Name converter. In-Reply-To: <1c2a2c590901310544l7f261ef3xeceb2633030b7e05@mail.gmail.com> References: <6410451598.20090131201141@gmail.com> <1c2a2c590901310544l7f261ef3xeceb2633030b7e05@mail.gmail.com> Message-ID: <23816288.20090131221128@gmail.com> On Saturday, January 31, 2009 at 21:44, kent37 at tds.net wrote: > On Sat, Jan 31, 2009 at 7:11 AM, wrote: >> Hi all, >> >> The script in the following can do the batch conversion from domain name to IP: > This is a Python list, not Perl! OMG! It's my mistake, sorry for this. -- Hongyi Zhao Xinjiang Technical Institute of Physics and Chemistry Chinese Academy of Sciences GnuPG DSA: 0xD108493 2009-1-31 From sierra_mtnview at sbcglobal.net Sat Jan 31 15:45:47 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sat, 31 Jan 2009 06:45:47 -0800 Subject: [Tutor] IDLE vs PythonWin In-Reply-To: <4981DB8D.5050108@sbcglobal.net> References: <49810945.8050402@sbcglobal.net> <49819EBA.3030208@sbcglobal.net> <589697.85007.qm@web86706.mail.ird.yahoo.com> <4981DB8D.5050108@sbcglobal.net> Message-ID: <4984641B.5010302@sbcglobal.net> An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: image/jpeg Size: 25184 bytes Desc: not available URL: From ldl08 at gmx.net Sat Jan 31 16:09:54 2009 From: ldl08 at gmx.net (David) Date: Sat, 31 Jan 2009 23:09:54 +0800 Subject: [Tutor] methods split and join in sequence Message-ID: <498469C2.2020608@gmx.net> Dear list, many thanks for all your help - much appreciated. Today I have continued reading Harrington, and produced the following code, which works flawlessly. I wonder, though, how I could join all the supplied words with underscores _without_ making use of split first? This I didn't manage. Thanks for your ideas! David ''' convert text with whitespace, supplied by the user, into a string joined by underscores. ''' seq = raw_input("Please write some words: ") print "You wrote the following words: ", seq print "The program now joins all words with underscores: ", seq2 = seq.split() print '_'.join(seq2) From srilyk at gmail.com Sat Jan 31 16:52:02 2009 From: srilyk at gmail.com (W W) Date: Sat, 31 Jan 2009 09:52:02 -0600 Subject: [Tutor] methods split and join in sequence In-Reply-To: <498469C2.2020608@gmx.net> References: <498469C2.2020608@gmx.net> Message-ID: <333efb450901310752j5313e224s490c6335f71c34ec@mail.gmail.com> On Sat, Jan 31, 2009 at 9:09 AM, David wrote: > Dear list, > > many thanks for all your help - much appreciated. > Today I have continued reading Harrington, and produced the following code, > which works flawlessly. > I wonder, though, how I could join all the supplied words with underscores > _without_ making use of split first? This I didn't manage. I'm really not sure if you could. Strings don't support item reassignment, so you can't do it this way: In [1]: x = 'foo bar' In [2]: x[3] = '_' --------------------------------------------------------------------------- TypeError Traceback (most recent call last) C:\Documents and Settings\Wayne\ in () TypeError: 'str' object does not support item assignment But there are other string methods available, such as the replace method. http://docs.python.org/library/string.html for the string documentation. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Sat Jan 31 16:56:06 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sat, 31 Jan 2009 07:56:06 -0800 Subject: [Tutor] IDLE vs PythonWin In-Reply-To: <333efb450901310741u62d08674u31597850be35244c@mail.gmail.com> References: <49810945.8050402@sbcglobal.net> <49819EBA.3030208@sbcglobal.net> <589697.85007.qm@web86706.mail.ird.yahoo.com> <4981DB8D.5050108@sbcglobal.net> <4984641B.5010302@sbcglobal.net> <333efb450901310741u62d08674u31597850be35244c@mail.gmail.com> Message-ID: <49847496.5060204@sbcglobal.net> An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: image/jpeg Size: 25184 bytes Desc: not available URL: From andreengels at gmail.com Sat Jan 31 16:59:09 2009 From: andreengels at gmail.com (Andre Engels) Date: Sat, 31 Jan 2009 16:59:09 +0100 Subject: [Tutor] methods split and join in sequence In-Reply-To: <498469C2.2020608@gmx.net> References: <498469C2.2020608@gmx.net> Message-ID: <6faf39c90901310759s20f2a2c6s757a300f9706678c@mail.gmail.com> On Sat, Jan 31, 2009 at 4:09 PM, David wrote: > Dear list, > > many thanks for all your help - much appreciated. > Today I have continued reading Harrington, and produced the following code, > which works flawlessly. > I wonder, though, how I could join all the supplied words with underscores > _without_ making use of split first? This I didn't manage. > > Thanks for your ideas! seq.replace(' ','_') -- Andr? Engels, andreengels at gmail.com From srilyk at gmail.com Sat Jan 31 17:15:48 2009 From: srilyk at gmail.com (W W) Date: Sat, 31 Jan 2009 10:15:48 -0600 Subject: [Tutor] IDLE vs PythonWin In-Reply-To: <49847496.5060204@sbcglobal.net> References: <49810945.8050402@sbcglobal.net> <49819EBA.3030208@sbcglobal.net> <589697.85007.qm@web86706.mail.ird.yahoo.com> <4981DB8D.5050108@sbcglobal.net> <4984641B.5010302@sbcglobal.net> <333efb450901310741u62d08674u31597850be35244c@mail.gmail.com> <49847496.5060204@sbcglobal.net> Message-ID: <333efb450901310815w43823e6ekc713c7b4fe317244@mail.gmail.com> On Sat, Jan 31, 2009 at 9:56 AM, Wayne Watson wrote: > Hi, sorry, but I have no idea what vim is, let alone how to use any of the > features. I'd still like to know why pythonwin prints almost completely > blank pages. vim=vi(m), linux?? > VIM = Vi IMproved = vim +- vi. Basically, vim is just an upgraded vi. Available at www.vim.org - it's "just" a text editor (that happens to be phenomenally powerful and the vi(m) disciples have waged holy wars against the followers of emacs since the beginning of time... or at least since vi and emacs got popular. It's not too unlike Israel vs. Palestine. The best way to avoid bad feelings is to agree that each person prefers a different belief system and move on to the awesome stuff like actually programming ;) ) that certain people prefer because of its ability to be customized to fit ones needs and wants. If you are interested in learning vim theres a vim tutor that comes with your install of vim (available on Windows, Mac, and Unix systems). When it comes to the pythonwin problem, I'm almost completely inexperienced. If you have the ability to "print to pdf" that's an inexpensive way to try and troubleshoot. You can also take a look at the print preview. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From prasadaraon50 at gmail.com Sat Jan 31 17:29:06 2009 From: prasadaraon50 at gmail.com (prasad rao) Date: Sat, 31 Jan 2009 21:59:06 +0530 Subject: [Tutor] Thank you Message-ID: <9e3fac840901310829i2343cd85l2612e98726ce746d@mail.gmail.com> Hello Thanks .Today I learned to use operator.itemgetter() to set key. Thank you prasad -------------- next part -------------- An HTML attachment was scrubbed... URL: From tim at johnsons-web.com Sat Jan 31 17:57:44 2009 From: tim at johnsons-web.com (Tim Johnson) Date: Sat, 31 Jan 2009 07:57:44 -0900 Subject: [Tutor] Is instance of what? Message-ID: <200901310757.44807.tim@johnsons-web.com> Using python 2.5.1 If I create a class a class a: pass initialize o as: o=a and call isinstance(o,a) the return value is True. Is there a function that takes one argument and returns the class? Example: class = whatclass(o) >> "a" Since I'm hoping the answer to this question will help me answer some bigger questions, pointers to relevant docs and discussions is invited. FYI: preparing to migrate to python 3.0 thanks tim -------------- next part -------------- An HTML attachment was scrubbed... URL: From andreengels at gmail.com Sat Jan 31 18:39:37 2009 From: andreengels at gmail.com (Andre Engels) Date: Sat, 31 Jan 2009 18:39:37 +0100 Subject: [Tutor] Re : Is instance of what? In-Reply-To: <6faf39c90901310939n789915aesbc6911b36f94cdca@mail.gmail.com> References: <200901310757.44807.tim@johnsons-web.com> <6faf39c90901310939n789915aesbc6911b36f94cdca@mail.gmail.com> Message-ID: <6faf39c90901310939m768b6b18n2884bbf8ffc45469@mail.gmail.com> On Sat, Jan 31, 2009 at 5:57 PM, Tim Johnson wrote: > Using python 2.5.1 > > If I create a class a > > class a: > > pass > > initialize o as: > > o=a > > and call > > isinstance(o,a) > > the return value is True. Actually, it is false. To make it true, you have to do o=a() rather than o=a > Is there a function that takes one > > argument and returns the class? > > Example: > > class = whatclass(o) > >>> "a" > > Since I'm hoping the answer to this question will help me > > answer some bigger questions, pointers to relevant docs > > and discussions is invited. o.__class__ (or rather o.__class__.__name__) will work. -- Andr? Engels, andreengels at gmail.com From jay.amorin at gmail.com Sat Jan 31 19:07:41 2009 From: jay.amorin at gmail.com (Jay Jesus Amorin) Date: Sun, 1 Feb 2009 02:07:41 +0800 Subject: [Tutor] string fomatting Message-ID: Hi, I'm a newbie trying to learn python. Kindly help me on string formatting. test = https://www.localhost.org/testmodule/dev/trunk/admin/sql/mytest.sql what will i use to print this output? 1, https://www.localhost.org/ 2. testmodule 3. /dev/trunk/admin/sql/mytest.sql Thanks, Jay -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Sat Jan 31 19:22:31 2009 From: bgailer at gmail.com (bob gailer) Date: Sat, 31 Jan 2009 13:22:31 -0500 Subject: [Tutor] string fomatting In-Reply-To: References: Message-ID: <498496E7.3070600@gmail.com> Jay Jesus Amorin wrote: > Hi, > > I'm a newbie trying to learn python. Kindly help me on string formatting. > > test = https://www.localhost.org/testmodule/dev/trunk/admin/sql/mytest.sql My browser can't establish a connection to that site! > > what will i use to print this output? > > 1, https://www.localhost.org/ > > 2. testmodule > > 3. /dev/trunk/admin/sql/mytest.sql > > > > Thanks, > > > Jay > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Bob Gailer Chapel Hill NC 919-636-4239 From bgailer at gmail.com Sat Jan 31 19:29:55 2009 From: bgailer at gmail.com (bob gailer) Date: Sat, 31 Jan 2009 13:29:55 -0500 Subject: [Tutor] string fomatting In-Reply-To: References: Message-ID: <498498A3.7030003@gmail.com> Jay Jesus Amorin wrote: > Hi, > > I'm a newbie trying to learn python. Kindly help me on string formatting. > > test = https://www.localhost.org/testmodule/dev/trunk/admin/sql/mytest.sql > > what will i use to print this output? > > 1, https://www.localhost.org/ > > 2. testmodule > > 3. /dev/trunk/admin/sql/mytest.sql > > Oh now I get it. I thought that you had posted code at that site. Now I think you want to do something to the string " https://www.localhost.org/testmodule/dev/trunk/admin/sql/mytest.sql" Too bad you did not put it in quotes! It is not clear as to how "string formating" applies to this question. The obvious answer is: print("1, https://www.localhost.org/"" print() print("2. testmodule") print() print("3. /dev/trunk/admin/sql/mytest.sql") If that is not what you are looking for please explain. -- Bob Gailer Chapel Hill NC 919-636-4239 From jay.amorin at gmail.com Sat Jan 31 19:44:02 2009 From: jay.amorin at gmail.com (Jay Jesus Amorin) Date: Sun, 1 Feb 2009 02:44:02 +0800 Subject: [Tutor] string fomatting In-Reply-To: <498498A3.7030003@gmail.com> References: <498498A3.7030003@gmail.com> Message-ID: Thanks bob. I want to search any characters in test after https://www.localhost.org/and the search will end after it finds another / and when i print it will display *testmodule*. Newbie, Jay On Sun, Feb 1, 2009 at 2:29 AM, bob gailer wrote: > Jay Jesus Amorin wrote: > >> Hi, >> >> I'm a newbie trying to learn python. Kindly help me on string formatting. >> >> test = >> https://www.localhost.org/testmodule/dev/trunk/admin/sql/mytest.sql >> >> what will i use to print this output? >> >> 1, https://www.localhost.org/ >> >> 2. testmodule >> >> 3. /dev/trunk/admin/sql/mytest.sql >> >> >> Oh now I get it. I thought that you had posted code at that site. Now I > think you want to do something to the string > > " https://www.localhost.org/testmodule/dev/trunk/admin/sql/mytest.sql" > > Too bad you did not put it in quotes! > > It is not clear as to how "string formating" applies to this question. > > The obvious answer is: > > print("1, https://www.localhost.org/"" > print() > print("2. testmodule") > print() > print("3. /dev/trunk/admin/sql/mytest.sql") > > If that is not what you are looking for please explain. > > > -- > Bob Gailer > Chapel Hill NC > 919-636-4239 > -------------- next part -------------- An HTML attachment was scrubbed... URL: From srilyk at gmail.com Sat Jan 31 19:47:40 2009 From: srilyk at gmail.com (W W) Date: Sat, 31 Jan 2009 12:47:40 -0600 Subject: [Tutor] Tkinter program start with focus?` Message-ID: <333efb450901311047o34059716o923fe286acfc63bb@mail.gmail.com> Hi, I'm running into a problem that's bugging me because I know a program used it, I just can't find which one it was... I want my Tkinter program to start with the focus, but I can't remember the command. TIA, Wayne -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn't. - Primo Levi -------------- next part -------------- An HTML attachment was scrubbed... URL: From tim at johnsons-web.com Sat Jan 31 19:54:24 2009 From: tim at johnsons-web.com (Tim Johnson) Date: Sat, 31 Jan 2009 09:54:24 -0900 Subject: [Tutor] Re : Is instance of what? In-Reply-To: <6faf39c90901310939m768b6b18n2884bbf8ffc45469@mail.gmail.com> References: <200901310757.44807.tim@johnsons-web.com> <6faf39c90901310939n789915aesbc6911b36f94cdca@mail.gmail.com> <6faf39c90901310939m768b6b18n2884bbf8ffc45469@mail.gmail.com> Message-ID: <200901310954.24588.tim@johnsons-web.com> On Saturday 31 January 2009, Andre Engels wrote: <...> > > o=a <....> > Actually, it is false. To make it true, you have to do o=a() rather than > o=a You're correct. That was my typo. > > Is there a function that takes one > > > > argument and returns the class? > > > > Example: > > > > class = whatclass(o) <...> > o.__class__ (or rather o.__class__.__name__) will work. Understood. Thank you. tj From srilyk at gmail.com Sat Jan 31 16:41:58 2009 From: srilyk at gmail.com (W W) Date: Sat, 31 Jan 2009 09:41:58 -0600 Subject: [Tutor] IDLE vs PythonWin In-Reply-To: <4984641B.5010302@sbcglobal.net> References: <49810945.8050402@sbcglobal.net> <49819EBA.3030208@sbcglobal.net> <589697.85007.qm@web86706.mail.ird.yahoo.com> <4981DB8D.5050108@sbcglobal.net> <4984641B.5010302@sbcglobal.net> Message-ID: <333efb450901310741u62d08674u31597850be35244c@mail.gmail.com> On Sat, Jan 31, 2009 at 8:45 AM, Wayne Watson wrote: > Did I miss a response here? > > Wayne Watson wrote: > > vim? I'm looking at the interactive window now. Here are two choices for > what you say: > 1. > alt-tab vim > Traceback ( File "", line 1 > alt-tab vim > ^ > SyntaxError: invalid syntax > > 2. Pressing the alt-tab keys moves me to the next Windows window, which > happens to contain my mail window. > > I'm putting an image here. It may not get through to tutor. > > > ALAN GAULD wrote: > > > I'm not familiar with these acronyms. MDI, SDI, > > MDI = Multi Document Interface - has many windows within one single outer > window. > This was MS Standard for apps from Windows 2 through to Windows 95. > > SDI = Single Document Inteface - has each document within its own window. > This has been the preferred styule since XP (between 95 and XP I think the > preferred style was up to the developers!) > > Alt-Tab and up-arrow for navigating between windows/commands > works for me :-) > > > As soon as I hit, alt-tab, Win moves between all the icons on my screen. > > There's not chance to press an up arrow. > > Alt tab switches windows > Up/Down arrow moves up/down the command history within a window > > So a typical session goes like: > > Experiment at >>> prompt > Alt-Tab to vim > Edit & save file in vim > Alt-Tab to Console > use up arrow to retrieve last command > execute last command(ie run the script) > Alt Tab to vim to fix bugs or >>> to try out new ideas > > I think you may have misunderstood Alan. He has open a vim editor and a python prompt. So he might do something like: >>> def test(): ... print "Hello, does" + " this work?" ... >>> test() Hello, does this work? in his interactive shell. So now he knows string concatenation works so he might hit alt+tab to his open vim window and there add something like this: def salutation(fname, lname): print "Good morning, " + fname + " " + lname + ". Welcome to my program!" Or of course he could experiment with the actual bit of code he's trying to write, but the illustration still stands. Then he saves his code in vim and runs the script in the shell (in Ipython you'd use the magic function %run, I'm not sure about the regular shell), to see how well his code works with the rest of his program. That's the same way I edit my code - vim + Ipython gives me all the tools I need. The nice thing about working with another shell like that is you can use your favourite editor, whether it be vim, or emacs, or gedit, or notepad++ or scite, or MS Visual Studio, or notepad, or wordpad... I'm sure you get the picture ;) Heck, you can even use pythonwin the same way. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: image/jpeg Size: 25184 bytes Desc: not available URL: From goldwamh at slu.edu Sat Jan 31 19:56:57 2009 From: goldwamh at slu.edu (Michael H. Goldwasser) Date: Sat, 31 Jan 2009 12:56:57 -0600 Subject: [Tutor] PyCon2009 Tutorial: An Introduction to Object-Oriented Programming Message-ID: <18820.40697.568054.637852@Michael-Goldwassers-Computer.local> David Letscher and I will be leading a tutorial at this year's PyCon titled "An Introduction to Object-Oriented Programming." This tutorial is designed for programmers who are familiar with Python yet new to the concept of object-oriented programming. We also welcome programmers who are experienced with other object-oriented languages yet new to Python. We will begin the tutorial by introducing the general principles of object-oriented programming. We then focus on Python's treatment of object orientation. The tutorial will be organized as a mix of formal presentations together with hands-on demonstrations and exercises. For a more detailed outline of the topics or a link to registration, see http://us.pycon.org/2009/tutorials/schedule/2PM1 If you have other questions about what to expect, feel free to contact me. With regard, Michael Goldwasser +----------------------------------------------- | Michael Goldwasser | Associate Professor | Dept. Mathematics and Computer Science | Saint Louis University | 220 North Grand Blvd. | St. Louis, MO 63103-2007 | URL: http://cs.slu.edu/~goldwasser From denis.spir at free.fr Sat Jan 31 20:47:39 2009 From: denis.spir at free.fr (spir) Date: Sat, 31 Jan 2009 20:47:39 +0100 Subject: [Tutor] Re : Is instance of what? In-Reply-To: <200901310954.24588.tim@johnsons-web.com> References: <200901310757.44807.tim@johnsons-web.com> <6faf39c90901310939n789915aesbc6911b36f94cdca@mail.gmail.com> <6faf39c90901310939m768b6b18n2884bbf8ffc45469@mail.gmail.com> <200901310954.24588.tim@johnsons-web.com> Message-ID: <20090131204739.2eff54c0@o> Le Sat, 31 Jan 2009 09:54:24 -0900, Tim Johnson a ?crit : > On Saturday 31 January 2009, Andre Engels wrote: > <...> > > > o=a > <....> > > Actually, it is false. To make it true, you have to do o=a() rather than > > o=a > You're correct. That was my typo. > > > Is there a function that takes one > > > > > > argument and returns the class? > > > > > > Example: > > > > > > class = whatclass(o) > <...> > > o.__class__ (or rather o.__class__.__name__) will work. > Understood. Thank you. > tj type(a) has been changed (since 2.2?) to return the same value as a.__class__ isinstance(a,t) will also be True for any supertype of a's type class C(): pass class D(C): pass o = D() print isinstance(o,D), isinstance(o,C), isinstance(o,object) ==> True True True ------ la vida e estranya From kent37 at tds.net Sat Jan 31 20:51:00 2009 From: kent37 at tds.net (Kent Johnson) Date: Sat, 31 Jan 2009 14:51:00 -0500 Subject: [Tutor] string fomatting In-Reply-To: References: <498498A3.7030003@gmail.com> Message-ID: <1c2a2c590901311151g7c90dc1q990d329159511da0@mail.gmail.com> On Sat, Jan 31, 2009 at 1:44 PM, Jay Jesus Amorin wrote: > Thanks bob. > > I want to search any characters in test after https://www.localhost.org/ and > the search will end after it finds another / > > and when i print it will display testmodule. One way to do this would be to use urlparse.urlparse() to split the URL into parts, then reassemble the bits you want. Alternately, you can use a regular expression to split it up: In [1]: import re In [2]: test = "https://www.localhost.org/testmodule/dev/trunk/admin/sql/mytest.sql" This re finds everything up to the third / as group 1, everything after the third / as group3: In [10]: match = re.search(r'(http(s)?://[^/]+/)(.*)', test) In [11]: match.group(1) Out[11]: 'https://www.localhost.org/' In [12]: match.group(3) Out[12]: 'testmodule/dev/trunk/admin/sql/mytest.sql' You can now split on / to get the first path element: In [13]: match.group(3).split('/')[0] Out[13]: 'testmodule' Kent From denis.spir at free.fr Sat Jan 31 20:56:47 2009 From: denis.spir at free.fr (spir) Date: Sat, 31 Jan 2009 20:56:47 +0100 Subject: [Tutor] string fomatting In-Reply-To: References: <498498A3.7030003@gmail.com> Message-ID: <20090131205647.6bf822e9@o> Le Sun, 1 Feb 2009 02:44:02 +0800, Jay Jesus Amorin a ?crit : > Thanks bob. > > I want to search any characters in test after > https://www.localhost.org/and > the search will end after it finds another / > > and when i print it will display *testmodule*. > > Newbie, > > Jay I think your question is not of string formatting, rather of string parsing, meaning identifying parts of string according to a given format. I your case, you want a function that able to extract a substring that: * starts with "test" * ends with "/" You can do this step by step using simple string method 'find', and slicing: * find the (position of the) first occurrence of "test" * find the (position of the) first occurrence of "/", after "test"'s position * extract the slice defined by these positions Denis ------ la vida e estranya From kent37 at tds.net Sat Jan 31 21:00:02 2009 From: kent37 at tds.net (Kent Johnson) Date: Sat, 31 Jan 2009 15:00:02 -0500 Subject: [Tutor] Re : Is instance of what? In-Reply-To: <20090131204739.2eff54c0@o> References: <200901310757.44807.tim@johnsons-web.com> <6faf39c90901310939n789915aesbc6911b36f94cdca@mail.gmail.com> <6faf39c90901310939m768b6b18n2884bbf8ffc45469@mail.gmail.com> <200901310954.24588.tim@johnsons-web.com> <20090131204739.2eff54c0@o> Message-ID: <1c2a2c590901311200r84b674evca84c16e7a23507d@mail.gmail.com> On Sat, Jan 31, 2009 at 2:47 PM, spir wrote: >> > o.__class__ (or rather o.__class__.__name__) will work. >> Understood. Thank you. >> tj > > type(a) has been changed (since 2.2?) to return the same value as a.__class__ I think you mean type(o) (type of the instance) rather than type(a) (type of the class object). type(o) == o.__class__ is only true if o is an instance of a new-style class. Instances of oldstyle classes all have type 'instance'. Kent From zebra05 at gmail.com Sat Jan 31 21:27:42 2009 From: zebra05 at gmail.com (OkaMthembo) Date: Sat, 31 Jan 2009 22:27:42 +0200 Subject: [Tutor] Want to write a Perl based IP to Domain Name converter. In-Reply-To: <23816288.20090131221128@gmail.com> References: <6410451598.20090131201141@gmail.com> <1c2a2c590901310544l7f261ef3xeceb2633030b7e05@mail.gmail.com> <23816288.20090131221128@gmail.com> Message-ID: Lol..thats okay. Now that you are here and have seen what fun we have writing Python code - why not join the party? Don't be shy to join us :p - i bet you won't be sorry. On Sat, Jan 31, 2009 at 4:11 PM, wrote: > On Saturday, January 31, 2009 at 21:44, kent37 at tds.net wrote: > > On Sat, Jan 31, 2009 at 7:11 AM, wrote: > >> Hi all, > >> > >> The script in the following can do the batch conversion from domain name > to IP: > > > This is a Python list, not Perl! > > OMG! It's my mistake, sorry for this. > -- > Hongyi Zhao > Xinjiang Technical Institute of Physics and Chemistry > Chinese Academy of Sciences > GnuPG DSA: 0xD108493 > 2009-1-31 > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Lloyd Dube -------------- next part -------------- An HTML attachment was scrubbed... URL: From cappy2112 at gmail.com Sat Jan 31 21:39:36 2009 From: cappy2112 at gmail.com (Tony Cappellini) Date: Sat, 31 Jan 2009 12:39:36 -0800 Subject: [Tutor] Determining periodicity of rand.randint() Message-ID: <8249c4ac0901311239ld2e7db9td668b7c11f71eb4d@mail.gmail.com> Has anyone ever measured how random (or deterministic) a given sequence of numbers generated by rand.randint() are? Using these arguments for rand.randint(0, 10000000 ) if a program which calls rand.randint() runs for 10 hours (or a few days), will it keep generating a repeatable set of numbers at some point? I'm trying to understand the periodicity (or lack of) of the numbers generated by rand.randint() -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Sat Jan 31 22:00:22 2009 From: bgailer at gmail.com (bob gailer) Date: Sat, 31 Jan 2009 16:00:22 -0500 Subject: [Tutor] string fomatting In-Reply-To: References: <498498A3.7030003@gmail.com> Message-ID: <4984BBE6.6050800@gmail.com> Jay Jesus Amorin wrote: > Thanks bob. > > I want to search any characters in test after > https://www.localhost.org/ > > and the search will end after it finds another / > > and when i print it will display *testmodule*. Ah. Much clearer. header = "https://www.localhost.org/" test = "https://www.localhost.org/foo/bar" # we desire to extract 'foo' start = len(header) end = test[start:].find('/') + start result = test[start: end] print result -- Bob Gailer Chapel Hill NC 919-636-4239 From bgailer at gmail.com Sat Jan 31 22:04:07 2009 From: bgailer at gmail.com (bob gailer) Date: Sat, 31 Jan 2009 16:04:07 -0500 Subject: [Tutor] Determining periodicity of rand.randint() In-Reply-To: <8249c4ac0901311239ld2e7db9td668b7c11f71eb4d@mail.gmail.com> References: <8249c4ac0901311239ld2e7db9td668b7c11f71eb4d@mail.gmail.com> Message-ID: <4984BCC7.4080206@gmail.com> Tony Cappellini wrote: > > > Has anyone ever measured how random (or deterministic) a given > sequence of numbers generated by rand.randint() are? > > Using these arguments for rand.randint(0, 10000000 ) > if a program which calls rand.randint() runs for 10 hours (or a few > days), will it keep generating a repeatable set of numbers at some > point? I'm trying to understand the periodicity (or lack of) of the > numbers generated by rand.randint() random uses AFAIK the Mersenne Twister algorithm. See http://en.wikipedia.org/wiki/Mersenne_twister -- Bob Gailer Chapel Hill NC 919-636-4239 From kent37 at tds.net Sat Jan 31 22:05:43 2009 From: kent37 at tds.net (Kent Johnson) Date: Sat, 31 Jan 2009 16:05:43 -0500 Subject: [Tutor] Determining periodicity of rand.randint() In-Reply-To: <8249c4ac0901311239ld2e7db9td668b7c11f71eb4d@mail.gmail.com> References: <8249c4ac0901311239ld2e7db9td668b7c11f71eb4d@mail.gmail.com> Message-ID: <1c2a2c590901311305n5791fe59pa1bb631696d74666@mail.gmail.com> On Sat, Jan 31, 2009 at 3:39 PM, Tony Cappellini wrote: > > > Has anyone ever measured how random (or deterministic) a given sequence of > numbers generated by rand.randint() are? > > Using these arguments for rand.randint(0, 10000000 ) > if a program which calls rand.randint() runs for 10 hours (or a few days), > will it keep generating a repeatable set of numbers at some point? I'm > trying to understand the periodicity (or lack of) of the numbers generated > by rand.randint() According to the docs http://docs.python.org/library/random.html "Python uses the Mersenne Twister as the core generator. It produces 53-bit precision floats and has a period of 2**19937-1." http://en.wikipedia.org/wiki/Mersenne_twister 2**29937-1 is about 10**13819 which is a pretty big number :-) You would have to use over 10**13808 numbers per second to start repeating in 10 hours. So I think you are safe. Kent PS The exact value of 2**19937-1 is 43154247973881626480552355163379198390539350432267115051652505414033306801376580911304513629318584665545269938257648835317902217334584413909528269154609168019007875343741396296801920114486480902661414318443276980300066728104984095451588176077132969843762134621790396391341285205627619600513106646376648615994236675486537480241964350295935168662363909047948347692313978301377820785712419054474332844529183172973242310888265081321626469451077707812282829444775022680488057820028764659399164766265200900561495800344054353690389862894061792872011120833614808447482913547328367277879565648307846909116945866230169702401260240187028746650033445774570315431292996025187780790119375902863171084149642473378986267503308961374905766340905289572290016038000571630875191373979555047468154333253474991046248132504516341796551470575481459200859472614836213875557116864445789750886277996487304308450484223420629266518556024339339190844368921018424844677042727664601852914925277280922697538426770257333928954401205465895610347658855386633902546289962132643282425748035786233580608154696546932563833327670769899439774888526687278527451002963059146963875715425735534475979734463100678367393327402149930968778296741391514599602374213629898720611431410402147238998090962818915890645693934483330994169632295877995848993366747014871763494805549996163051541225403465297007721146231355704081493098663065733677191172853987095748167816256084212823380168625334586431254034670806135273543270714478876861861983320777280644806691125713197262581763151313596429547763576367837019349835178462144294960757190918054625114143666384189433852576452289347652454631535740468786228945885654608562058042468987372436921445092315377698407168198376538237748614196207041548106379365123192817999006621766467167113471632715481795877005382694393400403061700457691135349187874888923429349340145170571716181125795888889277495426977149914549623916394014822985025331651511431278802009056808456506818877266609831636883884905621822262933986548645669080672191704740408891349835685662428063231198520436826329415290752972798343429446509992206368781367154091702655772727391329424277529349082600585884766523150957417077831910016168475685658673192860882070179760307269849987354836042371734660257694347235506301744118874141292438958141549100609752216882230887611431996472330842380137110927449483557815037586849644585749917772869926744218369621137675101083278543794081749094091043084096774144708436324279476892056200427227961638669149805489831121244676399931955371484012886360748706479568669048574782855217054740113945929622177502575565811067452201448981991968635965361551681273982740760138899638820318776303668762730157584640042798880691862640268612686180883874939573818125022279689930267446255773959542469831637863000171279227151406034129902181570659650532600775823677398182129087394449859182749999007223592423334567850671186568839186747704960016277540625331440619019129983789914712515365200336057993508601678807687568562377857095255541304902927192220184172502357124449911870210642694565061384919373474324503966267799038402386781686809962015879090586549423504699190743519551043722544515740967829084336025938225780730880273855261551972044075620326780624448803490998232161231687794715613405793249545509528052518010123087258778974115817048245588971438596754408081313438375502988726739523375296641615501406091607983229239827240614783252892479716519936989519187808681221191641747710902480633491091704827441228281186632445907145787138351234842261380074621914004818152386666043133344875067903582838283562688083236575482068479639546383819532174522502682372441363275765875609119783653298312066708217149316773564340379289724393986744139891855416612295739356668612658271234696438377122838998040199739078061443675415671078463404673702403777653478173367084844734702056866636158138003692253382209909466469591930161626097920508742175670306505139542860750806159835357541032147095084278461056701367739794932024202998707731017692582046210702212514120429322530431789616267047776115123597935404147084870985465426502772057300900333847905334250604119503030001704002887892941404603345869926367501355094942750552591581639980523190679610784993580896683299297681262442314008657033421868094551740506448829039207316711307695131892296593509018623094810557519560305240787163809219164433754514863301000915916985856242176563624771328981678548246297376249530251360363412768366456175077031977457534912806433176539995994343308118470147158712816149394421276614228262909950055746981053206610001560295784656616193252269412026831159508949671513845195883217147982748879261851417819979034417285598607727220866677680426090308754823803345446566305619241308374452754668143015487710877728011086004325892262259413968285283497045571062757701421761565262725153407407625405149931989494459106414660534305378576709862520049864880961144869258603473714363659194013962706366851389299692869491805172556818508298824954954815796063169517658741420159798754273428026723452481263569157307213153739781041627653715078598504154797287663122946711348158529418816432825044466692781137474494898385064375787507376496345148625306383391555145690087891955315994462944493235248817599907119135755933382121706191477185054936632211157222920331148502487563303118018805685073569841580518118710778653953571296014372940865270407021924383167290323231567912289419486240594039074452321678019381871219092155460768444573578559513613304242206151356457513937270939009707237827101245853837678338161023397586854894230696091540249987907453461311923963852950754758058205625956600817743007191746812655955021747670922460866747744520875607859062334750627098328593480067789456169602494392813763495657599847485773553990957557313200809040830036446492219409934096948730547494301216165686750735749555882340303989874672975455060957736921559195480815514035915707129930057027117286252843197413312307617886797506784260195436760305990340708481464607278955495487742140753570621217198252192978869786916734625618430175454903864111585429504569920905636741539030968041471 From wescpy at gmail.com Sat Jan 31 23:42:50 2009 From: wescpy at gmail.com (wesley chun) Date: Sat, 31 Jan 2009 14:42:50 -0800 Subject: [Tutor] Want to write a Perl based IP to Domain Name converter. In-Reply-To: References: <6410451598.20090131201141@gmail.com> <1c2a2c590901310544l7f261ef3xeceb2633030b7e05@mail.gmail.com> <23816288.20090131221128@gmail.com> Message-ID: <78b3a9580901311442t791abf63vb034df85f8b3bddc@mail.gmail.com> >> >> The script in the following can do the batch conversion from domain >> >> name to IP: >> >> > This is a Python list, not Perl! >> >> OMG! It's my mistake, sorry for this. > > Lol..thats okay. Now that you are here and have seen what fun we have > writing Python code - why not join the party? > > Don't be shy to join us :p - i bet you won't be sorry. well, he had to join Tutor to post, unless a mod allowed his msg, so there should be *some* interest in doing it in Python. after all, the equivalent code is already slightly shorter and easier to read than the Perl version... import socket import sys for hp in sys.argv[1:]: h, p = hp.strip().split(':') print '%s -> %s:%s' % (hp, socket.gethostbyname(h), p) cheers, -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 "Python Fundamentals", Prentice Hall, (c)2009 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From wescpy at gmail.com Sat Jan 31 23:49:59 2009 From: wescpy at gmail.com (wesley chun) Date: Sat, 31 Jan 2009 14:49:59 -0800 Subject: [Tutor] PyCon2009 Tutorial: An Introduction to Object-Oriented Programming In-Reply-To: <18820.40697.568054.637852@Michael-Goldwassers-Computer.local> References: <18820.40697.568054.637852@Michael-Goldwassers-Computer.local> Message-ID: <78b3a9580901311449g62e267e5v5315c59ad6089385@mail.gmail.com> > David Letscher and I will be leading a tutorial at this year's > PyCon titled "An Introduction to Object-Oriented Programming." likewise, i'll be doing one on network programming, so if you ever wanted to know all about it, we take it from the lowest layer (socket level), up thru internet protocols (FTP, NNTP, SMTP, POP3), give an intro to web/CGI, and then end at the highest level with a demo of Django. to see all of the tutorials at this year's PyCon coming up at the end of Mar in chicago, check out the schedule here: http://us.pycon.org/2009/tutorials/schedule tutorials are one of the most popular aspects of PyCon, and we've actually grown it to TWO full days now! also, conference registration is open now so please sign up. as far as the rest of the conference goes, there is also 2 days of exhibit hall and here is a list of all the talks being presented at PyCon09: http://us.pycon.org/2009/conference/talks/ hope to meet some of you in the windy city in about 2 months! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 "Python Fundamentals", Prentice Hall, (c)2009 http://corepython.com "Python Web Development with Django", Addison Wesley, (c) 2009 http://withdjango.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com