[英]Can someone help me understanding this code please? [closed]
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
尝试对n
使用几个不同的数字,看看你会得到什么结果。 你应该得到斐波那契数字。
感谢您提出问题。 此代码基本上用于添加斐波那契系列的系列。以 n 或系列元素的数量为参数。
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))
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.