Python Fibonacci Generator

Viewed 95958

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(),
20 Answers

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, ...]
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)
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))

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

Below are two solution for fiboncci generation:

def fib_generator(num):
    '''
    this will works as generator function and take yield into account.
    '''
    assert num > 0
    a, b = 1, 1
    while num > 0:
        yield a
        a, b = b, a+b
        num -= 1


times = int(input('Enter the number for fib generaton: '))
fib_gen = fib_generator(times)
while(times > 0):
    print(next(fib_gen))
    times = times - 1


def fib_series(num):
    '''
    it collects entires series and then print it.
    '''
    assert num > 0
    series = []
    a, b = 1, 1
    while num > 0:
        series.append(a)
        a, b = b, a+b
        num -= 1
    print(series)


times = int(input('Enter the number for fib generaton: '))
fib_series(times)

Why do you go for complex here is one of my snippet to work on!!

n = int(input('Enter your number..: '))
a = 0
b = 1
c = 0
print(a)
print(b)
for i in range(3, n+1):
    c = a+b
    print(c)
    a,b=b,c 

check out my git - rohith-sreedharan

We can use it in a short way without through 'yield and 'next' statements

def fib(n):
    return n if n <= 1 else fib(n - 1) + fib(n - 2)
Related