Python斐波纳契数列

时间:2015-05-12 20:16:33

标签: python

from decimal import Decimal
pos_inf = Decimal('Infinity')

f1 = 1
f2 = 1
n = 0

while n < pos_inf:
    n = f1 + f2

    f1 = n
    f2 = f1 + f2

    print(f1)
    if(len(str(f1) == 3):
         break
     print(f1 + the number is found)
print(f2)

if(len(str(f2) == 3):
    break
print(f2 + the number is found)

这显然是一个Fibonacci生成器,其中一个打印的数字中的一个将是144,这将是第一个有3位数的数字。我不确定为什么以上不起作用?

6 个答案:

答案 0 :(得分:1)

问题是你如何计算斐波纳契数。它应该是

while n < pos_inf:
    n = f1 + f2
    f2 = f1
    f1 = n

答案 1 :(得分:1)

你的代码有很多简单的语法错误(例如错误的括号,错误的缩进和多余的代码),但这个概念大多是正确的。

你犯的唯一逻辑错误是对f2迭代器的多次使用。

我在这里修复了你的代码:

from decimal import Decimal
pos_inf = Decimal('Infinity')

f1 = 1
f2 = 1
n = 0

while n < pos_inf:
    n = f1 + f2

    f1 = f2
    f2 = n


    if len(str(f1)) == 3:
       print(str(f1) + " the number is found")
       print(f2)
       break
    print(f1)

这给了我们

1
2
3
5
8
13
21
34
55
89
144 the number is found
233

答案 2 :(得分:0)

我假设你想在while循环之后缩进所有内容

这是你想要做的:

f1 = f2
f2 = n

此外,一旦f1达到3位数字,你的代码就会打印出来,然后打破。

此外,您需要在print语句中使用引号并将整数转换为字符串:

print(str(f1) + ' the number is found')

答案 3 :(得分:0)

你的if语句中也有错误的parens错误。这应该有效:

from decimal import Decimal
pos_inf = Decimal('Infinity')
f1 = 1
f2 = 1
n = 0

while n < pos_inf:
    n = f1 + f2

    f1 = n
    f2 = f1 + f2
    print(f1)
    if(len(str(f1)) == 3):
       print(str(f1) + 'the number is found')
       break
    print(f2)
    if(len(str(f2)) == 3):
       print(str(f2) + 'the number is found')
       break

答案 4 :(得分:0)

如果您只是寻找前3位febbonaci号码,那么下面的代码应该可以正常工作

from decimal import Decimal
pos_inf = Decimal('Infinity')

f1 = 1
f2 = 1
n = 0

while n < pos_inf :
    n = f1 + f2
    f1 = f2
    f2 = n
    print(f2)
    if (len(str(f2)) == 3):
        break

print f2, "3 digit number found"

答案 5 :(得分:0)

这是我的解决方案。虽然我无法通过与你正在使用的pos_inf变量有关的错误。它说无法将无穷大转换为整数。也许这对你造成了一个问题。

var1 = var2 = 1
result = 0

print(result)
print(var1)
print(var2)

for x in range(1,100):
    result = var1 + var2
    print(result)
    var2 = var1
    var1 = result
    if result == 144:
        print("The number has been found")
        break
相关问题