In: Computer Science
PYTHON PROBLEM: TASKED TO FIND THE FLAW WITH THE FOLLOWING CODE:
from itertools import count
def take_e(n, gen):
return [elem for (i, elem) in enumerate(gen) if i < n]
def take_zc(n, gen):
return [elem for (i, elem) in zip(count(), gen) if i < n]
FIBONACCI UNBOUNDED:
def fibonacci_unbounded():
"""
Unbounded Fibonacci numbers generator
"""
(a, b) = (0, 1)
while True:
# return a
yield a
(a, b) = (b, a + b)
SUPPOSED TO RUN THIS TO ASSIST WITH FINDING THE FLAW:
take_e(5, fibonacci_unbounded())
The code under function fibonacci_unbounded is 100% correct.It will create and return a infinite fibonacci generator object.
FLAW:-
return [elem for (i, elem) in enumerate(gen()) if i < n]
This is a normal list comprehension statment. The wrong here is that a termination statement is not provided .
NO ,i<n will not terminate and return the list. It is a check condition for the values which has to inserted in list . It is not responsible for the termination and returning of the list. i<n will keep checking for the next element till infinity .
Same problem in the take_zc function
Thats why this code is not working.
REMEDY:- Replace your take_e function with this
def take_e(n, gen):
l1 = []
for i,elem in enumerate(gen):
l1.append(elem)
if i>=n:return l1
Attaching the full code with output:-
NOTE :- Since , you haven't asked for
take_zc function and I am not sure what this
function want to achieve .It is difficult for me to write an
alternative solution for that function.