簡體   English   中英

Python - 關於斐波那契數列

[英]Python - About Fibonacci sequence

我嘗試編寫一個代碼,要求用戶輸入一個正數,然后告訴他/她這個數字是否屬於斐波那契數列。 問題是,當我運行代碼時,它永遠不會停止運行(或者最終我會得到一個錯誤)。 到目前為止,這是我的代碼:

print("\nEnter any positive number, to see if it")
user = input("belongs to the Fibonacci sequence: ")

def fibo(user):
    if user in [0,1]:
        return user
    else:
        return fibo(user-1) + fibo(user-2)


while user.isdigit() == False:
    user = input("Input error. Please enter a positive number: ")
else:
    user = int(user)

if user == fibo(user):
    print("\nNumber",user,"belongs to the Fibonacci sequence.\n")
else:
    print("\nNumber",user,"doesn't belong to the Fibonacci sequence.\n")
def fibo(input):
    if int(input) == 0: return [0]
    x = 0; y = 1; z = 0; erg = []
    while True:
        z = x + z; x = y; y = z
        if y > int(input): break
        else: erg.append(y)
    if int(input) in erg: return True
    else: return False
 
print(fibo(input("fibonacci?: ")))
def fibo(input):
    i = int(input)
    # set z to 1 if you want
    # False to be returned for 0
    x = 0; y = 1; z = 0
    while z < i:
        z = x + y; x = y; y = z
    if z == i: return True
    return False
 
print(fibo(input("fibonacci?: ")))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM