python - 具有 2 个迭代器和 2 个范围的 for 循环

标签 python loops iterator

我是 Python 新手,正在处理素数生成器。我想使用的算法是 Sieve of Atkin .

此刻,我正在尝试按照算法的伪代码作为我的练习。但是,我遇到了一个问题,我找不到任何关于它的引用。 (也许我不擅长搜索......)。在伪代码中,for (x, y) in [1, √limit] × [1, √limit]:... 让我感到困惑。我知道这是什么意思,但不知道如何将这段代码翻译成 Python 代码。

如果我的问题不合适,请见谅,感谢您的帮助。 :)

下面是我的部分代码。

itx = iter(range(1, int(limit**0.5)))
ity = iter(range(1, int(limit**0.5)))
for x, y in zip(itx, ity):
    n = 4*(x**2)+(y**2)
    if n <= limit and (n%12 == 1 or n%12 == 5):
        sieve[n] = not sieve[n]

    n = 3*(x**2)+(y**2)
    if n <= limit and n%12 == 7:
        sieve[n] = not sieve[n]

    n = 3*(x**2)-(y**2)
    if x > y and n <= limit and n%12 == 11:
        sieve[n] = not sieve[n]

    itx.next()
    ity.next()

最佳答案

for (x, y) in [1, √limit] × [1, √limit] 应该翻译成乘积:

for x in itx:
    for y in ity:

或使用 itertools.product() :

from itertools import product

for x, y in product(itx, ity):

请注意,您不需要需要在迭代器上调用.next()!删除 itx.next()ity.next() 行,除非您意思跳过生成的值。 for 构造为您改进迭代器。

关于python - 具有 2 个迭代器和 2 个范围的 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20968854/

相关文章:

c++ - 无法创建由 "Parent"链接的元素列表

python - 缺少必需的参数,类中的多处理

python - 如何检测函数是否已在本地定义?

python - 在 python 中获取空 CSV

python - 如何检查列表是否只包含某个项目

C# 计数元音

iphone - 只要在Xcode中按住按钮,如何使声音循环?

javascript - Closure 函数的输出出现奇怪的 "undefined"值

java - 如何使用ListIterator向空列表添加元素?

java - 在 Java TreeMap 中查找元素位置