Re: [Tutor] (no subject)
Jim and Laura Ahl said unto the world upon 2005-04-14 02:09: How come when I ask it to print i[2:4] from an inputted string it gives me the letters between two and four But when I ask it to print i[-1:-4] it does not print anything. Jim Hi Jim, good to see you are still working at it. And posting some bits of code to focus a response around is helpful :-) >>> 'my test string'[-1:-4] '' This tells Python to start at the end of the string and go *forward*, one position at a time, up to, but not including, the -4 position. But, since there is nothing forward from the end of the string, this gives the empty string. That suggests we need to one of two things: >>> 'my test string'[-1:-4:-1] 'gni' >>> That says start at the end and go *backwards*, one position at a time, up to, but not including, the -4 position. Or, >>> 'my test string'[-4:-1] 'rin' >>> This says start at the -4 position and go forwards, one position at a time, up to, but not including the -1 position (i.e. the last letter). We can also do >>> 'my test string'[-4:] 'ring' >>> to remove the "but not including the -1 position" part of the instruction. Try playing around with indexes using 1, 2, or 3, `slots'[*] and specifying all, none, or some, and see what comes out. If you don't understand the results, post again with the examples you don't understand. [*] slots? I mean: 'I am indexed with 1 slot'[4] 'I am indexed with 2 slots'[4:6] 'I am indexed with 3 slots'[4:6:1] 'None of my slots have been "specified" '[:] (There must be a better term that `slots', but it is 3am :-) Best, Brian vdB ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Re: (no subject)
Jim and Laura Ahl psci.net> writes: > How come when I ask it to print i[2:4] from an inputted string it gives me the letters between two and four > > But when I ask it to print i[-1:-4] it does not print anything. Because the range is counting forward from -1 (the last element) onward, and since there's nothing after the last element, it can't print anything. It's the same as typing range(5,2) for example. If you want it to give you the letters beteen -1 and -4 backwards, type i[-1:-4:-1] (I'm not sure that works in older Pythons). If you need the last 4 letters, type i[-4:]. Yours, Andrei ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] (no subject)
Hi Jim, on Thu, 14 Apr 2005 01:09:14 -0500 "Jim and Laura Ahl" <[EMAIL PROTECTED]> wrote : - Jim and Laura Ahl > How come when I ask it to print i[2:4] from an inputted string it gives me the letters between two and four Jim and Laura Ahl > Jim and Laura Ahl > But when I ask it to print i[-1:-4] it does not print anything. Here you extract a slice starting with the last entry in i and ending much earlier, so you are asking for a slice with a negative length. Perhaps what you like is print i[-4:-1] ? --- end -- HTH Ewald ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] _winreg problems enumerating
Gallagher Timothy-TIMOTHYG wrote: am new to python and want to learn this language. I am having troubles finding examples and tutorials for use on windows boxes. I do most of my stuff in perl and php but want better socket support, so I am giving python a try. I am writing a script to connect to remote registry's because of this new IM virus. I can create reg entries and delete them but I cannot enumerate them, here is my code. import _winreg host = "127.0.0.1" # local host key = _winreg.ConnectRegistry(host, _winreg.HKEY_LOCAL_MACHINE) E_key = _winreg.EnumValue(key, r"SOFTWARE\Microsoft\Windows\CurrentVersion\Run") _winreg is pretty low level. It can only access one level down from the current key. Here is a program that navigates a path in the registry one step at a time: import _winreg def openKey(key, path): pathElements = path.split('\\') for elem in pathElements: key = _winreg.OpenKey(key, elem) return key key = _winreg.ConnectRegistry(None, _winreg.HKEY_LOCAL_MACHINE) runKey = openKey(key, r"SOFTWARE\Microsoft\Windows\CurrentVersion\Run") print _winreg.QueryInfoKey(runKey) Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] odd behavior within __init__
Hello all, As part of a project i'm doing (mostly for the fun of it), I have a class which creates a sort of wrapper around any object to make it suitable for use in a custom container. However, if the class receives an already wrapped object, I want it to just return the object (same id and everything as the original). Now, the following seems to work in the __init__ method (due to output), but then it disappears as soon as the __init__ method is left: class Node: ... def __init__(self, cargo=None, prev=None, next=None, nod=False): """x.__init__(...) initializes x; see x.__class__.__doc__ for signature""" if not isinstance(cargo, Node) or nod: self.cargo = cargo self.prev = prev self.next = next else: self = cargo print id(self), id(cargo) print self.cargo >>> a = Node(1) >>> b = Node(a) 12932600 12932600 1 >>> id(b) 12960632 Any ideas on why this happens, or suggestions as to how to implement the behavior I'm looking for (in which b and a would refer to the same object, have the same id, etc.), would be greatly appreciated. Thanks in advance, Orri -- Email: singingxduck AT gmail DOT com AIM: singingxduck Programming Python for the fun of it. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] odd behavior within __init__
On Apr 14, 2005, at 12:58, Orri Ganel wrote: a = Node(1) b = Node(a) 12932600 12932600 1 id(b) 12960632 Any ideas on why this happens, or suggestions as to how to implement the behavior I'm looking for (in which b and a would refer to the same object, have the same id, etc.), would be greatly appreciated. Well, if you want b and a to refer to the same object, just use b = a. Everything is a reference in Python, make use of this feature. (at that point, I expect Alan to drop in and explain why what I said is not entirely accurate, but good enough ;) ) -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] odd behavior within __init__
Orri Ganel wrote: Hello all, As part of a project i'm doing (mostly for the fun of it), I have a class which creates a sort of wrapper around any object to make it suitable for use in a custom container. However, if the class receives an already wrapped object, I want it to just return the object (same id and everything as the original). Now, the following seems to work in the __init__ method (due to output), but then it disappears as soon as the __init__ method is left: class Node: ... def __init__(self, cargo=None, prev=None, next=None, nod=False): """x.__init__(...) initializes x; see x.__class__.__doc__ for signature""" if not isinstance(cargo, Node) or nod: self.cargo = cargo self.prev = prev self.next = next else: self = cargo print id(self), id(cargo) print self.cargo a = Node(1) b = Node(a) 12932600 12932600 1 id(b) 12960632 Any ideas on why this happens, or suggestions as to how to implement the behavior I'm looking for (in which b and a would refer to the same object, have the same id, etc.), would be greatly appreciated. Thanks in advance, Orri Orri, Maybe you could use a factory. It would allow you to simplify your Node class, and encapsulate the instantiation behavior you want outside the class. class Node(object): def __init__(self,cargo=None,prev=None,next=None): self.cargo = cargo self.prev = prev self.next = next def factory(cargo=None,prev=None,next=None): if isinstance(cargo,Node): return cargo else: return Node(cargo,prev,next) n1 = factory(1) print id(n1) n2 = factory(n1) print id(n2) Good luck, Rich ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Question regarding the len function of a list while using a loop
Could somebody explain to me why the code I used to complete this exercise doesn't work. And how do you send an integer to len? Thanks Ben == As an exercise, write a loop that traverses a list and prints the length of each element. What happens if you send an integer to len? >>> foo = ['spam!', 1, ['brie', 'cheddar', 'swiss'], [1, 2, 3]] >>> i = 0 >>> while i < len(foo): print len(foo[i]) i = i+1 5 Traceback (most recent call last): File "", line 2, in -toplevel- print len(foo[i]) TypeError: len() of unsized object___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] i need to see a var from any where in my app - im clueless
pxlpluker wrote: i want to read a global (OPTIONS) from file1 from a class method (func1) in file2 but i cant see the OPTION from func1 -- #file1.py import file2 import sys OPTION = sys.argv[1:] pass a=global2.class1() Presumably you mean file2.class1() here; global2 is not defined a.func1() One good option is just to pass OPTION as a parameter here: a.func1(OPTION) #file2.py import __main__ Alternately you can import file1 then in func1() you can refer to file1.OPTION Kent pass class class1: .def func1(self): .pass --- ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Question regarding the len function of a list while using a loop
On Apr 14, 2005, at 14:14, Ben Markwell wrote: Could somebody explain to me why the code I used to complete this exercise doesn't work. And how do you send an integer to len? Well, I think you've successfully completed that exercise. len() doesn't work on integers because integers don't have a length. Think of it that way: - "foo" is a string of length 3 (it contains 3 elements (characters)) - [1, 2, 3] is a list of length 3 (it contains 3 elements) - {'a': 1, 'b': 2, 'foo': 5} is a dict of length 3 (it contains 3 elements) - 100 is an integer. How, as a human being, would you define its "length"? How many elements does it contain? It doesn't make sense, does it? Well, you have it. Numbers (ints, floats...) don't have a length. Therefore, calling len() on an integer is a non-sense that results in an exception. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to calculate pi with another formula?
Dick Moores wrote: Now to my new question. I have an artist friend who knows an artist who needs pi expressed in base 12. I don't know how many digits he needs, but I think he'll take what he can get. Is there a way to use math.log(x, base) with the decimal module to accomplish this? Or is there another way? Or is there no way? I think I would try to write a program that converts base-10 decimal fractions to base 12. Then feed it the output of a pi-generating program. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Is it cookielib or is it me?
Hi all, It's probably me, actually, I was hoping someone who spot my error. I am attempting to use cookielib, and running into difficulties. I have been following this recipe - http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/302930 as an example, as the official documentation is a bit sparse, but it seems rather easy. However, as my code will demonstrate - >>> import re >>> import urllib2 >>> import cookielib >>> >>> a = re.compile('href\=\"showthread.php\?s\=.+?pagenumber=(?P\d+?)\"', re.IGNORECASE) >>> >>> Jar = cookielib.MozillaCookieJar(filename = 'c:/cookies.txt') >>> opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(Jar)) >>> urllib2.install_opener(opener) Now, that's all by the recipe I linked too. No exceptions, so I figured it was good. >>> f = urllib2.urlopen('http://www.gpforums.co.nz/forumdisplay.php?s=&forumid=7029 ') >>> j = f.read() >>> ww = a.finditer(j) >>> print ww.next().group() href=""> Now, that's an issue. When I'm in a cookied session in Firefox, that link would be showthread.php?s=&threadid=267930&pagenumber=2 Hmm... so I check by requesting an url that needs a cookie to get into - >>> f = urllib2.urlopen(' http://www.gpforums.co.nz/newthread.php?s=&action="">') >>> print f.read() You are not logged in, or you do not have permission to access this page. This could be due to one of several reasons: Now, I'm using the exact same cookies.txt ol Firefox uses, so I'm a little perplexed. I check to see if I've actually got a cookie - >>> print Jar <_MozillaCookieJar.MozillaCookieJar[, , , ]> Which is exactly how that cookie looks, both in my cookies.txt, and when I packet sniff it going out. I also tried it the way shown in the recipe, including changing the User-Agent - >>> txheaders = {'User-agent' : 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'} >>> print txheaders {'User-agent': 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'} >>> theurl = 'http://www.gpforums.co.nz/newthread.php?s=&action="" ' >>> req = urllib2.Request(theurl, data = "" headers = txheaders) >>> handle = urllib2.urlopen(req) >>> g = handle.read() >>> print g You are not logged in, or you do not have permission to access this page. This could be due to one of several reasons: So yeah, I'm at a loss, no doubt my mistake is painfully obvious when pointed out, but any pointing would be greatly appreciated. Regards, Liam Clarke GET /newthread.php?s=&action="" HTTP/1.1\r\n Request Method: GET Request URI: /newthread.php?s=&action=""> Request Version: HTTP/1.1 Accept-Encoding: identity\r\n Host: www.gpforums.co.nz\r\n Cookie: bblastvisit=1113481269; sessionhash=f6cba21ed58837ab935a564e6b9c3b05; bblastvisit=1113481269; sessionhash=f6cba21ed58837ab935a564e6b9c3b05\r\n Connection: close\r\n User-agent: Python-urllib/2.4\r\n \r\n ...and the response Hypertext Transfer Protocol HTTP/1.1 200 OK\r\n Request Version: HTTP/1.1 Response Code: 200 Date: Thu, 14 Apr 2005 12:44:12 GMT\r\n Server: Apache/2.0.46 (CentOS)\r\n Accept-Ranges: bytes\r\n X-Powered-By: PHP/4.3.2\r\n Set-Cookie: sessionhash=43bcebcf4dba6878802b25cb126ed1f7; path=/; domain=gpforums.co.nz\r\n Set-Cookie: sessionhash=43bcebcf4dba6878802b25cb126ed1f7; path=/; domain=www.gpforums.co.nz\r\n Set-Cookie: sessionhash=43bcebcf4dba6878802b25cb126ed1f7; path=/; domain=gpforums.co.nz\r\n Set-Cookie: sessionhash=43bcebcf4dba6878802b25cb126ed1f7; path=/; domain=www.gpforums.co.nz\r\n -- 'There is only one basic human right, and that is to do as you damn well please.And with it comes the only basic human duty, to take the consequences.' ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Craps, eternal loop (Joseph Q.)
I get an eternal loop on this game that I don't want and can't figure out how to fix. BTW any of you know the rules to craps? I don't remember them all so this game may be different than the casino version. Here's my code: import random # generate random numbers 1 - 6 loop = True def play_again(): play_again = raw_input("Play again? (Y/N)\n>> ") if play_again == ("Y") or ("y") or ("Yes") or ("yes") or ("YES"): crapps() else: loop = False print "\nCome play again." def roll(): raw_input("\nPress the 'Enter' key (Return) to roll.") def crapps(): while loop: die1 = random.randrange(6) + 1 die2 = random.randrange(6) + 1 die1_2 = random.randrange(6) + 1 die2_2 = random.randrange(6) + 1 total_cash = 100 title_ = "The fun game of craps." print title_.title() print "You have %d dollars on hand." % total_cash print "Now you will wager 10 dollars for the game." total = die1 + die2 total_2 = die1_2 + die2_2 roll() print "\nYou rolled a", die1, "and a", die2, "for a total of", total raw_input("\nPress the 'Enter' key (Return) to let your opponent roll") print "\nYour opponent rolled a", die1_2, "and a", die2_2, "for a total of", total_2 if total > total_2: total_cash = total_cash + 10 print "\nYou won! You now have %d dollars on hand." % total_cash play_again() else: total_cash = total_cash - 10 print "You lost. Too bad. Better luck next time." if total_cash < 0: print "Get out of this casino and work! You're in debt!" elif total_cash == 0: print "Better stop now before you get into debt." play_again() crapps() I also can't get the counter to save the added or removed money. every time I play again, I always have $100 Thanks, Joe ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
RE: [Tutor] Question regarding the len function of a list while using aloop
Hey Ben The problem is quite simple. You're trying to get the lenght of an INTEGER. That's why it gives you the error. In the position 1 of your list you have an integer and unless you call str(int) you won't be able to get the lenght. Moving on, there is another way to accomplish the loop using this sentence: for element in foo: print len(element) Regards Alberto>From: Ben Markwell <[EMAIL PROTECTED]> >Reply-To: Ben Markwell <[EMAIL PROTECTED]> >To: Python Tutor >Subject: [Tutor] Question regarding the len function of a list while using aloop >Date: Thu, 14 Apr 2005 08:14:12 -0400 > >Could somebody explain to me why the code I used to complete this exercise >doesn't work. >And how do you send an integer to len? > >Thanks > >Ben > >== > > >*As an exercise, write a loop that traverses a list and prints the length of >each element. What happens if you send an integer to len? > >*>>> foo = ['spam!', 1, ['brie', 'cheddar', 'swiss'], [1, 2, 3]] > >>> i = 0 > >>> while i < len(foo): >print len(foo[i]) >i = i+1 > > >5 > >Traceback (most recent call last): >File "", line 2, in -toplevel- >print len(foo[i]) >TypeError: len() of unsized object >___ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
RE: [Tutor] _winreg problems enumerating
It seems to work but the output isn't right. I do have 10 things in the Run folder but the out put is not telling me what they are, it just says none for each entry. I guess that I am not sure what to do now. I can do this in Perl and other languages but I really want to learn Python. Here is what I have done: import _winreg host = "127.0.0.1" # local host key = _winreg.ConnectRegistry(host, _winreg.HKEY_LOCAL_MACHINE) hkey = _winreg.OpenKey(key, r"SOFTWARE\Microsoft\Windows\CurrentVersion\Run") i = 0 regKeys = [] try: while 1: test_key = regKeys.append(_winreg.EnumValue(hkey, i)) print test_key i += 1 except EnvironmentError: pass when I run this script I am getting this for my output: None None None None None None None None None None Thanks Tim Timothy F. Gallagher Timothyg- AT 0-Motorola.com From: Liam Clarke [mailto:[EMAIL PROTECTED] Sent: Wednesday, April 13, 2005 9:45 PM To: Gallagher Timothy-TIMOTHYG; tutor@python.org Subject: Re: [Tutor] _winreg problems enumerating Hi Tim, Hmmm, I may have to play with _winreg, is is new with Python 2.4? Anyway, from the _winreg docs - EnumValue( key, index) Enumerates values of an open registry key, returning a tuple. key is an already open key, or any one of the predefined HKEY_* constants. index is an integer that identifies the index of the value to retrieve. The function retrieves the name of one subkey each time it is called. It is typically called repeatedly, until an EnvironmentError exception is raised, indicating no more values. There's your issue - E_key = _winreg.EnumValue(key,r"SOFTWARE\Microsoft\Windows\CurrentVersion\Run") The second value needs to be an integer that is an index. Typical usage would look like this - i = 0 regKeys = [] try: while 1: regKeys.append(_winreg.EnumValue(key, i)) i += 1 except EnvironmentError: pass Good luck, Liam Clarke On 4/14/05, Gallagher Timothy-TIMOTHYG <[EMAIL PROTECTED]> wrote: am new to python and want to learn this language. I am having troubles finding examples and tutorials for use on windows boxes. I do most of my stuff in perl and php but want better socket support, so I am giving python a try. I am writing a script to connect to remote registry's because of this new IM virus. I can create reg entries and delete them but I cannot enumerate them, here is my code. import _winreg host = " 127.0.0.1" # local host key = _winreg.ConnectRegistry(host, _winreg.HKEY_LOCAL_MACHINE) E_key = _winreg.EnumValue(key, r"SOFTWARE\Microsoft\Windows\CurrentVersion\Run") I get an error when I run the script: Traceback (most recent call last): File "reg4.py", line 9, in ? E_key = _winreg.EnumValue(key, r"SOFTWARE\Microsoft\Windows\CurrentVersion\R un") TypeError: an integer is required Can someone tell me what I am doing wrong??? Thanks Timothy F. Gallagher Timothyg- at -Motorola.com ___ Tutor [EMAIL PROTECTED] http://mail.python.org/mailman/listinfo/tutor -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences.' ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
RE: [Tutor] _winreg problems enumerating
Let me know if there is a Tkinter list that is more appropriate for this question. I am writing a function whose job is it delete all of the selected items in a Listbox. The only ways I can think of doing this is to 1) Get list of selected items using the listbox.curselection and then delete each item one at a time. 2) Iterate through each item in the listbox and then call listbox.delete(index) on each one that is selected. The problem with each one is: 1) once the first item in the list of indexes is deleted, I think all of the remaining items will "shift down" and their index number will change, resulting in problem such as "index out of bounds", or deleting the wrong item. 2) Skip over a selected item if there are two selected items next to each other. i.e. indexes 1 and 2 are selected, the for loop hits index 1 and deletes it, the original "1" is gone and now the previous "2" becomes "1"( shifts down ), the for loop continues on to index "2", failing to delete the new index "1". Is there an algorithm that can delete the selected items in one pass? Or would I have to iterate over the listbox items until finally it does not find any selected items. Thank You, John A. Gooch Systems Administrator IT - Tools EchoStar Satellite L.L.C. 9601 S. Meridian Blvd. Englewood, CO 80112 Desk: 720-514-5708 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] New to programming question (Ben M.) (Joseph Q.)
if letter == 'O': >print letter + 'u' + suffix >elif 'Q': >print letter + 'u' + suffic >else: >print letter + suffix > >Do you see? The == "binds more tightly" than the or. And, in python, 'Q' is >considered True for the purposes of tests. > >So this is what happens: > prefixes = 'JKLMNOPQ' suffix = 'ack' for letter in prefixes: > >... if letter == ('O') or ('Q'): >... print letter + 'u' + suffix >... else: >... print letter + suffix >... >Juack >Kuack >Luack >Muack >Nuack >Ouack >Puack >Quack > > >What you can do instead is this: > >for letter in prefixes: >if letter in ['O', 'Q']: >print letter + 'u' + suffix >else: >print letter + suffix Oh, ok. Sorry, my bad :) So there is a special use for ==. I must look into this. Thanks, Joe ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
RE: [Tutor] Craps, eternal loop (Joseph Q.)
-Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of Joseph Quigley Sent: Wednesday, April 13, 2005 6:57 PM To: tutor@python.org Subject: [Tutor] Craps, eternal loop (Joseph Q.) >I get an eternal loop on this game that I don't want and can't figure out >how to fix. >BTW any of you know the rules to craps? I don't remember them all so this >game may be different than the casino version. This is your problem: if play_again == ("Y") or ("y") or ("Yes") or ("yes") or ("YES"): Which is interpreted as (note the extra parens): if (play_again == ("Y")) or ("y") or ("Yes") or ("yes") or ("YES"): What you want is: if play_again in ("Y","y","Yes","yes","YES"): Or better yet: if play_again.upper() in ('Y','YES'): Jeff ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] (no subject)
Jim and Laura Ahl said unto the world upon 2005-04-14 02:09:> How come when I ask it to print i[2:4] from an inputted string it> gives me the letters between two and four> > But when I ask it to print i[-1:-4] it does not print anything.> > Jim> Hi Jim,good to see you are still working at it. And posting some bits of code to focus a response around is helpful :-) >>> 'my test string'[-1:-4]''This tells Python to start at the end of the string and go *forward*, one position at a time, up to, but not including, the -4 position. But, since there is nothing forward from the end of the string, this gives the empty string.That suggests we need to one of two things: >>> 'my test string'[-1:-4:-1]'gni' >>>When I do this it tells me that the sequence index must be an integer. What is that telling me and how do I fix that? Jim That says start at the end and go *backwards*, one position at a time, up to, but not including, the -4 position.Or, >>> 'my test string'[-4:-1]'rin' >>>This says start at the -4 position and go forwards, one position at a time, up to, but not including the -1 position (i.e. the last letter).We can also do >>> 'my test string'[-4:]'ring' >>> Ok, I agree with what this is doing. So if I type in print i[-1] this gives me that last letter of the string. But when I type in print i[-1:] it does nothing, because there is nothing after -1. So I need to find some charecter that takes the string in the opposite direction. like print i[-1:-4] but that does not print anything (why)? When I put another number behind this it gives me it must be an integer print i[-1:-4:-1] so what have I got messed up and why can't this work? And if an iputted word or string in typed in how do you tell it to go to the end of it and stop? I assumed that print i[-1:] would have done itto remove the "but not including the -1 position" part of the instruction.Try playing around with indexes using 1, 2, or 3, `slots'[*] and specifying all, none, or some, and see what comes out. If you don't understand the results, post again with the examples you don't understand.[*] slots? I mean:'I am indexed with 1 slot'[4]'I am indexed with 2 slots'[4:6]'I am indexed with 3 slots'[4:6:1]'None of my slots have been "specified" '[:](There must be a better term that `slots', but it is 3am :-)Best,Brian vdB ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] (no subject)
Jim and Laura Ahl wrote: >>> 'my test string'[-1:-4:-1] 'gni' >>> When I do this it tells me that the sequence index must be an integer. What is that telling me and how do I fix that? Jim It's telling you that it doesn't support "extended slicing" - indexes with three components. Upgrade to Python 2.3 or later to make it work. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
RE: [Tutor] Craps, eternal loop (Joseph Q.)
Thanks a lot. Now I need to find the rules. BTW. What about the counter? If I win I get 110 dollars. On the next round I start out with 100 dollars again, when I should have 110! Joe ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] New to programming question (Ben M.) (Joseph Q.)
Joseph Quigley wrote: if letter == 'O': >print letter + 'u' + suffix >elif 'Q': >print letter + 'u' + suffic >else: >print letter + suffix > >Do you see? The == "binds more tightly" than the or. And, in python, 'Q' is >considered True for the purposes of tests. > >So this is what happens: > prefixes = 'JKLMNOPQ' suffix = 'ack' for letter in prefixes: > >... if letter == ('O') or ('Q'): >... print letter + 'u' + suffix >... else: >... print letter + suffix >... >Juack >Kuack >Luack >Muack >Nuack >Ouack >Puack >Quack > > >What you can do instead is this: > >for letter in prefixes: >if letter in ['O', 'Q']: >print letter + 'u' + suffix >else: >print letter + suffix Oh, ok. Sorry, my bad :) So there is a special use for ==. I must look into this. Thanks, Joe "=" is for assignment of a value to a variable, as in a = 33 "==" is equivalent to, as in 2 * 2 == 4 I've been caught out on more than a few occasions on this distinction!! :) HtH /j ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] New to programming question (Ben M.) (Joseph Q.)
Joseph Quigley said unto the world upon 2005-04-14 10:46: >Do you see? The == "binds more tightly" than the or. And, in python, 'Q' is >considered True for the purposes of tests. >What you can do instead is this: > >for letter in prefixes: >if letter in ['O', 'Q']: >print letter + 'u' + suffix >else: >print letter + suffix Oh, ok. Sorry, my bad :) So there is a special use for ==. I must look into this. Thanks, Joe Hi Joe, I'm not sure what you mean by a "special use", but maybe this will help: In arithmetic: 4 * 10 + 2 = 42 as ( 4 * 10 + 2 ) = ( ( 4 * 10 ) + 2 ) This is because '*' comes before '+' in the oder of operations when parenthesis don't settle the issue. One way to express that is to say "'*' binds more tightly than '+'". In Python '==' binds more tightly than 'or'. So: ( a == b or c ) == ( ( a == b ) or c ) Hence: >>> 42==0 or True True >>> 42 == 0 or 42 == True False >>> # Better is >>> 42 in (0, True) False >>> Does that help? Best, Brian vdB ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python backwards program (fwd)
-- Forwarded message -- Date: Thu, 14 Apr 2005 00:41:40 -0500 From: Jim and Laura Ahl <[EMAIL PROTECTED]> To: Danny Yoo <[EMAIL PROTECTED]> Subject: Re: [Tutor] Python backwards program I thought you were on me a bit but I am so frustrated at this point. My instructor wrote and told me it was easy. So if it is easy why am I having so much trouble. I figured the other three programs by just reading the book and working on the computer. Does the 2.2 python have the ability to do this? I think that the program will work with something like this in an expanded form. The following gives me the last letter of the string. backwords=raw_input("enter number or string:") print backwords[-1] I have looked on a couple of sites and it says to use s.reverse() this does not work for some reason Jim - Original Message - From: Danny Yoo To: Jim and Laura Ahl Cc: Tutor ; Feziwe Mpondo Sent: Thursday, April 14, 2005 12:24 AM Subject: Re: [Tutor] Python backwards program > We're not going to do your homework problems; please understand that we > actually don't care if you get your homework done. And I really hope that > people don't just start blurting stuff at Jim for the other three homework > problems he's dumping on us. Hi Jim, Ok, I screwed up big time today, and I'd better say this in public, so that people know that I made a huge mistake. I usually make small ones that can be easily corrected, but I get the feeling I did damage today, and I wish I could take it back. Jim, I sincerely apologize about snapping at you like that. I was wrong to do so, especially since I completely misread your sentence. I thought you were saying that those were three other problems that you had to do soon, when you had actually wrote that those were three programs that you had written already. But even so, I had no excuse to say things like that. I will try to better answer your questions, without making such stupid mistakes. And I hope that folks on the list will forgive me for the bad temper in my last emails. Sincerely, Danny Yoo ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Text Boxes - deleting and inserting
Sean Fioritto? If this is the same Sean who I used to live behind in mesa, AZ…drop me a line some time! Andrew Sakal Personal Banker Desert Foothills MAC S3836-011 (480)460-4166 office This message may contain confidential and/or privileged information. If you are not the addressee or authorized to receive this for the addressee, you must not use, copy, disclose, or take any action based on this message or any information herein. If you have received this message in error, please advise the sender immediately by reply e-mail and delete this message. Thank you for your cooperation. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to calculate pi with another formula?
On 4/14/05, Kent Johnson <[EMAIL PROTECTED]> wrote: > Dick Moores wrote: > > Now to my new question. I have an artist friend who knows an artist who > > needs pi expressed in base 12. I don't know how many digits he needs, > > but I think he'll take what he can get. Is there a way to use > > math.log(x, base) with the decimal module to accomplish this? Or is > > there another way? Or is there no way? > > I think I would try to write a program that converts base-10 decimal > fractions to base 12. Then feed > it the output of a pi-generating program. > I just thought I would reference the fascinating thread that ensued from this request on comp.lang.python : http://groups-beta.google.com/group/comp.lang.python/browse_frm/thread/1839b7d733ae37d0/3b5f7138f0e5fbd1?q=pi+base+12&rnum=1#3b5f7138f0e5fbd1 Peace Bill Mill bill.mill at gmail.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Question regarding the len function of a list while using a loop
Ben Markwell said unto the world upon 2005-04-14 08:14: Could somebody explain to me why the code I used to complete this exercise doesn't work. And how do you send an integer to len? Thanks Ben == *As an exercise, write a loop that traverses a list and prints the length of each element. What happens if you send an integer to len? *>>> foo = ['spam!', 1, ['brie', 'cheddar', 'swiss'], [1, 2, 3]] i = 0 while i < len(foo): print len(foo[i]) i = i+1 5 Traceback (most recent call last): File "", line 2, in -toplevel- print len(foo[i]) TypeError: len() of unsized object Hi Ben, Max and Alberto have already explained why you got the error message. Depending on the context in which you are doing this, the having the error crash the program might be what is desired. (I get that the context is simply an exercise, but let's pretend it is an actual program, written in anger :-).) Or, you might want your program to handle the problem more elegantly. Using the general framework Alberto suggested, here's a way to do that (I've also thrown some string formatting in to make the output more friendly): >>> foo = ['spam!', 1, ['brie', 'cheddar', 'swiss'], [1, 2, 3]] >>> for item in foo: ... try: ... print "Item: %s has length %s" %(item, len(item)) ... except TypeError: ... print "Item: %s has no length" %item ... Item: spam! has length 5 Item: 1 has no length Item: ['brie', 'cheddar', 'swiss'] has length 3 Item: [1, 2, 3] has length 3 >>> This works by attempting to do the thing in the try part, and catching any case than raises a TypeError (as your original code did), doing the routine of the except block instead. Does that make sense? If not, post back and I can try to explain in more detail. Best, Brian vdB ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Re: Craps, eternal loop (Joseph Q.)
Joseph Quigley gmail.com> writes: > I also can't get the counter to save the added or removed money. every time > I play again, I always have $100 Without reading all the code (there might be other issues) I've snipped the parts of the code away which are not interesting to this question, which highlights the cause: def play_again(): crapps() def crapps(): while loop: total_cash = 100 if total > total_2: total_cash = total_cash + 10 play_again() else: total_cash = total_cash - 10 play_again() total_cash is a local variable in the crapps function and is reset to 100 at the start of every loop. Move this initialization to a different place (I'm not sure when exactly you want to reset it as I don't know your intentions, but perhaps before the loop, or make it a global variable and only initialize it at the start of the program). Yours, Andrei ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] (no subject)
Jim and Laura Ahl said unto the world upon 2005-04-14 12:08: 'my test string'[-1:-4:-1] 'gni' When I do this it tells me that the sequence index must be an integer. What is that telling me and how do I fix that? Jim Kent addressed that already. But, my mistake for not thinking about which versions of Python my examples required. We can also do 'my test string'[-4:] 'ring' Ok, I agree with what this is doing. So if I type in print i[-1] this gives me that last letter of the string. But when I type in print i[-1:] it does nothing, because there is nothing after -1. So I need to find some charecter that takes the string in the opposite direction. like print i[-1:-4] but that does not print anything (why)? >>> '[-1:] does give something!'[-1:] '!' >>> Again (from my last post on the thread): This tells Python to start at the end of the string and go *forward*, one position at a time, up to, but not including, the -4 position. But, since there is nothing forward from the end of the string, this gives the empty string. I don't know how to say that more clearly :-) Perhaps you could say more about why it doesn't help? (It is also possible you weren't asking again -- your email client isn't putting in quote marks so it is hard to be sure, and I've deleted the original email. If you weren't asking again; never mind ;-) When I put another number behind this it gives me it must be an integerprint i[-1:-4:-1] so what have I got messed up and why can't this work? Again, see Kent's post. And if an iputted word or string in typed in how do you tell it to go to the end of it and stop? I assumed that print i[-1:] would have done it Go to the end from where? >>> 'a string'[-1:] # "start at the last character, and go forward." 'g' >>> 'a string'[3:] # "start at the 4th character, and go forward." 'tring' >>> 'a string'[0:] # "start at the 1st character, and go forward." 'a string' >>> ([3:] gives 4th on, as indicies start at 0; thus [0:] gives the whole string.) (from my last post on the thread): [*] slots? I mean: 'I am indexed with 1 slot'[4] 'I am indexed with 2 slots'[4:6] 'I am indexed with 3 slots'[4:6:1] 'None of my slots have been "specified" '[:] (There must be a better term that `slots', but it is 3am :-) Some one wrote me off list to mention I was looking for "index parameters". Thanks, anonymous donor! Best to all, Brian vdB ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python backwards program (fwd)
-- Forwarded message -- Date: Thu, 14 Apr 2005 00:41:40 -0500 From: Jim and Laura Ahl <[EMAIL PROTECTED]> To: Danny Yoo <[EMAIL PROTECTED]> Subject: Re: [Tutor] Python backwards program I thought you were on me a bit but I am so frustrated at this point. My instructor wrote and told me it was easy. So if it is easy why am I having so much trouble. I figured the other three programs by just reading the book and working on the computer. Does the 2.2 python have the ability to do this? I think that the program will work with something like this in an expanded form. The following gives me the last letter of the string. backwords=raw_input("enter number or string:") print backwords[-1] I have looked on a couple of sites and it says to use s.reverse() this does not work for some reason Jim Hi Jim, do you know about the dir function? You can use it to show you all methods of an object. (Methods are, more or less, the things an object comes with support for doing to it. Ugly vagueness, but roughly right.) The output of dir statements on my computer will be a bit different than yours, as I am using Python 2.4.1. But here is the result of doing dir on a string and a list: >>> dir('a string') ['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__str__', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'replace', 'rfind', 'rindex', 'rjust', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill'] >>> dir(['a', 'list']) ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__str__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort'] >>> >>> 'some string'.reverse() Traceback (most recent call last): File "", line 1, in ? AttributeError: 'str' object has no attribute 'reverse' >>> And, that is what we would expect, as dir('a string') didn't show us any reverse method. *But* dir(['a', 'list']) did! So: >>> my_list = ['this', 'is', 'my', 'list'] >>> my_list.reverse() >>> my_list ['list', 'my', 'is', 'this'] >>> Does your version of Python have list.reverse()? (I've no idea when that got in, but I assume its been there since God was a lad.) If so, one way you could solve your problem would be to take a string, convert it into a list, reverse the list, and then make a string out of the list again. To try that, you will want to combine some or all of the list and str builtin functions, and the string.split and string.join methods.[*] I'm still leaving work for you to do -- which pieces and how to combine them? Give it a try and show us what you've done. [*] Really old Pythons do not have string methods at all. If yours is that old, we will have to suggest something else. Run this: >>> if 'join' in dir(str): print "My Python version has string methods" else: print "Oh, oh. I *really* need to upgrade my Python" HTH, Brian vdB ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python backwards program (fwd)
> Does the 2.2 python have the ability to do this? Hi Jim, Python 2.2 is actually a bit old; you may want to update the version of Python on your system to Python 2.4. You can find it here: http://www.python.org/2.4/ A lot of the approaches you were trying earlier used features that were added in the 2.3 or 2.4 Python series; they're absent from Python 2.2. > The following gives me the last letter of the string. > > backwords=raw_input("enter number or string:") > print backwords[-1] Yes, this is an interesting approach! We can go along this approach a little more, if you'd like. The code above is getting the last letter, so we're closer to printing out the word backwards. How would you print out the second to last letter of the string? ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] how to display an image using python
All, I have asked this question before, but one more time most have commented about manipulation but displaying the image has become the big issue. I want to display png and gif images on a Linux machine using python. I am using PyNGL to make the images and PIL to manipulate them but I cannot load xv on the machines and PIL uses xv to display. I have looked at PythonMagick but I could not even get past installing it. It does not have a setup.py and uses boost. I am hoping for a more straightforward Python way. Thanks, John Ertl ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Re: Recursion....what are the best situations to use it?
I've seen a couple of nice tutorials on recursion, and a lot of awful ones. The latter always trot out the fibonacci and factorial examples for some reason. And that's about it! The good ones showed me how to trace through recursive calls and gave me practical examples(tictactoe, magic squares, Tower of Hanoi, 4-Square, etc)What I want to know is this: what are other specific situations where a recursive algorithm would be better or easier to program than an iterative one?I know that the Eight Queens puzzle is a good recursion candidate, but I don't understand why as yet. I'm still on simple recursion, and am just beginning to understand backtracking in a simple example, like adding numbers in an array.From what I've read, it seems like two dimensional games or puzzles would be good candidates for recursive programming. Also, things like random maz! e generation...I saw something on Pierzonski's(sic) Carpet, but I didn't really understand it. I did understand that anything to do with manipulating patterns might be a good recursion candidate.If this is too general a question, perhaps you can tell me when NOT to use recursion(where it would be inappropriate or inefficient).I'd certainly like to learn what seems like a powerful tool, but I don't want to use it where I shouldn't.Any hints appreciated.John=John Soares, WebmasterFamily Safe Surfinghttp://www.family-safe-surfing.net[EMAIL PROTECTED][EMAIL PROTECTED]"Your best bet for online family-friendly resources"=___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to display an image using python
> xv on the machines and PIL uses xv to display. I have looked at > PythonMagick but I could not even get past installing it. It does not have > a setup.py and uses boost. I am hoping for a more straightforward Python > way. Hi John, You may want to try PyGame: http://www.pygame.org/ Although it's mainly for game development, it provides a simple graphics API that we can use to display images. If you're running Linux, it's likely that you have the Simple DirectMedia Layer (SDL) library installed. I'm not too familiar with the API, but I was able to get some kind of working example. We can first construct an image surface: http://www.pygame.org/docs/ref/pygame_image.html by loading one from our file: ## >>> import pygame.image >>> picture = pygame.image.load("na-cat.gif") >>> >>> picture.get_size() (256, 48) ## At this point, 'picture' contains a "surface": http://www.pygame.org/docs/ref/Surface.html We can copy ('blit') this surface onto our main screen: ## >>> import pygame.display >>> pygame.display.set_mode(picture.get_size()) >>> main_surface = pygame.display.get_surface() >>> main_surface.blit(picture, (0, 0)) >>> pygame.display.update() ## I hope this helps! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
RE: [Tutor] how to display an image using python
Danny, Pygame.org...I would not have thought to look there. In my google it did not pop up. I will definitely take a look and thanks for the example. John Ertl -Original Message- From: Danny Yoo [mailto:[EMAIL PROTECTED] Sent: Thursday, April 14, 2005 12:25 To: Ertl, John Cc: Tutor Subject: Re: [Tutor] how to display an image using python > xv on the machines and PIL uses xv to display. I have looked at > PythonMagick but I could not even get past installing it. It does not have > a setup.py and uses boost. I am hoping for a more straightforward Python > way. Hi John, You may want to try PyGame: http://www.pygame.org/ Although it's mainly for game development, it provides a simple graphics API that we can use to display images. If you're running Linux, it's likely that you have the Simple DirectMedia Layer (SDL) library installed. I'm not too familiar with the API, but I was able to get some kind of working example. We can first construct an image surface: http://www.pygame.org/docs/ref/pygame_image.html by loading one from our file: ## >>> import pygame.image >>> picture = pygame.image.load("na-cat.gif") >>> >>> picture.get_size() (256, 48) ## At this point, 'picture' contains a "surface": http://www.pygame.org/docs/ref/Surface.html We can copy ('blit') this surface onto our main screen: ## >>> import pygame.display >>> pygame.display.set_mode(picture.get_size()) >>> main_surface = pygame.display.get_surface() >>> main_surface.blit(picture, (0, 0)) >>> pygame.display.update() ## I hope this helps! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] high score lists
Anyone have some good beginning ideas/references to creating a high score list and storing scores in a simple python game? (if there's something in the pygames module, or a simpler python way). I'm mod'ing a space invaders-type game and would like to add a high score list :) Thanks! ~Denise ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] _winreg problems enumerating
Hi Tim, Change this - try: while 1: test_key = regKeys.append(_winreg.EnumValue(hkey, i)) print test_key i += 1 except EnvironmentError: pass to try: while 1: regKeys.append(_winreg.EnumValue(hkey, i)) print regKeys[i] i += 1 except EnvironmentError: pass What this does test_key = regKeys.append(_winreg.EnumValue(hkey, i)) is assign to test_key any value the append may return, which is None. Out of curiosity, you know how lists work in Python? Regards, Liam Clarke On 4/15/05, Gallagher Timothy-TIMOTHYG <[EMAIL PROTECTED]> wrote: It seems to work but the output isn't right. I do have 10 things in the Runfolder but the out put is not telling me what they are, it just says nonefor each entry. I guess that I am not sure what to do now. I can do this in Perl and other languages but I really want to learn Python.Here is what I have done:import _winreghost = "127.0.0.1" # local hostkey = _winreg.ConnectRegistry(host, _winreg.HKEY_LOCAL_MACHINE) hkey = _winreg.OpenKey(key,r"SOFTWARE\Microsoft\Windows\CurrentVersion\Run")i = 0regKeys = []try: while 1:test_key = regKeys.append(_winreg.EnumValue(hkey, i))print test_key i += 1except EnvironmentError: passwhen I run this script I am getting this for my output:NoneNoneNoneNoneNoneNoneNoneNoneNoneNoneThanksTim Timothy F. GallagherTimothyg- AT 0-Motorola.comFrom: Liam Clarke [mailto:[EMAIL PROTECTED] ]Sent: Wednesday, April 13, 2005 9:45 PMTo: Gallagher Timothy-TIMOTHYG; tutor@python.orgSubject: Re: [Tutor] _winreg problems enumeratingHi Tim,Hmmm, I may have to play with _winreg, is is new with Python 2.4?Anyway, from the _winreg docs -EnumValue(key, index)Enumerates values of an open registry key, returning a tuple.key is an already open key, or any one of the predefined HKEY_* constants.index is an integer that identifies the index of the value to retrieve. The function retrieves the name of one subkey each time it is called. It istypically called repeatedly, until an EnvironmentError exception is raised,indicating no more values.There's your issue -E_key = _winreg.EnumValue(key,r"SOFTWARE\Microsoft\Windows\CurrentVersion\Run")The second value needs to be an integer that is an index.Typical usage would look like this -i = 0regKeys = []try: while 1: regKeys.append(_winreg.EnumValue(key, i)) i += 1except EnvironmentError: passGood luck,Liam ClarkeOn 4/14/05, Gallagher Timothy-TIMOTHYG < [EMAIL PROTECTED]> wrote:am new to python and want to learn this language.I am having troublesfinding examples and tutorials for use on windows boxes.I do most of mystuff in perl and php but want better socket support, so I am giving python a try.I am writing a script to connect to remote registry's because ofthis new IM virus.I can create reg entries and delete them but I cannotenumerate them, here is my code.import _winreghost = " 127.0.0.1" # local hostkey = _winreg.ConnectRegistry(host, _winreg.HKEY_LOCAL_MACHINE)E_key = _winreg.EnumValue(key,r"SOFTWARE\Microsoft\Windows\CurrentVersion\Run") I get an error when I run the script:Traceback (most recent call last):File "reg4.py", line 9, in ?E_key = _winreg.EnumValue(key,r"SOFTWARE\Microsoft\Windows\CurrentVersion\R un")TypeError: an integer is requiredCan someone tell me what I am doing wrong???ThanksTimothy F. GallagherTimothyg- at -Motorola.com___ Tutor [EMAIL PROTECTED]http://mail.python.org/mailman/listinfo/tutor--'There is only one basic human right, and that is to do as you damn well please.And with it comes the only basic human duty, to take the consequences.'-- 'There is only one basic human right, and that is to do as you damn well please.And with it comes the only basic human duty, to take the consequences.' ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to display an image using python
If you don't mind using an external program, you could use the 'display' command from ImageMagick. -Jay On Thursday 14 April 2005 07:59 pm, Ertl, John wrote: > All, > > I have asked this question before, but one more time most have commented > about manipulation but displaying the image has become the big issue. I > want to display png and gif images on a Linux machine using python. I am > using PyNGL to make the images and PIL to manipulate them but I cannot load > xv on the machines and PIL uses xv to display. I have looked at > PythonMagick but I could not even get past installing it. It does not have > a setup.py and uses boost. I am hoping for a more straightforward Python > way. > > Thanks, > > John Ertl > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Question regarding the len function of a list while using a loop
Yes this does make sense. Thank youOn 4/14/05, Brian van den Broek <[EMAIL PROTECTED]> wrote: Ben Markwell said unto the world upon 2005-04-14 08:14:> Could somebody explain to me why the code I used to complete this exercise > doesn't work.> And how do you send an integer to len?>> Thanks>> Ben>> ==>>> *As an exercise, write a loop that traverses a list and prints the length of > each element. What happens if you send an integer to len?>> *>>> foo = ['spam!', 1, ['brie', 'cheddar', 'swiss'], [1, 2, 3]]>i = 0while i < len(foo): >> print len(foo[i])> i = i+1>>> 5>> Traceback (most recent call last):> File "", line 2, in -toplevel-> print len(foo[i]) > TypeError: len() of unsized objectHi Ben,Max and Alberto have already explained why you got the error message.Depending on the context in which you are doing this, the having theerror crash the program might be what is desired. (I get that the context is simply an exercise, but let's pretend it is an actualprogram, written in anger :-).) Or, you might want your program tohandle the problem more elegantly.Using the general framework Alberto suggested, here's a way to do that (I've also thrown some string formatting in to make the output morefriendly): >>> foo = ['spam!', 1, ['brie', 'cheddar', 'swiss'], [1, 2, 3]] >>> for item in foo:... try:... print "Item: %s has length %s" %(item, len(item)) ... except TypeError:... print "Item: %s has no length" %item...Item: spam! has length 5Item: 1 has no lengthItem: ['brie', 'cheddar', 'swiss'] has length 3Item: [1, 2, 3] has length 3 >>>This works by attempting to do the thing in the try part, and catchingany case than raises a TypeError (as your original code did), doingthe routine of the except block instead.Does that make sense? If not, post back and I can try to explain in more detail.Best,Brian vdB___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Re: Recursion....what are the best situations to use it?
> I know that the Eight Queens puzzle is a good recursion candidate, > but I don't understand why as yet. I'm still on simple recursion, > and am just beginning to understand backtracking in a simple > example, like adding numbers in an array. If you make a typo when typing an email, do you delete the whole message and start over? Probably not :^) With recursion, you can just back up a few steps to the parts that were known to be working and carry on again from there. Alan ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] high score lists
> Anyone have some good beginning ideas/references to creating a high > score list and storing scores in a simple python game? (if there's > something in the pygames module, or a simpler python way). I'm > mod'ing a space invaders-type game and would like to add a high score > list :) Quick and dirty approach: make a list of tuples [ (4, 'John Doe'), (3, 'Steve Austin') ] You can append new ones to the end of the list, sort it, reverse it, etc. Alan ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] "paused" graphic leaves a 'residue' when returning to game?
Another quick question: I can pause and unpause the little game I created, and I have a graphic to display over top of the game screen when it is paused, which tells the user which key to press to unpause, right? It's set up the same way as my "game over" graphic. But in any case, when I unpause, it leaves this "residue" of the "paused" text on the game screen. the moving game characters move over it and sort of wipe it out, but I have no idea why it's there or how to clear it! Has anyone else encountered a problem like this before? I can post the specific code if that would be helpful. I've tried to clear the screen, refresh, etc., and since the pause screen uses the same code as the game over screen I figured the former should not leave a residue if the latter does not. Any suggestions for things to try out, to fix this? Thanks a ton! ~Denise ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Re: Recursion....what are the best situations to use it?
> What I want to know is this: what are other specific situations where a > recursive algorithm would be better or easier to program than an > iterative one? Hello, Programs that have to deal with data often have an internal structure that mimics that data. A program that deals with lists looks slightly different from one that doesn't deal with lists. And if the data that we deal with is recursive, then we may want our program to have a recursive structure too. So recursive algorithms work best on recursive data. This is a bit circular, so let's sketch a quick example to make this concrete. If we were to write a program to grab all the names in a directory of files, we have a situation where the thing that we're processing has an internal structure that itself can contain substructures. Your computer's file system has a recursive shape! When use use a general term "file", we really mean one of the following: 1. a directory 2. a regular, non-directory file And we know that a directory is itself a list of files. Slightly more formally, we can use a few funny symbols and say that: file ::= directory | regularfile directory ::= list of file "A file is made up of either a directory or a regular file" "A directory is made up of a list of files" It's a little loopy if you think about it, which is exactly why programs that deal with directories are often recursive. If we wanted to get a list of all the regular files in a particular directory, then it's natural for our program's structure to mimic this recursive structure. We might say: ### Pseudocode ### def listAllRegularFilesInDirectory(someDirectory): ## ... fill me in. We'll probably have to refer to ## listAllRegularFilesInFile() somewhere in here. def listAllRegularFilesInFile(someFile): if someFile is a directory: return listAllRegularFilesInDirectory(someFile) else if someFile is a regular file: return listAllRegularFilesInRegularFile(someFile) def listAllRegularFilesInRegularFile(someRegularFile): ## ... fill me in. This one is easy: just return a list with a single # element. ## This is a quick sketch of a recursive program to get at all the regular files, and its form is strongly influenced by the data structure that it works with. Once we have the recursive version working, we can optimize it to remove the explicit recursion by using a stack. But the fundamental algorithm for going through the directories is recursive traversal. Does this make sense? There are actually a lot of data out there that have recursive structure. One of the the most visible being web pages, since web pages have links to other web pages. So recursion is very fundamental: master it, and certain programs get a lot easier to solve. But I have no clue why factorial() seems to be the main doorway to recursion. *grin* Most Lisp or Scheme books will use recursive ideas as a major focus, so if you really want to learn more, you might want to look at a book like "How To Design Programs": http://www.htdp.org/ or the Little Schemer. Best of wishes! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Re: Recursion....what are the best situations to use it?
[EMAIL PROTECTED] wrote: I've seen a couple of nice tutorials on recursion, and a lot of awful ones. The latter always trot out the fibonacci and factorial examples for some reason. And that's about it! The good ones showed me how to trace through recursive calls and gave me practical examples(tictactoe, magic squares, Tower of Hanoi, 4-Square, etc) What I want to know is this: what are other specific situations where a recursive algorithm would be better or easier to program than an iterative one? Many algorithms that break down into sub-parts that have the same structure as the main algorithm can naturally be expressed recursively. For example flattening a list that may contain sublists can be expressed something like this: def flatten(l): result = [] for item in l: if type(item) == list: # (This test is a bit simplistic) result.extend(flatten(item)) else: result.append(item) Another good candidate for recursive processing is tree algorithms, for example printing out nodes of a tree. I once wrote an audit engine for a dom tree that recursively descends the dom tree and a tree of audit rules at the same time. I wrote about it here: http://www.pycs.net/users/323/stories/2.html There are non-recursive ways of doing these things also. But IMO the recursive formulation is often easier to understand. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Re: Recursion....what are the best situations to use it?
Quoting "[EMAIL PROTECTED]" <[EMAIL PROTECTED]>: > If this is too general a question, perhaps you can tell me when NOT to > use recursion(where it would be inappropriate or inefficient). In my opinion --- Some problems are naturally recursive. A good example is traversing data structures (particularly trees), but there are other problems where there is an obvious solution in terms of solving the same problem on smaller subinstances, which obviously lends itself well to a recursive function. In terms of efficiency: You should write your program first in the most obvious, easy-to-understand way. This may involve recursion if you are dealing with naturally recursive data structures. Then run your program and see if it's slow. If it is, try to figure out where the slowness is, either with profiling or with theory. If you conclude that your recursive function is slowing the program down, then you can look to replace it with something else. (I guess the traditional example of when it would be inappropriate is Pascall's triangle --- ie: computing (n, r) == n!/(n-r)!r!. The recursive algorithm looks like this; def C(n, r): """ Compute N choose R. Require: assert((type(n), type(r)) == (int, int)) assert(n >= r) assert(r >= 0) """ if r in (0, n): return 1 else: return C(n-1, r-1) + C(n-1, r) But if you do this, you end up computing a lot of values multiple times. It works better if you use an array to build up the answers from the bottom --- a technique called dynamic programming. ) -- John. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] high score lists
R. Alan Monroe wrote: Anyone have some good beginning ideas/references to creating a high score list and storing scores in a simple python game? (if there's something in the pygames module, or a simpler python way). I'm mod'ing a space invaders-type game and would like to add a high score list :) Quick and dirty approach: make a list of tuples [ (4, 'John Doe'), (3, 'Steve Austin') ] You can append new ones to the end of the list, sort it, reverse it, etc. And you can use the pickle module to save and restore the list. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] high score lists
Hi I've read somewhere that the appropiate way to make a best score list is with a dictionarie So you'll have something like this: best_score={"Peter":100,"Jhon":23} Best Regards Alberto Gaucho>From: Kent Johnson <[EMAIL PROTECTED]> >CC: Python tutor >Subject: Re: [Tutor] high score lists >Date: Thu, 14 Apr 2005 18:24:55 -0400 > >R. Alan Monroe wrote: >>>Anyone have some good beginning ideas/references to creating a >>>high >>>score list and storing scores in a simple python game? (if there's >>>something in the pygames module, or a simpler python way). I'm >>>mod'ing a space invaders-type game and would like to add a high >>>score >>>list :) >> >> >>Quick and dirty approach: make a list of tuples >>[ (4, 'John Doe'), >> (3, 'Steve Austin') ] >> >>You can append new ones to the end of the list, sort it, reverse >>it, >>etc. > >And you can use the pickle module to save and restore the list. > >Kent > >___ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] sys.path.append issues with cgi
Hello all, I'm trying to modify the sys.path in my cgi scripts to import modules that I've installed in my home directory. The top of the script reads as follows: #!/usr/local/bin/python import cgi, sys sys.path.append('/net/u/16/g/gsf/lib/python2.4/site-packages') from ElementTree import Element, SubElement, tostring But my traceback reads: ImportError: No module named ElementTree The appended path is the same I've added to my PYTHONPATH variable and it works fine from the python interactive prompt. I thought it might be a permissions issue since it's a cgi script so I chmodded everything up to the ElementTree directory 755 but still no luck. TIA, gabe ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
RE: [Tutor] _winreg problems enumerating
Quoting "Gooch, John" <[EMAIL PROTECTED]>: > I am writing a function whose job is it delete all of the selected items > in a Listbox. I think this problem is the same as the general problem of deleting a selection of items from a python list. The general solution is to iterate through the list of selected indices backwards. eg: >>> from Tkinter import * >>> tk = Tk() >>> lb = Listbox(tk, selectmode=EXTENDED) >>> lb.pack() >>> for i in range(10): # Inserting integers, so initially the item in each ... lb.insert(END, i) # position will be the same as its index. ... >>> lb.curselection() ('2', '4', '5', '7') >>> for i in lb.curselection()[-1::-1]: ... lb.delete(i) ... >>> lb.get(0, END) (0, 1, 3, 6, 8, 9) >>> ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] sys.path.append issues with cgi
Sorry, addendum to that post. The line from ElementTree import Element, SubElement, tostring should read from elementtree.ElementTree import Element, SubElement, tostring but that still doesn't work. gabe ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] high score lists
my apologize to Alberto - instead of replying to the whole list, I accidentally replied only to him! Here are my replies, for anyone else who might be reading/interested: This is what I have so far: high_scorelist = [(1000,"Denise"), (945,"Denise"), (883,"Denise"), (823,"Grant"), (779,"Aaron"), (702,"Pete"), (555,"Tom"), (443,"Tom"), (442,"Robin"), (404,"Pete")] userscore = (441,"Joe") def add_score(userscore): if userscore[0] > high_scorelist[len(high_scorelist)-1][0]: print "You made the high score list!" high_scorelist.append(userscore) high_scorelist.sort(reverse=True) del high_scorelist[len(high_scorelist)-1] return high_scorelist else: print high_scorelist I had to enter in the variable for "userscore" like that, when I add a tuple directly into the add_score function, it seems to delete the last item in the list (i.e., the one I just added) BEFORE it sorts it (i.e., removing the lowest score). I have no idea why this is. But if I define userscore = (465,"Jane"), for instance, and then run add_score(userscore), it'll change and print my 10-person high score list, just like I want it to. But the problem remains both how I could display this (if even just in the python window), and how I could get my program to create the tuple to plug in there. (I also just ended up writing the list like [score,user] because I couldnt figure out how to get it to sort by the second half of the tuple. I need a better tutorial book, I think!) Thanks again for any suggestions/pointers! ~Denise and a question about sorting (either way): I am trying it out with a list of tuples right now. The first problem I ran into is that when i sort it (scorelist.sort(reverse=True)), it sorts by the person's name (the first entry), and not by the score. plus I'm not quite sure yet how I'd get the user's name or score *into* the list - without manually adding it as a tuple? Since I can't do something like ... ("John", 100) username = "John", userscore = 100, if userscore > lowestuserscore etc. With a dictionary, could I point something like username to key and something like userscore to value? But then the problem with dictionaries comes back around to sorting too: Can I sort (and then display) a dictionary? Also, thanks for the idea about the pickle module - where can I get that and documentation for it? Thank you guys for your suggestions, and I apologize for the "newbie" level of my questions. I am trying to answer as much as I can from the tutorial materials I have here, but they don't always explain everything (such as what the "cmp=None, key=None" means in the ( ) helper of the .sort function. I figured reverse=True/False out by playing with it). I really appreciate all this help! I'm trying to make this game for a birthday joke for the person who is teaching me programming, so obviously I cant ask him for help! :) Denise > On 4/14/05, Alberto Troiano <[EMAIL PROTECTED]> wrote: > > > > > > Hi > > > > I've read somewhere that the appropiate way to make a best score list is > > with a dictionarie > > > > So you'll have something like this: > > > > best_score={"Peter":100,"Jhon":23} > > > > Best Regards > > > > Alberto > > > > > > > > > > Gaucho>From: Kent Johnson <[EMAIL PROTECTED]> >CC: Python tutor > > >Subject: Re: [Tutor] high score lists >Date: Thu, 14 Apr > > 2005 18:24:55 -0400 > >R. Alan Monroe wrote: >>>Anyone have some good > > beginning ideas/references to creating a >>>high >>>score list and storing > > scores in a simple python game? (if there's >>>something in the pygames > > module, or a simpler python way). I'm >>>mod'ing a space invaders-type game > > and would like to add a high >>>score >>>list :) >> >> >>Quick and dirty > > approach: make a list of tuples >>[ (4, 'John Doe'), >> (3, 'Steve > > Austin') ] >> >>You can append new ones to the end of the list, sort it, > > reverse >>it, >>etc. > >And you can use the pickle module to save and > > restore the list. > >Kent > > > >___ >Tutor > > maillist - Tutor@python.org > > >http://mail.python.org/mailman/listinfo/tutor > > ___ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Re: Recursion....what are the best situations to use it?
On Apr 14, 2005, at 21:06, [EMAIL PROTECTED] wrote: I've seen a couple of nice tutorials on recursion, and a lot of awful ones. The latter always trot out the fibonacci and factorial examples for some reason. And that's about it! The good ones showed me how to trace through recursive calls and gave me practical examples(tictactoe, magic squares, Tower of Hanoi, 4-Square, etc) What I want to know is this: what are other specific situations where a recursive algorithm would be better or easier to program than an iterative one? Heh. This is perhaps one of the few times where Microsoft makes something easy to explain. If you've used Windows 2.0 or later, chances are you've seen an excellent example of recursive programming: the world's second-most used productivity application, Minesweeper. In Minesweeper, when you click on a tile that doesn't contain a mine, the number of mines in adjacent tiles appears. But you've probably seen that if there are no mines in any of the adjacent tiles, the program explores all the "safe zone" instead of letting you click on all those empty tiles. That is recursion. The way it does that is as follows (this is simplified pseudocode, which doesn't take into account edges, among other things): def explore(minefield, (y, x)): numMines = countSurroundingMines(minefield, (y, x)) minefield[(y, x)] = EXPLORED if numMines == 0: for i in ((y-1, x), (y+1, x), (y, x-1), (y, x+1)): if minefield[i] != EXPLORED: explore(minefield, i) Voilà. Aside from the GUI and this piece of code, writing an implementation of the Windows Minesweeper is perfectly trivial. In fact, I did just that a few years ago on my dear TI-92 to learn how to use recursion. You should do the same if you've got a few hours of spare time, it's an enlightening experience. ^^ -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] high score lists
On Apr 15, 2005, at 01:33, D. Hartley wrote: This is what I have so far: high_scorelist = [(1000,"Denise"), (945,"Denise"), (883,"Denise"), (823,"Grant"), (779,"Aaron"), (702,"Pete"), (555,"Tom"), (443,"Tom"), (442,"Robin"), (404,"Pete")] userscore = (441,"Joe") def add_score(userscore): if userscore[0] > high_scorelist[len(high_scorelist)-1][0]: print "You made the high score list!" high_scorelist.append(userscore) high_scorelist.sort(reverse=True) del high_scorelist[len(high_scorelist)-1] return high_scorelist else: print high_scorelist Okay, a few little comments: - high_scorelist[len(high_scorelist)-1] can be written as high_scorelist[-1]. Python slicing operators are very powerful. - That's me nitpicking, but you should pick a naming convention for your whole program (camelCase, names_with_underscores or whatever) and stick to it. It makes things more readable. For example, userscore and high_scorelist should be named userScore and highScoreList, or user_score and high_score_list. - Since lists are mutable objects, the function add_score, by way of the append and sort methods, modifies the high_scorelist list in place. Why do you return it afterwards? I had to enter in the variable for "userscore" like that, when I add a tuple directly into the add_score function, it seems to delete the last item in the list (i.e., the one I just added) BEFORE it sorts it (i.e., removing the lowest score). I have no idea why this is. But if I define userscore = (465,"Jane"), for instance, and then run add_score(userscore), it'll change and print my 10-person high score list, just like I want it to. What did your code look like when it did that? (I also just ended up writing the list like [score,user] because I couldnt figure out how to get it to sort by the second half of the tuple. I need a better tutorial book, I think!) Not really. Writing things that way is the natural thing to do (even though it might feel counter-intuitive at the beginning), as it allows you to do what you want without extra code, and the less code you write for a given functionality, the better. Every line of code you write is a liability. Formatting data for display is left to the programmer (i.e. you). The user never sees what the internal data structure looks like, so when you're designing it, the only thing you should take into account is how easy to use it's going to be for *you*, the programmer. but they don't always explain everything (such as what the "cmp=None, key=None" means in the ( ) helper of the .sort function. I figured reverse=True/False out by playing with it). cmp is a user-supplied comparison function. When it is given 2 arguments, x and y, it must return -1 when x < y, 0 when x == y and 1 when x > y. it allows you to sort the list based on arbitrary criteria without having to re-write a sort function. If it is None, the default sort function is used. I'm still using Python 2.3, so someone else will have to tell you what the "key" argument is. Oh, and when you're wondering what something does, remember that: - Experimenting is good. - Your 2 best friends are the interactive Python shell, and the help() function. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Re: Defining a function (Joseph Q.)
Also I would like to point out that def foo(*args): #this allows for any number of arguments to be passed. The *args is powerful when used correctly. *args is a list of any length of arguments being passed to the function and/or class, and the arguments passed can be any type/object you want to pass . So you might do something like. def foo(*args): print len(args) # this prints the length of the list of the arguements passed # so using that function you would see something like. in the example I only used basic types but you can pass objects as well. foo(1, 2, 3, "cat", "mouse", ['bee', 'honey', 'stinger']) 6 Notice that the length that is returned is only 6 but there are 8 items so it appears to have been passed to the function. In actuallity it is only 6 items. There is 3 integers, then 2 strings, then 1 list that is 3 items long. Thus the length of the list args is 6 items long. I wouldn't recomend passing mixed types like this to a function using args because it can get very confusing. The star sugar sytax goes even further though def foo(*args): print len(args) foo(1,2,3,"cat","mouse",*['bee','honey','stinger']) 8 The star in the call means to apply each member of the list as an argument. Isn't that cool? HTH, Jacob ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Re: Recursion....what are the best situations to use it?
It is really more of a question of the type of problem and the solution approach in general. For example, one can find the intersection of two lines with a simple equation, but that equation depends on the dimension the lines are in (2D, 3D, ...). If one were working in 2D space only, then the simple equation is the simplest solution. However if one wanted a function that would work in any space, then setting up the problem as a matrix and solving it recursively might be a better approach. One more concrete consideration is that if you find yourself tackling a problem with nested looping and the algorithm at each level is mostly the same, then perhaps recursion would be better. Some time ago I wrote a recursion article for an audience using Lingo scripting (in Macromedia Director). The actual code at the end is Lingo (not all that different) but the thrust of the article is constructing a recursive solution for matrix type problems (more than one unknown in an equation). I put the pdf in my .Mac account if you wish to view it. http://homepage.mac.com/lee_cullens/ A_Simple_Recursive_Solution_(article_v2).pdf Of course, with Python we have math packages to do the grunt work, but it helps to understand the problem. Lee C On Apr 14, 2005, at 21:06, [EMAIL PROTECTED] wrote: I've seen a couple of nice tutorials on recursion, and a lot of awful ones. The latter always trot out the fibonacci and factorial examples for some reason. And that's about it! The good ones showed me how to trace through recursive calls and gave me practical examples(tictactoe, magic squares, Tower of Hanoi, 4-Square, etc) What I want to know is this: what are other specific situations where a recursive algorithm would be better or easier to program than an iterative one? ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Re: PyGTk and Glade help
We are developing a CBT based "Free Software" for our social activities. We are using PyGTK alongwith Glade. We want to print a document through Printer and also we want to provide "Sound" support in our software. Has somebody worked on PyGTK or Python? We are not getting the PyGTK API's for sound and printing support. Can somebody help us? It's a bit scary that your message is the first hit on this google search: http://www.google.com/search?q=pygtk+printing Looks like you might find some good help on the pygtk mailing list though: http://www.daa.com.au/mailman/listinfo/pygtk _ Don't just search. Find. Check out the new MSN Search! http://search.msn.com/ ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] high score lists
Quoting Max Noel <[EMAIL PROTECTED]>: > On Apr 15, 2005, at 01:33, D. Hartley wrote: > > (I also > > just ended up writing the list like [score,user] because I couldnt > > figure out how to get it to sort by the second half of the tuple. I > > need a better tutorial book, I think!) > I'm still using Python 2.3, so someone else will have to tell you what > the "key" argument is. Interestingly, the key argument is the solution to this problem: >>> arr = zip(range(10), range(10,0,-1)) >>> arr [(0, 10), (1, 9), (2, 8), (3, 7), (4, 6), (5, 5), (6, 4), (7, 3), (8, 2), (9, 1)] >>> arr.sort(key=lambda x: x[1]) >>> arr [(9, 1), (8, 2), (7, 3), (6, 4), (5, 5), (4, 6), (3, 7), (2, 8), (1, 9), (0, 10)] Basically, key takes a function which, given a list element, returns the value you actually want to sort by. > - Your 2 best friends are the interactive Python shell, and the help() > function. True, although help(sort) could be more helpful... >>> help([].sort) Help on built-in function sort: sort(...) L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*; cmp(x, y) -> -1, 0, 1 >>> -- John. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] odd behavior within __init__
On 4/14/05, Rich Krauter <[EMAIL PROTECTED]> wrote: > Maybe you could use a factory. It would allow you to simplify your Node > class, and encapsulate the instantiation behavior you want outside the > class. Thanks for the suggestion; I think that's what I'll do. On 4/14/05, Max Noel <[EMAIL PROTECTED]> wrote: >Well, if you want b and a to refer to the same object, just use b = a. If you'll look at my code, you'll see that I *did* try that approach, and it did not persist past __init__ for some reason: class Node: ... def __init__(self, cargo=None, prev=None, next=None, nod=False): """x.__init__(...) initializes x; see x.__class__.__doc__ for signature""" if not isinstance(cargo, Node) or nod: self.cargo = cargo self.prev = prev self.next = next else: # self = cargo ## see? # print id(self), id(cargo) print self.cargo >>> a = Node(1) >>> b = Node(a) 12932600 12932600 1 >>> id(b) 12960632 -- Email: singingxduck AT gmail DOT com AIM: singingxduck Programming Python for the fun of it. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] high score lists
On Thursday, Apr 14, 2005, D. Hartley wrote: and a question about sorting (either way): I am trying it out with a list of tuples right now. The first problem I ran into is that when i sort it (scorelist.sort(reverse=True)), it sorts by the person's name (the first entry), and not by the score. You aren't trying to do any fancy comparison; you just want to compare the 2nd values in a tuple rather than the tuple itself (in the case where the name comes first). So you supply a 2 argument function that returns the comparison of the 2nd values of two tuples: ### def mycmp(a, b): return cmp(a[1], b[1]) ### And now do your sort like this: ### high_scorelist.sort(cmp=mycmp, reverse=True) ### On the other hand, if you put the numbers first then the task of printing is the problem..but that's easily overcome in your loop that prints the values: just print the number first! ### for score, who in highscores: print score, who ### which gives, 200 Nina 20 Ben 2 Raj If you want to get the numbers looking pretty, try finding the longest number and then justify all numbers in a space that big: ### highscores = [(200, 'Nina') , (20, 'Ben') , (2, 'Raj')] longest_num = max( [ len(str(score)) for score,who in highscores] ) for score, who in highscores: print str(score).rjust(longest_num), who ### which gives 200 Nina 20 Ben 2 Raj plus I'm not quite sure yet how I'd get the user's name or score *into* the list - without manually adding it as a tuple? Since I can't do something like ... ("John", 100) username = "John", userscore = 100, if userscore > lowestuserscore etc. Your code was this: #- def add_score(userscore): #1 if userscore[0] > high_scorelist[len(high_scorelist)-1][0]: #2 print "You made the high score list!"#3 high_scorelist.append(userscore) #4 high_scorelist.sort(reverse=True)#5 del high_scorelist[len(high_scorelist)-1]#6 return high_scorelist#7 else:#8 print high_scorelist #9 #- Lines 2-7 handle the case when the user beats the high score but if they don't you go to line 9 and just print the high score without inserting them in the list to see if they make it. How about modifying this so the "else" part... appends the user to the list; sorts the list; keeps only the first 10 items; prints the list List slices are a nice way to get the first 10 (or whatever) items of a list: ### >>> def first10(l): ... return l[:10] ... >>> print first10(range(20)) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> print first10(range(3)) [0, 1, 2] ### One final note, in lines 2 and 6 you use "len(high_scorelist)-1" to get the last item of the list. A nice way to get the last item in the list is to use the index "-1" which refers to the "last one" in a list. (You can use negative indices, too.) BTW, the HOWTO on sorting < http://www.amk.ca/python/howto/sorting/sorting.html > is helpful and the site starship site < http://starship.python.net/crew/theller/pyhelp.cgi > is a nice place to do a search of KEYWORDS (like sort) in python documentation. HTH, /c ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python backwards program (fwd)
Hello, I wanted to thank all of you who helped me with the backwards program. I finally got off my stubborn butt and downloaded 2.4.1 and the program finally works. That 2.2 was not compatible with the way I was thinking, or maybe I wasn't compatible with it was thinking who knows. i = raw_input("Enter a word.") print i[::-1] raw_input("\n\nPress the enter key to exit.") Thanks for allowing me to take some of your precious time. Jim - Original Message - From: Danny Yoo To: [EMAIL PROTECTED] Cc: Tutor Sent: Thursday, April 14, 2005 1:52 PM Subject: Re: [Tutor] Python backwards program (fwd) > Does the 2.2 python have the ability to do this?Hi Jim,Python 2.2 is actually a bit old; you may want to update the version ofPython on your system to Python 2.4. You can find it here: http://www.python.org/2.4/A lot of the approaches you were trying earlier used features that wereadded in the 2.3 or 2.4 Python series; they're absent from Python 2.2.> The following gives me the last letter of the string.>> backwords=raw_input("enter number or string:")> print backwords[-1]Yes, this is an interesting approach! We can go along this approach alittle more, if you'd like. The code above is getting the last letter, sowe're closer to printing out the word backwards.How would you print out the second to last letter of the string? ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] high score lists
On Thursday, Apr 14, 2005, I wrote: which gives 200 Nina 20 Ben 2 Raj oops, copy and paste error...should be: 200 Nina 20 Ben 2 Raj ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Re: Recursion....what are the best situations to use it?
Safe-mail.net> writes: > If this is too general a question, perhaps you can tell me when NOT to use recursion(where it would be > inappropriate or inefficient). Easy way to kill a Python program: >>> def a(): ... a() Recursion is dangerous if its depth is unchecked. I've recently seen a recursive quicksort implementation run wild for example, killing the program without any error message (not in Python, but the principle is the same regardless the programming language). You can use recursion it for a shortest route algorithm, given a group of points with certain connections between them (if there aren't too many points, otherwise you'll hit a recursion depth limit or a stack overflow). Or for a menu navigation system, where a showmenu() routine calls itself to display submenus. Yours, Andrei ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Re: high score lists
Alberto Troiano hotmail.com> writes: > I've read somewhere that the appropiate way to make a best score list is with a dictionarie > So you'll have something like this: > best_score={"Peter":100,"Jhon":23} I don't see how that is in any way superior to a list of tuples. In fact, it has distinct disadvantages, in that you'll have to do a 'lot' of work to get the scores listed from high to low (which is what is usually done with them). The situation would improve if you'd use the score as key and the player as value. But even then it's still easier to keep them in a list of tuples, because it's easier to do manipulations like "remove the lowest score" when you insert a higher one. Yours, Andrei ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor