Python中的Fibonacci解释这段代码?

2024-10-01 00:15:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我对编码相当陌生,我一直在使用alexbowers的《Python初学者手册》。每一章的结尾都是一个实验练习,这一章是关于Fabonacci的,这一章本身是关于forLoops,whileLoops,Try Except和Finally,以及中断和继续。 我对解很困惑,尤其是关于变量“set”的那些行,有人能给我解释一下这个解吗,因为他们没有在书中解释它。。。谢谢你

f0 = 0
f1 = 1
set = False              
while True:
    fn = f0 + f1
    f0 = f1
    f1 = fn 
    if (fn > 100):
        set = True
    else:
        set = False
    print(fn)
    if (set == True):
        break 

Tags: falsetrue编码if结尾手册f1fn
3条回答

在本例中,set一旦数字超过100,它将停止循环,因此它不会永远运行。这实际上是一个相当糟糕的斐波纳契序列,但我会解释,因为它无论如何都是有效的代码。。。在

f0 = 0 # initialize your
f1 = 1 # starting values
set = False              
while True:
    fn = f0 + f1 # fn is your current fib number
    f0 = f1 # advance the second-to-last number
    f1 = fn # and the last number
    if (fn > 100):
        set = True # if your current fib number is above 100, set a flag
                   # so we don't go another iteration
    else:
        set = False# otherwise, this should never ever do anything. This
                   # line of code does nothing but slow down the process
    print(fn) # print your current fib number to console
    if (set == True): # if that aforementioned flag is set...
        break         # then break out of the loop. Otherwise, loop.

不管怎样,我会做:

^{pr2}$

我假设你知道Fibonacci序列是什么(如果不知道,读this)。我一次就走这一步

这些是用于计算Fibonacci序列的变量。f0是序列中的第一个数字,f1是第二个数字。在

f0 = 0
f1 = 1

set将用作以下循环的条件,以确定何时停止。在

^{pr2}$

这是一个无限的while循环。在

^{3}$

计算序列中的下一个数字。在

    fn = f0 + f1

更新旧变量。在

    f0 = f1
    f1 = fn 

如果序列中的数字大于100,请将set设置为True。否则将set设置为False(它已经是了)。在

    if (fn > 100):
        set = True
    else:
        set = False

打印当前序列号。在

    print(fn)

如果setTrue,则离开无限循环。在

^{8}$

注意:此代码可以轻松简化。我很惊讶它出现在一本书里。您可以将其简化为:

f0 = 0
f1 = 1
while True:
    fn = f0 + f1
    f0 = f1
    f1 = fn 
    print(fn)
    if (fn > 100):
        break 

与使用set不同的是,可以用这种方式编写代码,以实现相同的目的,否则将完全相同:

f0 = 0
f1 = 1
fn = 0
while fn <= 100:
    fn = f0 + f1
    f0 = f1
    f1 = fn 
    print(fn)

使用set是使用适当循环条件(即fn <= 100位)的一种奇怪且冗长的替代方法,并且可能只有在有和没有else子句的if语句的示例中才会出现这种情况。在

使用本书其他地方可能遇到的更高级的逻辑,您还可以消除fn变量:

^{pr2}$

f0, f1 = f1, f0 + f1类似于:

^{3}$

除了在f0f1更改值之前,对两个右侧表达式求值。在

希望看到它以这种简化的形式写下来,可以帮助你准确地理解到底发生了什么。在

相关问题 更多 >