我写了一段代码来打印n个素数:
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)
代码工作正常。我得到2 3 5 7 11
作为输出。我试着上课iterable
。代码如下。但输出为0 1 2 3 4
。我无法弄清楚我哪里出错了。任何帮助表示赞赏。感谢
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,
答案 0 :(得分:3)
您正在使用此代码打印出值:
for p in range (5):
print p,
如果你看一下,它会打印范围的值。您可能想要从主要迭代器中打印东西。 itertools
有一些可能有用的功能:
for prime in itertools.islice(p, 5):
print prime,
此外,您可能需要考虑使用生成器:
def primes():
current = 1
while True:
current += 1
while True:
for i in xrange(2, current // 2 + 1):
if current % i == 0:
current += 1
break
else:
break
yield current
答案 1 :(得分:1)
您的问题是您在测试代码中重用变量p
:
if __name__ == '__main__':
p = PrimeIter() # first declaration of p
for p in range (5): # second declaration of p
print p, # uses second declaration of p
我建议使用itertools.islice
来获取迭代器的前5个元素:
if __name__ == '__main__':
p = PrimeIter()
for x in itertools.islice(p, 5):
print x,
答案 2 :(得分:0)
用于生成质数最大为m的迭代器:
class PrimeIter:
def ___init__(self, m):
self.max = m
def __iter__(self):
self.n = 1
return self
def __next__(self):
if self.n < self.max:
self.n += 1
i = 2
while i < (self.n//2+1):
if self.n % i == 0:
self.n = self.n+1
if self.n > self.max:
raise StopIteration
i = 1
i += 1
else:
return self.n
else:
raise StopIteration
p = PrimeIter (100)
for i in p:
print(i, end=' ')