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

Alan Gauld alan.gauld at btinternet.com
Sun Oct 8 19:32:22 CEST 2006

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

Something like this:

iterations = input('How many factorials? ')
facs = [input('Type a required factorial: ') for n in 
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

Alan G.

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
> ----------------------------------------------------------------------------

More information about the Tutor mailing list