I tried to print all the prime number less than 100 with flowing code:
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<100:
print(n)
else:
break
And it works fine.
But after I change the _not_divisible
function into lambda, it seems not work:
def _odd_iter():
n=1
while True:
n=n+2
yield n
def primes():
yield 2
it = _odd_iter()
while True:
n=next(it)
yield n
it = filter(lambda x:x%n>0,it)
for n in primes():
if n<100:
print(n)
else:
break
The result shows that the filter has dropped nothing.
Why doesn't it works with lambda?