【发布时间】:2020-08-14 21:41:46
【问题描述】:
我正在尝试学习 Python 中的迭代器,作为实践,我正在尝试构建一个可迭代对象,该对象提供的素数达到指定的限制。
这个想法是,该类可用于创建一个对象,该对象包含一个质数列表,直到用户给出的限制。
我使用的逻辑:
- 素数从2开始依次生成
- 将 1 添加到序列中迄今为止最大的素数上,并检查它们是否可以被迄今为止素数列表中的任何数字整除。
- 如果该数字可被素数列表中的任何一个整除,则将它们丢弃,并将当前数字加 1 以获取下一个要尝试的数字。
- 如果到目前为止它们不能被列表中的任何素数整除,它们将作为下一个素数添加到列表中。
以下是我正在处理的代码:
class PrimeList:
def __init__(self,limit):
self.val = 2
self.limit = limit
def __iter__(self):
return self
def __next__(self):
if self.val >= (self.limit**0.5+1):
raise StopIteration
else:
return_val = self.val
while return_val < (self.limit**0.5+1):
if is_prime(self, return_val+1): # Having problems in this step. Goes into an infinite loop
return return_val + 1
else:
return_val +=1
else:
return return_val
def is_prime(list_of_primes,x):
while True:
try:
y = next(list_of_primes)
if x % y == 0:
return False
except StopIteration:
return True
test = PrimeList(100)
print(list(test))
我得到的错误是RecursionError: maximum recursion depth exceeded while calling a Python object
我想我不知道如何递归地引用可迭代对象。
任何帮助将不胜感激。
【问题讨论】:
-
我无法重现您遇到的错误 - 我收到“AttributeError: type object 'PrimeList' has no attribute 'self'”
-
抱歉,我正在尝试进行实验并进行代码更改,结果被复制了。已还原代码。现在它给出了错误
RecursionError: maximum recursion depth exceeded while calling a Python object
标签: python recursion iterator iterable