源代码:
# 函数1:构造从3开始的奇数迭代器
def _odd_iter():
n = 1
while True:
n = n + 2
yield n
# 函数2:筛选素数
def _not_divisible(n):
return lambda x: x % n > 0 # x是 函数1 产生的新奇数,n是遍历经过筛选的素数序列it中的每一个元素
# 函数3:返回迭代器中的下一个素数
def primes():
yield 2
it = _odd_iter() # 初始序列
while True:
n = next(it) # n是'函数1'不断yield的奇数序列
yield n
it = filter(_not_divisible(n), it) # 构造新序列
# 函数4:打印的素数:
for n in primes():
print(n)
代码解释
-
yield 和return 的区别在于是否会从断点处的下一句继续运行
-
产生的2,3(进入it素数序列)没有经过验证,直接输出
-
it = filter(_not_divisible(n), it) 代码中,如果n有指定,则为n,没有指定的话,传入的参数为it中的经过筛选的元素
-
n 是如何被一遍遍调用来遍历的呢? x 被遍历很好理解
-
两个it 是不一样的,如下图所示
用打印id 的方式验证两个it 不同
相关测试—来自python教程底下的评论
'''
_not_divisible(n)是闭包函数,它需要外层函数参数n和内层函数参数x,是延迟计算。
n是第一个素数比如3,那么它的所有倍数6、9、12等为False,从而在重构新序列时被filter清除。
而x当然就是filter()的第一个参数,一个个遍历得到。
'''
>>> def _not_divisible(n):
def inner_mod(x):
return x % n > 0
return inner_mod
>>> f=_not_divisible(3)
>>> print(f(6))
False
>>> print(f(5))
True
Q&A
- 如何编写代码打印出小于某数值的质数?