在 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))
我已经在没有递归函数的情况下完成了此操作,但我正在考虑如何使用递归和记忆来完成此操作。你能帮我解决这个问题吗..
I am working with series like Fibonacci series... (In Fibonacci series the nth term is the sum of n-1 and n-2 only.)
But in my case I want to nth term is the sum of half of the previous terms..
for example:
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))
I have done this without recursive function but I am thinking how to do it using recursively and memoization. Can you help me to solve this..
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您在寻找这样的东西吗?
Are you looking for something like this?