5

I am practicing Python with Project Euler, question 1, but the function I wrote to solve it is taking way too long.

I figure it's because the way I coded it not the actual method itself.
When I run this function with 10 or 15 iterations it spits out an answer instantly, but as soon as I jump it up to even 20, it doesn't show me anything for even minutes.
This is obviously a big problem if I need to go to 1000 iterations.

def pe1(n):
    counter = 1
    total = 0
    while counter < n:
        if counter%3==0:
            total=total+counter
        if counter%5==0:
            if counter%3==0:
                continue
            total=total+counter
        if counter % 25 == 0:
            print (total)
        counter=counter+1
    return (total)
4

4 回答 4

6

Because as soon as counter hits 15, your loop goes into an infinite continue - it's always going to hit the second if statement's case.

You need to move your counter = counter + 1 line before the continue, or better yet, use something like for counter in range(1,n).

于 2013-08-23T02:29:00.663 回答
2

Consider the case if counter equals 15 and look at what happens where counter%5==0 and counter%3==0, which will first occur at that time.

Consider also what will not happen for that value of counter, specifically, the line counter=counter+1 won't be executed.

于 2013-08-23T02:28:51.660 回答
1

为了避免这样的陷阱,请考虑使用

if ...
elif ...
elif ...
else ...
于 2013-08-23T02:46:48.170 回答
0

你可以使用表驱动。像这样。

counter_map = {3:fun1, 5:func2, 25:fun3} # key is remainder.Of course,fun can be replaced with lambda.
于 2013-10-26T08:36:16.480 回答