nolefan33
nolefan33

Reputation: 13

While loop not adding right

I'm trying to make a simple Sieve of Eratosthenes script, and I'm just beginning Python and coding in general, so I'm not worried about efficiency right now.

import math
primes = range(2,500)
upperLimit = math.ceil(math.sqrt(float(primes[-1])))

def sieve(numbers):
    for item in range(0,int(upperLimit)):
        n = numbers[item]
        while n < upperLimit:
            n += numbers[item]
            print n
            print numbers
            numbers.remove(n)

sieve(primes)
print primes

This kept telling me that numbers.remove(n) in line 12 doesn't exist, so I put the print statements above it to try to figure out what was going on. It runs fine, removing what it's supposed to, up to 24. Then, instead of adding 2 to n again, it changes n to 6. That's what was giving me the error, but I can't figure out why it keeps doing that.

Upvotes: 1

Views: 89

Answers (1)

kkurian
kkurian

Reputation: 3944

The first time through the for loop:

item == 0
starting n == 2
removing 4
removing 6
removing 8
removing 10
removing 12
removing 14
removing 16
removing 18
removing 20
removing 22
removing 24

Next iteration:

item == 1
starting n == 3
removing 6 (but 6 is not in the list, because it has already been removed)
ValueError

As you'd expect, when item == 1, n == numbers[1] == 3. Then, n += numbers[1] results in n == 6. But you can't remove 6 twice, so you get an error.

Upvotes: 2

Related Questions