Python Fibonacci Generator
Python Fibonacci Generator
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)))
You are giving a
too many meanings:
a = int(raw_input(Give amount: ))
vs.
a = fib()
You wont 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)
.
Python Fibonacci Generator
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
…..