Home > Software engineering >  Can someone help me understanding this code please?
Can someone help me understanding this code please?

Time:10-23

def fibonacci(n):
    if 0 <= n <= 1:
        return n

    n_minus1, n_minus2 = 1, 0
    result = None
    for f in range(n - 1):
       result = n_minus2   n_minus1
       n_minus2 = n_minus1
       n_minus1 = result

    return result

CodePudding user response:

Try using a couple of different numbers for n and see what results you get. You should be getting Fibonacci numbers.

CodePudding user response:

Thanks for asking the questions. This code is for basically for adding the series of fibonacci series.Taking n or number of element of series are argument.

def fibonacci(n):
    if 0 <= n <= 1:
        return n
    n_minus1, n_minus2 = 1, 0
    result = None
    for f in range(n - 1):
        result = n_minus2   n_minus1
        n_minus2 = n_minus1
        n_minus1 = result
    return result
print(fibonacci(1))

CodePudding user response:

def fibonacci(n):
    if 0 <= n <= 1:
        return n
    n_minus1, n_minus2 = 1, 0
    result = None
    for f in range(n - 1):
        result = n_minus2   n_minus1
        n_minus2 = n_minus1
        n_minus1 = result
    return result
print(fibonacci(1))

The Fibonacci Sequence is the series of numbers:

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...

The next number is found by adding up the two numbers before it:

the 2 is found by adding the two numbers before it (1 1),
the 3 is found by adding the two numbers before it (1 2),
the 5 is (2 3),
and so on!
if 0 <= n <= 1:
        return n
In the given function if the number given is between 0 and 1 then that number is returned
n_minus1, n_minus2 = 1, 0
First you have initialised the values for variables n_minus1=1,n_minus2=0
result = None
For avoiding the garbage values you have taken result=None
for f in range(n - 1):
       result = n_minus2   n_minus1
       n_minus2 = n_minus1
       n_minus1 = result
Here you have taken a loop for repating addition
 result=0 1=1
so result=0
then you have assigned n_minus1 value to n_minus2 that is 
n_minus2=1
and assigned result value to n_minus1 that is n_minus1=1
So our new values are n_minus1=1,n_minus2=1
and again result is calculated by result = n_minus2   n_minus1
So result=1 1=2
and
n_minus2=n_minus1=1
n_minus1=result=2
again our new values are 
n_minus2=1
n_minus1=2
again result is calculated and we will get new values for n_minus1,n_minus2 
the above process runs for n-1 times
  • Related