Maison  >  Questions et réponses  >  le corps du texte

python 教程的有 2 个地方看不懂

用 Python 来实现这个算法,可以先构造一个从 3 开始的奇数序列:

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) # 构造新序列这个生成器先返回第一个素数 2 ,然后,利用 filter()不断产生筛选后的新的序列。


巴扎黑巴扎黑2899 Il y a quelques jours913

répondre à tous(1)je répondrai

  • 面对疾风吧

    面对疾风吧2016-11-11 17:27:36

    @sensui7 filter(function, iterable),传入一个函数和一个可迭代对象。

    répondre
    0
  • Annulerrépondre