I have problem understanding what the return fibonacci( number-1 ) + fibonacci( number-2 ) does in the following program:
import sys
def fibonacci( number ):
if( number <= 2 ):
return 1
else:
return fibonacci( number-1 ) + fibonacci( number-2 )
The problem is that I can't imagine how this line works:
return fibonacci( number-1 ) + fibonacci( number-2 )
Does the both of the "fibonacci( number-1 )" and "fibonacci( number-2 )" being processed at the same time? or the "fibonacci( number-1 )" is the first to be processed and then the second one?
I only see that processing both of them would eventually return '1' so the last result I expect to see it is a '1 + 1' = '2'
I would appreciate a lot, If someone can elaborately explain the process of its calculation.
I think this is a very newb question but I can't really get a picture of its process.
Why don't you do something like this:
>>> def fibonacci(number):
... if number < 2:
... return number
... print "Number is currently %d, getting fibonacci(%d)" % (number, number - 1)
... minus_one = fibonacci(number-1)
... print "Number is currently %d, just got fibonacci(%d), now getting fibonacci(%d)" % (number, number - 1, number - 2)
... minus_two = fibonacci(number-2)
... print "Number is currently %d, returning %d + %d" % (number, minus_one, minus_two)
... return minus_one + minus_two
So that when you call fibonacci you get something like this:
>>> fibonacci(4)
Number is currently 4, getting fibonacci(3)
Number is currently 3, getting fibonacci(2)
Number is currently 2, getting fibonacci(1)
Number is currently 2, just got fibonacci(1), now getting fibonacci(0)
Number is currently 2, returning 1 + 0
Number is currently 3, just got fibonacci(2), now getting fibonacci(1)
Number is currently 3, returning 1 + 1
Number is currently 4, just got fibonacci(3), now getting fibonacci(2)
Number is currently 2, getting fibonacci(1)
Number is currently 2, just got fibonacci(1), now getting fibonacci(0)
Number is currently 2, returning 1 + 0
Number is currently 4, returning 2 + 1
3
It's still complex, but at least now you can see what the function is doing to calculate your number.
Does the both of the "fibonacci( number-1 )" and "fibonacci( number-2 )" being processed at the same time? or the "fibonacci( number-1 )" is the first to be processed and then the second one?
Does it matter?
What is happening is that the function is called twice. Once with the value of number -1 and once -2, for the value of number that was passed in to the current "instance" of the function.
Say you call fibonacci(3). That line would end up being:
return fibonacci(2) + fibonacci(1)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With