Search code examples
pythoniterationfunc

Fib2 function without recursion in Python


I need help for defining the fibanocci 2 function. The fibanocci 2 function is decribed as : fib2(n) = {0 if n <= 0, 1 if n = 1, 2 if n = 2, ( fib2( n - 1) * fib2( n - 2)) - fib2( n - 3) else}

We need to define this function iterative. I tried my best but i couldn't write a working code.

def fib2(n: int) -> int:
    if n <= 0:
        return 0
    elif n == 1:
        return 1
    elif n == 2:
        return 2
    else:
        n = ((n - 1) * (n - 2) - (n - 3)
    return n
a = fib2(7)
print (a)
assert (fib2(7) == 37) 

the output from this fib2 function is 26 but it should be 37. Thank you in advance


Solution

  • For the iterative version you have to use a for loop. And just add the 3 previous numbers to get the next one.

    Here is a piece of code:

    def fib3(n):
        a = 0
        b = 1
        c = 0
        for n in range(n):
            newc = a+b+c
            a = b
            b = c
            c = newc
        return newc
    
    print(fib3(7))
    assert (fib3(7) == 37)