首页 > 解决方案 > 使用埃拉托色尼筛法的素数生成器

问题描述

此 python 代码使用 Sieve 技术生成素数。我无法理解代码,尤其是yield from部分。如何跟踪这样的代码或使其更易于理解。这段代码来自 Computerphile Youtube 频道关于 python 惰性的视频。

def nats(n):
    yield n
    yield from nats(n+1)


def sieve(s):
    n = next(s)
    yield n
    yield from sieve(i for i in s if i%n != 0)
    
    
p = sieve(nats(2))

next(p) # generates prime numbers 2, 3, 5, 7, 11, ........

标签: pythonpython-3.xmathgeneratorprimes

解决方案


推荐阅读