繁体   English   中英

开始使用Python Fibonacci生成器

[英]Beginning Python fibonacci generator

我正在尝试制作一个斐波那契数发生器,该发生器以给定的数量停止,但是通常会超过该数量。 我究竟做错了什么?

#Fibonacci number generator
a=0
b=1
print("Fibonacci number generator.")
stopNumber=input("How high do you want to go? If you want to go forever, put n.")
print(1)
while stopNumber=="n":
        a=a+b
        b=b+a
        print(a)
        print(b)
else:
    while int(stopNumber) > a or int(stopNumber) > b:
        a=a+b
        b=b+a
        print(a)
        print(b)

之所以获得更高的值,是因为您在一个循环中拥有a = a+bb = b+a 因此,当您在while int(stopNumber) > a or int(stopNumber) > b:中检查值while int(stopNumber) > a or int(stopNumber) > b:得到True并进入循环,但是a = a+bb = b+a可以得出ab的值大于stopNumber并且由于您不检查就打印它,因此得到了一些更高的值。 您应该在循环中仅增加一次,如果在while循环之后编写print语句,则不会获得正确的值

prev = 0                             
curr = 1
print("Fibonacci number generator.")
stopNumber = input("How high do you want to go? If you want to go forever, put n.")
if stopNumber == 'n':                    
    print(curr)                     
    curr = prev + curr
    prev = curr
else:
    while curr<stopNumber:
        print(curr)
        curr = prev + curr
        prev = curr

注意:如果输入为n则代码将永远运行。

同样,工作和使用一些更聪明的技术:

# returns generator
def fib(stop):
    prev, current = 0, 1
    while current < stop:  # a little hack here - python is ok comparing ints to floats
        yield current
        # multiple assginment - operands on the left are "frozen" just before theis instruction
        prev, current = current, prev + current 

# note inf - float('inf') results in "positive infinity" which is an appropriate math concept for "forever"
stop = float(input("How high do you want to go? If you want to go forever, put inf."))

for f in fib(stop):
    print (f)

注意:请不要尝试执行list(fib(float('inf'))) :)

进行检查stopNumber> a或b,然后递增a和b,将它们打印出来。 如果您只想在<= stopNumber的情况下打印它们,则执行以下操作:

#Fibonacci number generator
a=0
b=1
print("Fibonacci number generator.")
stopNumber=input("How high do you want to go? If you want to go forever, put n.")
print(1)
while stopNumber=="n":
        a=a+b
        b=b+a
        print(a)
        print(b)
else:
    while True:
        a = a+b
        b = b+a
        if int(stopNumber) >= a:
           print(a)
        if int(stopNumber) >= b:
           print(b)
        else:
          break

使用您的代码:

#Fibonacci number generator
a=0
b=1
print("Fibonacci number generator.")
stopNumber=input("How high do you want to go? If you want to go forever, put n.")
print(1)
while stopNumber=="n" or int(stopNumber) > a+b:
    a, b = b, a+b
    print(b)

第二个“ while”循环始终保持运行状态,即“ a”或“ b”低于“ stopNumber”。 因此,循环继续运行,直到“ a”和“ b”都大于“ stopNumber”。 因此,当“ b”大于“ stopLimit”但“ a”仍小于“ stopLimit”时,循环将继续运行。 因此,要应用的第一个解决方法是将“或”条件更改为“和”。

您只在检查条件是否适用于总和。 然后,在求和之时,其结果可能会大于“ stopLimit”; 这就是您要打印的内容。 要解决此问题,您可以添加“ if”语句以验证总和结果仍低于“ stopNumber”。

使用以下修复程序的代码如下所示:

#Fibonacci number generator
a=0
b=1
print("Fibonacci number generator.")
stopNumber=input("How high do you want to go? If you want to go forever, put n.")
print(1)
while stopNumber=="n":
        a=a+b
        b=b+a
        print(a)
        print(b)
else:
    while int(stopNumber) > a and int(stopNumber) > b:
        a=a+b
        b=b+a
        if int(stopNumber) > a:
            print(a)
        if int(stopNumber) > b:
            print(b)
 #This is a simple yet efficient program using recursion:

def fibonacci_rec(a, b):
    if a >= 0 and b > 0 or a > 0 and b >= 0:
        s = [a, b]
        while a+b <= 1000: #can set any upper boundary  
            f = a+b
            a = b
            b = f
            s.append(f)
            fibonacci_rec(a, b)
        return s
    else:
        return 'Invalid'

print(fibonacci_rec(1, 1))  # You can set any value of a and b, as you like and no need to iterate in here, just call function once and it does the iteration for you! 
def fib(n):
    if n == 0:
        return 0
    if n == 1:
        return 1
    return fib(n-1) + fib(n-2)

print("Fibonacci number generator.")
stopNumber=input("How high do you want to go? If you want to go forever, put n.")
if stopNumber == 'n':
    i=1
    while True:
        print 'Fibonacci #{0}: {1}'.format(i, fib(i))
        i=i+1
else:
    for i in range(1,int(n)):
        print 'Fibonacci #{0}: {1}'.format(i, fib(i))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM