gpt4 book ai didi

python - 开始Python斐波那契生成器

转载 作者:太空宇宙 更新时间:2023-11-03 18:44:31 25 4
gpt4 key购买 nike

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

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

最佳答案

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

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

关于python - 开始Python斐波那契生成器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19838152/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com