[Tutor] Tutorial back on line
My web site is up and running again, apologies for the loss of service. 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] First Try
G'day :) I started getting sick of reading tutorials so for a bit of a break I set myself the task of writing a program to pick lotto numbers, 6 numbers between 1 and 44 (inclusive). I had done this many years before in basic and I thought back then it would be a simple task but I struck a problem of the random number generator repeating numbers occasionally so I had to check each number against the other and generate another random number if there were duplicates. So I was prepared for the same problem with python but I found that python takes care of that for me so the program would only have to be one line. I decided to make it a little more user friendly and allow the user to pick home many games they want generated. Then I made the output a little easier to read with a few blank lines. Here is what I came up with: import random numberof = int(raw_input('Enter how many games you would like generated :')) #user input for number of games to choose print print print Here are your numbers : print for games in range(1, numberof + 1): #loop for the number of games selected by user lotto = random.sample(xrange(1,45), 6) #generate 6 random numbers between 1 and 44 inclusive print games, lotto print else: print print Hope you win! I know this is a very simple program but... could I have done this a better way? John _ Search for local singles online @ Lavalife - Click here http://a.ninemsn.com.au/b.aspx?URL=http%3A%2F%2Flavalife9%2Eninemsn%2Ecom%2Eau%2Fclickthru%2Fclickthru%2Eact%3Fid%3Dninemsn%26context%3Dan99%26locale%3Den%5FAU%26a%3D21550_t=21550_r=endtext_m=EXT ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] First Try
Nice Job John. I made a few comments below on a few things I noticed. On Sunday 19 February 2006 05:33, John Connors wrote: G'day :) I started getting sick of reading tutorials so for a bit of a break I set myself the task of writing a program to pick lotto numbers, 6 numbers between 1 and 44 (inclusive). I had done this many years before in basic and I thought back then it would be a simple task but I struck a problem of the random number generator repeating numbers occasionally so I had to check each number against the other and generate another random number if there were duplicates. So I was prepared for the same problem with python but I found that python takes care of that for me so the program would only have to be one line. I decided to make it a little more user friendly and allow the user to pick home many games they want generated. Then I made the output a little easier to read with a few blank lines. Here is what I came up with: import random numberof = int(raw_input('Enter how many games you would like generated :')) #user input for number of games to choose 10,000 lines of code or 6months later (whichever comes first...) will you remember what numberof represents? Number of times the cow jumped over the moon? I try not to end a var with a prep (and will usually just omit it). I would personally go for num_games_wanted or num_tickets. (Actually to tell the truth I am a mixedCase kinda guy so would really go for numGamesWanted or numTickets, but that is not really PEP 8 [1] friendly so I am trying to break my ways.) print print print Here are your numbers : print If you desire you can use \n for return to reduce this all into one line: print \n\n\Here are your numbers :\n\n No big deal. for games in range(1, numberof + 1): #loop for the number of games selected by user lotto = random.sample(xrange(1,45), 6) #generate 6 random numbers between 1 and 44 inclusive print games, lotto print else: print print Hope you win! You don't need an else block (you will always enter it, ). You can just do: for games in range(1,numberof + 1): lotto = random.sample(xrange(1,45),6) print games, lotto print print \nHope you win! I know this is a very simple program but... could I have done this a better way? Looks pretty good to me. If you want to expand this a little more you can try: 1.) Assign all the lottery tickets to a variable and then print out the lottery tickets after you have them all. ( A list would be helpful here...) 2.) Break your program into functions so that you can do something like: (num_tickets_wanted, min_num, max_num) = get_user_input() lotto_tickets=generate_tickets(num_tickets_wanted, min_num,max_num) print_results(lotto_tickets) NOTE: It would be pure evil to drop that alll into one line. print_results(generate_tickets(get_user_input())) I shouldn't have even mentioned that, but you get the idea. John _ Search for local singles online @ Lavalife - Click here http://a.ninemsn.com.au/b.aspx?URL=http%3A%2F%2Flavalife9%2Eninemsn%2Ecom%2 Eau%2Fclickthru%2Fclickthru%2Eact%3Fid%3Dninemsn%26context%3Dan99%26locale%3 Den%5FAU%26a%3D21550_t=21550_r=endtext_m=EXT ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor Have some fun with itat least until you win the lottery. --Todd Maynard -- Computers are unreliable, but humans are even more unreliable. Any system which depends on human reliability is unreliable. -- Gilb ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] First Try
and for a belated footnote: [1] = http://www.python.org/peps/pep-0008.html Style Guide for python code. --Todd On Sunday 19 February 2006 06:27, Todd Maynard wrote: Nice Job John. I made a few comments below on a few things I noticed. On Sunday 19 February 2006 05:33, John Connors wrote: G'day :) I started getting sick of reading tutorials so for a bit of a break I set myself the task of writing a program to pick lotto numbers, 6 numbers between 1 and 44 (inclusive). I had done this many years before in basic and I thought back then it would be a simple task but I struck a problem of the random number generator repeating numbers occasionally so I had to check each number against the other and generate another random number if there were duplicates. So I was prepared for the same problem with python but I found that python takes care of that for me so the program would only have to be one line. I decided to make it a little more user friendly and allow the user to pick home many games they want generated. Then I made the output a little easier to read with a few blank lines. Here is what I came up with: import random numberof = int(raw_input('Enter how many games you would like generated :')) #user input for number of games to choose 10,000 lines of code or 6months later (whichever comes first...) will you remember what numberof represents? Number of times the cow jumped over the moon? I try not to end a var with a prep (and will usually just omit it). I would personally go for num_games_wanted or num_tickets. (Actually to tell the truth I am a mixedCase kinda guy so would really go for numGamesWanted or numTickets, but that is not really PEP 8 [1] friendly so I am trying to break my ways.) print print print Here are your numbers : print If you desire you can use \n for return to reduce this all into one line: print \n\n\Here are your numbers :\n\n No big deal. for games in range(1, numberof + 1): #loop for the number of games selected by user lotto = random.sample(xrange(1,45), 6) #generate 6 random numbers between 1 and 44 inclusive print games, lotto print else: print print Hope you win! You don't need an else block (you will always enter it, ). You can just do: for games in range(1,numberof + 1): lotto = random.sample(xrange(1,45),6) print games, lotto print print \nHope you win! I know this is a very simple program but... could I have done this a better way? Looks pretty good to me. If you want to expand this a little more you can try: 1.) Assign all the lottery tickets to a variable and then print out the lottery tickets after you have them all. ( A list would be helpful here...) 2.) Break your program into functions so that you can do something like: (num_tickets_wanted, min_num, max_num) = get_user_input() lotto_tickets=generate_tickets(num_tickets_wanted, min_num,max_num) print_results(lotto_tickets) NOTE: It would be pure evil to drop that alll into one line. print_results(generate_tickets(get_user_input())) I shouldn't have even mentioned that, but you get the idea. John _ Search for local singles online @ Lavalife - Click here http://a.ninemsn.com.au/b.aspx?URL=http%3A%2F%2Flavalife9%2Eninemsn%2Ecom %2 Eau%2Fclickthru%2Fclickthru%2Eact%3Fid%3Dninemsn%26context%3Dan99%26local e%3 Den%5FAU%26a%3D21550_t=21550_r=endtext_m=EXT ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor Have some fun with itat least until you win the lottery. --Todd Maynard ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Threading + socket server (blocking IO)
Hi, Just poking at threads, I'm contemplating doing something that I think may be a very dumb thing to do, or it may work fine. In the following code - import threading import Queue import reg import msvcrt class ParseThread(threading.Thread): def __init__(self, Q, parser): self.Q = Q self.parser = parser self.sendIt = False threading.Thread.__init__(self) def run(self): while True: if self.sendIt: parser.send_data() self.sendIt = False try: data = self.Q.get(False) self.parser.check(data) except Empty: continue if __name__ == __main__: Q = Queue.Queue() parser = reg.Parser() t1 = ParseThread(Q, parser) t1.start() while True: if msvcrt.kbhit(): if msvcrt.getch()==S: t1.sendIt = True It's the sendIt attribute in t1. Is setting an attribute of a running thread a very bad thing, or a just be careful thing? The only usages for the attribute are as above, if it's set to True. the thread calls a method of the parser object, and then resets it to False. I can see an interesting collision if an external source sets self.sendIt to True as the thread sets it to False. I intend to use this with a timer, so that very x minutes, the attribute is changed, which hopefully sidesteps that particular collision. But yes, very unfamiliar territory, and I'm worried about sowing the seeds of my own destruction by being too clever/dumb. Regards, Liam Clarke On 2/19/06, Liam Clarke [EMAIL PROTECTED] wrote: Thanks Kent, I'll try swapping it around and see how it goes. As for the setDaemon, my apologies. There's a while True: if msvcrt.kbhit(): break loop afterwards, so at a keypress it exits, hence the daemon stuff. On 2/19/06, Kent Johnson [EMAIL PROTECTED] wrote: Liam Clarke wrote: Hi, Just coming back to the server end of things. Kent, could I please ask you to confirm that I'm not doing anything abnormal with the ThreadingMixIn? The code is here at rafb: http://www.rafb.net/paste/results/915JVm90.html Basically, when I test it using a script to generate the datagrams via localhost, the server misses anywhere between 200 - 400 datagrams out of 1041. I don't have time for a detailed response but it looks OK except ThreadingMixin needs to be the first base class because it overrides a method of UDPServer. It turns out there is a class SocketServer.ThreadingUDPServer that does this. Also I'm surprised the program stays running - ISTM with the server thread marked daemon and the main thread exiting the program should exit... Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] 'in-place' methods
[1] Every couple of years, I decide to learn Java, and start going through a book -- usually the same book. It doesn't go long before I say to my self, Gosh, why would I ever want to program this language, anyway? I've taught myself Java three times(*), first from the O'Reilly Nutshell book and then from their 'Learning Java' book (very good, I recommend it) and now from 'JSP for Dummies' - which is not really Java but uses it a lot... Unfortunately I have to read a lot of Java at work and very occasionally actually program in it, but I do not like it at all. But I prefer it to either COBOL or Perl... (*)I did the same with SmallTalk but I quite liked it, it just was too big a paradigm shift in style from Lisp, Object Pascal and C++ first time around. Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] pdf syntax
i want create n manipulate pdf files. can anybody tell me what is pdf syntax n how it works? PDF syntax is, I believe, a subset of Postscript. Postscript is a page description language so it defines a document something like a programming language draws graphics. Lots of positioning commands, draw lines,arcs etc. I've never written code to generate raw PDF but I have done Postscript and I can say that its very hard work! If you can find a toolkit use it and if you can avoid it altogether and just run your output through a translator like Acrobat then thats better still! I'm looking into this myself. From what I gather, Reportlab's PDF toolkit (The ReportLab Open Source PDF library) looks like the only sensible way to go if you want to write PDF from Python. I seem to recall a Python module in the Vaults of Parnassus(sp?) that did PDF generation. But I might be wrong... Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] First Try
I started getting sick of reading tutorials so for a bit of a break I set myself the task of writing a program to pick lotto numbers, Thats always a good idea! :-) Sometimes you discover you don't know enough to finish it but you can always go back, but in this case So I was prepared for the same problem with python but I found that python takes care of that for me so the program would only have to be one line. Yep, thats a common problem with Python, you start with what sounds an interesting challenge only to discover that Python makes it trivially easy! (Of course sometimes the trivially easy turns out to be astonishingly hard!) Now for some very nit-picking style stuff... import random numberof = int(raw_input('Enter how many games you would like generated :')) #user input for number of games to choose Its traditional to put comments above the lines to which they refer. print print print Here are your numbers : print print '\n\nHere are your numbers : \n \n is a newline. Or print ''' Here are your numbers : ''' Triple quotes allow newlines wiothin them. for games in range(1, numberof + 1): #loop for the number of games selected games is plural so implies some kind of collection or sequence, the singular form is more suitable here since its really a single game number that it holds lotto = random.sample(xrange(1,45), 6) #generate 6 random numbers between 1 and 44 inclusive print games, lotto print I'd probably use some string formatting here to ensure a neat layout: print %3s\t%s % (game, lotto) That will print a number right justified in 3 character width then a tab(\t) followed by the list. else: print print Hope you win! You don't need the else, you always want to print that at the end of the loop so just have it as part of the text. Its very rare to use the else part of a for loop. In fact I've never used it for anything real so far as I can recall! I know this is a very simple program but... could I have done this a better way? The technique is fine, the points above are really about style and therefore something of a matter of personal taste. One other technique you could have used is list comprehension (you probably haven't met those yet) which could have produced all of your output in one go then you would only need to print it. But the advantage in minimal. One enhancement you might like to try is to ask for an optional lucky number and only display sequences with the lucky number in (Hint: there is a very easy way to do this and there is a much harder 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] Bug in python
a = 1 a2 = a%2 a2 1 8*a2 8 8*(a%2) 8 8*a%2 0 The * is being given equal priority to %. Why isn't % given higher priority than *? Also, why am I getting a syntax error in the following? The def in the definition of the second function is being highlighted. IDLE 1.1.2 def transfac(v): a = v[0] b = v[1] c = v[2] d = v[3] m = v[4] n = v[5] z = v[6] k = v[7] k = k + 1 a2 = a%2 b2 = b%2 c2 = c%2 d2 = d%2 ma = ((d - n * c)/(a*m + b))/2 na = ((d - m * b)/(a * n +c) )/2 j = 8 * a2 + 4 * b2 + 2 * c2 + d2 if j == 0: a,b,c,d,m,n = a/2,b/2,c/2,d/2,m,n if j == 1: a,b,c,d,m,n = -1,-1,-1,-1,-1,-1 if j == 2: a,b,c,d,m,n = a,b/2,c,d/2,m,2*n if j == 3: a,b,c,d,m,n = a,(a+b)/2,c,(d-c)/2,2*n+1 if j == 4: a,b,c,d,m,n = a,b,c/2,d/2,2*m,n if j == 5: a,b,c,d,m,n = a,b,(a+c)/2,(d-b)/2,2*m+1,n if j == 6: a,b,c,d,m,n = a,a*na+b,a*ma+c,d-a*ma*na - b*ma - c * na,m+ma n+na if j == 7: a,b,c,d,m,n = a,a*na+b,a*ma+c,d-a*ma*na - b*ma - c * na,m+ma n+na if j == 8: a,b,c,d,m,n = -1,-1,-1,-1,-1,-1 if j == 9: a,b,c,d,m,n = 2*a,a+b,a+c,(d-a-b-c)/2,2*m+1,2*n+1 if j == 10: a,b,c,d,m,n = a,a*na+b,a*ma+c,d-a*ma*na - b*ma - c * na,m+ma n+na if j == 11: a,b,c,d,m,n = 2*a,a+b,c,(d-c)/2 if j == 12: a,b,c,d,m,n = a,a*na+b,a*ma+c,d-a*ma*na - b*ma - c * na,m+ma n+na if j == 13: a,b,c,d,m,n = 2*a,b,a+c,(d-b)/2,m,2*n+1 if j == 14: a,b,c,d,m,n = 2*a,b,c,d/2,2 *m,2*n if j == 15: a,b,c,d,m,n = a,a*na+b,a*ma+c,d-a*ma*na - b*ma - c * na,m+ma n+na z = a * d + b * c v = [a,b,c,d,m,n,z,k] return v comment: the def in the following line has been highlighted. def gcd(a,b): r2 = a r3 = b flag = 1 while flag0: if r3 == 0: return r2 flag = 0 else: r1=r2 r2=r3 r3 = r1 - r2*(r1/r2) def factor0(z): v = [1,0,0,341,1,1,341,1] v[3] = z v[6]= z flag = 1 while flag 0: v = transfac(v) g = gcd(z,v[0]) if g1: if gz: return g flag = 0 g = gcd(z,v[1]) if g1: if gz: return g flag = 0 g = gcd(z,v[2]) if g1: if gz: return g flag = 0 g = gcd(z,v[3]) if g1: if gz: return g flag = 0 if v[1]+v[2]+v[3]-v[4]==0: return v[0]+v[1] flag = 0 if v[1]+v[2]-v[3]+v[4]==0: return v[0]+v[1] flag = 0 if v[1]-v[2]+v[3]+v[4]==0: return v[0]+v[2] flag = 0 if -v[1]+v[2]+v[3]+v[4]==0: return v[3]+v[1] flag = 0 SyntaxError: invalid syntax ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Bug in python
On 20/02/06, Kermit Rose [EMAIL PROTECTED] wrote: 8*a%2 0 The * is being given equal priority to %. Why isn't % given higher priority than *? Calling it a bug is a bit harsh when it's documented that way :-) See: http://docs.python.org/ref/summary.html *, / and % all have the same precedence. I guess the reasoning is that / is (approximately) the inverse of * and % is remainder after /. Also, why am I getting a syntax error in the following? When you're using the interactive interpreter, you need to end a function definition with an extra carriage return. (at least, that's the way it works in the console version) eg: def foo(): ... pass ... def bar(): File stdin, line 3 def bar(): ^ SyntaxError: invalid syntax vs: def foo(): ... pass ... def bar(): ... pass ... HTH! -- John. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] How can I make Python Shell see new version of function subroutine?
From: John Fouhy Date: 02/19/06 16:33:18 To: Python Tutor Subject: [Tutor] Bug in python See: http://docs.python.org/ref/summary.html *, / and % all have the same precedence.I guess the reasoning is that / is (approximately) the inverse of * and % is "remainder after /". Hello John. Ok. I got steamed too quickly. ** Also,why am I getting a syntax errorin the following? When you're using the interactive interpreter, you need to end a function definition with an extra carriage return. (at least, that's the way it works in the console version) ** I believe you. However, when I added extra carriage returns to the script file between the function subroutines, it made no difference. Why? Is it because the windows copy and paste throws away the extra carriage returns? I pasted the function subroutines, one at a time, into the shell, and entered the carriage return directly into the shell between copies, and it worked. However, I have a debugging dilemma. I made changes to one of the function subroutines, and recopied that function to the shell and I put print statements in the new version of the function subroutine. None of the new print statements are printing. It's as if the old version is still runing. Is there anything short of closing the shell and re-opening it that I can do to fix this? ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How can I make Python Shell see new version of functionsubroutine?
From: John Fouhy Date: 02/19/06 17:14:39 To: Python Tutor Subject: Re: [Tutor] How can I make Python Shell see new version of functionsubroutine? Do you need to use copy and paste?For instance, say all your functions are in a file called "factorization.py".In IDLE, you could type "import factorization", and then you'll be able to call your functions by typing things like "factorization.gcd(x, y)". * import "c:\\math\\factoring\\factor30.py"SyntaxError: invalid syntax import "c:\math\factoring\factor30.py"SyntaxError: invalid syntax ** If you change the code, you can reload the module by using the 'reload' builtin function. Could you explain this more. I'm not compiling or recompiling the function subroutine. Have you tried restarting IDLE? The first thing to do would be to verify that the problem is what you think it is (as opposed to a bug in your code, for example). *** Yes. I made a mistake. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Generating small random integer
Hello. How can I find documentation on the random number generator function. It's not listed in the math module. In general, how can I find documentation on any particular function if I don't know what module it is in? Kermit[EMAIL PROTECTED] ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Generating small random integer
On 19/02/06, Kermit Rose [EMAIL PROTECTED] wrote: Hello.How can I find documentation on the random number generator function.It's not listed in the math module.You might want to try the random module.In general,how can I find documentation on any particular function if I don't know what module it is in?do a search on http://www.python.org/ ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Bug in python
8*a%2 0 The * is being given equal priority to %. Why isn't % given higher priority than *? Because that's the way Guido designed I guess. ;-) Although why would you expect % to be higher precedence than *? You can always use parentheses, and if in any doubt should do so. Also, why am I getting a syntax error in the following? The def in the definition of the second function is being highlighted. Its always good to send the complete error message. Python errors are extremely informative whemn you can see them in their entirety. def transfac(v): a = v[0] b = v[1] c = v[2] d = v[3] m = v[4] n = v[5] z = v[6] k = v[7] k = k + 1 a2 = a%2 b2 = b%2 c2 = c%2 d2 = d%2 ma = ((d - n * c)/(a*m + b))/2 na = ((d - m * b)/(a * n +c) )/2 j = 8 * a2 + 4 * b2 + 2 * c2 + d2 if j == 0: a,b,c,d,m,n = a/2,b/2,c/2,d/2,m,n if j == 1: a,b,c,d,m,n = -1,-1,-1,-1,-1,-1 if j == 2: a,b,c,d,m,n = a,b/2,c,d/2,m,2*n if j == 3: a,b,c,d,m,n = a,(a+b)/2,c,(d-c)/2,2*n+1 It might be better to use an elif chain here. It makes little differemce in this case but is more conventional for long chains like this. if x == 1: f(y) elif x == 2: g(y) elif x == 3: ...etc else: catch errors here comment: the def in the following line has been highlighted. Comments in Python startt with a # character and extend to the end of line. I appreciate its not part of the code but I thought I'd point it out :-) def gcd(a,b): r2 = a r3 = b flag = 1 while flag0: if r3 == 0: return r2 When you doi a return execution leaves the function so any lines after return will be ignored. This is like C. Buit its not your error, Python simply ignores them. However the error may be above the indicated line but since your post has lost all indentation its hard to tell. SyntaxError: invalid syntax We really need to see the full error plus the actual code with indentation etc for say 10 lines above and below the marked line. 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] How can I make Python Shell see new version of functionsubroutine?
I pasted the function subroutines, one at a time, into the shell, and entered the carriage return directly into the shell between copies, and it worked. I'm not sure why you are copying the code into the shell? Do you know about modules and the import and reload statements in Python? You can write a script and then save it and import it into the shell for testing. Change the script, save it and then reload() it into the shell for further testing. Not that intuitive I agree... Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How can I make Python Shell see new version offunctionsubroutine?
import c:\\math\\factoring\\factor30.py Just use import factor30 the file will need to be in Pythons search path. The easiest way is to use a single folder for all your code. the folder called site-packages should be included by default so you might like to use that. Alternatively you can use another one and add that folder to an environment vartiable called PYTHONPATH Could you explain this more. I'm not compiling or recompiling the function subroutine. Actually you are. When python imports a file (foo.py say) it compiles it into bytecode (and creates a file called foo.pyc in the process). Reload makes sure you get the latest updated version. reload(foo) Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Generating small random integer
From: Adam Date: 02/19/06 18:25:05 To: Kermit Rose Cc: tutor@python.org Subject: Re: [Tutor] Generating small random integer You might want to try the random module. * Why did I get this diagnostic? factor0(3737)[1, 0, 0, 3737, 1, 1, 3737, 1] Traceback (most recent call last): File "pyshell#50", line 1, in -toplevel- factor0(3737) File "pyshell#35", line 12, in factor0 v = transfac(v) File "pyshell#48", line 19, in transfac na = na + randint(1,na)NameError: global name 'randint' is not defined Inthe function that calls randint, I placed the import command. def transfac(v): import random a = v[0] randint( a, b) Return a random integer N such that a = N = b. *** In general,how can I find documentation on any particular function if I don't know what module it is in? do a search on http://www.python.org/ ** Patch: 3-argument pow() function I found this, but it doesn't tell me how to use it. I wanted to write a pseudo prime number tester. So, I wanted to use this function to test the value of pow(2,(z-1)/2,z) for positive integers z. *** ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Generating small random integer
How can I find documentation on the random number generator function. It's not listed in the math module. Its in the random module. BTW There are lots of random functions inPython depending on the algorithm you need. In general, how can I find documentation on any particular function if I don't know what module it is in? I usually just use Google - sounds primitive, but it usually gets it in the first 5 entries... For example try searching for python random function :-) 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] Generating small random integer
On 20/02/06, Kermit Rose [EMAIL PROTECTED] wrote: NameError: global name 'randint' is not defined In the function that calls randint, I placed the import command. def transfac(v): import random a = v[0] You need to tell python that randint is in the random module. ie, instead of calling randint(), call random.randint(). Have you been through the tutorial on python.org? It is quite helpful. -- John. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Generating small random integer
From: John Fouhy Date: 02/19/06 19:01:26 To: tutor@python.org Subject: Re: [Tutor] Generating small random integer You need to tell python that randint is in the random module. ie, instead of calling randint(), call random.randint(). ** oops. I should have know that. * Have you been through the tutorial on python.org? It is quite helpful. *** I skimmed it a couple of times. I did try to read it from "cover to cover", but too quickly got into places where I did not know what it talked about. So I am falling back on the tactic of using it as a reference to look things up as I develope my program, and if I can't find the answer there to ask you guys. Kermit [EMAIL PROTECTED] ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] File handling: open a file at specified byte?
HI. This is one I cant seem to find a solid answer on: First, some background: I have a log file that I wrote a python parser for it, and it works great , but in the interest of saving time and memory , and also to be able to read the currently active log file, say every 10 minutes , and update the static file, I was trying to find some way that I can get python to do this: Open log file, read lines up to end of file, and *very important* make a note of the bytes read, and stash this somewhere (I.E. mark the file) , and then handle the parsing of said file, until all lines have been read and parsed, write the new files, and close the handler. say, 10 minutes later, for example, the script would then check the bytes read , and *very important* start reading the file *from* the point it marked (I.E. pick up at the point it bookmarked) and read from that point. Since the log file will be active (webserver log file) it will have new data to be read, but I dont want to have to read through the *entire* log file all over again, just to get to the new data- I want to be able ot bookmark where the log file was read up to last time, and then open the file later at that point. My current script works well, but only reads the day old log file (post log rotate) , and it does very well, parsing as much as 3 GB in as little as 2 minutes if the server isnt heavily loaded when the parser runs. basically, the webserver runs Tux , which writes a log file for *all* domains on a server, and the script takes the tux log, and parses it, extracting the domain for which the log entry is for, and writes a new line into the domain's apache format CLF log file (this way we are able to run awstats on individual domains, and get relatively accurate stats) So.. my question is- is there any way to do what I want ? Open a live log file, read lines to x bytes, (say 845673231 bytes) , make a note of this, and 10 miutes later open the same file again *AT* 845673232 bytes - starting with the next byte after the bookmarked point, read to end of file, and update the bookmark. Thanks for any pointers- Advice appreciated. Bri! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How can I make Python Shell see new version offunctionsubroutine?
Restoring the tutor list on CC - Original Message - From: Kermit Rose [EMAIL PROTECTED] To: Alan Gauld [EMAIL PROTECTED] How can I add c:\math\factoring to the PYTHONPATH? What OS are you using? Assuming Windows NT/2000/XP you go to My Computer and right click Select Properties and go to the Advanced tab Click Environment Variables button Under System Variables click New In Varable Name type PYTHONPATH in upper case In variable value type your folder name c:\math\factoring in this case is reload(foo) equivalent to import foo More or less, yes. There may be a few subtle differences but if so I don't know what they are! Except you can only reload *after* using an import. And using import twice will not reload the module. 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] Showing code with errors
We really need to see the full error plus the actual code I had thought I had shown you exactly the code and error message. You only gave the error text not the fll message. A Python error message is multi line and looks like: File stdin, line 2 def g(): pass ^ SyntaxError: invalid syntax That shows the file name, the line at fault, the location within the line as well as the description. If the error ioccurs deep within a program there will be a full stack trace showing all of the nested function calls too. I did not anticipate that the email programs would clobber the indentation. Sadly it happens all too often. The best solution is to ensure you send in plain text rather than HTML or RTF formats. Another trick is to put a character in front of all blank lines (a dot or hyphen say) 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] Generating small random integer
Traceback (most recent call last): File pyshell#50, line 1, in -toplevel- factor0(3737) File pyshell#35, line 12, in factor0 v = transfac(v) File pyshell#48, line 19, in transfac na = na + randint(1,na) NameError: global name 'randint' is not defined Reading from the bottom uip it tells us that randint is not defined. randint is in the random module. def transfac(v): import random a = v[0] randint(a, b) You need to prepend the function name with the module name - this prevents name collisions across modules. ie random.randint(a,b) I found this, but it doesn't tell me how to use it. Having found your function (import the module if necessary) then use help() import math help(math) help(math.sqrt) Note when using help() do not put parens after the required function name - that would ask for help on the returned value! Use 'Q' to exit the help screen. Use 'b' to reverse up a screeen BTW there is a built in pow which is slightly different to the one in the math module... Tip: You can also use dir() to find out the names of functions in a module, including the built in functions: dir(__builtins__) dir(math) Note 2 underscores each side of builtins coz its a 'magic' name, imported modules are named as usual... 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] File handling: open a file at specified byte?
look at the file tell() and seek() methods. They will tell you the current location and allow you to move to a specific location. HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld - Original Message - From: Brian Gustin [EMAIL PROTECTED] To: tutor@python.org Sent: Monday, February 20, 2006 12:18 AM Subject: [Tutor] File handling: open a file at specified byte? HI. This is one I cant seem to find a solid answer on: First, some background: I have a log file that I wrote a python parser for it, and it works great , but in the interest of saving time and memory , and also to be able to read the currently active log file, say every 10 minutes , and update the static file, I was trying to find some way that I can get python to do this: Open log file, read lines up to end of file, and *very important* make a note of the bytes read, and stash this somewhere (I.E. mark the file) , and then handle the parsing of said file, until all lines have been read and parsed, write the new files, and close the handler. say, 10 minutes later, for example, the script would then check the bytes read , and *very important* start reading the file *from* the point it marked (I.E. pick up at the point it bookmarked) and read from that point. Since the log file will be active (webserver log file) it will have new data to be read, but I dont want to have to read through the *entire* log file all over again, just to get to the new data- I want to be able ot bookmark where the log file was read up to last time, and then open the file later at that point. My current script works well, but only reads the day old log file (post log rotate) , and it does very well, parsing as much as 3 GB in as little as 2 minutes if the server isnt heavily loaded when the parser runs. basically, the webserver runs Tux , which writes a log file for *all* domains on a server, and the script takes the tux log, and parses it, extracting the domain for which the log entry is for, and writes a new line into the domain's apache format CLF log file (this way we are able to run awstats on individual domains, and get relatively accurate stats) So.. my question is- is there any way to do what I want ? Open a live log file, read lines to x bytes, (say 845673231 bytes) , make a note of this, and 10 miutes later open the same file again *AT* 845673232 bytes - starting with the next byte after the bookmarked point, read to end of file, and update the bookmark. Thanks for any pointers- Advice appreciated. Bri! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How can I make Python Shell see new version offunctionsubroutine?
From: Alan Gauld Date: 02/19/06 19:55:13 To: Kermit Rose Cc: Python Tutor list Subject: Re: [Tutor] How can I make Python Shell see new version offunctionsubroutine? Restoring the tutor list on CC ** Thanks for reminding me. Assuming Windows NT/2000/XP you go to My Computer and right click Select Properties and go to the Advanced tab Click Environment Variables button Under System Variables click New In Varable Name type PYTHONPATH in upper case In variable value type your folder name c:\math\factoring I saw the PYTHONPATH name being added to the variable list. how might I verify, after the fact, that the name is correct? I did all that. Why did I get this diagnostic? import factor30.py Traceback (most recent call last): File "pyshell#270", line 1, in -toplevel- import factor30.pyImportError: No module named factor30.py ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How can I make Python Shell see new version offunctionsubroutine?
On 20/02/06, Kermit Rose [EMAIL PROTECTED] wrote: import factor30.py Traceback (most recent call last): File pyshell#270, line 1, in -toplevel- import factor30.py ImportError: No module named factor30.py Because the module is named 'factor30', not 'factor30.py' ... -- John. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How can I make Python Shell see new versionoffunctionsubroutine?
From: John Fouhy Date: 02/19/06 20:34:13 To: tutor@python.org Subject: Re: [Tutor] How can I make Python Shell see new versionoffunctionsubroutine? Traceback (most recent call last): File "pyshell#270", line 1, in -toplevel- import factor30.py ImportError: No module named factor30.py Because the module is named 'factor30', not 'factor30.py' ... -- John. Thank you very much ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Printing the Carriage return character
Hi, Not sure if this is a python thing or a Operating system peculiarity, but here goes: Why does the line print FirstLine + \rSecondLine produce different output when run via IDLE and when run in the python prompt (both under Windows XP)? Output in IDLE (ver 1.1.1, python 2.4.1): print FirstLine + \rSecondLine FirstLine SecondLine Output at the python prompt (python 2.4.1): C:\QVCS\Mobile Data\python Python 2.4.1 (#65, Mar 30 2005, 09:13:57) [MSC v.1310 32 bit (Intel)] on win32 Type help, copyright, credits or license for more information. print FirstLine + \rSecondLine SecondLine Cheers Hans ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] First program -- would like comments and criticisms
Thanks Andrei for your input.I've already implemented a couple of your suggestions and will certainlygive the others a go. On 2/18/06, Andrei [EMAIL PROTECTED] wrote: [EMAIL PROTECTED] wrote: Here is my first stab at putting together a working program. It is a glossary that you can add words and definitions to, or look up words and their definitions.There are a couple of problems here and there, but it basically does what I set out for it to do. All comments and criticisms are welcome. I attached the data file that goes with the script in case anybody wanted to actually run it, so they wouldn't have to make their own dictionary file to access.I haven't executed it, but it seems quite good, certainly for a firstworking program. For small programs there's no point in overengineering, but here are some simple improvements you could look into:- place a if __name__==__main__: condition at the bottom and putyour program code in there (or better yet, extract it in a function and call that function after the if __name__ stuff). This way the module canalso be imported.- make the location of the dictionary a 'constant' (which in Pythonmeans a variable with all-uppercase name :)). Having magic strings in code is bad practice.- the menu system could be redesigned to make it moremaintenance-friendly. At this point if you want to add/modify a choice,you'd have to modify a procedure and the main code. You could instead make a dictionary mapping each possible choice (keys) to tuplescontaining a description and a function name. Loop over the keys andprint them with the description. Once the user makes a choice, you couldlook up the function in the dictionary and execute it. This way adding new functionality items only means you need to add an entry to that onedictionary.- you could replace the while num != '3': condition with a whileTrue: - the loop is interrupted anyway if '3' is selected, because of the 'break'. This way you can also remove the initialization of num.- you could extract the actual logic (the glossary) to a class withmethods like load, save, lookup and separate it completely from all the user interaction. The glossary class shouldn't print/ask foruser input. It's overkill for such a small program, but you could thentheoretically reuse the glossary in a different application (e.g. put a webbased interface onto it, or subclass it and make a glossary which canalso do multiple language translations, or use a different storagebackend, etc.).snip 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 ulcpssedtels,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 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Fwd: Threading + socket server (blocking IO)
As requested. -- Forwarded message -- From: Kent Johnson [EMAIL PROTECTED] Date: Feb 20, 2006 2:39 PM Subject: Re: [Tutor] Threading + socket server (blocking IO) To: Cc: [EMAIL PROTECTED] Liam Clarke wrote: Hi, Just poking at threads, I'm contemplating doing something that I think may be a very dumb thing to do, or it may work fine. In the following code - import threading import Queue import reg import msvcrt class ParseThread(threading.Thread): def __init__(self, Q, parser): self.Q = Q self.parser = parser self.sendIt = False threading.Thread.__init__(self) def run(self): while True: if self.sendIt: parser.send_data() self.sendIt = False try: data = self.Q.get(False) self.parser.check(data) except Empty: continue if __name__ == __main__: Q = Queue.Queue() parser = reg.Parser() t1 = ParseThread(Q, parser) t1.start() while True: if msvcrt.kbhit(): if msvcrt.getch()==S: t1.sendIt = True It's the sendIt attribute in t1. Is setting an attribute of a running thread a very bad thing, or a just be careful thing? The only usages for the attribute are as above, if it's set to True. the thread calls a method of the parser object, and then resets it to False. I can see an interesting collision if an external source sets self.sendIt to True as the thread sets it to False. I intend to use this with a timer, so that very x minutes, the attribute is changed, which hopefully sidesteps that particular collision. But yes, very unfamiliar territory, and I'm worried about sowing the seeds of my own destruction by being too clever/dumb. Setting an attribute in one thread and checking it in another is OK, I think. But setting an atribute in two threads raises the possibility of a race condition. There is definitely a chance of missing a setting of sendIt to true: ParseThreadmain thread if self.sendIt: # if sendIt is already true t1.sendIt = True # main thread sets it true again parser.send_data() self.sendIt = False # set it false If the test is much more frequent than the set, this is unlikely but it is a weakness in the design. Also you have a busy loop (an infinite loop that just keeps polling), you should at least put a sleep in it, better is to use a get() with timeout or a blocking get(). I don't understand what your run() loop is doing - it seems to read data from the queue and throw it away, optionally calling parser.send_data(). Can you explain what you are trying to do? Presumably this is part of your UDP server? Kent PS My mail server has been blacklisted, can you forward this to the tutor list? ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] File handling: open a file at specified byte?
Hi Brian! There are two functions for an file-Object which deliver the position in the file and can seek-function to set the offset in the file: f=open(.emacs, r ) help(f.tell) Help on built-in function tell: tell(...) tell() - current file position, an integer (may be a long integer). help( f.seek ) Help on built-in function seek: seek(...) seek(offset[, whence]) - None. Move to new file position. Argument offset is a byte count. Optional argument whence defaults to 0 (offset from start of file, offset should be = 0); other values are 1 (move relative to current position, positive or negative), and 2 (move relative to end of file, usually negative, although many platforms allow seeking beyond the end of a file). If the file is opened in text mode, only offsets returned by tell() are legal. Use of other offsets causes undefined behavior. Note that not all file objects are seekable. HTH Ewald Brian Gustin wrote: HI. This is one I cant seem to find a solid answer on: First, some background: I have a log file that I wrote a python parser for it, and it works great , but in the interest of saving time and memory , and also to be able to read the currently active log file, say every 10 minutes , and update the static file, I was trying to find some way that I can get python to do this: Open log file, read lines up to end of file, and *very important* make a note of the bytes read, and stash this somewhere (I.E. mark the file) , and then handle the parsing of said file, until all lines have been read and parsed, write the new files, and close the handler. say, 10 minutes later, for example, the script would then check the bytes read , and *very important* start reading the file *from* the point it marked (I.E. pick up at the point it bookmarked) and read from that point. Since the log file will be active (webserver log file) it will have new data to be read, but I dont want to have to read through the *entire* log file all over again, just to get to the new data- I want to be able ot bookmark where the log file was read up to last time, and then open the file later at that point. My current script works well, but only reads the day old log file (post log rotate) , and it does very well, parsing as much as 3 GB in as little as 2 minutes if the server isnt heavily loaded when the parser runs. basically, the webserver runs Tux , which writes a log file for *all* domains on a server, and the script takes the tux log, and parses it, extracting the domain for which the log entry is for, and writes a new line into the domain's apache format CLF log file (this way we are able to run awstats on individual domains, and get relatively accurate stats) So.. my question is- is there any way to do what I want ? Open a live log file, read lines to x bytes, (say 845673231 bytes) , make a note of this, and 10 miutes later open the same file again *AT* 845673232 bytes - starting with the next byte after the bookmarked point, read to end of file, and update the bookmark. Thanks for any pointers- Advice appreciated. Bri! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor -- Ing. Ewald Ertl HartterGruppe Phone : +43-3352-33085-558 trinomic Projektmanagement Informationstechnik GmbH Fax : +43-3352-33085-600 Wiener Straße 41mailto:[EMAIL PROTECTED] A-7400 Oberwart http://www.trinomic.com mailto:[EMAIL PROTECTED] ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How can I make Python Shell see new version offunctionsubroutine?
Why did I get this diagnostic? import factor30.py ImportError: No module named factor30.py The module name is factor30 no need for the .py, thats the file name. Two differemt things! Alan g. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor