[Tutor] Can my code be optimized any further (speed-wise)?
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 <= 10My 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 ansPlease, 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.Kind regards - GeoframP.s. I know python is probably not the best language for these kinds of problems (I can code it in C or C++), it just bugs me that it's possible and my solution is failing... ;-) ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] error help
The main problem from what i can tell is that the number of '(' and ')' you use in declarations (and maybe even functions) are not correct.Take for instance :u0prime = beta*(sqrt(d**2 +(h +length1)**2) - h +length1)) You open 3 '(' and close 4 ')' .The problem is not the little test code at the end (as you illustrated yourself by moving it up and getting a different error).The "Token Error: EOF in multi-line statement" usually means you made an error using too many or too little ()'s. I suggest carefully re-examining your code and check if everything is entered correctly using the right amount of ()'s ;-)Hope this helps some.Ciao - GeoframOn 10/7/06, Chris Smith <[EMAIL PROTECTED]> wrote: I'm writing a numerical program for an assignment at school. So the codeof my program isn't too long I've coded the formulas, which are ratherlong, as funcions. However when I try to run my program I keep getting one of two errors. The first happens when I do a test run of my codewith the test portion of the code at the bottom. It keeps popping up anerror message that says that my import statement is spaced incorrectly. It's not supposed to be indented at all and I can't figure out why it'spopping up at all. If I try moving the test portion of the code up tothe top it gives me "Token Error: EOF in multi-line statement". I don't understand this one because I try to have the last line be the one withthe return statement of my last function and when the error happens itadds a line to my code and the error pops up.Can anyone tell me why I'm having these error or what I can do to get around them?Chris Smith#Functions for Numerical Program#--### The sine and cosine integrals are taken from Abramowitz and Stegun.### Only use the first 6 terms of the summation in the sine and cosine ### integrals.def Si(x):sine_integral = x - x**3/18. + x**5/600. - x**7/35280. \+ x**9/3265920. + x**11/439084800.return sine_integraldef Ci(x):# Euler's constant Euler_const = 0.5772156649cosine_integral = Euler_const + log(x) - x**2/4. + x**4/96. \ - x**6/4320. + x**8/322560. + x**10/36288000return cosine_integraldef Mutual_impedance(length1, length2, stagger, d): """Mutual impedance formulas for Parallel in Echelon ConfigurationThe formulas are taken from a paper by Howard King, "Mutual Impedanceof Unequal Length Antennas in Echelon" NOTE: all measurements should be entered in wavelengths"""# stagger (this is the vertical separation between antenna centers)# d (this is the horizontal separation between the antennas) # length1 and length2 (this is the half length of the antennas)# vertical separation between center of antenna 1 and bottom of antenna 2h = stagger - length2# wave propagation constant and eta beta = 2*pi# formulas to put into mutual impedance equationu0 = beta*(sqrt(d**2 +(h -length1)**2) +(h -length1))v0 = beta*(sqrt(d**2 +(h -length1)**2) -(h -length1))u0prime = beta*(sqrt(d**2 +(h +length1)**2) - h +length1)) v0prime = beta*(sqrt(d**2 +(h +length1)**2) +(h +length1))u1 = beta*(sqrt(d**2 +(h -length1 +length2)**2) +(h -length1 +length2))v1 = beta*(sqrt(d**2 +(h -length1 +length2)**2) - h -length1 +length2)) u2 = beta*(sqrt(d**2 +(h +length1 +length2)**2) -(h +length1 +length2))v2 = beta*(sqrt(d**2 +(h +length1 +length2)**2) +(h +length1 +length2))u3 = beta*(sqrt(d**2 +(h -length1 +2*length2)**2) +(h -length1 +2*length2)) v3 = beta*(sqrt(d**2 +(h -length1 +2*length2)**2) -(h -length1 +2*length2))u4 = beta*(sqrt(d**2 +(h +length1 +2*length2)**2) -(h +length1 +2*length2))v4 = beta*(sqrt(d**2 +(h +length1 +2*length2)**2) +(h +length1 +2*length2)) w1 = beta*(sqrt(d**2 +h**2) -h)y1 = beta*(sqrt(d**2 +h**2) +h)w2 = beta*(sqrt(d**2 +(h +length2)**2) -(h +length2))y2 = beta*(sqrt(d**2 +(h +length2)**2) +(h +length2)) w3 = beta*(sqrt(d**2 +(h +2*length2)**2) -(h +2*length2))y3 = beta*(sqrt(d**2 +(h +2*length2)**2) +(h +2*length2))R12 = 15*(cos(beta*(length1 - h))*(Ci(u0) +Ci(v0) -Ci(u1) -Ci(v1)) \ +sin(beta*(length1 - h))*(-Si(u0) +Si(v0) +Si(u1) -Si(v1)) \ +cos(beta*(length1 + h))*(Ci(u0prime) +Ci(v0prime) -Ci(u2) -Ci(v2)) \ +sin(beta*(length1 +h))*(-Si(u0prime) +Si(v0prime) +Si(u2) -Si(v2)) \ +cos(beta*(length1 -2*length2 -h))*(-Ci(u1) -Ci(v1) +Ci(u3) +Ci(v3)) \ +sin(beta*(length1 -2*length2 -h))*(Si(u1) -Si(v1) -Si(u3) +Si(v3)) \ +cos(beta*(length1 +2*length2 +h))*(-Ci(u2) -Ci(v2) +Ci(u4) +Ci(v4)) \ +sin(beta*(length1 +2*length2 +h))*(Si(u2) -Si(v2) -Si(u4) +Si(v4)) \ +2*cos(beta*length1)*cos(beta*h)*(-Ci(w1) -Ci(y1) +Ci(w2) +Ci(y2)) \ +2*cos(beta*length1)*sin(beta*h)*(Si(w1) -Si(y1) -Si(w2) +Si(y2))
Re: [Tutor] Can my code be optimized any further (speed-wise)?
The problem is that these assignments are evaluated automatically. So i can not use description strings to clearify output or input etc. Basically it's like this: 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 For those that didn't know the number of trailing zero's in a factorial is decided by the numer of factors of 5, because only a 5 can create a 0. Remember a factorial (n) = n**4*3*2*1. The list does not represent factorials. Example input of this program: 5 #number of times i'm going to read in a number 3 # 3! = 6, no trailing 0's zo the output 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... Ciao - Geofram On 10/8/06, Alan Gauld <[EMAIL PROTECTED]> wrote: Hi,Maybe its just me but I didn't understand what you aretrying to do...> 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()what does a represent? Its usually worth putting a prompt string intoinput() - and raw_input() - just as documentation if nothing else!And maybe a descriptive variable name if appropriate. > for i in range(a):>lst = (5, 25, 125, 625, 3125, 15625, 78125, 390625, 1953125,> 9765625,> 48828125, 244140625)None of these have any trailing zeros so far as I can tell?What answer are you expecting from this function? >ans = 0>b = input()similarly, what is b supposed to be?>for i in lst:And here you are throwing away the i from the outer loop>if i <= b:>ans += b//i And now you divide some arbitrary input value by each factorialin turn and sum the results?>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.I nbeed to understand what you are tryying to do first, itsnot making much sense at the moment. (But it is after midnight! :-)> P.s. I know python is probably not the best language for these kinds > of> problems (I can code it in C or C++), it just bugs me that it's> possible> and my solution is failing... ;-)Actually it looks like exactly what I would use Python for rarther than C/C++. The speed issue can be solved in numerous ways butas always lets be sure we get the functionality clear before startingto optimise things.Alan G.___ Tutor maillist - Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Can my code be optimized any further (speed-wise)?
Erm i made a typo Sample input should ofcourse be without the '!''s So input = 5 3 5 50 100 125 Sorry - Geoframer On 10/8/06, Geoframer <[EMAIL PROTECTED]> wrote: The problem is that these assignments are evaluated automatically. So i can not use description strings to clearify output or input etc. Basically it's like this: 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 For those that didn't know the number of trailing zero's in a factorial is decided by the numer of factors of 5, because only a 5 can create a 0. Remember a factorial (n) = n**4*3*2*1. The list does not represent factorials. Example input of this program: 5 #number of times i'm going to read in a number 3 # 3! = 6, no trailing 0's zo the output 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... Ciao - Geofram On 10/8/06, Alan Gauld <[EMAIL PROTECTED] > wrote: Hi,Maybe its just me but I didn't understand what you aretrying to do...> 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()what does a represent? Its usually worth putting a prompt string intoinput() - and raw_input() - just as documentation if nothing else!And maybe a descriptive variable name if appropriate. > for i in range(a):>lst = (5, 25, 125, 625, 3125, 15625, 78125, 390625, 1953125,> 9765625,> 48828125, 244140625)None of these have any trailing zeros so far as I can tell?What answer are you expecting from this function? >ans = 0>b = input()similarly, what is b supposed to be?>for i in lst:And here you are throwing away the i from the outer loop>if i <= b:>ans += b//i And now you divide some arbitrary input value by each factorialin turn and sum the results?>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.I nbeed to understand what you are tryying to do first, itsnot making much sense at the moment. (But it is after midnight! :-)> P.s. I know python is probably not the best language for these kinds > of> problems (I can code it in C or C++), it just bugs me that it's> possible> and my solution is failing... ;-)Actually it looks like exactly what I would use Python for rarther than C/C++. The speed issue can be solved in numerous ways butas always lets be sure we get the functionality clear before startingto optimise things.Alan G.___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Can 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
Re: [Tutor] Need problems to enhance programming skills
Hi Asrarahmed, I recently started learning python. To reinforce the core language concepts I used the following website : http://www.spoj.pl/ This site features a large number of programming problems which you can solve in any number of programming language (including Python) and you can have the programs checked online to see if they are valid. The programming exercises are not specific to python but more of the kind you find in programming contests. You can still get valuable lessons from them though. Have fun - Geoframer On 10/10/06, Asrarahmed Kadri <[EMAIL PROTECTED]> wrote: Folks, Have you got set of programming problems in python to reinforce the core language concepts and also build logic. thanks. Regards, Asrar-- To HIM you shall return. ___Tutor maillist - Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Python and rpy
Okay this might not be the best place to post my question, but on the rpy-list i'm getting no response and i'm really stuck with this problem. Perhaps anyone on here has run into the same problem... I'm thinking my newbieness to python probably is one of the reasons why i fail to see what i'm doing wrong... R is a statistical language and Rpy is the python interface for it. However somehow I'm failing to see a step in the python code with which I address the R language. in R I can do : a=diag(10) #produces an identity matrix of size 10 b=kmeans(a,2,5,10,"Forgy")#calculate a kmeans clustering algorithm on the 10 vectors contained by the matrix just declared. in Ipython this does : - In [1]: from rpy import * RHOME= C:\Program Files\R\R-2.4.0 RVERSION= 2.4.0 RVER= 2040 RUSER= C:\Documents and Settings\Ronald Loading the R DLL C:\Program Files\R\R-2.4.0\bin\R.dll .. Done. Loading Rpy version 2040 .. Done. Creating the R object 'r' .. Done In [2]: a = r.diag(10) In [3]: b = r.kmeans(a,2,10,5,"Forgy") --- rpy.RExceptionTraceback (most recent call last) C:\Python24\ RException: Error in as.double.default(x) : (list) object cannot be coerced to ' double' - I've tried numerous things to get it to work, but i basically can not find out how i do something as simple as the two statements in R in RPython. Apparently something is going wrong somewhere in the conversion of python objects to R objects but i can't seem to fix it. There is a code snippet in the RPy-reference manual but it's only valid for python 2.2 and 2.1 and i couldn't get it to work on 2.4. If anyone has a clue on how to do this or can point me in the right direction, i'd be much oblidged. Kind Regards - Geofram ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python and rpy
Thanks Kent that helps some, at least i can do the basic stuff i can do in R now. But you kinda hit the nail on the head with your statement "This seems to work, it keeps a in the internal R representation instead of converting it to a list of lists" This all started with me trying to get R to do a kmeans algorithm on a list of lists (a list composed of vectors containing integers). What i want to do is convert a python list of lists to the approperiate R object so that i can use the r.kmeans algorithm on it. I'll write the basic program below. As i stated i think the conversion from Python to R is going wrong, but i have no clue on how to properly address that. The code snippet i was talking about is on page 15 and 16 of the rpy reference guide http://rpy.sourceforge.net/rpy/doc/rpy.pdf ; the examples just don't work and i am lacking enough python experience to see why :-S. What i'm trying to do now is : from rpy import * class Test: def as_r(self): return [[1,2,3,4,5],[2,3,4,5,1],[3,4,5,1,2],[4,5,1,2,3],[5,1,2,3,4]] if __name__ == "__main__": a=with_mode(NO_CONVERSION, Test)() r.kmeans(a, 2, 5, 10, "Forgy") Which gives as a result : RHOME= C:\Program Files\R\R-2.4.0 RVERSION= 2.4.0 RVER= 2040 RUSER= C:\Documents and Settings\Ronald Loading the R DLL C:\Program Files\R\R-2.4.0\bin\R.dll .. Done. Loading Rpy version 2040 .. Done. Creating the R object 'r' .. Done Traceback (most recent call last): File "rpy-test2.py", line 9, in ? r.kmeans(a, 2, 5, 10, "Forgy") rpy.RException: Error in as.double.default(x) : (list) object cannot be coerced to 'double' Hope you can shed more light on it. Many thanx for your efforts - Geofram On 12/21/06, Kent Johnson <[EMAIL PROTECTED]> wrote: Geoframer wrote: > R is a statistical language and Rpy is the python interface for it. > However somehow I'm failing to see a step in the python code with which I > address the R language. > > in R I can do : > > a=diag(10) #produces an identity matrix of > size 10 > b=kmeans(a,2,5,10,"Forgy")#calculate a kmeans clustering algorithm > on the 10 vectors contained by the matrix just declared. > > > in Ipython this does : > > - > In [1]: from rpy import * > RHOME= C:\Program Files\R\R-2.4.0 > RVERSION= 2.4.0 > RVER= 2040 > RUSER= C:\Documents and Settings\Ronald > Loading the R DLL C:\Program Files\R\R-2.4.0\bin\R.dll .. Done. > Loading Rpy version 2040 .. Done. > Creating the R object 'r' .. Done > > In [2]: a = r.diag(10) > > In [3]: b = r.kmeans(a,2,10,5,"Forgy") > --- > rpy.RExceptionTraceback (most recent > call last) > > C:\Python24\ > > RException: Error in as.double.default(x) : (list) object cannot be > coerced to ' > double' > - This seems to work, it keeps a in the internal R representation instead of converting it to a list of lists: In [1]: from rpy import * RHOME= C:\Program Files\R\R-2.3.1 RVERSION= 2.3.1 RVER= 2031 RUSER= G:\ Loading the R DLL C:\Program Files\R\R-2.3.1\bin\R.dll .. Done. Loading Rpy version 2031 .. Done. Creating the R object 'r' .. Done In [22]: aa=with_mode(NO_CONVERSION, r.diag)(10) In [25]: b=r.kmeans(aa,2,10,5,"Forgy") In [26]: b Out[26]: {'centers': [[0., 0., 0., 0., 0.0, 0., 0., 0., 0., 0.], [0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0]], 'cluster': [1, 1, 1, 1, 2, 1, 1, 1, 1, 1], 'size': [9, 1], 'withinss': [8.0018, 0.0]} > I've tried numerous things to get it to work, but i basically can not > find out how i do something as simple as the two statements in R in > RPython. Apparently something is going wrong somewhere in the conversion > of python objects to R objects but i can't seem to fix it. There is a > code snippet in the RPy-reference manual but it's only valid for python > 2.2 and 2.1 and i couldn't get it to work on 2.4. Where is the snippet? Cheers, Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python and rpy
Hey Kent, Well i've gotten exactly no response on the Rpy-list on both my questions :-(. However i switched to Ubuntu 6.10 today (from WinXP) and to my suprise it does work under linux! :-) RHOME= /usr/lib/R RVERSION= 2.3.1 RVER= 2031 RUSER= /home/geofram Loading Rpy version 2031 .. Done. Creating the R object 'r' .. Done In [2]: r.diag(2) Out[2]: array([[ 1., 0.], [ 0., 1.]]) In [3]: r.kmeans(r.diag(2),1,2,5,"Forgy") Out[3]: {'centers': array([ [ 0.5, 0.5]]), 'cluster': [1, 1], 'size': 2, 'withinss': 1.0} Older version somewhat but apparently this works, so it might just be a bug under windows or in the newer version from Rpy... For now at least I can work with it. Thanx a bunch for all your help Kent. Regards - Geofram On 12/25/06, Kent Johnson <[EMAIL PROTECTED]> wrote: Geoframer wrote: > As i stated i think the conversion from Python to R is going wrong, but > i have no clue on how to properly address that. I agree. If you have Numeric installed (which I do) then r.diag() should return a Numeric array, not a list of lists. This looks like the same problem discussed in this thread: http://sourceforge.net/mailarchive/message.php?msg_id=15307721 which does not seem to have been resolved. I don't want to get involved in the Rpy mailing list but I would suggest posting a very simple question asking why the result of r.diag() is not a Numeric array. Perhaps this will lead to a solution. > The code snippet i was talking about is on page 15 and 16 of the rpy > reference guide http://rpy.sourceforge.net/rpy/doc/rpy.pdf ; the > examples just don't work and i am lacking enough python experience to > see why :-S. > > What i'm trying to do now is : > > > from rpy import * > > class Test: > def as_r(self): > return [[1,2,3,4,5],[2,3,4,5,1],[3,4,5,1,2],[4,5,1,2,3],[5,1,2,3,4]] > > if __name__ == "__main__": > a=with_mode(NO_CONVERSION, Test)() > r.kmeans(a, 2, 5, 10, "Forgy") I don't see how this will help. My understanding is that as_r() should return an Robj, not a Python object. I think this code is the same as passing a list of lists directly to kmeans. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python and rpy
I actually had Numeric under WinXP also, manually installed it and could import Numeric so that wasn't it imho. On 1/11/07, Hugo González Monteverde <[EMAIL PROTECTED]> wrote: Geoframer wrote: > > However i switched to Ubuntu 6.10 today (from WinXP) and to my suprise > it does work under linux! :-) Probably Numeric is included in Ubuntu's Python distro. Hugo ___ 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] Division doesn't work
You assign s as an integer... it should be a float to get the right result... So either define s as s = 14105.0 or as s = float(14105) it'll then result in the right answer : In [17]: s=14105.0 In [18]: s/1024 Out[18]: 13.7744140625 In [19]: s = float(14105) In [20]: s/1024 Out[20]: 13.7744140625 HTH - Geofram On 1/18/07, Johan Geldenhuys <[EMAIL PROTECTED]> wrote: Hi all, In my script I want to convert 14105 bytes to kilobytes and and this is what I do: >>> s = 14105 >>> print '%0.2f' % (s/1024) 13.00 This not correct and I don't know why. The answer is 13.77. Any pointers please that would help my in the right direction? Thanks Johan -- No virus found in this outgoing message. Checked by AVG Free Edition. Version: 7.5.432 / Virus Database: 268.16.13/632 - Release Date: 2007/01/16 04:36 PM ___ 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] Division doesn't work
Or actually an even easier way is to just to divide bij a float and the end result will also be a float. So in your case divide bij 1024.0 ;-) In [21]: s=14105 In [22]: s/1024.0 Out[22]: 13.7744140625 HTH - Geofram On 1/18/07, Geoframer <[EMAIL PROTECTED]> wrote: You assign s as an integer... it should be a float to get the right result... So either define s as s = 14105.0 or as s = float(14105) it'll then result in the right answer : In [17]: s=14105.0 In [18]: s/1024 Out[18]: 13.7744140625 In [19]: s = float(14105) In [20]: s/1024 Out[20]: 13.7744140625 HTH - Geofram On 1/18/07, Johan Geldenhuys <[EMAIL PROTECTED]> wrote: > Hi all, > > In my script I want to convert 14105 bytes to kilobytes and and this is > what I do: > > >>> s = 14105 > >>> print '%0.2f' % (s/1024) > 13.00 > > This not correct and I don't know why. The answer is 13.77. > > Any pointers please that would help my in the right direction? > > Thanks > > Johan > > -- > No virus found in this outgoing message. > Checked by AVG Free Edition. > Version: 7.5.432 / Virus Database: 268.16.13/632 - Release Date: > 2007/01/16 04:36 PM > > ___ > 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] 'elp!!!!!!!1Totally Clueless Newbie In Distress
Alright this code is actually littered with bugs, but don't feel bad, because as you state you are new to the whole programming thing. I'll try to explain the things i see going wrong (please take into account that i'm also a new pythonist ;-)) *** You get the error 'variable undefined' because you are declaring a global in an incorrect manner. The correct manner is to define the variable in the global scope then start a definition, declare that you are using a global variable and then assign it. Like this : bla = 'Hello world' def func(): global bla print bla *** If you do : porao = raw_input() You'll define the integer value as a string, not an integer. If you are sure that only an integer will be entered use input() (slower) or int(raw_input()). In either case you should use try and except clauses more in your code because if not a 1 or 4 is entered your code will continue without having the variables declared! Leading to other errors. *** Now suppose you get the definitions using globals correct then you'll get new errors stating that an 'int' is not callable. This happens because you define for example altura as an integer and then also define a function called altura. If you now use : altura() It'll try to call the integer object and will fail. Easy solution would be to make the function something like alturadef() *** As for your identation you should use consistent identation... I suggest using python -t or python -tt to compile your script and it will give warnings/errors where the identation goes wrong. *** Here's how i altered your code (quick and dirty probably, it should be more clean using try and except clauses and what not) to get it to work but you can probably better look that up in a python book and then return to the list if you don't understand it : #Ok,this is supposed to be a 2 option choice between values 1 and 4, #i want the value to determine the variable values inside the function altura_aeronave = 0 largura_aeronave = 0 comprimento_aeronave = 0 comprimento = 0 largura = 0 altura = 0 def porao(): global altura_aeronave, largura_aeronave, comprimento porao = input() if porao == 1 : altura_aeronave = 111 largura_aeronave = 112 comprimento = 211 elif porao == 4: altura_aeronave = 112 largura_aeronave = 113 comprimento = 212 else: print "Porão inexistente" #These three functions were supposed to get input from user so it can be compared #with the values determinated(determined?)above def larguradef(): global largura largura=input() def alturadef(): global altura altura=input() def comprimentodef(): global comprimento comprimento = input() #These are the comparison functions def largura_compativel (): global largura, largura_aeronave if not largura <= largura_aeronave: print 'Volume largo demais!' def altura_compativel (): global altura, altura_aeronave if not altura <= altura_aeronave: print 'Volume alto demais!' def comprimento_compativel (): global comprimento, comprimento_aeronave if not comprimento<=comprimento_aeronave: print 'Volume comprido demais!' #Try to run this damn thing,man!1 porao() #print altura_aeronave, largura_aeronave, comprimento larguradef() alturadef() comprimentodef() largura_compativel() altura_compativel comprimento_compativel() On 1/19/07, Karl Wittgenstein <[EMAIL PROTECTED]> wrote: Dear Smart Caring Dude, I've been dabbling into Python for about 6 weeks now.I'm a Social Sciences student who just got interested in programming and chose Python as first language.I have little time to practice and I am just getting into programming concepts,so please be patient,in case you are so kind as to enlighten this poor soul. I am trying to write this program which should compare values that are set by the program through user's choice to values that the user enters on a prompt.I use SPE on windows xp,and it tells me that there are indentation erros on the definitions.Isn't it legal to start a new block of code when starting a definition?And how come it returns 'variable' not defined,when they are defined by the = ??Should i make them global? I would be very grateful to the patient soul that answers these questions,as my learning interest is sincere and the knowledge sources so disperse. Here goes the code: #Ok,this is supposed to be a 2 option choice between values 1 and 4, #i want the value to determine the variable values inside the function def porao(): porao = raw_input() if porao == 1 : global altura_aeronave = 111 global largura_aeronave = 112 global comprimento = 211 elif porao == 4: global altura_aeronave = 112 global largura_aeronave = 113 global comprimento = 212 else: print "Porão inexistente" #These three functions were supposed to get input from user so it can be compared #with the values determinated(determined?)above def largura():
Re: [Tutor] 'elp!!!!!!!1Totally Clueless Newbie In Distress
Accidentally the number of function definitions does not help the clarity of the program, even though it's completely unclear to me what exactly you are trying to do. :-) I rewrote your program a bit combining the definition of the functions, the comparision of the functions and removed the chance that your program goes on the define/compare values that have not been defined. *** Insert redone code *** altura_aeronave = 0 largura_aeronave = 0 comprimento_aeronave = 0 comprimento = 0 largura = 0 altura = 0 def compativel(): global altura, altura_aeronave, comprimento, comprimento_aeronave, \ largura, largura_aeronave if not largura <= largura_aeronave: print 'Volume largo demais!' elif not altura <= altura_aeronave: print 'Volume alto demais!' elif not comprimento<=comprimento_aeronave: print 'Volume comprido demais!' def define(): global largura, altura, comprimento largura=input() altura=input() comprimento=input() def porao(): global altura_aeronave, largura_aeronave, comprimento porao = input() if porao == 1 : altura_aeronave = 111 largura_aeronave = 112 comprimento = 211 return 1 elif porao == 4: altura_aeronave = 112 largura_aeronave = 113 comprimento = 212 return 1 else: print "Porao inexistente!" if porao(): define() compativel() On 1/19/07, Geoframer <[EMAIL PROTECTED]> wrote: Alright this code is actually littered with bugs, but don't feel bad, because as you state you are new to the whole programming thing. I'll try to explain the things i see going wrong (please take into account that i'm also a new pythonist ;-)) *** You get the error 'variable undefined' because you are declaring a global in an incorrect manner. The correct manner is to define the variable in the global scope then start a definition, declare that you are using a global variable and then assign it. Like this : bla = 'Hello world' def func(): global bla print bla *** If you do : porao = raw_input() You'll define the integer value as a string, not an integer. If you are sure that only an integer will be entered use input() (slower) or int(raw_input()). In either case you should use try and except clauses more in your code because if not a 1 or 4 is entered your code will continue without having the variables declared! Leading to other errors. *** Now suppose you get the definitions using globals correct then you'll get new errors stating that an 'int' is not callable. This happens because you define for example altura as an integer and then also define a function called altura. If you now use : altura() It'll try to call the integer object and will fail. Easy solution would be to make the function something like alturadef() *** As for your identation you should use consistent identation... I suggest using python -t or python -tt to compile your script and it will give warnings/errors where the identation goes wrong. *** Here's how i altered your code (quick and dirty probably, it should be more clean using try and except clauses and what not) to get it to work but you can probably better look that up in a python book and then return to the list if you don't understand it : #Ok,this is supposed to be a 2 option choice between values 1 and 4, #i want the value to determine the variable values inside the function altura_aeronave = 0 largura_aeronave = 0 comprimento_aeronave = 0 comprimento = 0 largura = 0 altura = 0 def porao(): global altura_aeronave, largura_aeronave, comprimento porao = input() if porao == 1 : altura_aeronave = 111 largura_aeronave = 112 comprimento = 211 elif porao == 4: altura_aeronave = 112 largura_aeronave = 113 comprimento = 212 else: print "Porão inexistente" #These three functions were supposed to get input from user so it can be compared #with the values determinated(determined?)above def larguradef(): global largura largura=input() def alturadef(): global altura altura=input() def comprimentodef(): global comprimento comprimento = input() #These are the comparison functions def largura_compativel (): global largura, largura_aeronave if not largura <= largura_aeronave: print 'Volume largo demais!' def altura_compativel (): global altura, altura_aeronave if not altura <= altura_aeronave: print 'Volume alto demais!' def comprimento_compativel (): global comprimento, comprimento_aeronave if not comprimento<=comprimento_aeronave: print 'Volume comprido demais!' #Try to run this damn thing,man!1 porao() #print altura_aeronave, largura_aeronave, comprimento larguradef() alturadef() comprimentodef() largura_compativel()
Re: [Tutor] 'elp!!!!!!!1Totally Clueless Newbie In Distress
As i stated i'm somewhat new to python myself so i defined the variables in a somewhat old fashion manner. The correct code is below. I also added some comments because i think you defined the wrong variable somewhere also... Because your code led to comprimento being compared to comprimento_aeronave which was never defined anywhere, so i took it you ment comprimento_aeronave there This code below is fully functional without any errors (not even identation warnings ;-) ). So if this doesn't work at your computer something else is possible wrong. Incidentally if you hit the following sequence : 1 2 3 4. The program just terminates without a message... You'd have to insert what's happening in such a case yourself. insert code global altura_aeronave, largura_aeronave, comprimento_aeronave, comprimento, \ largura, altura def compativel(): global altura, altura_aeronave, comprimento, comprimento_aeronave, \ largura, largura_aeronave if not largura <= largura_aeronave: print 'Volume largo demais!' elif not altura <= altura_aeronave: print 'Volume alto demais!' elif not comprimento<=comprimento_aeronave: print 'Volume comprido demais!' def define(): global largura, altura, comprimento largura=input() altura=input() comprimento=input() def porao(): global altura_aeronave, largura_aeronave, comprimento_aeronave porao = input() if porao == 1 : altura_aeronave = 111 largura_aeronave = 112 comprimento_aeronave = 211 #You originally had comprimento here? return 1 elif porao == 4: altura_aeronave = 112 largura_aeronave = 113 comprimento_aeronave = 212 #Same here return 1 else: print "Porao inexistente!" if porao(): define() compativel() *** end inserted code *** HTH - Geoframer On 1/19/07, Geoframer <[EMAIL PROTECTED]> wrote: Accidentally the number of function definitions does not help the clarity of the program, even though it's completely unclear to me what exactly you are trying to do. :-) I rewrote your program a bit combining the definition of the functions, the comparision of the functions and removed the chance that your program goes on the define/compare values that have not been defined. *** Insert redone code *** altura_aeronave = 0 largura_aeronave = 0 comprimento_aeronave = 0 comprimento = 0 largura = 0 altura = 0 def compativel(): global altura, altura_aeronave, comprimento, comprimento_aeronave, \ largura, largura_aeronave if not largura <= largura_aeronave: print 'Volume largo demais!' elif not altura <= altura_aeronave: print 'Volume alto demais!' elif not comprimento<=comprimento_aeronave: print 'Volume comprido demais!' def define(): global largura, altura, comprimento largura=input() altura=input() comprimento=input() def porao(): global altura_aeronave, largura_aeronave, comprimento porao = input() if porao == 1 : altura_aeronave = 111 largura_aeronave = 112 comprimento = 211 return 1 elif porao == 4: altura_aeronave = 112 largura_aeronave = 113 comprimento = 212 return 1 else: print "Porao inexistente!" if porao(): define() compativel() On 1/19/07, Geoframer <[EMAIL PROTECTED]> wrote: > > Alright this code is actually littered with bugs, but don't feel bad, > because as you state you are new to the whole programming thing. I'll try to > explain the things i see going wrong (please take into account that i'm also > a new pythonist ;-)) > > *** > You get the error 'variable undefined' because you are declaring a > global in an incorrect manner. The correct manner is to define the variable > in the global scope then start a definition, declare that you are using a > global variable and then assign it. Like this : > > bla = 'Hello world' > > def func(): > global bla > print bla > *** > If you do : > porao = raw_input() > You'll define the integer value as a string, not an integer. If you are > sure that only an integer will be entered use input() (slower) or > int(raw_input()). In either case you should use try and except clauses more > in your code because if not a 1 or 4 is entered your code will continue > without having the variables declared! Leading to other errors. > *** > Now suppose you get the definitions using globals correct then you'll > get new errors stating that an 'int' is not callable. > This happens because you define for example altura as an integer and > then also define a function called altura. If you now use : > altura() > It'll try to c
Re: [Tutor] [Tutor} Why doesn't it choose a new number each time?
The one thing people told me when i started learning python was that python has this lovely structure called dictionaries. Your particular problem is very easy to solve using dictionaries in about 12 lines (i coded it myself just to see ;-)). For instance you could define the various values as a dictionary : values = {1:'rock', 2:'paper', 3:'scissors'} and the outcome of possible combinations (cchoice, hchoice) as : combinations = {(1,1):'Tie game!', (1,2):'You win!', (1,3):'You lost!', (2,1):'You lost!', (2,2):'Tie game!', (2,3):'You win!', (3,1):'You win!', (3,2):'You lost!', (3,3):'Tie game!'} That way it's very easy to take a random value for computer , get input for human player and print the result in a single print like so : print "AI chose %s, you chose %s. %s", %(values.get(cchoice),values.get (hchoice),combinations.get((cchoice,hchoice))) Probably this is not unlike Alan suggest, but i got confused when i read about tables. Unless he means dictionaries instead. HTH - Geoframer On 2/15/07, Rikard Bosnjakovic <[EMAIL PROTECTED]> wrote: On 2/15/07, Nathan Pinno <[EMAIL PROTECTED]> wrote: > and that was a suggestion. (Thanks!) But can anyone explain why I can > shorten the code? I looked at it a long while yesterday, and came up with > nothing. The only thing I decided was to try to get it to the GUI stage. If you take a look at your if-cases, you see that a lot of strings in there are the same. The code is therefore redundant, and this is what can be trimmed down. Consider this code: if var1 = 1 and var2 = 0: print "Var1 is 1, var2 is 0" if var1 = 0 and var2 = 0: print "Var1 is 0, var2 is 0" if var1 = 1 and var2 = 1: print "Var1 is 1, var2 is 1" if var1 = 0 and var2 = 1: print "Var1 is 0, var2 is 1" This scope is redundant in a lot of ways and can be trimmed down to one if and one print: if (var1 in [0,1]) and (var2 in [0,1]): print "Var1 is %d, var2 is %d" % (var1, var2) Your code is similiar to the above. It takes time to learn how to trim down redundant code. Vast knowledge of a language itself is not required, but a pretty solid knowledge about the basics is probably required. If you are entirely new to programming, it might be cumbersome though. Give it a try, and don't hesitate to ask again. -- - Rikard. ___ 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] Finding the minimum value in a multidimensional array
Hey everyone, I've been trying to locate a way to find the location of the minimum value in an n*n array. For instance suppose we have a 10x10 array. In [1]: import numpy In [2]: a = numpy.zeros((10,10)) In [3]: a Out[3]: array([[ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]]) And we set a value in that array to be the smallest just for illustration purposes. In [4]: a[9][8] = -1 In [5]: a Out[5]: array([[ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0., 0., 0., 0., -1., 0.]]) I can find this minimum using the 'min' function, but is there a way to find the index to that position? In [6]: a.min() Out[6]: -1.0 Any help is appreciated. Please keep in mind that this is only a 'small' example. What i'm trying to accomplish is to find the location of the minimum value in a huge n*n array and quickly and efficiently finding the index to that position. Regards - Geofram ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Finding the minimum value in a multidimensional array
I don't see a solution here... It is not conclusive on what's the minimum for an array. ln [1]: import numpy In [2]: a = numpy.array([[1,2,3,0],[2,3,4,5],[6,5,4,3],[-1,2,-4,5]]) In [3]: a Out[3]: array([[ 1, 2, 3, 0], [ 2, 3, 4, 5], [ 6, 5, 4, 3], [-1, 2, -4, 5]]) In [4]: a.argmin(0) Out[4]: array([3, 0, 3, 0]) In [5]: a.argmin(1) Out[5]: array([3, 0, 3, 2]) a.argmin(0) shows where the minimum is for each row a.argmin(1) shows whree the minimum is for each column Which combined gives (row, column) : (0,3), (1,0), (2,3) and (3,2). So basically 4 values which i still need to compare. In a small array this might not be a hefty computational effort. In a n*n array this will lead to N values which need both indexing and comparing. Perhaps this is the only solution around but i hope not. In either way thanks for your time and suggestion. Regards Geofram On 3/13/07, Eike Welk <[EMAIL PROTECTED]> wrote: On Tuesday 13 March 2007 11:57, Geoframer wrote: > Hey everyone, > > I've been trying to locate a way to find the location of the > minimum value in an n*n array. The 'argmin' function is probably what you are looking for. See the examples at: http://www.scipy.org/Numpy_Example_List Regards Eike. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor