【问题标题】:Building a Prime Number Iterable Object in Python在 Python 中构建质数可迭代对象
【发布时间】:2020-08-14 21:41:46
【问题描述】:

我正在尝试学习 Python 中的迭代器,作为实践,我正在尝试构建一个可迭代对象,该对象提供的素数达到指定的限制。

这个想法是,该类可用于创建一个对象,该对象包含一个质数列表,直到用户给出的限制。

我使用的逻辑:

  1. 素数从2开始依次生成
  2. 将 1 添加到序列中迄今为止最大的素数上,并检查它们是否可以被迄今为止素数列表中的任何数字整除。
  3. 如果该数字可被素数列表中的任何一个整除,则将它们丢弃,并将当前数字加 1 以获取下一个要尝试的数字。
  4. 如果到目前为止它们不能被列表中的任何素数整除,它们将作为下一个素数添加到列表中。

以下是我正在处理的代码:

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


【解决方案1】:

这是一场灾难!您正在创建一个迭代器以返回素数,但在内部您使用相同的迭代器来生成素数除数以查看数字是否为素数。实际上,在迭代器试图提出返回值时耗尽了它。或类似的东西。相反,在内部,我们需要创建这个迭代器的新实例(具有更小的限制)来生成素数除数。 (即递归。)类似:

class PrimeList:
    def __init__(self, limit):
        self.limit = limit
        self.value = 2

    def __iter__(self):
        return self

    def is_prime(self, x):
        while True:
            try:
                y = next(self)

                if x % y == 0:
                    return False

            except StopIteration:
                return True

    def __next__(self):

        while self.value < self.limit:
            divisors = PrimeList(int(self.value ** 0.5) + 1)  # recursion

            found = divisors.is_prime(self.value)

            self.value += 1

            if found:
                return self.value - 1

        raise StopIteration()

test = PrimeList(100)
print(*test, sep=", ")

这行得通,但它必须是缓慢的:

% python3 test.py
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97
%

很酷的问题!

【讨论】:

    猜你喜欢
    • 2020-02-12
    • 2013-08-03
    • 1970-01-01
    • 1970-01-01
    • 2012-02-12
    • 2014-11-04
    • 1970-01-01
    • 1970-01-01
    • 2011-04-22
    相关资源
    最近更新 更多