how to write generate Fibonacci in python

Question:

def fib(a, b, f):

fib must generate (using yield) the generalized Fibonacci
sequence, a and b is first and second element. f is function to get the third element instead of a+b as normal Fibonacci sequence. Use take function(which show below) to test it.

my code is below

def fib(a, b, f):
    x = a
    y = b
    yield x
    x, y = y, f(x,y)
    fib(x,y,f)

I don’t know what is wrong of my code, when I try to test it, it show
"TypeError: 'generator' object is not subscriptable"

the test case is:

 take(5, fib(0, 1, lambda x, y: x - y))

It should out put:

[0, 1, -1, 2, -3]

and take function as i write is :

def take(n, iterable):
       x = []
    if n <= 0:
        return x
    else:
        for i in range (0,n):
            x.append(iterable[i])
        return x
Asked By: user3609909

||

Answers:

The message means that generators do not support indexing, so iterable[i] fails. Instead, use the next() function to get the next item from the iterator.

def take(n, iterable):
    x = []
    if n > 0
        itr = iter(iterable)     # Convert the iterable to an iterator
        for _ in range(n):       # Repeat n times
            x.append(next(itr))  # Append the next item from the iterator
    return x

Also, your fib() function will not work. You should not recurse at the end of the function; instead write a loop that yields a value each iteration.

def fib(a, b, f):
    x = a
    y = b
    while True:
        yield x
        x, y = y, f(x,y)
Answered By: augurar

You can’t index into the results coming from a generator function like fib(). This following avoids that by using zip() with a range() argument. zip() stops automatically when one of its arguments reaches then end.

def fib(a, b, f):
    x, y = a, b
    while True:
        yield x
        x, y = y, f(x, y)

def take(n, iterable):
    return [] if n <= 0 else [v for _, v in zip(range(n), iterable)]

print( take(5, fib(0, 1, lambda x, y: x-y)) )

Output:

[0, 1, -1, 2, -3]
Answered By: martineau

Fibonacci simplest method you’ll ever come across:

a , b =0 , 1

for n in range(100):#any number 
    print(a)
    a = a + b
    print (b)
    b = b + a
Answered By: Rxnaiross
def fibo(n):
    if n == 0:
        return 0
    elif n == 1:
        return 1
    else:
        return fibo(n - 1) + fibo(n - 2)


n = int(input("enter the number: "))
for i in range(n):
    print(fibo(i))
Answered By: Tushar Parmar