我试图使下面的生成器能够设置返回数字的上限。
调用会list(it.takewhile(lambda x: x < 100, get_primes()))按预期返回 100 以下所有素数的列表,但list(get_primes(100))(应该以相同的方式返回相同的列表)仅返回一个空列表。
显然,我可以在循环if n and candidate>=n: break中包含一个for,但我最感兴趣的是为什么该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
Run Code Online (Sandbox Code Playgroud)
这里:
return it.takewhile(lambda x: x < n, get_primes())
Run Code Online (Sandbox Code Playgroud)
由于这是一个生成器,因此它需要yield这些值而不是对return它们进行 ing。根据您的 Python 版本,您也许可以使用该yield from语法。
以下内容可能对背景阅读有用:Return in Generator with Yield in Python 3.3
| 归档时间: |
|
| 查看次数: |
3335 次 |
| 最近记录: |