[Tutor] Isolation of code
Greetings everyone, I'm working on a little project that's similar to tcltutor for python. I have a string which has some python code. I "compile" and "eval" this to get the output. So far so good. However, when this happens, the evaluation is happening in the current namespace so I'm afraid of symbols being redefined and messed up. What I want to do is to create a separate namespace for all the code so that I can execute it without worrying about symbol mangling. Something like if the code I have is code = """ x=5 if x==5: print "Yes" else: print "No" """ I'd like to be able to create a separate module called (say) "tester" with contents def __start_exec__(): then say something like import tester tester.__start_exec__() to actually run the code. This way, the namespace would be separate. Any idea how I can go about this? I'm guessing I should use the parser module to actually create the construct and then compile it but that looks little hairy. Is there something I'm missing? Any suggestions? Peace, -- -NI ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Isolation of code
Greetings everyone, I'm working on a little project that's similar to tcltutor for python. I have a string which has some python code. I "compile" and "eval" this to get the output. So far so good. However, when this happens, the evaluation is happening in the current namespace so I'm afraid of symbols being redefined and messed up. What I want to do is to create a separate namespace for all the code so that I can execute it without worrying about symbol mangling. Something like if the code I have is code = """ x=5 if x==5: print "Yes" else: print "No" """ I'd like to be able to create a separate module called (say) "tester" with contents def __start_exec__(): then say something like import tester tester.__start_exec__() to actually run the code. This way, the namespace would be separate. Any idea how I can go about this? I'm guessing I should use the parser module to actually create the construct and then compile it but that looks little hairy. Is there something I'm missing? Any suggestions? Peace, -- -NI ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Can my code be optimized any further (speed-wise)?
Thanks, thats a lot clearer. > a = the number of times i'm going to read input to evaluate > lst = the factors of 5. I.e. (5, 5^2, 5^3, 5^4 etc) until the > last one > wich is smaller then 10 OK, I had assumed it was a list of sample factorial results. Not reading it carefully enough. But a comment would have been good since its not self evident. > Example input of this program: > 5 #number of times i'm going to read > in a So a could be called iterations maybe? > number > 3 # 3! = 6, no trailing 0's zo the > output and b could be called factorial_number or similar? > would be 0 > 5 # 5! = 120, 1 trailing 0's so the > output > would be 1 > 50! #50!= , 12 > trailing 0's > (50/5 + 50/25=12) > 100!#100!= , 24 > trailing 0's > (100/5 + 100/25 = 24) > 125!#125!= , 31 > trailing 0's > (125/5 + 125/25 +125/125 = 31) > > Output would be: > 0 > 1 > 12 > 24 > 31 > > Hope this clarifies what i'm trying to achieve here... Yes, thats very clear now. I'll go back to the original post and reread the code. Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Variable help
I have a number of arrays: player1 = [data, data, data] player2 = [data, data, data] player3 = [data, data, data] player4 = [data, data, data] I want to be able to do something like: count = 2 if player + count[3] == 5: do this do that count += 1 And that would do this and that to the array 'player2' in slot 3. It adds 1 to 'count', so next time through it will access the array 'player3'. Basically I want to be able to integrate the value of one variable into another variables name. It's hard explain, hopefully the code above will give you an idea of what I'm trying to achieve. Alternately, how can I use the return of a function as a variables name? eg: def choose_player(player): if player == 1: return player1[3 if player == 2: return player2[3] if player == 3: return player3[3] if player == 4: return player4[3] choose_player(2) = 5 This was another way I thought of doing it - one that might actually work - but it comes back with "Can't assign to function call." I'm not trying to assign it to the function itself, but the outcome of the function. I can use it to read the value of the player2 variable (ie. if choose_player(2) == 5), but not set it. Once again, I hope I've given an idea of what I'm trying to do. Any way I can achieve this? ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Can my code be optimized any further (speed-wise)?
2006/10/7, Geoframer <[EMAIL PROTECTED]>: > Hi everyone, > > The last few days i've been learning python and have been doing this by > trying to solve problems for a programming competition. > One particular problem is bugging me. I have already solved it but my > solution does not compute in the set time-condition. I know > for a fact that this particular problem is solvable in the time-limit using > Python, so i was wondering if my solution is maybe inefficitient code-wise. > If my code can't be optimized for speed any more i must be missing something > and should labor hard to find a new algorithm ;-). > > The problem is to compute the number of trailing zero's in factorials (n! = > 1*2*3*4*...*n). with n <= 10 > > My solution is as follows (a = times to read a number (b) to process) : > > --- > > a = input() > for i in range(a): > lst = (5, 25, 125, 625, 3125, 15625, 78125, 390625, 1953125, 9765625, > 48828125, 244140625) > ans = 0 > b = input() > for i in lst: > if i <= b: > ans += b//i > print ans > > > > Please, if you have suggestions to improve the speed of this algorithm give > an argumentation as to why a certain something is faster. > That would allow me to learn to program faster algorithms in Python al > together instead of just in this problem. The program as you have shown it, skims to incorrectness. Please don't use the same variable (i) for two nested loops! Regarding speed, I see some small improvements: * lst is created each time you go through the loop; creating it once would suffice as well * If we have found that some i is larger than b, then definitely the next one will be a = input() lst = (5, 25, 125, 625, 3125, 15625, 78125, 390625, 1953125, 9765625, 48828125, 244140625) for i in range(a): ans = 0 b = input() for j in lst: if j <= b: ans += b//i else: break print ans The first thing (moving the lst= out of the loop) will definitely make a (tiny) improvement on speed; it also improves the logic of your code. The second (the else: break) I am not sure whether it will improve things (because often you will go into the else at the last time or not at all). Your program goes wrong for large values of b. This should be avoided - the program should have as little chance as possible for the user to give 'wrong' input, either by forbidding it or by dealing with it. Here the latter is easily done: The way I would do this (although it would make the program slower rather than faster because it would make the check each time that b is set: replace lst = (5, 25, 125, 625, 3125, 15625, 78125, 390625, 1953125, 9765625, 48828125, 244140625) by lst = [5] and after b=input() add: while lst[-1]*5 < b: lst.append(lst[-1]*5) And finally I wonder why on Earth you would worry about the speed of this program, given that the running time over 1 number is just a fraction of the time it costs you to type in that number. -- Andre Engels, [EMAIL PROTECTED] ICQ: 6260644 -- Skype: a_engels ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Variable help
Tom R. escribió: > I have a number of arrays: > > player1 = [data, data, data] > player2 = [data, data, data] > player3 = [data, data, data] > player4 = [data, data, data] > > I want to be able to do something like: > > count = 2 > if player + count[3] == 5: >do this >do that > count += 1 > > And that would do this and that to the array 'player2' in slot 3. It adds 1 > to 'count', so next time through it will access the array 'player3'. > Basically I want to be able to integrate the value of one variable into > another variables name. It's hard explain, hopefully the code above will > give you an idea of what I'm trying to achieve. > Put the players in a list. player_list = [player1, player2, player3... ] So if you want to get to player1 data, you use player_list[0][0...2], which would be the same as player1[0...2]. If you then want to do something to every player, you could do: for player in player_list: do something > Alternately, how can I use the return of a function as a variables name? eg: > > def choose_player(player): > if player == 1: > return player1[3 > if player == 2: > return player2[3] > if player == 3: > return player3[3] > if player == 4: > return player4[3] > > choose_player(2) = 5 > > Functions return values. To keep the return value, you simply have to assign it to a variable: result = choose_player(3) And then you can do whatever you want with result. Bear in mind that result and player3[3] are *not* the same thing, they only have the same value. HTH! Ismael ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Can my code be optimized any further (speed-wise)?
Geoframer wrote: > Hi everyone, > > The problem is to compute the number of trailing zero's in factorials > (n! = 1*2*3*4*...*n). with n <= 10 > > My solution is as follows (a = times to read a number (b) to process) : > > --- > > a = input() > for i in range(a): > lst = (5, 25, 125, 625, 3125, 15625, 78125, 390625, 1953125, > 9765625, 48828125, 244140625) > ans = 0 > b = input() > for i in lst: > if i <= b: > ans += b//i > print ans > > > > Please, if you have suggestions to improve the speed of this algorithm > give an argumentation as to why a certain something is faster. > That would allow me to learn to program faster algorithms in Python al > together instead of just in this problem. Try putting the actual computation into a function. Make any variable that is used more than once a local variable of the function (ans, b,i). Accessing local variables is faster than accessing global variables. This gives about 40% speedup in my tests. Use psyco if it is available in your contest, for me that shaved off another 30-50%; you will get more benefit from psyco the more iterations you have, because psyco introduces some compilation overhead that has to be made up by the faster code. http://psyco.sourceforge.net/ You really aren't doing much so there's not a lot to optimize that I can see. You could try asking on comp.lang.python, lots of people there are good at optimization. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python, wxPython a databázová aplik ace
Sorry for this mail, was sent by error. Pavel Kosina superman napsal(a): > Dobrý den, > > mohli byste mě nějak nakopnout v tom, jak se dělá databázová aplikace v > Pythonu s použitím wxPython? Respektive jestli wxPython má nějaké prvky, > které slouží přímo pro práci s databázemi, a nebo jestli je potřeba to > udělat ručně a všechno si ošetřit sám. > > nevím > Už jsem se do toho pustil, nakreslil jsem si i volič záznamů jako je v > MS Accessu, chtěl jsem použít nějaký grid a sázet so něj data, ale došlo > mi, že zatím každé prostředí mělo něco, čím to ulehčit. Prostě nějaké > grafické prvky stylu "grid napojený na databázi", nebo "textedit > napojený na databázi", apod.. Pak by bylo škoda to dělat ručně. > neznám > Případně zda takové prvky někdo už nenaprogramoval jako nadstavbu nad > něco existujícího. Pak prosím ať to proboha není GPL, nechci tuto > licenci. Tím vylyčuji předem i cokoli s PyQt. > hehe, to mě pobavilo. A jakou bys rád? Nějakou komerční? LGPL by šla? Myslím že vyloučením GPL vyřazuješ většinu žhavých kandidátů, pokud tedy nějací jsou :-) Příště pls vytvoř s novým tématem nový mail, at se to neřadí někam do nepatřičného místa stromu příspěvků, jako teď. -- geon Pavel Kosina ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python, wxPython a databázová aplik ace
superman napsal(a): > Dobrý den, > > mohli byste mě nějak nakopnout v tom, jak se dělá databázová aplikace v > Pythonu s použitím wxPython? Respektive jestli wxPython má nějaké prvky, > které slouží přímo pro práci s databázemi, a nebo jestli je potřeba to > udělat ručně a všechno si ošetřit sám. > > nevím > Už jsem se do toho pustil, nakreslil jsem si i volič záznamů jako je v > MS Accessu, chtěl jsem použít nějaký grid a sázet so něj data, ale došlo > mi, že zatím každé prostředí mělo něco, čím to ulehčit. Prostě nějaké > grafické prvky stylu "grid napojený na databázi", nebo "textedit > napojený na databázi", apod.. Pak by bylo škoda to dělat ručně. > neznám > Případně zda takové prvky někdo už nenaprogramoval jako nadstavbu nad > něco existujícího. Pak prosím ať to proboha není GPL, nechci tuto > licenci. Tím vylyčuji předem i cokoli s PyQt. > hehe, to mě pobavilo. A jakou bys rád? Nějakou komerční? LGPL by šla? Myslím že vyloučením GPL vyřazuješ většinu žhavých kandidátů, pokud tedy nějací jsou :-) Příště pls vytvoř s novým tématem nový mail, at se to neřadí někam do nepatřičného místa stromu příspěvků, jako teď. -- geon Pavel Kosina ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Tkinter and python
first off i just started looking for Tkinter tutorials but havent found much and what i have found was not very good if anyone knows og any Tkinter tutorials pleas let me know second is thair anyway to change the path that python looks for a program in ex: if i enter python hello into the command line then i get this error /Library/Frameworks/Python.framework/Versions/2.4/Resources/Python.app/Contents/MacOS/Python: can't open file 'hello1': [Errno 2] No such file or directory can i chage that search path? if so how? thx ^_^" s33 y4 _ SearchYour way, your world, right now! http://imagine-windowslive.com/minisites/searchlaunch/?locale=en-us&FORM=WLMTAG ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Tkinter and python
Hi,You can try:>> import sys>> sys.path.append('')>> import Or else you can append the path to global PYTHONPATH environment variable and whenever you will type: python on the command prompt/bash shell the script gets executed.Hope that helps.Thanks,- Arun On 10/8/06, max . <[EMAIL PROTECTED]> wrote: first off i just started looking for Tkinter tutorials but havent found muchand what i have found was not very good if anyone knows og any Tkintertutorials pleas let me knowsecond is thair anyway to change the path that python looks for a program in ex: if i enter python hello into the command line then i get this error/Library/Frameworks/Python.framework/Versions/2.4/Resources/Python.app/Contents/MacOS/Python:can't open file 'hello1': [Errno 2] No such file or directory can i chage that search path?if so how?thx^_^" s33 y4_Search—Your way, your world, right now! http://imagine-windowslive.com/minisites/searchlaunch/?locale=en-us&FORM=WLMTAG___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] Tkinter and python
max . wrote: > first off i just started looking for Tkinter tutorials but havent found > much and what i have found was not very good if anyone knows og any > Tkinter tutorials pleas let me know Try this for a good tutorial http://www.pythonware.com/library/tkinter/introduction/ Peace. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Isolation of code
On Sun, Oct 08, 2006 at 12:36:32PM +0530, Noufal Ibrahim wrote: > Greetings everyone, >I'm working on a little project that's similar to tcltutor for python. > I have a string which has some python code. I "compile" and "eval" this > to get the output. So far so good. However, when this happens, the > evaluation is happening in the current namespace so I'm afraid of > symbols being redefined and messed up. >What I want to do is to create a separate namespace for all the code so > that I can execute it without worrying about symbol mangling. > >Something like if the code I have is > code = """ > x=5 > if x==5: > print "Yes" > else: > print "No" > """ > > I'd like to be able to create a separate module called (say) "tester" > with contents > > def __start_exec__(): > > > then say something like > import tester > tester.__start_exec__() > > to actually run the code. This way, the namespace would be separate. > Two points: 1. (Stating something obvious) Code in a module, when called, does run in a separate namespace. For example, if I run: import modB modB.f() then any variables set in modB are local to modB. 2. If that separation of namespaces is not "strong" enough for you, try something like the following: exec somecode in globalDict where globalDict is a dictionary. globalDict will be the namespace used by somecode, and, for example, variables created (perhaps using assignment) in somecode will be created in globalDict rather than in the current namespace. See: http://docs.python.org/ref/exec.html. Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Tkinter and python
On Sun, Oct 08, 2006 at 08:36:31PM +0530, Arun Kumar PG wrote: > Hi, > > You can try: > > >>import sys > >>sys.path.append('') > >>import > > Or else you can append the path to global PYTHONPATH environment variable > and whenever you will type: > > python on the command prompt/bash shell the script gets > executed. > Not true, if I understand you correctly. PYTHONPATH affects where Python looks for modules to be imported. But if I type the following at the command line: $ python mymodule.py it is the shell (in my case bash) that looks for mymodule.py, not Python. It analogous to my typing: $ vi mymodule.py or (trying to avoid a fight between vi and emacs fanatics): $ emacs mymodule.py Neither vi nor emacs try to find mymodule.py; the (bash or other) shell does. So perhaps a solution to the problem is to make mymodule.py executable and put it somewhere on your path. Then execute it by typing at the command line: $ mymodule.py Now the shell will run it just like any other executable script and it will use Python as the interpreter for that script. How you make the script executable probably depends on which shell you are using. For bash, you could do the following: 1. Insert the following line as the first line of your script: #!/usr/bin/env python 2. Change the priveleges of the script to make it executable. Example: $ chmod u+x mymodule.py 3. Put mymodule.py on your path, that is, in a directory that is in your PATH environment variable. Alternatively, add the path to the directory containing mymodule.py to your PATH environment variable. Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Can my code be optimized any further (speed-wise)?
> You really aren't doing much so there's not a lot to optimize that I can > see. You could try asking on comp.lang.python, lots of people there are > good at optimization. ** spoiler space: don't read ahead here unless you've attempted this problem already, or if you don't want to be spoiled ** You may be able to treat this as a combinatorial problem: how many ways can you get a factor of 10 from the product of all those numbers? Every factor of ten contributes to a trailing zero, so if we can count those, we're done. Concretely: if we're computing 10! factorial, imgaine we have the numbers 1-10 in front of us. 1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 Next, we'll do something a little funny: we break up everything into its prime factors: 1 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 3 * 3 * 3 * 3 * 5 * 5 * 7 Chop chop. Then we know that we're going to get a trailing zero when we multiply with the first five: 2 * 5 and we also get a trailing zero when we multiply with the other five: 2 * 5 Even without computing the factorial, we know there's going to be two trailing zeros in 10!, because there's only two ways of making tens. The key is to see that factors of five can be combined with the overabundance of twos that we have: that's how we can get tens. And those tens are going to contribute to trailing zeros in the final product. There are some complications, because some numbers produce more than one factor of five (like 25, for example...), but they can be handled with a little thought. As a reference point: because you're explicitely given the upper bounds on this assignment, this problem should be solvable in constant time, with a single math formula. Good luck. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Shell Output Format - [was: Is there Python code for accessing an object's reference count?]
Kent Johnson wrote: ... > In [2]: sys.getrefcount(100) > Out[2]: 43 > > In [3]: def foo(): > ...: return 100 > ...: > > In [4]: sys.getrefcount(100) > Out[4]: 44 off-topic: how to you get this output format of the shell? In [2]: Out[2]: I've tried to alter IDLE: IDLE - Customizing output format http://groups.google.com/group/comp.lang.python/browse_frm/thread/b81ef0c0b134def2 . -- http://lazaridis.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Can my code be optimized any further (speed-wise)?
I've had a look at the other comments, particularly Kents, but I'll add a few more comments: > One particular problem is bugging me. I have already solved it but > my > solution does not compute in the set time-condition. How can you tell since you pause for user input in the middle of the loop? The time to enter the data will be more than the time doing the calculation in most cases. You will need to move the extraneous stuff outsidethe loop to have any h0pe of timing sensibly. Something like this: iterations = input('How many factorials? ') facs = [input('Type a required factorial: ') for n in range(iterations)] factors = (5, 25, 125, 625, 3125, 15625, 78125, 390625, 1953125, 9765625, 48828125, 244140625) # start timing here for i in range(iterations): num = facs[i] print sum([num//f for f in factors if f<= num]) # end timing Now you have something you can time. I'm assuming that the sum/list comprehension will be faster than the explicit loop/add/break combination that Kent suggested for the low number of factors involved, but I haven't tried it... Its based on the theory that it maximises the time in C code as opposed to native Python... Alan G. PS. In looking at this I wondered whether an extension to list comprehension syntax would be a good idea. Namely to add a while condition at the end to limit the number of iterations: In this case the LC would become: [num//f for f in factors while f <= num]) It could even be combined with the conditional form I think: [num//f for f in factors if f == 7 while f <= num]) Just a thought... > My solution is as follows (a = times to read a number (b) to > process) : > > --- > > a = input() > for i in range(a): >lst = (5, 25, 125, 625, 3125, 15625, 78125, 390625, 1953125, > 9765625, > 48828125, 244140625) >ans = 0 >b = input() >for i in lst: >if i <= b: >ans += b//i >print ans > > > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Shell Output Format - [was: Is there Python code for accessing an object's reference count?]
Ilias Lazaridis wrote: > how to you get this output format of the shell? > > In [2]: > Out[2]: IPython http://ipython.scipy.org/ Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Variable help
On Sun, 2006-10-08 at 10:40 -0300, Ismael Garrido wrote: > Tom R. escribió: > > I have a number of arrays: > > > > player1 = [data, data, data] > > player2 = [data, data, data] > > player3 = [data, data, data] > > player4 = [data, data, data] > > > > I want to be able to do something like: > > > > count = 2 > > if player + count[3] == 5: > >do this > >do that > > count += 1 > > > > And that would do this and that to the array 'player2' in slot 3. It adds 1 > > to 'count', so next time through it will access the array 'player3'. > > Basically I want to be able to integrate the value of one variable into > > another variables name. It's hard explain, hopefully the code above will > > give you an idea of what I'm trying to achieve. > > > Put the players in a list. > player_list = [player1, player2, player3... ] > So if you want to get to player1 data, you use player_list[0][0...2], > which would be the same as player1[0...2]. > > If you then want to do something to every player, you could do: > > for player in player_list: > do something > > > > Alternately, how can I use the return of a function as a variables name? eg: > > > > def choose_player(player): > > if player == 1: > > return player1[3 > > if player == 2: > > return player2[3] > > if player == 3: > > return player3[3] > > if player == 4: > > return player4[3] > > > > choose_player(2) = 5 > > > > > Functions return values. To keep the return value, you simply have to > assign it to a variable: > > result = choose_player(3) > > And then you can do whatever you want with result. Bear in mind that > result and player3[3] are *not* the same thing, they only have the same > value. (let me offer a correction to that last sentence.) result = player3[3] # player3 must contain at least 4 values result and player3[3] *do* reference the same thing. My preferred analogy is that names in Python are written on sticky notes and stuck on the objects they refer to. The name and the object are separate and distinct. So we take a sticky note labeled result and stick it on the *same* object that player3[3] refers to. If that object is immutable, then it can't be changed and you can only bind result or that position in the player3 list to different things. Both bindings are independent. HOWEVER, both start off referring (bound) to the same thing. If we have a succeeding line that says: result = 4 The "result sticky note" is peeled off the original object and stuck onto the the "4 object". player3[3] is not affected. This distinction between value and object reference becomes important when the object is mutable. Then lines like: result.sort() result.append('new stuff') affect player3[3] because both are actually bound to the same object. > > > HTH! > Ismael > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Can my code be optimized any further (speed-wise)?
[Geoframer] > The last few days i've been learning python and have been doing this by > trying to solve problems for a programming competition. I assume you're talking about: http://www.spoj.pl/problems/FCTRL/ If so, you'll note that I'm tied for the fastest Python solution there ;-) The /guts/ of my method is just: # count <- number of trailing zeroes in n! count = 0 base = 5 while n >= base: count += n // base base *= 5 There are several reasons for why that's faster than what you tried, which have been explained by others (doesn't create a list of divisors each time; gets out of the loop as soon as there's no point to continuing). It's /possible/ that it would be faster if you did keep a canned list of powers of 5. But for some of the SPOJ problems (like this one ;-)), that's not the real thing to worry about! Some have very large input sets, and the time spent doing I/O, and converting between strings and integers, swamps the time needed to do calculations. So, for example, in this problem I didn't read one line at a time. Instead I did: def main(): import sys ncases = int(sys.stdin.readline()) all = map(int, sys.stdin.read().split()) assert ncases == len(all) for n in z(all): print n The important part there is sucking in all of the test cases "in one gulp", and converting to them /all/ to integers with a /single/ fast map() call. The z() function is basically what I wrote above, containing a loop to march over all the inputs. It's also important for peak speed to use functions so that faster local-variable lookups can be used instead of slower global-variable lookups. But those aren't the most important parts either ;-) When it comes to speed, it's rarely what you think it is. Using the input() function was almost certainly your primary problem, because input() endures the relatively enormous expense of /compiling/ the input string as a fully general Python expression, generating a code object for that expression, interpreting that dynamically generated Python code, and then tearing down the code object again. For every input. It's not the slowest possible way to convert a string to an integer, but you'd have to work hard to find a slower way ;-) Just for fun, you might want to try /just/ changing: b = input() in your program to b = int(raw_input()) I don't know whether you'll meet the time limit then, but it will run much faster. Finally, if you look at the 20 accepted Python solutions: http://www.spoj.pl/ranks/FCTRL/lang=PYTH you'll see that the top 5 all used enormously more memory than the other 15. That's an almost-certain sign that they used psyco (which the SPOJ folks have installed), like so: # the rest of the code goes here import psyco psyco.full() if __name__ == "__main__": main() Note that psyco doesn't always help -- sometimes it makes a program slower. As the 15 other accepted Python solutions show, it's not necessary to use psyco to meet the time limit for this problem. If I could, I'd retract my run using psyco and settle for a non-psyco run -- I couldn't care less about being "the fastest" on these, and just /tried/ psyco here out of professional curiousity. Alas, SPOJ only remembers the fastest correct run you submit. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Variable help
Tom R. wrote: > Alternately, how can I use the return of a function as a variables name? eg: > > def choose_player(player): > if player == 1: > return player1[3 > if player == 2: > return player2[3] > if player == 3: > return player3[3] > if player == 4: > return player4[3] > > choose_player(2) = 5 You actually can do this very easily by returning the correct playerx list: def choose_player(player): if player == 1: return player1 if player == 2: return player2 if player == 3: return player3 if player == 4: return player4 then the result of choose_player() is a list that you can index normally: choose_player(2)[3] = 5 This actually looks a lot like the solution with a list of player lists, where you would write players[2][3] = 5 I recommend the list-of-lists solution, but I thought it was worth noting that the function version is easy to write. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Can my code be optimized any further (speed-wise)?
Thanks everyone for the valuable suggestions. Lots of suggestions which i'm sure will improve the speed and performance of my solution. It is indeed the problem Tim said, and it helps a lot to get some help from one of the fastest people on there ;-). I just find it's more fun (and probably more productive) to learn by trying as well as reading. I'm sure i'll be able to solve some other problems with the suggestions here as i've run into the timelimit more often already. Next time i'll try to be more clear on what my problem is and how it is supposed to achieved! (The input was all streamed into the program automatically there was no manual input. I just used the input() function because i didn't have a clue yet how else to read in an integer ;-) ) Besides doing these little excersises i'm reading :O'reilly's - 'Learning Python'and 'Dive into python' (www.diveintopython.org).So i'm hoping i can soon help people the way you guys helped me ;-) Once again thanks everyone for their suggestions and time!!!Regards - GeoframerOn 10/8/06, Tim Peters < [EMAIL PROTECTED]> wrote:[Geoframer]> The last few days i've been learning python and have been doing this by > trying to solve problems for a programming competition.I assume you're talking about:http://www.spoj.pl/problems/FCTRL/If so, you'll note that I'm tied for the fastest Python solution there ;-) The /guts/ of my method is just:# count <- number of trailing zeroes in n!count = 0base = 5while n >= base:count += n // basebase *= 5 There are several reasons for why that's faster than what you tried,which have been explained by others (doesn't create a list of divisorseach time; gets out of the loop as soon as there's no point tocontinuing). It's /possible/ that it would be faster if you did keep a canned list of powers of 5.But for some of the SPOJ problems (like this one ;-)), that's not thereal thing to worry about! Some have very large input sets, and thetime spent doing I/O, and converting between strings and integers, swamps the time needed to do calculations.So, for example, in this problem I didn't read one line at a time.Instead I did:def main():import sysncases = int(sys.stdin.readline()) all = map(int, sys.stdin.read().split())assert ncases == len(all)for n in z(all):print nThe important part there is sucking in all of the test cases "in onegulp", and converting to them /all/ to integers with a /single/ fast map() call. The z() function is basically what I wrote above,containing a loop to march over all the inputs. It's also importantfor peak speed to use functions so that faster local-variable lookupscan be used instead of slower global-variable lookups. But those aren't the most important parts either ;-) When it comes tospeed, it's rarely what you think it is.Using the input() function was almost certainly your primary problem,because input() endures the relatively enormous expense of /compiling/ the input string as a fully general Python _expression_, generating acode object for that _expression_, interpreting that dynamicallygenerated Python code, and then tearing down the code object again.For every input. It's not the slowest possible way to convert a string to an integer, but you'd have to work hard to find a slower way;-)Just for fun, you might want to try /just/ changing:b = input()in your program tob = int(raw_input()) I don't know whether you'll meet the time limit then, but it will runmuch faster.Finally, if you look at the 20 accepted Python solutions: http://www.spoj.pl/ranks/FCTRL/lang=PYTHyou'll see that the top 5 all used enormously more memory than theother 15. That's an almost-certain sign that they used psyco (whichthe SPOJ folks have installed), like so: # the rest of the code goes hereimport psycopsyco.full()if __name__ == "__main__":main()Note that psyco doesn't always help -- sometimes it makes a program slower. As the 15 other accepted Python solutions show, it's not necessary touse psyco to meet the time limit for this problem. If I could, I'dretract my run using psyco and settle for a non-psyco run -- Icouldn't care less about being "the fastest" on these, and just /tried/ psyco here out of professional curiousity. Alas, SPOJ onlyremembers the fastest correct run you submit. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Fw: pretty_printing
Forwarding to the list for interests sake, mainly for vim users. - Original Message - From: "LandSurveyor" <[EMAIL PROTECTED]> Sent: Monday, October 09, 2006 12:00 AM Subject: Re: pretty_printing > This issue has been solved! in a big way!! > (I hope I'm doing this right, replying to your email this way...I'm > new to this. Hope this makes its' way to the 'big screen') > > The entire issue [that I raised] regarding printing scripts with the > same syntax highlighting with which they were displayed in the Vim > editor turn out to be a Vim issue, and Vim solves it in an elegant, > rich way. By using the command, > > ":hardcopy" > > (from within the Vim editor) a printout of the current file [being > edited] is produced, with very rich colors, faithful to the > displayed syntax colors. Two companion :help 'modules' provide a > smorgasbord of options to apply to the desired hardcopy. They are: > > ":printoptions", and > ":printfont" > > Ask for ":help" with either of the two options listed above, and a > very clear and detailed file is offered in each case, from which to > draw examples and/or specific coding types. > > -Original Message- >>From: Alan Gauld <[EMAIL PROTECTED]> >>Sent: Sep 3, 2006 7:03 PM >>To: "Lowell H. Tackett" <[EMAIL PROTECTED]> >>Subject: Re: pretty_printing >> >>> It had occured to me that the root of my lack of success is simply >>> that file >>> XYZ.py sits on my HD as a simple string of X's and O's, not as a >>> pretty, >>> colorful text repository. Only thru the magic of say, Vim, is the >>> display >>> converted to meaningful hues. Therefor, Vim somehow knows how to >>> detect each >>> of the discrete syntax types: comments, quotes, reserved words, >>> etc., and to >>> apply an appropriate color into its' display. >> >>No magic, the patterns are defined in the .vim files in the >>syntax >>folder. >>Each one defines a keyword/style and the regex that defines the >>terms. >> >>> It occured to me that it ought to be very simple to gain access to >>> those >>> syntax discrimnators, write a code script that creates a 'dye' for >>> each >>> syntax type, and pipe a print request thru such a file. >> >>Yes, not impossible, but not trivial either. >>The simplest way to generate the printed output is probably to >>create an intermediate html file and print that via a browser >>- possibly using the python browser module... >> >>Alan Gauld >>Author of the Learn to Program web site >>http://www.freenetpages.co.uk/hp/alan.gauld >> > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] embedding python
hello i have a myspace and a blog both of wich allow me to input html and i know a little html not much i can make a page with backround coler a title words and pictures as well as links but i cant find any tutorials on embedding python useing html i found some that use c++ and i think one that used asp if anyone knows how or knows of a tutorial that would be great ^_^" s33 y4 _ Share your special moments by uploading 500 photos per month to Windows Live Spaces http://clk.atdmt.com/MSN/go/msnnkwsp007001msn/direct/01/?href=http://www.get.live.com/spaces/features ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] embedding python
max . wrote: > hello i have a myspace and a blog both of wich allow me to input html and i > know a little html not much i can make a page with backround coler a title > words and pictures as well as links > > but i cant find any tutorials on embedding python useing html i found some > that use c++ and i think one that used asp > > if anyone knows how or knows of a tutorial that would be great > > > your http server has to be capable of running python code examples of hosts that aren't: myspace other blog sites :) > ^_^" s33 y4 > > _ > Share your special moments by uploading 500 photos per month to Windows Live > Spaces > http://clk.atdmt.com/MSN/go/msnnkwsp007001msn/direct/01/?href=http://www.get.live.com/spaces/features > > ___ > 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] Tkinter and python
> python on the command prompt/bash shell the script gets> executed.Hey Dave,Thanks for correcting me. I should read what I am writing before I hit the send button :). It was a stupid mistake.. Appending path to PYTHONPATH will allow us to import the module in some other Python script without requiring us to do sys.path.apend(). To execute the script from bash what Dave suggests is correct.Also, if you don't want to append path to PYTHONPATH you can also place the module under site-packages directory under Python home directory. Thanks,- AOn 10/8/06, Dave Kuhlman <[EMAIL PROTECTED]> wrote: On Sun, Oct 08, 2006 at 08:36:31PM +0530, Arun Kumar PG wrote:> Hi,>> You can try:>> >>import sys> >>sys.path.append('')> >>import < module.py>>> Or else you can append the path to global PYTHONPATH environment variable> and whenever you will type:>> python on the command prompt/bash shell the script gets > executed.>Not true, if I understand you correctly. PYTHONPATH affects wherePython looks for modules to be imported. But if I type thefollowing at the command line:$ python mymodule.py it is the shell (in my case bash) that looks for mymodule.py, notPython. It analogous to my typing:$ vi mymodule.pyor (trying to avoid a fight between vi and emacs fanatics):$ emacs mymodule.pyNeither vi nor emacs try to find mymodule.py; the (bash or other)shell does.So perhaps a solution to the problem is to make mymodule.pyexecutable and put it somewhere on your path. Then execute it by typing at the command line:$ mymodule.pyNow the shell will run it just like any other executable script andit will use Python as the interpreter for that script.How you make the script executable probably depends on which shell you are using. For bash, you could do the following:1. Insert the following line as the first line of your script: #!/usr/bin/env python2. Change the priveleges of the script to make it executable. Example: $ chmod u+x mymodule.py3. Put mymodule.py on your path, that is, in a directory that is in your PATH environment variable. Alternatively, add the path to the directory containing mymodule.py to your PATH environment variable.Dave--Dave Kuhlmanhttp://www.rexx.com/~dkuhlman___ 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] byte[] array
gert wohlgemuth wrote: > As anybody an idea how I can do this in python? I can think of three ways: Strings in Python can contain arbitrary binary values, so they can be used. If they're going to be modified often, you may use a list, or you may use the array module for performance. Are you sure you cannot use any already written module? Are you getting data from the http protocol? are you using XML-RPC or something like this? Hugo ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] question about looping.
Doug Potter wrote: > for i in routers: > os.system('/bin/touch' %s) % i > > of course this dosn't work. > > Is there a simple way to get this done? Yep, someone already answered that you can create the file in write mode and then close it, but I wanted to add a little more in why your solution doesn't work. You're not interpolating the filename INTO the os.system string The following would work for i in routers: os.system('/bin/touch %s'%1) Granted, you should also provide a filename with a full path for simplicity. HTH Hugo ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor