a_here_and_now
a_here_and_now

Reputation: 187

Sieve of Eratosthenes not working

My computer basically crashes when I try to run this code.

Could someone please point out why?

I realize that resizing a list is not the most efficient way of doing this, but even typing in any number under 10 will yield nothing at all and makes spyder or my computer crash.

My goal was to set up a class that I could store the instance of someone's number as so that I wouldn't have to run the function again if someone wanted to call the same number.

class eratosthenes(object):

    def __init__(self, b):
        self.b = b
        count1 = 2
        self.lst = []
        while count1 <= b:
            self.lst.append(count1)
            count1+=1

    def sieve(self):
        self.count2 = 2
        while self.count2 < self.b/2.0:
            for i in self.lst:
                if i%self.count2==0:
                    self.lst.remove(i)
            self.count2+=1

a=raw_input("How far are you willing to go in this search for what you seek, young traveler?: ")
q = eratosthenes(a)  
print q.sieve()

Upvotes: 0

Views: 77

Answers (1)

Rob Hansen
Rob Hansen

Reputation: 317

Consider this:

lst = [1, 2, 3, 4, 5]
for entry in lst:
    print(entry)
    lst.remove(entry)

You'd think that code would print the values 1, 2, 3, 4, and 5. Instead (under Python 3.6 on macOS Sierra) you get 1, 3, and 5.

Modifying a list as you're walking down it is a no-no. And if you look in your sieve method, that's what you're doing.

Hope this helps!

Upvotes: 1

Related Questions