繁体   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