Re: [Tutor] os.system sending of break signals
So far: I tried >>> f = os.popen('ping 192.168.8.85 -c 100 > cap2.txt') You will see that I send the output from the command to a file, because I want to test how stop the command before it reaches 100 pings. If I don't write the output to the file 'cap2.txt' and succeeds in closing 'f', all the data returned to 'f' will be lost. If i use: >>>f.close() Then 'f' is not closed and the commands until 100 packets has been send. So, I am still looking for a way to stop the command before it terminates by itself. I will not be able to get the process ID in all he cases to kill it that way. Then I tried : >>> f = os.popen2('ping 192.168.8.85 -c 100 > cap3.txt') >>> f (', mode 'w' at 0x40389530>, ', mode 'r' at 0x404a69f8>) >>> f[0].close() >>> f[1].close() >>> f (', mode 'w' at 0x40389530>, ', mode 'r' at 0x404a69f8>) This as you can see closes the fd's but the command is not terminated, because I can see my filesize is growing. Any other Ideas or what am I doing wrong? TIA, Alan Gauld wrote: >> I send a command to os.system(cmd) and want to send a break signal in >> the same way. Is this possible? The break signal is ctrl c (^c). >> I tried this, but it didn't work: os.system('\x03') I think Hex 03 is >> the signal for ctrl c. > > > Its not possible with os.system because os.system runs the called > program to completion in a separate process. You would need to mess > about with threads and process ids to do it that way. However if you > use popen() (or maybe popen2()? )you should be able to send a Ctrl-C > character to the process. However whether that actually terminates it > will depend on the OS, the process and whether Ctrl-C is being caught > anywhere. But at least there's a chance of it working! > > HTH, > > Alan G > Author of the learn to program web tutor > http://www.freenetpages.co.uk/hp/alan.gauld > > > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] os.system sending of break signals
> Python has a "signal" module in the standard library. Will that work? Yes potentially, but you still need to mess about with process ids etc to find which process to send the signal... And you would have to do the two things in separate threads since system() blocks your main program. Alan g ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Can anyone help me?
Nathan, look at the functions in the random module. randrange() would be one potential candidate. Alan G - Original Message - From: "Nathan Pinno" <[EMAIL PROTECTED]> To: Sent: Friday, October 28, 2005 3:07 AM Subject: [Tutor] Can anyone help me? Hey all, I am trying to create a program that draws 6 numbers between 1 and 49 at random for creating lottery tickets. I want to have a better chance when I play. Can anyone help me code this or show me how to, please? Thanks, Nathan Pinno For great sites go to: http://falcon3166.tripod.com MSN Messenger: [EMAIL PROTECTED],com Yahoo! Messenger: spam_swatter31 ICQ: 199020705 AIM: f3mighty ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] os.system sending of break signals
> >>> f = os.popen('ping 192.168.8.85 -c 100 > cap2.txt') > > You will see that I send the output from the command to a file, because > I want to test how stop the command before it reaches 100 pings. > If I don't write the output to the file 'cap2.txt' and succeeds in > closing 'f', all the data returned to 'f' will be lost. You can read the output of popen into your program with f.read(), but that will read all of the output after the program has run. However I think you can readline() too to catch it line by line. You can also write() data to f thus allowing you to send your Ctrl-C.(You may need popen2 or even popen3 to do the simultaneous read//write bit. #Or better still use the new subprocess module in v2.4) Does that do what you need? Alan G ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] os.system sending of break signals
If I use popen2, I need to write to one of the tuple parts. >>> f = os.popen2('ping 192.168.8.85 -c 100 > cap1.txt') >>> f[0].write('\x03') Thank command works, but 'f[1]' is in read-only mode and I can't write to it. My command in the background is still not terminated. BTW I use Linux as OS. So, it doesn't work. Alan Gauld wrote: >> >>> f = os.popen('ping 192.168.8.85 -c 100 > cap2.txt') >> >> You will see that I send the output from the command to a file, >> because I want to test how stop the command before it reaches 100 pings. >> If I don't write the output to the file 'cap2.txt' and succeeds in >> closing 'f', all the data returned to 'f' will be lost. > > > You can read the output of popen into your program with > f.read(), but that will read all of the output after the program has > run. However I think you can readline() too to catch it line by line. > You can also write() data to f thus allowing you to send your > Ctrl-C.(You may need popen2 or even popen3 to do the simultaneous > read//write bit. #Or better still use the new subprocess module in v2.4) > > Does that do what you need? > > Alan G > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] OT - Re: Can anyone help me?
You can actually increase your chance of winning in the English lottery. If two many tickets win a prize in one draw, the lowest prize (£10 for three numbers) is not paid out. Also the jackpot is shared between all the winning tickets (6 numbers) some sets of numbers like 1,2,3,4,5,6 are chosen by over 20,000 people a week. You would share the jackpot with 20,000 other people. Picking random numbers makes you less likely to chose the same numbers as everyone else. Incidently, the odds of winning the jackpot are 1 in 14 million (roughly). I've seen the jackpot go up to £25million which makes it theoretically a good bet. Ed On 28/10/05, bob <[EMAIL PROTECTED]> wrote: > At 07:07 PM 10/27/2005, Nathan Pinno wrote: > >Hey all, > >I am trying to create a program that draws 6 numbers between 1 and 49 at > >random for creating lottery tickets. I want to have a better chance when I > >play. > > Define "better chance". Lottery odds are how many tickets you buy relative > to how many tickets everyone else has bought. No program will improve or > degrade your odds. The only way you can reduce your odds is to buy more > than one ticket with the same numbers. > > Keep in mind that a lottery is as truly random as one can get (assuming no > rigging). There is no memory of past outcomes involved nor of better > guessing techniques. > > ___ > 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] os.system sending of break signals
> >>> f = os.popen2('ping 192.168.8.85 -c 100 > cap1.txt') > >>> f[0].write('\x03') > > Thank command works, but 'f[1]' is in read-only mode and I can't write > to it. > My command in the background is still not terminated. Thats almost certainly because ping never reads its input. In that case you'll need to send a kill signal to the process and to do that you need to find the process ID. I'm not sure if popen() provides access to the PID but if not you could either search for it (this might be too slow) or just drop down to use fork rather than popen, as fork will return the PID. Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] os.system sending of break signals
With what can I try and see what the PID is when using popen() or popen2() ? One thing that I noticed now is that when using popen() and the sys.exit(). The command is completed before my Python shell is terminated and if I use popen2(), sys.exit() works immediately but the ping command runs still as a process untill completed. Alan Gauld wrote: >> >>> f = os.popen2('ping 192.168.8.85 -c 100 > cap1.txt') >> >>> f[0].write('\x03') >> >> Thank command works, but 'f[1]' is in read-only mode and I can't >> write to it. >> My command in the background is still not terminated. > > > Thats almost certainly because ping never reads its input. > In that case you'll need to send a kill signal to the process and > to do that you need to find the process ID. I'm not sure if popen() > provides access to the PID but if not you could either search for it > (this might be too slow) or just drop down to use fork rather than > popen, as fork will return the PID. > > > Alan G. > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] OT - Re: Can anyone help me?
Any chance of winning £25million is a good one. ;-) Ed Singleton wrote: You can actually increase your chance of winning in the English lottery. If two many tickets win a prize in one draw, the lowest prize (£10 for three numbers) is not paid out. Also the jackpot is shared between all the winning tickets (6 numbers) some sets of numbers like 1,2,3,4,5,6 are chosen by over 20,000 people a week. You would share the jackpot with 20,000 other people. Picking random numbers makes you less likely to chose the same numbers as everyone else. Incidently, the odds of winning the jackpot are 1 in 14 million (roughly). I've seen the jackpot go up to £25million which makes it theoretically a good bet. Ed On 28/10/05, bob <[EMAIL PROTECTED]> wrote: At 07:07 PM 10/27/2005, Nathan Pinno wrote: Hey all, I am trying to create a program that draws 6 numbers between 1 and 49 at random for creating lottery tickets. I want to have a better chance when I play. Define "better chance". Lottery odds are how many tickets you buy relative to how many tickets everyone else has bought. No program will improve or degrade your odds. The only way you can reduce your odds is to buy more than one ticket with the same numbers. Keep in mind that a lottery is as truly random as one can get (assuming no rigging). There is no memory of past outcomes involved nor of better guessing techniques. ___ 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] Passing Functions or Code as Parameters
Ed Singleton wrote: > On 27/10/05, Kent Johnson <[EMAIL PROTECTED]> wrote: > >>Ed Singleton wrote: >>>Can I pass a block of code that will be executed within the function's >>>scope? >> >>Yes, you can define a function within traverse() and pass that function to >>things_to_do(), but I don't know how that will help. > > > I was thinking more of something I think I read in Ruby where you can > pass a block of code to a function and it will perform the block of > code at each iteration, and you can operate within the scope of the > function. (I think they were actually called blocks or something). Ruby has code blocks which are passed to a function. They are widely used in Ruby. The closest equivalent in Python 2.4 is to pass a function to the other function. This has much the same capabilities as Ruby blocks but not as natural a syntax. There is a proposal to add a similar capability to Python but it has not been finalized - see PEP 343: http://www.python.org/peps/pep-0343.html Kent -- http://www.kentsjohnson.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] syracuse sequence (collatz or hailstone)
[EMAIL PROTECTED] wrote: > Hello > > I am trying to create a program that will calculate the syracuse sequence > which is also known as collatz or hailstone. the number that is input by > the user may be either even or odd. the number goes through a series of > functions which are x/2 if the number is even and 3x+1 if the number is > odd. it keeps doing so until the number reaches 1. An example would be if > the user inputed 5 they should recieve: 5, 16, 8, 4, 2, 1 as the sequence > for the value that they started with. My code currently just prints a 1 > and none of the numbers that would have preceded it. any ideas on how I > could get the program to not do this would be greatly appreciated. > > > def main(): > try: > x = input("Please enter a starting value: ") > while x != 1: > > if x%2 == 0: > x = x/2 > else: > x = x*3+1 Above you have a loop. Each time through the loop you change the value of x. You don't retain the old value of x so it is lost. The simplest thing would be to print x in the loop so each successive value is shown to the user. Kent > > except ValueError, excObj: > msg = str(excobj) > if msg == "math domain error": > print "No negatives or decimals." > else: > print "Something went wrong." > > > > print "The Syracuse sequence of your starting value is:", x > > main() > > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > -- http://www.kentsjohnson.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Can anyone help me?
>>> def randnum(): ... c = [] ... for x in range(6): ... s = random.randrange(50) ... c.append(s) ... print 'Randoms: ',c ... c = [] This works good !! Johan R. Alan Monroe wrote: Hey all, I am trying to create a program that draws 6 numbers between 1 and 49 at random for creating lottery tickets. I want to have a better chance when I play. Can anyone help me code this or show me how to, please? Create (empty for now) list to hold your final numbers. Have a for-loop that runs 6 times using range(6) Inside the loop, just pick a random number and append it to your final number list. Alan ___ 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] Random number generator (was: Can anyone help me?)
After I tested the previous code, I noticed that the odds is 1:49 that a duplicate number can be found in the 6 digit range (and it happended) and that 0 can also be found. Here is the fix: import random def randnum(): c = [] for x in range(6): s = random.randrange(0, 50) if s not in c: c.append(s) else: return print ('Randoms: ',c) c = [] if __name__ == '__main__': for x in range(10): # For number of 6-digit sequences randnum() AYS? R. Alan Monroe wrote: Hey all, I am trying to create a program that draws 6 numbers between 1 and 49 at random for creating lottery tickets. I want to have a better chance when I play. Can anyone help me code this or show me how to, please? Create (empty for now) list to hold your final numbers. Have a for-loop that runs 6 times using range(6) Inside the loop, just pick a random number and append it to your final number list. Alan ___ 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] os.system sending of break signals
Johan Geldenhuys wrote: > So far: > I tried > >>> f = os.popen('ping 192.168.8.85 -c 100 > cap2.txt') > > You will see that I send the output from the command to a file, because > I want to test how stop the command before it reaches 100 pings. > If I don't write the output to the file 'cap2.txt' and succeeds in > closing 'f', all the data returned to 'f' will be lost. > > If i use: > >>>f.close() > Then 'f' is not closed and the commands until 100 packets has been send. > > So, I am still looking for a way to stop the command before it > terminates by itself. I will not be able to get the process ID in all he > cases to kill it that way. Trent Mick's process.py shows how to kill a process started from Python. http://starship.python.net/crew/tmick/ Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Random number generator
Johan Geldenhuys wrote: > After I tested the previous code, I noticed that the odds is 1:49 that a > duplicate number can be found in the 6 digit range (and it happended) > and that 0 can also be found. Look at random.sample() for a simpler way to do this. Kent > > Here is the fix: > > import random > > def randnum(): > c = [] > for x in range(6): > s = random.randrange(0, 50) > if s not in c: >c.append(s) > else: > return > print ('Randoms: ',c) > > c = [] > > if __name__ == '__main__': > >for x in range(10): # For number of 6-digit sequences >randnum() > > AYS? > >> >> >> R. Alan Monroe wrote: >> Hey all, I am trying to create a program that draws 6 numbers between 1 and 49 at random for creating lottery tickets. I want to have a better chance when I play. Can anyone help me code this or show me how to, please? >>> >>>Create (empty for now) list to hold your final numbers. >>>Have a for-loop that runs 6 times using range(6) >>>Inside the loop, just pick a random number and append it to your final >>>number list. >>> >>>Alan >>> >>>___ >>>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 -- http://www.kentsjohnson.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] File IO help
Mike Haft wrote: > Hello all, > I'm new to python but so far I have to say its a really good language > > I've been having some trouble with File IO can anyone help? I've got the > basics but my problem is that I have many files (one for each year of the > last 100 years or so) that look like this: > > MONTH RAIN AVTEMP RAD EVAP > > 1 12.412.0* 10 > 2 13.930.0* 11 > 3 > > etc until month 12 > > So far all I know how to do in Python looks something like this: > > def readInFile(inputName): > input = open(inputName, "r") > result = [] > for line in input: > if line[:1] == "1": > fields = line.split() > data = fields[1] + fields[2] + fields[7] > result.append(data) > input.close() > return result As you know this program returns data for the months that start with 1. Since you really want the data for all the months, you should just take out the conditional: for line in input: fields = line.split() data = fields[1] + fields[2] + fields[7] result.append(data) Now result will have the data for all the months in order (though from your sample data there doesn't seem to be a field 7?). > > Thats basically all I've been able to do but I need to write script that > opens a file, reads the relevent data, stores that data and then closes > the file and moves on to the next file repeating the action until all the > files have been read. Then it needs to write a file with all the data it > has collected but in a different format. To do this you need a list of the files to read, and a loop that calls readInFile() for each file and stores the data somewhere. Then you need another function to write out the data to a new file. > > If anyone can help I'd be really grateful. I hope I'm not asking too much > of the list but I haven't found anything that says READ THIS BEFORE > POSTING! on it to tell me otherwise. Beginner questions are welcome. Have you read a tutorial or introductory book? It might give you some help with the basics. See this page for suggestions: http://wiki.python.org/moin/BeginnersGuide/NonProgrammers Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Joining non strings in to string
Hi, I have a list containing numbers. I want to join this list in to a string which I can then output. The problem is I cant seem to join list of non-string items in to a string. My list looks something like: list = [5,7,20,19,49,32] I could loop through the list outputing each number individually but I am sure there is a nicer method of doing it. Cheers Eddie ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] os.system sending of break signals
Alan Gauld wrote: > > You can read the output of popen into your program with > f.read(), but that will read all of the output after the program > has run. However I think you can readline() too to catch it > line by line. You can also write() data to f thus allowing you > to send your Ctrl-C.(You may need popen2 or even popen3 > to do the simultaneous read//write bit. #Or better still use > the new subprocess module in v2.4) > Quick query with os.popen, popen2,3,4. Playing with IronPython, and decided to see what I could do with os.popen() and it. With the various popens, calling read() would block, as would calling readline() when what was currently displayed was the ">>>" prompt. What would be causing this? Is it because having displayed the ">>>" IronPython is looping waiting for input? It was pure mucking about, really, but curiosity... the .NET framework has some sane access to various bits of Win32, and if it weren't for the grinding loadtime of the CLR, I'd like to use IronPython scripts to get data which normal Python could then grab as text (on account of how there's no compatiable serialisation between the two), thus forgoing having to deal with the Win32 API. Regards, Liam Clarke ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] os.system sending of break signals
On 10/28/05, Alan Gauld <[EMAIL PROTECTED]> wrote: > > >>> f = os.popen2('ping 192.168.8.85 -c 100 > cap1.txt') > > >>> f[0].write('\x03') > > > > Thank command works, but 'f[1]' is in read-only mode and I can't write > > to it. > > My command in the background is still not terminated. > > Thats almost certainly because ping never reads its input. > In that case you'll need to send a kill signal to the process and > to do that you need to find the process ID. I'm not sure if > popen() provides access to the PID but if not you could > either search for it (this might be too slow) or just drop > down to use fork rather than popen, as fork will return > the PID. Would calling PS via another popen() and using string methods to get the Pid work? I'm rather new to Linux & Python... Regards, Liam Clarke ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Joining non strings in to string
Eddie S wrote: > Hi, > I have a list containing numbers. I want to join this list in to a > string which I can then output. The problem is I cant seem to join > list of non-string items in to a string. > > My list looks something like: > > list = [5,7,20,19,49,32] > > I could loop through the list outputing each number individually but I > am sure there is a nicer method of doing it. > > Cheers Eddie Use List Comprenhensions, join() and str(): numlist = [5,7,20,19,49,32] ','.join([str(x) for x in numlist]) BTW: never use "list" as a name for your list http://docs.python.org/tut/node7.html#SECTION00714 HTH, Wolfram ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Fwd: File IO help
On 10/27/05, Mike Haft <[EMAIL PROTECTED]> wrote: > Hello all, > I'm new to python but so far I have to say its a really good language > > I've been having some trouble with File IO can anyone help? I've got the > basics but my problem is that I have many files (one for each year of the > last 100 years or so) that look like this: > > MONTH RAIN AVTEMP RAD EVAP > > 1 12.412.0* 10 > 2 13.930.0* 11 > 3 > > Thats basically all I've been able to do but I need to write script that > opens a file, reads the relevent data, stores that data and then closes > the file and moves on to the next file repeating the action until all the > files have been read. Then it needs to write a file with all the data it > has collected but in a different format. Hi Mike, **forward to list also... Couple of things you'll need to get familiar with, to make your life easier, are the os and os.path module. I assume you've got all your files in one directory. os.listdir(directory) will return a list of all the files/directories in that directory. If you've got other directories in there as well, you can use os.path.isdir() to check if a given path is a directory or not. As listdir returns the names, and you need the full-path for simplicity, and also because os.path.isdir() requires it, you can use os.path.join() to join the directory and filename in a platform independent way. So, for example, to find only the files in my python directory import os import os.path dirPath = "c:/python24" #Either. filePaths = [] for item in os.listdir(dirPath): fullpath = os.join(dirPath, item) if not os.path.isdir(fullpath): filepaths.append(fullpath) for item in filePaths: parsedataFunc(item) #Or names = os.listdir(dirPath) for item in names: fullpath = os.join(dirPath, item) if os.path.isdir(fullpath): continue else: parsedataFunc(item) #Or, if you really want filePaths = [os.path.join(direc, item) for item in os.listdir(direc) if not os.path.isdir(os.path.join(direc, item))] for item in filePaths: parseDataFunc(item) With regards to your data, you seem to be turning it into a string... what format are you looking to write out? If it's tab/comma delimited, check out the csv module also. I'd recommend just ignoring the header lines, so you're only dealing with the data, assuming that your column headers remain static. for line in dataFile: if line.startswith("MONTH") or line.startswith("**"): continue And that will skip that line. Hope that helps, good luck handling wx data. I just used to import it into Excel and spend several hours swearing... I hope Python treats you better. And, a question for the group, I've always found that line[:1] is a complicated way of writing line[0]... is there any time when line[:1] != line[0]? Regards, Liam Clarke ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] File IO help
Oops, filePaths = [os.path.join(direc, item) for item in os.listdir(direc) if not os.path.isdir(os.path.join(direc, item))] should be > filePaths = [os.path.join(dirPath, item) for item in os.listdir(dirPath) > if not os.path.isdir(os.path.join(dirPath, item))] ... ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] File IO Help again
Heh, Cut 'im some slack there Bob, I only just figured out that line[:1] == line[0]... On 10/28/05, bob <[EMAIL PROTECTED]> wrote: > At 01:42 PM 10/27/2005, Adam wrote: > > >if line[:1] == "1": > > > >This line won't work because you're getting the first 2 characters from > >the line > > Oh? Did you test that? When I do that I get 1 character. Why? Because > slicing goes UP TO the 2nd argument. > >>> 'abc'[:1] > 'a' > > ___ > 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] Fwd: File IO help
Liam Clarke wrote: > And, a question for the group, I've always found that line[:1] is a > complicated way of writing line[0]... is there any time when line[:1] > != line[0]? Actually I would say that the general case is for them to be different and in the special case where line is a string they are the same. line[0] means, "the first element of the sequence line" line[:1] means, "the sequence consisting of everything from the start of line up to (but not including) line[1]" If line is a list, these two meanings are different: >>> r=range(4) >>> r [0, 1, 2, 3] >>> r[0] 0 >>> r[:1] [0] In the case of a string, line[0] is actually a sequence itself - a new string. This is kind of strange, really, that an element of a sequence can be the same as a subsequence of the sequence. It is a consequence of Python not having a character type - single characters are represented as strings. Kent -- http://www.kentsjohnson.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Can anyone help me?
At 09:42 PM 10/27/2005, Nathan Pinno wrote: >If I create a program that randomly draws 6 numbers, its like the lottery. >According to an article I read in Reader's Digest, if you get a Quick Pick >- which is six numbers at random - you increase your odds of winning. Odds are how many tickets you buy relative to how many tickets everyone else has bought. Has nothing to do with the mechanism for generating numbers. Any guesses you make are "random". You might as well buy fortune cookies and copy the numbers in them. Or add 1 to each number. Or No action on your part will ensure that you win, or give you a better shot at winning than anyone else. >I want to create a program that will imitate the Quick Pick process for >myself. So ask the lottery people what random number algorithm they use and program it for yourself. Not that doing that will make any difference. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python as Application (OT now)
On 10/27/05, Lee Harr <[EMAIL PROTECTED]> wrote: > >My son is learning something about using a spreadsheet - extremely > >useful and I support it 100%. That he thinks what he is learning is > >Excel is absolutely unforgivable, in terms of my understanding of > >ethical norms that once prevailed in an institute of higher education. > > I've never worked in any workplace where anything else other than Excel was used. For a majority (pick a percentage out of the air) of workplaces, Excel will be used as well. Why? Because everyone uses it. Yes, it's horribly circular, but I would like to offer the pragmatic view on this. > >We understand that all the functionality he will ever need from Excel is > >available for free in other spreadsheet software. > > Probably couldn't leave nasty scripted easter eggs in your bosse's favourite spreadsheet upon finding a new job so easily... > Probably. Anything beyond the common spreadsheet functions is almost > certainly better done another way. > For better or worse, Excel is the market leader because Lotus 1-2-3 isn't anymore, so they had to have done something right along the way. It also depends on what you'd call common spreadsheet functions. > > More frightening to me than the ubiquitous use of MS Office is the > omnipresence of windows. Every time a student sits down in front > of KDE in our lab and says "Where is the internet?" I can only cringe. As one who's recently installed Ubuntu, and played with Gnome/KDE/XFCE among others, I can't honestly see any advantage from an open source GUI environment, other than the fee. When I was learning how to use computers, the phrase "X11 Windows Server" would've left me terrified to use a GUI, lest I be incurring charges for connecting to the internet. Gnome & KDE run worse than Windows XP does on my computer, which I'm somewhat gobsmacked about still, as I can't really see why that would be so. I would blame the composite windows, but XFCE does them fine. I note that with the release of Breezy Badger, XFCE is what you get from using startx at console, which is nice. I do wonder why you cringe. Educate the user. He is expecting his usual metaphor, and it's not there. The majority of the world has it, remember, so he expects you to as well. I must apologise, but I'm detecting a slight theme of... dedication to open source from both of you gentlemen. Open source is a wonderful and lovely thing, but it has it's flaws, as does a certain corporation dominant in the market. If you look at ease-of-use for beginners, you can see why the majority of computer users, a great deal of whom have had to learn how to use them to stay viable in the job market, but really don't understand them, learn Windows & MS Office, which is usually more applicable in the job market, and then stick with what they know. As a semi-coherent bunch of metaphors, Windows does alright. 98% of Office's features aren't used by anyone, but they can get the basics done. With regard to moving to Open Office... I've worked with people who have books of 'pathways'. The Copy pathway is 'Select text > Edit > Copy' and trying to teach them about the wonders of Control + C is a dead end. These people resent any and all change. When a recent workplace of mine moved to Mozilla, there were some very unhappy people, and in the end, they relented and reinstalled IE for those who really wanted it. Don't mess with the pathways. > Microsoft may not own the internet, but that is not what we are > teaching. I seriously get about 10% of users who are unable to > see any other browser as performing the same function as > internet explorer. This is annoying, when the head of IT has made his living chanting "Outsource" and his favourite outsourcing firm says "Only if it's Microsoft." as it means I can't get a browser with tabs. > If "what is a spreadsheet?" is pretty scary. "What is a browser?" is > downright terrifying. > I get that all the time at work, as I take calls from people who are having trouble using my employer's website. Generally it's cookies/caching, which is simple, and 1 out of 20 people will say "Oh right, my cookies, yeah no worries." and hang up. The other 19 as there's different... 'pathways' for various browsers, we ask "What browser do you use?", followed by "A browser is the programme you use to view web-pages." and then "No... that's your ISP. Can you click the Help menu... It's right up the top... No, it is there. Can you see the word File? At the other end of the list of words, it should say Help. Ok, now click on Help. Down the bottom it will say About, can you read that out? Okay, you have Internet Explorer!" This is a website used to form limited liability companies (www.companies.govt.nz), search the companies database, and is generally very useful, and a lot of people will use their minimal skill and get hopelessly out of their depth, as they've installed 4 programmes which block cookies, and don't know how to disable them. Or ther
Re: [Tutor] equivalent of 'last' in perl
At 09:50 PM 10/27/2005, Johan Meskens CS3 jmcs3 approximated: >what is Python's equivalent of 'last' in perl? > >if flag == 1: > break Yes. If flag is either 1 or 0 you may code it thus: if flag: break That's not the whole truth. Most types have a value that is seen as false in boolean expressions. They includes 0 '' None False [] (,) {} ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Can anyone help me?
Aren't the odds just based on how many tickets you buy? The odds aren't affected by different people buying more tickets. If only one person buys a ticket in the entire lottery system, his odds of winning are the same as if two people play, and the same as if 20 million play. Jeff -Original Message- From: bob [mailto:[EMAIL PROTECTED] Sent: Friday, October 28, 2005 10:17 AM To: Nathan Pinno; Tutor@python.org Subject: Re: [Tutor] Can anyone help me? At 09:42 PM 10/27/2005, Nathan Pinno wrote: >If I create a program that randomly draws 6 numbers, its like the >lottery. >According to an article I read in Reader's Digest, if you get a Quick Pick >- which is six numbers at random - you increase your odds of winning. Odds are how many tickets you buy relative to how many tickets everyone else has bought. Has nothing to do with the mechanism for generating numbers. Any guesses you make are "random". You might as well buy fortune cookies and copy the numbers in them. Or add 1 to each number. Or No action on your part will ensure that you win, or give you a better shot at winning than anyone else. >I want to create a program that will imitate the Quick Pick process for >myself. So ask the lottery people what random number algorithm they use and program it for yourself. Not that doing that will make any difference. ___ 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] Can anyone help me?
At 07:28 AM 10/28/2005, Smith, Jeff wrote: Aren't the odds just based on how many tickets you buy? The odds aren't affected by different people buying more tickets. If only one person buys a ticket in the entire lottery system, his odds of winning are the same as if two people play, and the same as if 20 million play. According to the wikipedia: "In probability theory and statistics the odds in favor of an event or a proposition are the quantity p / (1-p), where p is the probability of the event or proposition." If you assign equal probability of winning to each ticket then odds are how many tickets you buy relative to how many tickets everyone else has bought. The probability of a ticket winning is 1 / m**n where m is the highest number possible and n is the number of numbers. If a lottery uses 6 numbers each in the range 1..42 then the probability of a ticket winning is 1/5489031744. All of this is mathematics. Sometimes one or more tickets win. Is that "luck"? ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] ***[Possible UCE]*** Can anyone help me?
Thanks Martin. You have a solid point. It would be a fun programming exercise anyway...I haven't programmed in ages it seems. :) Nathan Pinno For great sites go to: http://falcon3166.tripod.comMSN Messenger: [EMAIL PROTECTED],comYahoo! Messenger: spam_swatter31ICQ: 199020705AIM: f3mighty - Original Message - From: Marcin Komorowski To: Nathan Pinno Sent: Friday, October 28, 2005 6:19 AM Subject: Re: ***[Possible UCE]*** [Tutor] Can anyone help me? Hey Nathan, I do not think Python, nor any other programming language, nor any other form of analysis can help you here. We all would want to have a better chance in winning 6/49 lottery, but the reality is that each draw in the lottery is what is called an 'independent event', which means there is no correlation between the numbers what so ever. Every pick of 6 numbers has equal probability of winning as every other set of 6 numbers. There are sites out there that do statistical analysis and claim that some numbers are more probable than other, but his is total BS. Given how many possible combination of 6 numbers out of 49 there is, the lottery has not existed long enough to provide sufficient sample set to perform any meaningful statistical analysis. What I am saying is that any increased probabilities they are reporting are only there because we have not had enough draws to show otherwise. Playing lottery might be a fun thing to do, but please, do yourself a favour and don't let yourself be fooled into thinking that there are ways of improving your chances. And even if there were, improving your chance from next-to-none to next-to-next-to-none is not worth it. Do not count on chance to help you financially - there are better ways. Cheers, Marcin - Original Message - From: Nathan Pinno To: Tutor@python.org Sent: Thursday, October 27, 2005 10:07 PM Subject: ***[Possible UCE]*** [Tutor] Can anyone help me? Hey all, I am trying to create a program that draws 6 numbers between 1 and 49 at random for creating lottery tickets. I want to have a better chance when I play. Can anyone help me code this or show me how to, please? Thanks, Nathan Pinno For great sites go to: http://falcon3166.tripod.comMSN Messenger: [EMAIL PROTECTED],comYahoo! Messenger: spam_swatter31ICQ: 199020705AIM: f3mighty ___Tutor maillist - Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Can anyone help me?
Hey, I created it. Want to see the code? Here it is: [code] import random numbers = [] while True: q = int(raw_input("Do you want a lottery number drawing? 1 for yes, 2 for no ")) if q == 1: for i in range(6): draw = random.choice(range(1,50)) numbers.append(draw) print numbers numbers = [] elif q == 2: break else: print "Read the instructions please." [/code] Enjoy! Nathan Pinno For great sites go to: http://falcon3166.tripod.com MSN Messenger: [EMAIL PROTECTED],com Yahoo! Messenger: spam_swatter31 ICQ: 199020705 AIM: f3mighty - Original Message - From: "Alan Gauld" <[EMAIL PROTECTED]> To: "Nathan Pinno" <[EMAIL PROTECTED]>; Sent: Friday, October 28, 2005 2:01 AM Subject: Re: [Tutor] Can anyone help me? > Nathan, > > look at the functions in the random module. > randrange() would be one potential candidate. > > Alan G > > - Original Message - > From: "Nathan Pinno" <[EMAIL PROTECTED]> > To: > Sent: Friday, October 28, 2005 3:07 AM > Subject: [Tutor] Can anyone help me? > > > Hey all, > I am trying to create a program that draws 6 numbers between 1 and 49 at > random for creating lottery tickets. I want to have a better chance when I > play. Can anyone help me code this or show me how to, please? > Thanks, > Nathan Pinno > For great sites go to: http://falcon3166.tripod.com > MSN Messenger: [EMAIL PROTECTED],com > Yahoo! Messenger: spam_swatter31 > ICQ: 199020705 > AIM: f3mighty > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Can anyone help me?
Title: Message But the odds that you will win are not impacted by the number of tickets that are sold in total...only the number you buy. When you take into account the total number of tickets sold, all you get are the odds that the lottery will be won by anyone. I'm also a little confused by that def of odds. Consider flipping a coin. The probability that it will come up heads is 1/2. That def says that the odds in favor of it coming up heads is 1. Jeff -Original Message-From: bob [mailto:[EMAIL PROTECTED] Sent: Friday, October 28, 2005 10:52 AMTo: Smith, Jeff; Tutor@python.orgSubject: Re: [Tutor] Can anyone help me?At 07:28 AM 10/28/2005, Smith, Jeff wrote: Aren't the odds just based on how many tickets you buy? The odds aren'taffected by different people buying more tickets. If only one personbuys a ticket in the entire lottery system, his odds of winning are thesame as if two people play, and the same as if 20 million play.According to the wikipedia: "In probability theory and statistics the odds in favor of an event or a proposition are the quantity p / (1-p), where p is the probability of the event or proposition." If you assign equal probability of winning to each ticket then odds are how many tickets you buy relative to how many tickets everyone else has bought. The probability of a ticket winning is 1 / m**n where m is the highest number possible and n is the number of numbers. If a lottery uses 6 numbers each in the range 1..42 then the probability of a ticket winning is 1/5489031744. All of this is mathematics. Sometimes one or more tickets win. Is that "luck"? ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] syracuse sequence (collatz or hailstone)
hello, Could I gather all of the values from print x into a string or a range? Since, I am not familiar with lists yet. def main(): x = input("Please enter a positive starting value: ") while x != 1: if x%2 == 0: x = x/2 else: x = x*3+1 print x print "The Syracuse sequence of your starting value is:", x main() - Original Message - From: "Frank Bloeink" <[EMAIL PROTECTED]> To: <[EMAIL PROTECTED]> Sent: Friday, October 28, 2005 5:06 AM Subject: Re: [Tutor] syracuse sequence (collatz or hailstone) > Hey, > > your code seems almost alright to me, except that in your case it's only > printing the last number of your sequence, which obviously is not what > you want. Quick fix would be to insert a line "print x" just below else > statement: > ---snip-- > else: >x=x*3+1 > print x > ---snip > This should make clear where the error is: You are just calculating, but > not printing the sequence! > If you want to leave the output to the end of the program you could as > well gather all the calculated values in a list or similar structure and > then print the contents of the list.. > > hth Frank > > On Fri, 2005-10-28 at 01:22 -0400, [EMAIL PROTECTED] wrote: > > Hello > > > > I am trying to create a program that will calculate the syracuse sequence > > which is also known as collatz or hailstone. the number that is input by > > the user may be either even or odd. the number goes through a series of > > functions which are x/2 if the number is even and 3x+1 if the number is > > odd. it keeps doing so until the number reaches 1. An example would be if > > the user inputed 5 they should recieve: 5, 16, 8, 4, 2, 1 as the sequence > > for the value that they started with. My code currently just prints a 1 > > and none of the numbers that would have preceded it. any ideas on how I > > could get the program to not do this would be greatly appreciated. > > > > > > def main(): > > try: > > x = input("Please enter a starting value: ") > > while x != 1: > > > > if x%2 == 0: > > x = x/2 > > else: > > x = x*3+1 > > > > except ValueError, excObj: > > msg = str(excobj) > > if msg == "math domain error": > > print "No negatives or decimals." > > else: > > print "Something went wrong." > > > > > > > > print "The Syracuse sequence of your starting value is:", x > > > > main() > > > > > > ___ > > 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] Can anyone help me?
At 08:08 AM 10/28/2005, Smith, Jeff wrote: But the odds that you will win are not impacted by the number of tickets that are sold in total...only the number you buy. When you take into account the total number of tickets sold, all you get are the odds that the lottery will be won by anyone. I'm also a little confused by that def of odds. Consider flipping a coin. The probability that it will come up heads is 1/2. That def says that the odds in favor of it coming up heads is 1. Ah there's the rub. Odds are not "in favor". The odds of heads is 1 and the odds of tails is 1. The odds therefore are the same. If you flip 2 coins then the odds of both being heads is 1/3, ditto both tails. Odds of being different is 1/2. Jeff -Original Message- From: bob [mailto:[EMAIL PROTECTED]] Sent: Friday, October 28, 2005 10:52 AM To: Smith, Jeff; Tutor@python.org Subject: Re: [Tutor] Can anyone help me? At 07:28 AM 10/28/2005, Smith, Jeff wrote: Aren't the odds just based on how many tickets you buy? The odds aren't affected by different people buying more tickets. If only one person buys a ticket in the entire lottery system, his odds of winning are the same as if two people play, and the same as if 20 million play. According to the wikipedia: "In probability theory and statistics the odds in favor of an event or a proposition are the quantity p / (1-p), where p is the probability of the event or proposition." If you assign equal probability of winning to each ticket then odds are how many tickets you buy relative to how many tickets everyone else has bought. The probability of a ticket winning is 1 / m**n where m is the highest number possible and n is the number of numbers. If a lottery uses 6 numbers each in the range 1..42 then the probability of a ticket winning is 1/5489031744. All of this is mathematics. Sometimes one or more tickets win. Is that "luck"? ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Can anyone help me?
At 08:03 AM 10/28/2005, Nathan Pinno wrote: >Hey, >I created it. Want to see the code? >Here it is: >[code] >import random >numbers = [] Move this inside the loop following if q == 1 and get rid of the occurrence of this statement following print numbers. Less code, easier to read, more to the point. >while True: > q = int(raw_input("Do you want a lottery number drawing? 1 for yes, 2 >for no ")) This could fail if user enters a string that does not represent an integer. Either stick it in a try: block or leave the input character. I prefer the latter as there is no advantage to treating it as a number. > if q == 1: > for i in range(6): > draw = random.choice(range(1,50)) > numbers.append(draw) > print numbers > numbers = [] > elif q == 2: > break > else: > print "Read the instructions please." >[/code] > >Enjoy! >Nathan Pinno >For great sites go to: http://falcon3166.tripod.com >MSN Messenger: [EMAIL PROTECTED],com >Yahoo! Messenger: spam_swatter31 >ICQ: 199020705 >AIM: f3mighty >- Original Message - >From: "Alan Gauld" <[EMAIL PROTECTED]> >To: "Nathan Pinno" <[EMAIL PROTECTED]>; >Sent: Friday, October 28, 2005 2:01 AM >Subject: Re: [Tutor] Can anyone help me? > > > > Nathan, > > > > look at the functions in the random module. > > randrange() would be one potential candidate. > > > > Alan G > > > > - Original Message - > > From: "Nathan Pinno" <[EMAIL PROTECTED]> > > To: > > Sent: Friday, October 28, 2005 3:07 AM > > Subject: [Tutor] Can anyone help me? > > > > > > Hey all, > > I am trying to create a program that draws 6 numbers between 1 and 49 at > > random for creating lottery tickets. I want to have a better chance when I > > play. Can anyone help me code this or show me how to, please? > > Thanks, > > Nathan Pinno > > For great sites go to: http://falcon3166.tripod.com > > MSN Messenger: [EMAIL PROTECTED],com > > Yahoo! Messenger: spam_swatter31 > > ICQ: 199020705 > > AIM: f3mighty > > >___ >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] os.system sending of break signals
>> to do that you need to find the process ID. I'm not sure if >> popen() provides access to the PID but if not you could >> either search for it (this might be too slow) or just drop >> down to use fork rather than popen, as fork will return >> the PID. > >Would calling PS via another popen() and using string methods to get > the Pid work? That was my initial thought but there may be better tricks available in pythons os arsenal, I need to take a peek Nope can't see anything obvious. The snag with using ps is that it can be easy to find duplicate processes with the same name so you need to check the user ID and start time against when the local process launched its vdersion, and its still not foolproof Personally I'd go down the fok/exec route. It works something like: pid = fork() if pid == 0: exec(myprog) else: sleep(1) os.kill(pid,SIGINT) HTH, Alan G ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] syracuse sequence (collatz or hailstone)
[EMAIL PROTECTED] wrote: > hello, > > Could I gather all of the values from print x into a string or a range? > Since, I am not familiar with lists yet. Here is a simple example of gathering values into a list and making a string: >>> r=[] # Start with an empty list >>> for x in range(3): # x will be 0, 1, 2 in sequence ... r.append(str(x*x)) # Put x*x (as a string) onto r ... >>> r ['0', '1', '4'] >>> ', '.join(r) # make a single string by joining the elements of r with ', ' '0, 1, 4' Kent > > > def main(): > x = input("Please enter a positive starting value: ") > while x != 1: > if x%2 == 0: > x = x/2 > else: > x = x*3+1 > print x > print "The Syracuse sequence of your starting value is:", x > > main() > > > > > - Original Message - > From: "Frank Bloeink" <[EMAIL PROTECTED]> > To: <[EMAIL PROTECTED]> > Sent: Friday, October 28, 2005 5:06 AM > Subject: Re: [Tutor] syracuse sequence (collatz or hailstone) > > > >>Hey, >> >>your code seems almost alright to me, except that in your case it's only >>printing the last number of your sequence, which obviously is not what >>you want. Quick fix would be to insert a line "print x" just below else >>statement: >>---snip-- >> else: >> x=x*3+1 >> print x >>---snip >>This should make clear where the error is: You are just calculating, but >>not printing the sequence! >>If you want to leave the output to the end of the program you could as >>well gather all the calculated values in a list or similar structure and >>then print the contents of the list.. >> >>hth Frank >> >>On Fri, 2005-10-28 at 01:22 -0400, [EMAIL PROTECTED] wrote: >> >>>Hello >>> >>>I am trying to create a program that will calculate the syracuse sequence >>>which is also known as collatz or hailstone. the number that is input by >>>the user may be either even or odd. the number goes through a series of >>>functions which are x/2 if the number is even and 3x+1 if the number is >>>odd. it keeps doing so until the number reaches 1. An example would be if >>>the user inputed 5 they should recieve: 5, 16, 8, 4, 2, 1 as the sequence >>>for the value that they started with. My code currently just prints a 1 >>>and none of the numbers that would have preceded it. any ideas on how I >>>could get the program to not do this would be greatly appreciated. >>> >>> >>>def main(): >>>try: >>>x = input("Please enter a starting value: ") >>>while x != 1: >>> >>>if x%2 == 0: >>>x = x/2 >>>else: >>>x = x*3+1 >>> >>>except ValueError, excObj: >>>msg = str(excobj) >>>if msg == "math domain error": >>>print "No negatives or decimals." >>>else: >>>print "Something went wrong." >>> >>> >>> >>>print "The Syracuse sequence of your starting value is:", x >>> >>>main() >>> >>> >>>___ >>>Tutor maillist - Tutor@python.org >>>http://mail.python.org/mailman/listinfo/tutor >> >> >> > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > -- http://www.kentsjohnson.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python as Application (OT now)
> >useful and I support it 100%. That he thinks what he is learning is > >Excel is absolutely unforgivable, in terms of my understanding of > >ethical norms that once prevailed in an institute of higher education. > > > > I've never worked in any workplace where anything else other > than Excel was used. Certainly true for the majority case. However many smaller businesses (especially outside the USA) use other office packages for the simple reason that they are cheaper. For example in the UK, MS Office costs around £350 here whereas Lotus SmartSuite and Corel Office both cost less than £100. Ability Office although less known is also much less than £100. And of course OpenOffice is free and a lot of high street system builders are now shipping that. And finally there is MS Works which is also common in very small businesses. At the other end of the scale many high end financial organisations use more sophisticated spreadsheets than Excel - Improv was very popular until lotus withdrew it! 20/20 is another comon contender. There are a couple of other high power Unix spreadsheets that I've seen in financial clients offices. But I agree with Liam that 99% of businesses use EXcel just because everyone else does. And because MS Office is the standard suite on high volume system builders PCs - Dell, HP, IBM, Gateway, etc. Alan G. FWIW I use Excel at work and Quattro Pro at home... ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Circular approach to a dictionary structure
Hello: # I have the following dictionary: next_phases = {"open":"review","review":"write","write":"open"} # a 'phase is extracted by next_phase = next_phases[self.phase Note that the value for each of the first keys is the key for the next item, and that the value for the last key is the *first* key. Is there a different way to do this? Works fine for me this way, but I'm just curious about an alternative, :-) expecially if it is better. thanks tim -- Tim Johnson <[EMAIL PROTECTED]> http://www.alaska-internet-solutions.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] nokia 60 series
Hi As you know nokia company lauched python for its cell phones. Do you know a good tutorial to write python programs for cellphones?-- -- Mohammaddo you Python?!! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Recursion and List Comprehensions
Greetings: I'm trying to improve my programming and Python skills. To that end I have implemented a word jumble program as a recursive function: given a string of arbitrary length, return a list of all permutations of the string each character exactly once. In other words: permute('t') = ['t'], permute('te') = ['te', 'et'], permute('tes') = ['tes', 'tse', 'ets', 'est', 'ste', 'set'], etc. Here is my first try, the brute force method: def permute1 (word): retList=[] if len(word) == 1: # There is only one possible permutation retList.append(word) else: # Return a list of all permutations using all characters for pos in range(len(word)): # First isolate the char that goes in the first spot firstChar=word[pos] # Then assemble the rest of the word restWord=word[0:pos]+word[pos+1:len(word)] # Get the permutations of the rest of the word restList=permute1(restWord) # Now, tack the first char onto each word in the list for item in restList: newWord=firstChar+item # and add it to the output retList.append(newWord) return retList My second version combines statements to remove intermediate variables: def permute2 (word): retList=[] if len(word) == 1: # There is only one possible permutation retList.append(word) else: # Return a list of all permutations using all characters for pos in range(len(word)): # Get the permutations of the rest of the word permuteList=permute2(word[0:pos]+word[pos+1:len(word)]) # Now, tack the first char onto each word in the list # and add it to the output for item in permuteList: retList.append(word[pos]+item) return retList I'm told that I can collapse the logic further by using a list comprehension, something like: def permute3 (word): retList=[] if len(word) == 1: # There is only one possible permutation retList.append(word) else: # Return a list of all permutations using all characters retlist = [a list comprehension that calls permute3] return retList Unfortunately, I don't understand how list comprehensions work and how to implement them. Can someone point me in the right direction, please. Thanks in advance for your help. I'm learning a lot by following this list. Barry ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Circular approach to a dictionary structure
Hi, There may be, but I do not understand what is it exactly what you are trying to do. If you're trying to implement a circular something that goes back to the first element after iterating the last one, then I'd think of a list, and using some modulus when iterating. Can you explain more of what you are trying to do? Hugo Tim Johnson wrote: > Hello: > > # I have the following dictionary: > next_phases = {"open":"review","review":"write","write":"open"} > > # a 'phase is extracted by > next_phase = next_phases[self.phase > > Note that the value for each of the first keys is the key for > the next item, and that the value for the last key is the *first* key. > > Is there a different way to do this? Works fine for me this way, but > I'm just curious about an alternative, :-) expecially if it is better. > > thanks > tim > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Global var problem
Hi Folks, messing about with classes I've come across something basic that I don't understand. Take this class class T: def p(self): print x if __name__ == '__main__': x = 1 t = T() t.p() This outputs 1 Now this class T: def p(self): x += 1 print x if __name__ == '__main__': x = 1 t = T() t.p() This outputs UnboundLocalError: local variable 'x' referenced before assignment So I tried this class T: def p(self): x += 1 print x if __name__ == '__main__': global x x = 1 t = T() t.p() but that gives me the same UnboundLocalError exception. This has got me confused. Why does the first example work ok, but not the second ? And in the third example I get the same error even after declaring x to be global. No doubt the answer is staring me in the face ... but I still can't see it. Cheers Nick . ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Circular approach to a dictionary structure
* Hugo González Monteverde <[EMAIL PROTECTED]> [051028 12:51]: > Hi, > > There may be, but I do not understand what is it exactly what you are > trying to do. > > If you're trying to implement a circular something that goes back to the > first element after iterating the last one, Yes. You are correct! tj > then I'd think of a list, > and using some modulus when iterating. > Can you explain more of what you are trying to do? > > > Hugo > > Tim Johnson wrote: > > Hello: > > > > # I have the following dictionary: > > next_phases = {"open":"review","review":"write","write":"open"} > > > > # a 'phase is extracted by > > next_phase = next_phases[self.phase > > > > Note that the value for each of the first keys is the key for > > the next item, and that the value for the last key is the *first* key. > > > > Is there a different way to do this? Works fine for me this way, but > > I'm just curious about an alternative, :-) expecially if it is better. > > > > thanks > > tim > > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Tim Johnson <[EMAIL PROTECTED]> http://www.alaska-internet-solutions.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Circular approach to a dictionary structure
Tim, I don;t know if theres a better way but > next_phases = {"open":"review","review":"write","write":"open"} > > Note that the value for each of the first keys is the key for > the next item, and that the value for the last key is the *first* key. But I think this is pretty neat, I like it. Now I just need to find a problem that I can use it on :-) Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] nokia 60 series
> As you know nokia company lauched python for its cell phones. Wild. > Do you know a good tutorial to write python programs for cellphones? That will depend on what kindf API they offer. Unless they open up the phone with a Nokia specific library/moduile it will be hard to do much that is useful. But the concept is fun! Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Recursion and List Comprehensions
>def permute3 (word): >retList=[] >if len(word) == 1: ># There is only one possible permutation >retList.append(word) >else: ># Return a list of all permutations using all characters >retlist = [a list comprehension that calls permute3] retlist += [ word[0] + item , item for item in permute3(word[1:]) ] >return retList > Unfortunately, I don't understand how list comprehensions work and how to > implement them. Can someone point me in the right direction, please. Take a look in the functional programming topic of my tutor for an explanation of comprehensions. The code above is untested but should be close I think. It tries to produce a list of each item in the permutation list plus the same item with the first char added. However one point to consider is whether order matters. Take 'te' as your word t, te, e is what the above gives but you could argue that 'et' is also a permutation, if so, my comprehension doesn't give that. And its quite hard to generate (ie I can't think of an easy way! :-) HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Global var problem
> messing about with classes I've come across something basic that I don't > understand. As you say this has nothing to do with classes its more basic. Its about namespaces. Try reading the namespaces topic in my tutor for more info. Meanwhile lets simplify by removing the class bit def f(): print x def g(): x = x + 1# expanded version of ++ shortcut print x x = 42 f()# prints 42 g() # gives an error The error is because you are assigning to x thus creating a local var of that name, but you are using x in the definition of x which doesn't make any kind of sense def h(): global x x += 1 print x h() # prints 43 HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Question about an re
> - ->: \d+/?\d* > - -> > - ->ie 1 or more digits followed by 0 or 1 slashes followed by 0 or more > digits. this looks like it'll also accept invalid data, such as "1/" ... i think there's some more tweaking involved to get it so that if there's a '/', there is at least one digit afterwards. -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2006,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Circular approach to a dictionary structure
* Alan Gauld <[EMAIL PROTECTED]> [051028 14:05]: > Tim, > > I don;t know if theres a better way but > > > next_phases = {"open":"review","review":"write","write":"open"} > > > > Note that the value for each of the first keys is the key for > > the next item, and that the value for the last key is the *first* key. > > But I think this is pretty neat, I like it. Now I just need to find a > problem that I can use it on :-) Coming from you that is gratifying! Here's how it manifests: A CGI project involving forms. Forms may be either "new" or "edit", and that "mode" is described by the first part of the virtual document path (path part 1). path part 2 is the phase: "open" => either "new" form or "edit" form filled in from database record "review" => after posting form gives review of data added or changed . "write" => third page, signaling successful write of data to database (either update or new record) and presenting another URL with "open" as path part 2. Example: http://www.mydomain.com/cgi-bin/script.py/new/open => http://www.mydomain.com/cgi-bin/script.py/new/review => http://www.mydomain.com/cgi-bin/script.py/new/write => http://www.mydomain.com/cgi-bin/script.py/new/open => tim -- Tim Johnson <[EMAIL PROTECTED]> http://www.alaska-internet-solutions.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Global var problem
Hi Nick, > messing about with classes I've come across something basic that I don't > understand. Your issue is not so much with classes as it is with namespaces. You'll hit the exact same problem with simple functions. > Take this class > > class T: > def p(self): > print x In this case, the Python reference states that if a name (x) is not found in a block (i.e. inside the p method), it will look in its surrounding scope for it. That would be the global namespace. Given the fact that you defined x as a global variable, it finds it there and it works as expected. > Now this > class T: > def p(self): > x += 1 > print x > This outputs > UnboundLocalError: local variable 'x' referenced before assignment Here is what the Python docs have to say about assignment: If the target is an identifier (name): If the name does not occur in a global statement in the current code block: the name is bound to the object in the current local namespace. In other words, when trying to assign a new value to x, it: 1. looks if x was defined as global *inside the current function/class* 2. sees that it was not defined as global -> therefore it must be local 3. tries to get the value of that local x 4. finds there is no local x -> raises exception > So I tried this > > class T: > def p(self): > x += 1 > print x > > if __name__ == '__main__': > global x > x = 1 > t = T() > t.p() > but that gives me the same UnboundLocalError exception. This second attempt is almost but not quite right: the global statement is in the wrong place. x is by definition global if defined outside a class or function, so adding "global" in front of it won't make a difference. The point is that if you try to assign a value to a global variable inside a function or class definition, you must tell Python *in that block* that you want to assign to a global variable, not a local one. >>> def p(): ... global x ... x += 1 >>> x = 5 >>> p() >>> x 6 Similar problems can occur when defining a function inside another function: >>> def a(): ... aa = 2 ... def b(): ... print aa # aa in surrounding namespace, not local to b() ... b() >>> a() 2 >>> def a(): ... aa = 2 ... def b(): ... aa += 1 # in surrounding namespace, not local to b() ... print aa ... b() >>> a() UnboundLocalError: local variable 'aa' referenced before assignment > No doubt the answer is staring me in the face ... but I still can't see it. I would recommend against using global variables this way (modifying them inside functions). It's better to use method parameters for input and the return statement to output any necessary modifications, e.g.: def p(inp): output = inp + 1 print output return output if __name__ == '__main__': x = 5 x = p(x) It would be even better with a decent function name of course :). More info available in paragraph 4.1 of the Python reference manual. -- Yours, Andrei = Mail address in header catches spam. Real contact info: ''.join([''.join(s) for s in zip( "[EMAIL PROTECTED] pmfe!Pes ontuei ulcpss edtels,s hr' one oC.", "rjc5wndon.Sa-re laed o s npbi ot.Ira h it oteesn edt C")]) ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Global var problem
Hi Nick, Global variables in Python are global for *reading*, based in the precedence order for looking into the namespace: locals, globals(module scope actually), builtins for writing, as variables are created on the fly, a local variable will be created and will mask the global one. That's why the keyword global "exists" Do: global x whenever there is a variable that you need to *modify*, and that already exists ourside the function. In your example: > Now this > class T: > def p(self): global x #this line brings x into existence for writing > x += 1 > print x > > if __name__ == '__main__': > x = 1 > t = T() > t.p() > You'll get rid of the exception and the error. Hope it helps. Hugo Nick Lunt wrote: > Hi Folks, > > messing about with classes I've come across something basic that I don't > understand. > > Take this class > > class T: > def p(self): > print x > > if __name__ == '__main__': > x = 1 > t = T() > t.p() > > This outputs 1 > > Now this > class T: > def p(self): > x += 1 > print x > > if __name__ == '__main__': > x = 1 > t = T() > t.p() > > This outputs > UnboundLocalError: local variable 'x' referenced before assignment > > So I tried this > > class T: > def p(self): > x += 1 > print x > > if __name__ == '__main__': > global x > x = 1 > t = T() > t.p() > > but that gives me the same UnboundLocalError exception. > > This has got me confused. Why does the first example work ok, but not > the second ? > And in the third example I get the same error even after declaring x to > be global. > > No doubt the answer is staring me in the face ... but I still can't see it. > > Cheers > Nick . > > ___ > 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] Global var problem
> if __name__ == '__main__': > global x > x = 1 > t = T() > t.p() as alan mentioned, it's all about namespaces. the "global x" you have in the above piece of code doesn't do anything (because you're already or still in the global [name]space). you're getting the error in your p() method because there is an assignment to x in there. when that happens, it's part of p's local namespace. during compilation, the interpreter sees this creation of a local name, but because you access it before you assign it, i.e., x = x + 1, you get that error. add your global request to p(), and you'll be fine: def p(self): global x x += 1 print x hope this helps! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2006,2001 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Recursion and List Comprehensions
Carroll, Barry wrote: >> >>>permuteList=permute2(word[0:pos]+word[pos+1:len(word)]) >> >>># Now, tack the first char onto each word in the list >> >>># and add it to the output >> >>>for item in permuteList: >> >>>retList.append(word[pos]+item) This could be retList.extend([word[pos]+item for item in permuteList]) or in Python 2.4 omit the extra brackets: retList.extend(word[pos]+item for item in permuteList) The list comprehension lst = [word[pos]+item for item in permuteList] is equivalent to lst = [] for item in permuteList: lst.append(word[pos]+item) PS Don't get too crazy about eliminating intermediate variables, they can make the code more readable. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Question about an re
w chun wrote: >>- ->: \d+/?\d* >>- -> >>- ->ie 1 or more digits followed by 0 or 1 slashes followed by 0 or more >>digits. > > > > this looks like it'll also accept invalid data, such as "1/" ... i > think there's some more tweaking involved to get it so that if there's > a '/', there is at least one digit afterwards. \d+(/\d+)? Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Can anyone help me?
Nathan, While testing I noticed the same number coming up more that once in a set of 6 so what I've done: import random while True: q = raw_input("Do you want a lottery number drawing? 1 for yes, 2 for no ") if q == '1': numbers = [] for i in range(6): while True: draw = random.choice(range(1,50)) if not(numbers.count(draw)): numbers.append(draw) break print numbers elif q == '2': break else: print "Read the instructions please." Mark Brown Nathan Pinno wrote: >Hey, >I created it. Want to see the code? >Here it is: >[code] >import random >numbers = [] >while True: >q = int(raw_input("Do you want a lottery number drawing? 1 for yes, 2 >for no ")) >if q == 1: >for i in range(6): >draw = random.choice(range(1,50)) >numbers.append(draw) >print numbers >numbers = [] >elif q == 2: >break >else: >print "Read the instructions please." >[/code] > >Enjoy! >Nathan Pinno >For great sites go to: http://falcon3166.tripod.com >MSN Messenger: [EMAIL PROTECTED],com >Yahoo! Messenger: spam_swatter31 >ICQ: 199020705 >AIM: f3mighty >- Original Message - >From: "Alan Gauld" <[EMAIL PROTECTED]> >To: "Nathan Pinno" <[EMAIL PROTECTED]>; >Sent: Friday, October 28, 2005 2:01 AM >Subject: Re: [Tutor] Can anyone help me? > > > > >>Nathan, >> >>look at the functions in the random module. >>randrange() would be one potential candidate. >> >>Alan G >> >>- Original Message - >>From: "Nathan Pinno" <[EMAIL PROTECTED]> >>To: >>Sent: Friday, October 28, 2005 3:07 AM >>Subject: [Tutor] Can anyone help me? >> >> >>Hey all, >>I am trying to create a program that draws 6 numbers between 1 and 49 at >>random for creating lottery tickets. I want to have a better chance when I >>play. Can anyone help me code this or show me how to, please? >>Thanks, >>Nathan Pinno >>For great sites go to: http://falcon3166.tripod.com >>MSN Messenger: [EMAIL PROTECTED],com >>Yahoo! Messenger: spam_swatter31 >>ICQ: 199020705 >>AIM: f3mighty >> >> >> >___ >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] Recursion and List Comprehensions
Carroll, Barry wrote: > Greetings: > I'm trying to improve my programming and Python skills. To that end I > have implemented a word jumble program as a recursive function: given a > string of arbitrary length, return a list of all permutations of the > string each character exactly once. In other words: > > permute('t') = ['t'], > permute('te') = ['te', 'et'], > permute('tes') = ['tes', 'tse', 'ets', 'est', 'ste', 'set'], > etc. > I'm told that I can collapse the logic further by using a list > comprehension, something like: >> >>>def permute3 (word): >> >>>retList=[] >> >>>if len(word) == 1: >> >>># There is only one possible permutation >> >>>retList.append(word) >> >>>else: >> >>># Return a list of all permutations using all characters >> >>>retlist = [a list comprehension that calls permute3] >> >>>return retList > Unfortunately, I don't understand how list comprehensions work and how > to implement them. Can someone point me in the right direction, please. There's nothing magic about writing a list comprehension - they're just an inside-out way of writing a for-loop :). newlist = [] for item in mylist: newlist.append(item * 2) becomes (imagine this as an animation with bits of code from above floating down to fill in the blanks :)): newlist = [ ] newlist = [ for item in mylist] newlist = [item * 2 for item in mylist] In your case, you could start with your permute2 implementation and turn it inside out to get a list comprehension: for item in permuteList: retList.append(word[pos] + item) would become according to the example above: retList = [word[pos] + item for item in permuteList] Testing this shows that it tends to cut off a bunch of combinations, because retList is overwritten in every iteration of "for pos in range". Let's fix that by extending the list instead: retList.extend([word[pos] + item for item in permuteList]) That works. Now we replace 'permuteList' with its definition a few lines above: retList.extend([word[pos] + item for item in permute2(word[0:pos]+word[pos+1:len(word)])]) Getting ugly now. Let's see what's missing: word is an argument, item comes from the "for item in ...", but pos still needs to be defined. We get that by wrapping the "for pos in range" loop around this list comprehension: for pos in range(len(word)): dosomething(pos) becomes: [dosomething(pos) for pos in range(len(word))] Where dosomething(pos) is our earlier list comprehension. Let's fill it in: [ retList.extend( [ word[pos] + item for item in permute2(word[0:pos]+word[pos+1:len(word)]) ] ) for pos in range(len(word))] The net result: def permute3(word): retList=[] if len(word) == 1: # There is only one possible permutation retList.append(word) else: # Return a list of all permutations using all characters [ retList.extend( [ word[pos] + item for item in permute3(word[0:pos]+word[pos+1:len(word)]) ] ) for pos in range(len(word))] return retList 4 lines of perfectly readable code have become 4 lines of perfectly unreadable list comprehension. Any reader interested in understanding this will have to perform the exact opposite set of operations to go back to the original code. -- Yours, Andrei = Mail address in header catches spam. Real contact info: ''.join([''.join(s) for s in zip( "[EMAIL PROTECTED] pmfe!Pes ontuei ulcpss edtels,s hr' one oC.", "rjc5wndon.Sa-re laed o s npbi ot.Ira h it oteesn edt C")]) ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Can anyone help me?
On Fri, 28 Oct 2005, bob wrote: > At 09:42 PM 10/27/2005, Nathan Pinno wrote: > > >If I create a program that randomly draws 6 numbers, its like the lottery. > >According to an article I read in Reader's Digest, if you get a Quick Pick > >- which is six numbers at random - you increase your odds of winning. > > Odds are how many tickets you buy relative to how many tickets everyone > else has bought. Has nothing to do with the mechanism for generating > numbers. Any guesses you make are "random". My guess is that the point of the Reader's Digest article (I haven't read it, this is just my conjecture) is that a truly random (or pseudo-random) number is a better lottery play than a "favorite" number like an anniversary date, your kids' ages, etc. It's not that a random number is any more likely to hit the winning combination. But numbers that are based on dates or ages of a typical family are more likely to be played than a completely random set of numbers; and therefore, a win with a random set of numbers will likely have a smaller pool of winners with whom you'll need to split the payout. Put another way: a set of randomly selected numbers is no more or less likely to hit the lotto than a set of non-randomly selected numbers, so randomness does not affect the likelihood of there being a payout. However, the collision space for a set of randomly selected numbers is likely to be smaller than the collision space for a non-randomly selected set of numbers, which does affect the amount of a payout, in the event of a win. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Circular approach to a dictionary structure
Tim Johnson wrote: > Hello: > > # I have the following dictionary: > next_phases = {"open":"review","review":"write","write":"open"} > > # a 'phase is extracted by > next_phase = next_phases[self.phase > > Note that the value for each of the first keys is the key for > the next item, and that the value for the last key is the *first* key. I too would be tempted to use a list for this. Something along the lines of: phases = ['open', 'review', 'write'] nextphase = phases[((1 + phases.index(phase)) % len(phases)] This is not as friendly as the dictionary option, but I'd wrap that in a function call (or object interface). It has some advantages: - there's a single instance of every string - it's obvious that it's a sequence - it's one of the standard ways of doing circular structures - there's no chance of introducing a dead branch, breaking the circle - it's easier to add/remove things. E.g. if you'd add and an "approve" step between review and write, the list approach requires a single update, while the dictionary requires one new key-value pair and modifications in another two places in order to get it working correctly. -- Yours, Andrei = Mail address in header catches spam. Real contact info: ''.join([''.join(s) for s in zip( "[EMAIL PROTECTED] pmfe!Pes ontuei ulcpss edtels,s hr' one oC.", "rjc5wndon.Sa-re laed o s npbi ot.Ira h it oteesn edt C")]) ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] nokia 60 series
On 28/10/05, Mohammad Moghimi <[EMAIL PROTECTED]> wrote: Hi As you know nokia company lauched python for its cell phones. Do you know a good tutorial to write python programs for cellphones?-- -- Mohammaddo you Python?!! ___Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor You might want to have a look at this. http://www.forum.nokia.com/python ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Can anyone help me?
> >If I create a program that randomly draws 6 numbers, its like the lottery. > >According to an article I read in Reader's Digest, if you get a Quick Pick > >- which is six numbers at random - you increase your odds of winning. > > Odds are how many tickets you buy relative to how many tickets everyone > else has bought. Has nothing to do with the mechanism for generating > numbers. Any guesses you make are "random". My guess is that the point of the Reader's Digest article (I haven't read it, this is just my conjecture) is that a truly random (or pseudo-random) number is a better lottery play than a "favorite" number like an anniversary date, your kids' ages, etc. It's not that a random number is any more likely to hit the winning combination. But numbers that are based on dates or ages of a typical family are more likely to be played than a completely random set of numbers; and therefore, a win with a random set of numbers will likely have a smaller pool of winners with whom you'll need to split the payout. Put another way: a set of randomly selected numbers is no more or less likely to hit the lotto than a set of non-randomly selected numbers, so randomness does not affect the likelihood of there being a payout. However, the collision space for a set of randomly selected numbers is likely to be smaller than the collision space for a non-randomly selected set of numbers, which does affect the amount of a payout, in the event of a win. If this is the case, you are working on the wrong program. A random number program, like the one used for the lotto game, will give equal opportunity to any possible number. Whereas, you are now looking to maximize your winnings, when that win finally comes, by picking numbers that humans would not be prone to pick. That means your program needs to be finding numbers that are MORE popular to humans, in order to isolate numbers that are LESS popular to humans. This is sounding more like a massive search of all data and databases on the web, looking to count occurrences of numbers that have an immediacy to the human experience, while grading out counting numbers that are more arbitrarily nuetral or even inactive in the human experience, and after that evaluation is done, simply looking at your tally list of numbers and which numbers occur less frequently. The more you are able to evaluate whether a number has great or small impact upon the human mind, the more accurate your final results. Can you say, WEB CRAWLER? BUT!! I have good news! I got a great deal on car insurance at Geiko! And, by the way, Reader's Digest is just a tad above the National Enquirer in credibility, although they both have big readerships..which should tell you something about them. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Recursion and List Comprehensions
> Unfortunately, I don't understand how list comprehensions work and how to > implement them. Can someone point me in the right direction, please. Compare these two pieces of code x=[1,2,3,4] y=[] for eachnum in x: y.append(eachnum * 2) versus x=[1,2,3,4] y = [each * 2 for each in x] Try them both on your box :^) Alan ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Recursion and List Comprehensions
Alan et al: After reading the topic you recommended I tried rewriting my permute function as follows: ## def permute3 (word): if len(word) == 1: # There is only one possible permutation retList=[word] else: # Return a list of all permutations using all characters for pos in range(len(word)): # Get the permutations of the rest of the word, # tack the first char onto each word in the list # and add it to the output retList=[word[pos]+item for item in permute3(word[0:pos]+ word[pos+1:])] return retList ## The list comprehension looks correct to my eyes. However, when I run the function I always get back a one element list. For example >> >>> permute.permute3('test') ['tset'] >> By contrast my previous version returns the correct output: >> >>> permute.permute2('test') ['test', 'tets', 'tset', 'tste', 'ttes', 'ttse', 'etst', 'etts', 'estt', 'estt', 'etts', 'etst', 'stet', 'stte', 'sett', 'sett', 'stte', 'stet', 'ttes', 'ttse', 'tets', 'test', 'tste', 'tset'] >>> >> Note that permute3 returns the last element of the list returned by permute2. This is true in general: permute3 always returns the last element generated by permute2. I think there is a problem with the assignment (retList= ...), but the append operator (retList+= ...) causes this error: >> >>> permute.permute3('tests') Traceback (most recent call last): File "", line 1, in ? File "permute.py", line 50, in permute3 retList+=[word[pos]+item for item in permute3(word[0:pos]+word[pos+1:len(word)])] UnboundLocalError: local variable 'retList' referenced before assignment >> Ideas, anyone? Thanks again. Barry -Original Message- From: Alan Gauld [mailto:[EMAIL PROTECTED] Sent: Friday, October 28, 2005 3:01 PM To: Carroll, Barry; tutor@python.org Subject: Re: [Tutor] Recursion and List Comprehensions >def permute3 (word): >retList=[] >if len(word) == 1: ># There is only one possible permutation >retList.append(word) >else: ># Return a list of all permutations using all characters >retlist = [a list comprehension that calls permute3] retlist += [ word[0] + item , item for item in permute3(word[1:]) ] >return retList > Unfortunately, I don't understand how list comprehensions work and how to > implement them. Can someone point me in the right direction, please. Take a look in the functional programming topic of my tutor for an explanation of comprehensions. The code above is untested but should be close I think. It tries to produce a list of each item in the permutation list plus the same item with the first char added. However one point to consider is whether order matters. Take 'te' as your word t, te, e is what the above gives but you could argue that 'et' is also a permutation, if so, my comprehension doesn't give that. And its quite hard to generate (ie I can't think of an easy way! :-) HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Albertito and I want you to help us create a search engine.
Hey all, Albertito and I want you all to help us create a search engine for our site. Albertito heard that Google was created in Python, is this true? I want to know if such a task is possible, and if so, who is willing to help us create the script needed for our site. Thanks, Nathan Pinno Crew, McDonalds Restaurant and fan extraordinaire of the Oilers. http://www.the-web-surfers.store.com/ P.S. If you want to take a look at what we have done so far on the site, go right ahead. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Circular approach to a dictionary structure
* Andrei <[EMAIL PROTECTED]> [051028 15:57]: Andrei, I really like your approach. Will which up an object interface for it. Will have other applications, I'm sure. thanks tim > Tim Johnson wrote: > > Hello: > > > > # I have the following dictionary: > > next_phases = {"open":"review","review":"write","write":"open"} > > > > # a 'phase is extracted by > > next_phase = next_phases[self.phase > > > > Note that the value for each of the first keys is the key for > > the next item, and that the value for the last key is the *first* key. > > I too would be tempted to use a list for this. Something along the lines of: > >phases = ['open', 'review', 'write'] > >nextphase = phases[((1 + phases.index(phase)) % len(phases)] > > This is not as friendly as the dictionary option, but I'd wrap that in a > function call (or object interface). It has some advantages: >- there's a single instance of every string >- it's obvious that it's a sequence >- it's one of the standard ways of doing circular structures >- there's no chance of introducing a dead branch, breaking the circle >- it's easier to add/remove things. > E.g. if you'd add and an "approve" step between review and write, > the list approach requires a single update, while the dictionary > requires one new key-value pair and modifications in another two > places in order to get it working correctly. > > -- > Yours, > > Andrei > > = > Mail address in header catches spam. Real contact info: > ''.join([''.join(s) for s in zip( > "[EMAIL PROTECTED] pmfe!Pes ontuei ulcpss edtels,s hr' one oC.", > "rjc5wndon.Sa-re laed o s npbi ot.Ira h it oteesn edt C")]) > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Tim Johnson <[EMAIL PROTECTED]> http://www.alaska-internet-solutions.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] AJAX resources for Python
Hi All: Are AJAX resources available for python? http://en.wikipedia.org/wiki/AJAX thanks Tim -- Tim Johnson <[EMAIL PROTECTED]> http://www.alaska-internet-solutions.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Code Readability (was: Recursion and List Comprehensions)
Kent Johnson <[EMAIL PROTECTED]> wrote: <> >>PS Don't get too crazy about eliminating intermediate variables, they can >>make the code more readable. >> >>Kent I agree. When writing for keeps (i.e. production code) I prefer clarity and ease of maintenance over 'elegance' or 'trickiness'. This exercise is intended, in part, to sharpen my understanding of Python idioms. If I can write highly idiomatic code that works, chances are better that I will be able to decipher it when I come across it elsewhere. Barry ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Recursion and List Comprehensions
Greetings: Andrei gave me the answer I needed: <> >Let's fix that by extending the list instead: > > retList.extend([word[pos] + item for item in permuteList]) > <> The extend method solved the problem. Barry >-Original Message- >From: Carroll, Barry >Sent: Friday, October 28, 2005 5:49 PM >To: 'Alan Gauld'; Carroll, Barry; tutor@python.org >Subject: RE: [Tutor] Recursion and List Comprehensions > >Alan et al: > >After reading the topic you recommended I tried rewriting my permute >function as follows: > <> ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Recursion and List Comprehensions
Andrei: >Date: Sat, 29 Oct 2005 01:13:45 +0200 >From: Andrei <[EMAIL PROTECTED]> >Subject: Re: [Tutor] Recursion and List Comprehensions >To: tutor@python.org >Message-ID: <[EMAIL PROTECTED]> >Content-Type: text/plain; charset=ISO-8859-1; format=flowed <> >There's nothing magic about writing a list comprehension - they're just >an inside-out way of writing a for-loop :). <> That was just what I needed. Your description was clear and easy to follow. >4 lines of perfectly readable code have become 4 lines of perfectly >unreadable list comprehension. Any reader interested in understanding >this will have to perform the exact opposite set of operations to go >back to the original code. <> I couldn't agree more. This was a learning exercise for me. In a real program (one that I or someone else would have to maintain a year or so from now) I would have stopped with the first version, with all the loops and intermediate variables left in. Thanks for your help. I really enjoy this list. Barry ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] syracuse sequence (collatz or hailstone)
would this be a possible use of a list and appending even though I recieve an error from it: def main(): x = [1] x[0] = input('enter an int to start your syracuse sequence\n') while not isinstance(x[0], int): x[0] = input('no, please enter an int to start your syracuse sequence\n') while x[-1] != 1: if ((x[-1] % 2) == 0): x.append(x[-1] / 2) else: x.append((3 * x) + 1) print len(x), x print "The Syracuse sequence of your starting value is:", x main() line 10, in main x.append((3 * x) + 1) TypeError: can only concatenate list (not "int") to list >>> > [EMAIL PROTECTED] wrote: >> hello, >> >> Could I gather all of the values from print x into a string or a range? >> Since, I am not familiar with lists yet. > > Here is a simple example of gathering values into a list and making a > string: > >>> r=[] # Start with an empty list > >>> for x in range(3): # x will be 0, 1, 2 in sequence > ... r.append(str(x*x)) # Put x*x (as a string) onto r > ... > >>> r > ['0', '1', '4'] > >>> ', '.join(r) # make a single string by joining the elements of r with > ', ' > '0, 1, 4' > > Kent > >> >> >> def main(): >> x = input("Please enter a positive starting value: ") >> while x != 1: >> if x%2 == 0: >> x = x/2 >> else: >> x = x*3+1 >> print x >> print "The Syracuse sequence of your starting value is:", x >> >> main() >> >> >> >> >> - Original Message - >> From: "Frank Bloeink" <[EMAIL PROTECTED]> >> To: <[EMAIL PROTECTED]> >> Sent: Friday, October 28, 2005 5:06 AM >> Subject: Re: [Tutor] syracuse sequence (collatz or hailstone) >> >> >> >>>Hey, >>> >>>your code seems almost alright to me, except that in your case it's only >>>printing the last number of your sequence, which obviously is not what >>>you want. Quick fix would be to insert a line "print x" just below else >>>statement: >>>---snip-- >>> else: >>> x=x*3+1 >>> print x >>>---snip >>>This should make clear where the error is: You are just calculating, but >>>not printing the sequence! >>>If you want to leave the output to the end of the program you could as >>>well gather all the calculated values in a list or similar structure and >>>then print the contents of the list.. >>> >>>hth Frank >>> >>>On Fri, 2005-10-28 at 01:22 -0400, [EMAIL PROTECTED] wrote: >>> Hello I am trying to create a program that will calculate the syracuse sequence which is also known as collatz or hailstone. the number that is input by the user may be either even or odd. the number goes through a series of functions which are x/2 if the number is even and 3x+1 if the number is odd. it keeps doing so until the number reaches 1. An example would be if the user inputed 5 they should recieve: 5, 16, 8, 4, 2, 1 as the sequence for the value that they started with. My code currently just prints a 1 and none of the numbers that would have preceded it. any ideas on how I could get the program to not do this would be greatly appreciated. def main(): try: x = input("Please enter a starting value: ") while x != 1: if x%2 == 0: x = x/2 else: x = x*3+1 except ValueError, excObj: msg = str(excobj) if msg == "math domain error": print "No negatives or decimals." else: print "Something went wrong." print "The Syracuse sequence of your starting value is:", x main() ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor >>> >>> >>> >> >> ___ >> Tutor maillist - Tutor@python.org >> http://mail.python.org/mailman/listinfo/tutor >> >> > > -- > http://www.kentsjohnson.com > > ___ > 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] AJAX resources for Python
Tim Johnson wrote: > Hi All: > > Are AJAX resources available for python? > http://en.wikipedia.org/wiki/AJAX Turbogears supports AJAX using MochiKit on the client side and JSON for the protocol. http://www.turbogears.org/ Kent -- http://www.kentsjohnson.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Albertito and I want you to help us create a search engine.
Mate, if I could write a search engine, let alone anything remotely as useful as Google, I'd hopefully be working for Google. Yah, Google heavily uses Python, but the Sphinxe's being built out of sandstone blocks does not mean that I'll be able to replicate the Sphinx by learning how to build with sandstone, if you catch my drift. I recommend some http://www.allegro-c.de/formate/tlcse.htm search theory reading. And, your site isn't working at the mo. Regards, Liam Clarke On 10/29/05, Nathan Pinno <[EMAIL PROTECTED]> wrote: > Hey all, > > Albertito and I want you all to help us create a search engine for our site. > Albertito heard that Google was created in Python, is this true? I want to > know if such a task is possible, and if so, who is willing to help us create > the script needed for our site. > > Thanks, > Nathan Pinno > Crew, McDonalds Restaurant and fan extraordinaire of the Oilers. > http://www.the-web-surfers.store.com/ > > P.S. If you want to take a look at what we have done so far on the site, go > right ahead. > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor