filter and map easily converted to list comprehension.
Here is a basic example:
[hex(n) for n in range(0, 100) if n > 20]
This is equivalent to:
list(map(hex, filter(lambda x: x > 20, range(0, 100))))
Understanding, in my opinion, is more readable. However, if the conditions become very advanced, I prefer filter .
So in your case:
[n for n in itertools.islice(fib_gen(), 100) if even(n)]
I used islice here because the sequence is infinite. But if you use a generator expression, it also becomes an endless stream:
gen = (n for n in fib_gen() if even(n))
Now you can also slice the sequence using islice :
print itertools.islice(gen, int(sys.argv[1]))
This avoids the need to use next in the insights themselves. Until you try to evaluate an infinite sequence (as if we skipped islice in list comprehension), we can work with your sequence.
source share