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
a = 3 #raw_input
def fib_gen():
a, b = 0, 1
while 1:
yield a
a, b = b, a + b
fs = fib_gen()
next(fs)
for i in range(a):
print (next(fs))
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
.....
def genFibanocciSeries():
a=0
b=1
for x in range(1,10):
yield a
a,b = b, a+b
for fib_series in genFibanocciSeries():
print(fib_series)
Your a
is a global name so-to-say.
a = int(raw_input('Give amount: '))
Whenever Python sees an a
, it thinks you are talking about the above one. Calling it something else (elsewhere or here) should help.
It looks like you are using the a
twice. Try changing that to a different variable name.
The following seems to be working great for me.
def fib():
a, b = 0, 1
while True:
yield a
a, b = b, a+b
f = fib()
for x in range(100):
print(f.next())
i like this version:
array = [0,1]
for i in range(20):
x = array[0]+array[1]
print(x)
array[0] = array[1]
array[1] = x