簡體   English   中英

通過循環查找/存儲斐波那契數列的前 50 個項

[英]Find/store the first 50 terms of the Fibonacci sequence via Looping

我正在嘗試通過循環查找斐波那契數列的前 50 個元素並將其存儲到一個數組中。 我對 Python 很陌生,我無法超越這一點,我很沮喪,因為我不知道該怎么做。

到目前為止我的代碼:

x=51
 def Fibonacci(x):
    First_Value=0
    Second_Value=1
    for i in range(x):
        Next_value = First_Value
        First_Value = Second_Value
        Second_Value = Next_value + Second_Value
    return Fist_Value"

但我不知道如何在必須顯示前 50 個值的數組中打印它。

您可以在 function 的開頭定義一個空列表(或數組),然后在 for 循環的每次迭代中添加到它。

這是一個例子

def Fibonacci(x):
    fib_array = [None]*x
    First_Value=0
    Second_Value=1
    for i in range(x):
        Next_value = First_Value
        First_Value = Second_Value
        Second_Value = Next_value + Second_Value
        fib_array[i] = First_Value
    return fib_array

Fibonacci(10)

Output

[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]

由於您已經知道如何生成斐波那契數,因此一種解決方案是簡單地從您預定義的 function 中生成一個數組:

result = [Fibonacci(x) for x in range(51)]

但這是非常低效的(你一直在重新計算斐波那契數)。 您可以通過調整 function 來改進它:

def Fibonacci(x):
    if x < 0:
        raise ValueError("Argument has to be a nonnegative integer")
    if x == 0:
        return []
    if x == 1:
        return [0]
    result = [0, 1]
    for _ in range(x-2, 0, -1):
        result.append(result[-1] + result[-2])
    return result

print(Fibonacci(51))

您的代碼可以修改為返回一個數組。

def Fibonacci(x):
   First_Value=0
   Second_Value=1
   Result = []
   for i in range(x):
       Next_value = First_Value
       First_Value = Second_Value
       Second_Value = Next_value + Second_Value
       Result.append(Next_value)
   return Result

print(Fibonacci(20))

Output:

[0、1、1、2、3、5、8、13、21、34、55、89、144、233、377、610、987、1597、2584、4181]

暫無
暫無

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

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