Python uses filter to find primes

examples of finding primes using filter in Liao Xuefeng"s Python tutorial are not clear,

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) -sharp
for n in primes():
    if n < 30:
        print(n)
    else:
        break

about the sentence it = filter (_ not_divisible (n), it) , since it is an iterator that is lazily calculated, then every time filter runs to this sentence, filter only Filter a value from the current yield of the infinite list represented by it, so why do you end up with an infinite list that passes all the filters?

Mar.21,2021

filter and map are similar, and the return is also an iterator. Filter each item of the iterable object with the specified function, convert it to list or use the for loop to filter each item at once. You can try this code

.
  official document  says: 
filter (function, iterable) is equivalent to (item for item in iterable if function (item))

Menu