Карл Кнехтель отвечает правильно, но вяло;проблема в том, что to_use продвигается слишком далеко и слишком рано.
Вот моя исправленная версия - я снял комментарии.
class prime_list():
def __init__(self):
self.primes = [2]
self.to_use = 0
def test(self, candidate):
next = self.primes[self.to_use]
if candidate >= next * next:
self.to_use += 1
print candidate, next
return all(candidate % p != 0 for p in self.primes[:self.to_use])
def __iter__(self):
import itertools
for candidate in itertools.count(3,2):
if self.test(candidate):
self.primes.append(candidate)
yield candidate
if __name__ == "__main__":
my_primes = prime_list()
# print my_primes.primes[0]
for p in my_primes:
print "Generated:", p
if p > 1000000: break
sum += p
print "Number of primes generated:", len(my_primes.primes)