Python 如何用函数法求元素和
我正在尝试编写一个函数,该函数映射列表中的元素,以获得该元素与列表中先前元素的总和,使用python实现函数式,例如:Python 如何用函数法求元素和,python,functional-programming,Python,Functional Programming,我正在尝试编写一个函数,该函数映射列表中的元素,以获得该元素与列表中先前元素的总和,使用python实现函数式,例如: func([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) = [0, 1, 3, 6, 10, 15, 21, 28, 36, 45] 我尝试过使用递归,但getRuntimeError:使用长列表超出了最大递归深度。: def recursion_way(inlist, accu, summ): if len(inlist) == 0:
func([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) = [0, 1, 3, 6, 10, 15, 21, 28, 36, 45]
我尝试过使用递归,但getRuntimeError:使用长列表超出了最大递归深度。:
def recursion_way(inlist, accu, summ):
if len(inlist) == 0:
return accu
else:
return recursion_way(inlist[1:], accu + [summ + inlist[0]], summ + inlist[0])
理解算数吗
>>> [sum(l[:i]) for i, _ in enumerate(l)]
[0, 0, 1, 3, 6, 10, 15, 21, 28, 36]
或者使用减少:
reduce(
lambda (sums, last), x: (sums+[x+last], x+last),
l, ([], 0)
)[0]
或者另一种方式:
reduce(lambda sums,x: sums+[x+sums[-1]], l[1:], l[:1])
你会用numpy吗
import numpy
numpy.cumsum([0,1,2,3,4,5,6,7,8,9])
array([ 0, 1, 3, 6, 10, 15, 21, 28, 36, 45])
以下是以函数式编程方式完成的累积和:
def func(l):
if len(l) < 2: return l
sub = func(l[:-1])
return sub + [sub[-1] + l[-1]]
print func([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
def func(l):
如果len(l)<2:返回l
sub=func(l[:-1])
返回sub+[sub[-1]+l[-1]]
打印函数([0,1,2,3,4,5,6,7,8,9])
如何减少?慢,但有趣,依我看
def func(p):
for i in xrange(1, len(p)+1):
yield reduce(lambda x, y: x + y, p[0:i])
>>> list(func(p))
[0, 1, 3, 6, 10, 15, 21, 28, 36, 45]
下面是我使用递归得到的结果:
def f(L, n=0):
# If the list is empty, that means we went through all the elements there
if len(L)>0:
# n is the last element in the sum list. Add to it the first remaining element
n = n+L[0]
# Return a list containing the newest item and those of the remaining elements
return [n] + f(L[1:], n)
else:
# It it is empty, there are no more sums to calculate
return []
你能发布你正在使用的函数吗?@user1879805:你可以编辑问题并在那里添加你的递归:)(这比评论中要清楚得多)@Martijn Pieters:你完全正确。。。我删除了我的评论。递归方法只适用于10个元素(在我学会阅读的那一天,我将征服世界!!):@user1879805只是为了让你知道,python中默认的最大递归限制为1000。@Trufa:默认递归限制-可在运行时重新配置。name错误:未定义名称“cumsum”
将我的答案更改为使用numpyy您实现的sum
,而不是“滚动和”OP正在寻找。for
循环的使用可变数据,因此可能不符合“函数式编程”的条件。您的reduce(lambda x,y:x+y,p[0:i])
与sum(p[:i])
相同,IMO更具可读性
def f(L, n=0):
# If the list is empty, that means we went through all the elements there
if len(L)>0:
# n is the last element in the sum list. Add to it the first remaining element
n = n+L[0]
# Return a list containing the newest item and those of the remaining elements
return [n] + f(L[1:], n)
else:
# It it is empty, there are no more sums to calculate
return []