Python Fibonacci Generator
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 following:
a = int(raw_input('Give amount: '))
def fib():
a, b = 0, 1
while 1:
yield a
a, b = b, a + b
a = fib()
a.next()
0
for i in range(a):
print a.next(),
Solution 1:
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)))
Solution 2:
You are giving a
too many meanings:
a = int(raw_input('Give amount: '))
vs.
a = fib()
You won't run into the problem (as often) if you give your variables more descriptive names (3 different uses of the name a
in 10 lines of code!):
amount = int(raw_input('Give amount: '))
and change range(a)
to range(amount)
.
Solution 3:
Since you are writing a generator, why not use two yields, to save doing the extra shuffle?
import itertools as it
num_iterations = int(raw_input('How many? '))
def fib():
a,b = 0,1
while True:
yield a
b = a+b
yield b
a = a+b
for x in it.islice(fib(), num_iterations):
print x
.....
Solution 4:
Really simple with generator:
def fin(n):
a, b = 0, 1
for i in range(n):
yield a
a, b = b, a + b
ln = int(input('How long? '))
print(list(fin(ln))) # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...]