I wrote a piece of code to print n prime numbers:
class PrimeGen:
def __init__(self):
self.current = 2
def genPrime(self, num):
for i in range(num):
while 1:
for j in range(2, self.current/2 + 1):
if self.current % j == 0:
self.current = self.current + 1
break
else:
break
print self.current,
self.current = self.current + 1
if __name__ == '__main__':
p = PrimeGen()
p.genPrime(5)
The code works fine. I get 2 3 5 7 11 as output. I tried to make the class iterable. Code below. But the output is 0 1 2 3 4. I could not quite figure out where I am going wrong. Any help is appreciated. Thanks
class PrimeIter:
def __init__(self):
self.current = 1
def next(self):
self.current = self.current + 1
while 1:
for i in range(2, self.current/2 + 1):
if self.current % i == 0:
self.current = self.current + 1
break # Break current for loop
else:
break # Break the while loop and return
return self.current
def __iter__(self):
return self
if __name__ == '__main__':
p = PrimeIter()
for p in range (5):
print p,
You’re using this code to print out the values:
If you look at that, it’s printing the values of the range. You probably want to print things from the prime iterator.
itertoolshas some functions that may help:Additionally, you may want to consider using a generator: