簡體   English   中英

使用遞歸 function 和 python 中的記憶處理系列

[英]Working with series using Recursive function and Memoization in python

我正在使用像斐波那契數列這樣的系列......(在斐波那契數列中,第 n 項僅是 n-1 和 n-2 的總和。)但在我的情況下,我想第 n 項是前一項的一半的總和.. 例如:

n=5
Output should be: [0, 1, 1, 2, 3]

n=12
Output should be: [0, 1, 1, 2, 3, 6, 11, 22, 42, 84, 165, 330]
def my_function(n):
    
    list1=[0,1]
    for i in range(0,n-2):
        if(i>2):
            value=sum(list1[i//2+1:])
        else:
            value=list1[i]+list1[i+1]
        list1.append(value)
    return list1
    
print(my_function(5))

我在沒有遞歸 function 的情況下完成了此操作,但我正在考慮如何使用遞歸和記憶來完成此操作。 你能幫我解決這個問題嗎..

你在找這樣的東西嗎?

# Python has a built-in decorator for memoizing any function automagically.

from functools import lru_cache

@lru_cache(maxsize=None)
def my_func_rec(n):
    if n == 1:
        return [0]
    elif n == 2:
        return [0,1]
    else:
        prev = my_func_rec(n-1)
        prev.append(sum(prev[(n-1)//2:]))
        return prev

print(my_func_rec(12)) # [0, 1, 1, 2, 3, 6, 11, 22, 42, 84, 165, 330]

暫無
暫無

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

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