简体   繁体   中英

Beginning Python fibonacci generator

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)

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 .

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

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

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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