python 中的 Fibonacci - 有人可以解释范围之间的 Fibonacci 数是如何工作的吗?
Fibonacci in python - Can some explain how this Fibonacci number between range works?
我正在学习 python 编程,但我 运行 遇到了一些麻烦。我发现这段代码通过用户输入的开始和结束数字来计算斐波那契数列。谁能解释一下这段代码是如何工作的?
def fib(lowerbound, upperbound):
x = 0
y = 1
while x <= upperbound:
if (x >= lowerbound):
yield x
x, y = y, x + y
startNumber = 10
endNumber = 100
for fib_sequence in fib(startNumber, endNumber):
print "And the next number is... %d!" % fib_sequence
函数 def fib( ...
returns 您可以使用 for i in <return val by fib>
对其进行迭代的列表
我想您的主要困惑在于 yield
部分。它所做的是记住过去的值(即 x
和 y
的值),下次它从以前的值继续,每当它看到 yield
时,它都会添加产生的值(x
这里)到返回的列表。
https://www.jeffknupp.com/blog/2013/04/07/improve-your-python-yield-and-generators-explained/
本文将为您解开所有疑惑。
干杯!
我正在学习 python 编程,但我 运行 遇到了一些麻烦。我发现这段代码通过用户输入的开始和结束数字来计算斐波那契数列。谁能解释一下这段代码是如何工作的?
def fib(lowerbound, upperbound):
x = 0
y = 1
while x <= upperbound:
if (x >= lowerbound):
yield x
x, y = y, x + y
startNumber = 10
endNumber = 100
for fib_sequence in fib(startNumber, endNumber):
print "And the next number is... %d!" % fib_sequence
函数 def fib( ...
returns 您可以使用 for i in <return val by fib>
我想您的主要困惑在于 yield
部分。它所做的是记住过去的值(即 x
和 y
的值),下次它从以前的值继续,每当它看到 yield
时,它都会添加产生的值(x
这里)到返回的列表。
https://www.jeffknupp.com/blog/2013/04/07/improve-your-python-yield-and-generators-explained/
本文将为您解开所有疑惑。
干杯!