Home > Net >  Memory Error in processing Python Code for Project Euler problem
Memory Error in processing Python Code for Project Euler problem

Time:10-14

Tried Running a cod to solve an archived Project Euler Problem

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.

Find the sum of all the multiples of 3 or 5 below 1000.

but I am now getting something called a memory error. Am I doing something wrong? Pl. Explain. My Code-

def euler_1(n):
    x=0
    abc=[]
    while x<n:
        if x%3==0 or x%5==0:
            abc.append(x)
            x =1
        else:
            pass

    return sum(abc)

CodePudding user response:

You need to make sure you increment your counter each time you iterate over the loop. Otherwise you'll get stuck on a non-multiple and encounter an infinite loop.

Consider the following case. When x=4:

if x%3==0 or x%5==0:
# evaluates to false

So we move the else statement and go back to the top of the loop. Nothing has changed, so x is still 4, and the process repeats infinitely. If you are set on using a while loop, you need to move x =1 outside the ifs to happen in all cases:

def euler_1(n):
    x=0
    abc=[]
    while x<n:
        if x%3==0 or x%5==0:
            abc.append(x)
        x =1
    return sum(abc)

However, if I could make a couple recommendations: First, you don't need to start your counter at 0, but at your smallest integer for which you want to find multiples. There is no sense iteration over 0, 1, and 2, since they won't ever count.

Secondly, I would recommend using either a for loop or a list comprehension, since these will take care of incrementing the counter with each loop, regardless of outcome. Make sure you set the end of the range to n 1 since Python ranges are half-open sets, i.e. do not include the last number.

abc = sum([x for x in range(0, n 1) if x%3==0 or x%5==0)]

or

abc=0
for x in range(0, n 1):
    if x%3==0 or x%5==0:
        abc  = x
return abc

CodePudding user response:

Just use list comprehension and skip the while-loop and the append which just slows things down.

sum([x for x in range(1, 1000) if x%3==0 or x%5==0]) # -> 233168

CodePudding user response:

In the else statement, delete the pass statement and write x =1 because updating x is independent of the condition. If you don't update x if condition is not satisfied then condition will remain unsatisfied forever and the loop will keep going

  • Related