In python, a recursive function for a Fibonacci sequence that returns the nth fibonacci number can be written as:
def fib(n):
if n == 1:
return 0
if n == 2:
return 1
return fib(n-2) + fib(n-1)
I understand how this function works, but if someone were to have never seen this function before, how would one derive it?
Thanks
It's just a crude translation of the mathematical definition of the Fibonacci sequence.
The Fibonacci sequence is defined as:
F 0 = 0
F 1 = 1
F n = F n-1 + F n-2
You can see that the Python code is basically a direct translation of this (except with n
off by 1).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.