考慮一個廣義的斐波那契數列:
Y_n = f({Y_i}_{nk}^{n-1})
我們可以在 Haskell 單行中實作這個系列:
gfib f xs = (head xs) : gfib f ((tail xs) [f xs])
結果:
ghci> take 10 $ gfib sum [0, 0, 1]
[0,0,1,1,2,4,7,13,24,44]
ghci> take 10 $ gfib sum [0, 1]
[0,1,1,2,3,5,8,13,21,34]
我想知道如何在 Python 中使用盡可能少的代碼而不使用類/物件來實作相同的系列。
謝謝。
uj5u.com熱心網友回復:
使用生成器:
def gfib(f, xs_init):
xs = xs_init[:] # make a copy to keep all mutations local
while True:
x = f(xs)
yield xs.pop(0)
xs.append(x)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/506261.html
上一篇:有沒有辦法在haskell中隱式地將一個型別強制轉換為另一個包裝型別?
下一篇:包含時不接受推斷型別
