Search code examples
pythongeneratorfibonacciyieldfunction

how to write generate Fibonacci in python


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

Solution

  • 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)