I need to make a program that asks for the amount of Fibonacci numbers printed and then prints them like 0, 1, 1, 2... but I can\'t get it to work. My code looks the followi
def fibonacci(n):
fn = [0, 1,]
for i in range(2, n):
fn.append(fn[i-1] + fn[i-2])
return fn
I've build this a while ago:
a = int(raw_input('Give amount: '))
fab = [0, 1, 1]
def fab_gen():
while True:
fab.append(fab[-1] + fab[-2])
yield fab[-4]
fg = fab_gen()
for i in range(a): print(fg.next())
No that fab
will grow over time, so it isn't a perfect solution.
You had the right idea and a very elegant solution, all you need to do fix is your swapping and adding statement of a and b. Your yield statement should go after your swap as well
a, b = b, a + b ####
should be a,b = a+b,a #####
`###yield a`
I would use this method:
Python 2
a = int(raw_input('Give amount: '))
def fib(n):
a, b = 0, 1
for _ in xrange(n):
yield a
a, b = b, a + b
print list(fib(a))
Python 3
a = int(input('Give amount: '))
def fib(n):
a, b = 0, 1
for _ in range(n):
yield a
a, b = b, a + b
print(list(fib(a)))
Also you can use enumerate infinite generator:
for i,f in enumerate(fib()):
print i, f
if i>=n: break
Also you can try the closed form solution (no guarantees for very large values of n due to rounding/overflow errors):
root5 = pow(5, 0.5) ratio = (1 + root5)/2 def fib(n): return int((pow(ratio, n) - pow(1 - ratio, n))/root5)