Beginning Python fibonacci generator

有些话、适合烂在心里 提交于 2019-12-08 07:31:06

问题


I'm trying to make a fibonacci number generator that stops at a given amount, but it usually goes past the amount. What am I doing wrong?

#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)

回答1:


Using your code:

#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)



回答2:


The same, working and using a little smarter techniques:

# 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)

Note: please don't try doing list(fib(float('inf'))) :)




回答3:


The reason you are getting some higher values is because you are having a = a+b and b = b+a in a single loop. So when you are checking the values in while int(stopNumber) > a or int(stopNumber) > b: you get True and enter the loop but a = a+b and b = b+a can make the value of a and b greater than stopNumber and since you are printing it without checking it, you are getting some higher values. You should increment only once in the loop and if you write the print statement just after the while loop you will not get correct values

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

Note: The code will run forever if the input is n.




回答4:


You do the check if stopNumber > a or b, then you increment a and b, printing them. If you only wanted to print them if they were <= stopNumber than do something like this:

#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



回答5:


The second "while" loop keeps running always either "a" OR "b" is lower than "stopNumber". Therefore, the loop continues to run until BOTH "a" and "b" are greater than "stopNumber". In consequence, when "b" is greater than "stopLimit" but "a" is still lower than "stopLimit" the loop keeps running. So the first fix to apply is to change the "or" condition by an "and" one.

You are only checking that the condition applies before the sums. Then, by the moment that the sums are done their results may be greater than "stopLimit"; and that is what you print. To fix this, you can add an "if" statement to verify that the sum results are still below "stopNumber".

This is how the code looks with these fixes:

#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)



回答6:


 #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! 



回答7:


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))


来源:https://stackoverflow.com/questions/19838152/beginning-python-fibonacci-generator

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!