Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

can anyone here explain me this python code?

+9 votes
asked Apr 27 by Deep Dharva (480 points)
def fib(n):
    if n == 0:
        return 0
    elif n == 1:
        return 1
    else:
        return fib(n-1) + fib(n-2)

num = int(input("Enter number of terms: "))

for i in range(num):
    print(fib(i), end=" ")

1 Answer

0 votes
answered Apr 29 by Imerukz (250 points)

It is the Fibonacci sequence implemented in code througth the Binet's formula. It essentially takes one parameter (n) and calculates it recursively to reach the "Gold number" ratio 1.618. The value supplied to (n) can be infinite but most of the time its performance decreases over time in O(2^n) and dies in (n=35) anything above 35 will take a very long time.

If we set the value of (n) to be 10 and run this exact piece of code, the sequence should look like this:

n = 10, result: 0 1 1 2 3 5 8 13 21 34

A similar behavior can be achieved with:

def fib(n):

    from math import sqrt

    return round(1.618**n / sqrt(5))

Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and receive answers from other members of the community.
...