我有一系列數字,我需要找到的總和。第一次迭代操作的值爲1,第二次爲20.隨後的每次迭代使用公式n *(n + 1)/ 2中的先前結果,因此第三次迭代,例如i03 = 20 *(20+ 1)/ 2,第四個,i04 = i03 *(i03 + 1)/ 2。這一直持續到i20 = i19 *(i19 + 1)/ 2的第20次迭代。我想使用memoization來做到這一點。這是我的代碼:破記憶代碼
def outFun():
def sumFun(squares, total = 0, CONST = 20):
if squares > 2:
total = sumFun(squares - 1) * int((sumFun(squares - 1) + 1)/2)
elif not squares - 2:
total = CONST
return total
return 1 + sumFun(20)
我在做什麼錯?
您有很多遞歸,但沒有記憶。也就是說,在返回它之前需要指定'_cache [inargs] = result'的地方,然後在調用時測試'if inargs in _cache:return cachedval'。 – 2013-02-20 20:04:42