In python: I am trying to construct a list using enumerate and takewhile from a Fibonaci generator. So far the code I have is the following:
def fibonacci():
(a, b) = (0, 1)
while True:
yield a
(a, b) = (b, a + b)
def createlist(n, fib):
return [elem for (i, elem) in enumerate(takewhile(lambda x: x <
n, fib)) if i < n]
I only get half the list when I do:
print(createlist(n, fibonacci()))
Output: [0, 1, 1, 2, 3, 5, 8]
Expected Output: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34], when n = 10.
Am I missing something in the predicate of takewhile? Could I use a counter inside takewhile? I was specifically asked to use takewhile and enumerate.
I have used Counter inside fibonacci() and in takewhile() i have compared Counter with n value
from itertools import takewhile
def fibonacci():
global count
count=0
(a, b) = (0, 1)
while True:
count+=1
yield (a,count)
(a, b) = (b, a +
b)
def createlist(n, fib):
return [elem[0] for (i, elem) in
enumerate(takewhile(lambda x: x[1]<=n, fib))]
print(createlist(10,fibonacci()))
Output
Get Answers For Free
Most questions answered within 1 hours.