对廖雪峰网站python教程中求素数的理解

原代码如下:

def _odd_iter():
    n = 1
    while True:
        n = n + 2
        yield n
def _not_divisible(n):
    return lambda x: x % n>0
def primes():
    yield 2
    it = _odd_iter() # 初始序列
    while True:
        n = next(it) # 返回序列的第一个数
        yield n
        it = filter(_not_divisible(n), it) # 构造新序列
for n in primes():
    if n < 1000:
        print(n)
    else:
        break

廖雪峰python教程的网站链接
对廖雪峰网站python教程中求素数的理解
该代码是取3到1000的奇数,并用前面的数消去后面成倍数的数。从for循环开始,primes()里的第一个数为2,即第一个数print为2。接着继续循环,从yield 2下句开始,it= _odd_iter(),即it为【3,5,7,9…】的奇数序列,n是对序列it内部的一个接一个的取值,从第一个数3开始取,此时yield n (n=3),print 3。继续for循环到yield n下一句:it = filter(_not_divisible(n), it),此时n为3,用_not_divisible(n)函数将it中3的倍数进行筛选,留下不是3的倍数的数,接着n=5,yield 5。再利用n=5将it中5的倍数的数筛选,就这样不断循环,不断筛选,最终得到小于1000的素数。

相关文章:

  • 2022-02-09
  • 2022-01-03
  • 2021-05-17
  • 2021-12-25
  • 2022-12-23
  • 2022-12-23
  • 2021-05-19
  • 2021-05-28
猜你喜欢
  • 2021-12-12
  • 2022-12-23
  • 2021-12-27
  • 2021-10-26
  • 2022-01-19
  • 2022-12-23
  • 2021-04-03
相关资源
相似解决方案