gpt4 book ai didi

python - 在 Python 中设置无限生成器的限制

转载 作者:太空狗 更新时间:2023-10-30 02:45:01 26 4
gpt4 key购买 nike

我正在尝试让下面的生成器能够为返回的数字设置上限。

调用 list(it.takewhile(lambda x: x < 100, get_primes()))按预期返回 100 以下所有素数的列表,但 list(get_primes(100)) (应该以相同的方式返回相同的列表)只是返回一个空列表。

显然,我可以包含一个 if n and candidate>=n: breakfor循环,但我最感兴趣的是为什么 if n: return构造不像我期望的那样工作。它不应该只返回相同的takewhile吗?在上面工作的迭代器?我在这里忽略了什么?

import itertools as it

def get_primes(n=None):
"""
Generates primes to a max of n.

>>> list(get_primes(100))
[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]
"""
if n:
return it.takewhile(lambda x: x < n, get_primes())
composites = {}
yield 2
for candidate in it.count(3, 2):
prime_factor = composites.pop(candidate, None)
if prime_factor is None:
yield candidate
composites[candidate**2] = candidate
else:
composite = candidate + 2*prime_factor
while composite in composites:
composite += 2*prime_factor
composites[composite] = prime_factor

最佳答案

这里:

return it.takewhile(lambda x: x < n, get_primes())

因为这是一个生成器,它需要产生这些值而不是返回它们。根据您的 Python 版本,您可以使用 yield from语法。

以下内容可能对背景阅读有用:Return in generator together with yield in Python 3.3

关于python - 在 Python 中设置无限生成器的限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26206422/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com