patternpythonModerate
Wrapping my head around generators
Viewed 0 times
aroundheadgeneratorswrapping
Problem
I am going on with refactoring my code base while migrating from Python 2 to Python 3. I am using generators to make reusable components this time as I am more comfortable with them this time then last time. But there are times when I am stuck at their use. Like below example. These two are essentially same with one infinitely generating and other with a limit.
Is there a way to make these as one function? Normally an extra optional parameter as limit will do the trick but with generators I am not sure how to use them. Is there some way to do that?
Is there a way to make these as one function? Normally an extra optional parameter as limit will do the trick but with generators I am not sure how to use them. Is there some way to do that?
def fibonacci_inf(a, b):
"""Lazily generates Fibonacci numbers Infinitely"""
while True:
yield b
a, b = b, a + b
def fibonacci(a, b, num):
"""Lazily generates Fibonacci numbers"""
while b < num:
yield b
a, b = b, a + bSolution
You could just implement the infinite generator, and use
itertools.takewhile to limit it:>>> list(itertools.takewhile(lambda x : x < 8, fibonacci_inf(0,1)))
[1, 1, 2, 3, 5]Code Snippets
>>> list(itertools.takewhile(lambda x : x < 8, fibonacci_inf(0,1)))
[1, 1, 2, 3, 5]Context
StackExchange Code Review Q#45752, answer score: 10
Revisions (0)
No revisions yet.