[英]How was the recursive fibonacci function derived?
In python, a recursive function for a Fibonacci sequence that returns the nth fibonacci number can be written as: 在python中,返回第n个斐波那契数的Fibonacci序列的递归函数可以写成:
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 0 = 0
F 1 = 1 F 1 = 1
F n = F n-1 + F n-2 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). 您可以看到Python代码基本上是对此的直接翻译(除非n
off by 1)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.