using filter and generator to generator endless prime number in python

前端 未结 3 733
清酒与你
清酒与你 2021-01-07 10:42

Below is a python program I found to find prime numbers using Sieve of Eratosthenes. It uses filter and generator. I\'m not able to understand it.

def _odd_i         


        
3条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-07 11:19

    First, filter over iterator returns another iterator. I.e. when we do something like:

    it = filter(_not_divisible(3), it)
    it = filter(_not_divisible(5), it)
    

    We get a chained iterator "odd number AND not divisible by 3 AND not divisible by 5". It is somewhat similar to chained decorators, where we get an equivalent of:

    # assuming we have decorator @not divisible
    @not_divisible(2)
    def iter():
        return xrange(inf)
    
    # then, at every subsequent prime we do something like:
    iter = not_divisible(3)(iter)
    # next prime is 5:
    iter = not_divisible(5)(iter)
    

    ... and so on

提交回复
热议问题