[Tutor] Can my code be optimized any further (speed-wise)?

Alan Gauld alan.gauld at btinternet.com
Sun Oct 8 01:33:35 CEST 2006


Hi,

Maybe its just me but I didn't understand what you are
trying to do...

> The problem is to compute the number of trailing zero's in 
> factorials (n! =
> 1*2*3*4*.......*n). with n <= 1000000000
>
> 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 into
input() - 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 factorial
in 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, its
not 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 but
as always lets be sure we get the functionality clear before starting
to optimise things.

Alan G.




More information about the Tutor mailing list