Reputation: 51
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)
Upvotes: 5
Views: 124
Reputation: 161
You can use table-driven. Like this.
counter_map = {3:fun1, 5:func2, 25:fun3} # key is remainder.Of course,fun can be replaced with lambda.
Upvotes: 0
Reputation: 565
To avoid traps like this one, consider using
if ...
elif ...
elif ...
else ...
Upvotes: 1
Reputation: 526593
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)
.
Upvotes: 6
Reputation: 10841
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.
Upvotes: 2