我想定义一个函数 accumulate_n(op, init, sequences) 使用 accumulate(op, init, seq) 这样:
accumulate_n(op, init, sequences) 函数与 accumulate(op, init, seq) 类似,只是它的第三个参数是一个序列序列等长。它应用累加函数 op 组合序列的所有第一个元素、序列的所有第二个元素,依此类推,并返回结果序列。例如,如果 s 是一个包含四个序列的序列,[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]],那么 accumulate_n(lambda x, y: x+y, 0, s) 的值应该是序列 [22, 26, 30]。
def accumulate(op, init, seq):
if not seq:
return init
else:
return op(seq[0], accumulate(op, init, seq[1:]))
def accumulate_n(op, init, sequences):
if (not sequences) or (not sequences[0]):
return type(sequences)()
else:
return ( [accumulate(op, init, ??)]
+ accumulate_n(op, init, ??) )
但我卡在了 ?? 部分,因为我不知道该在其中包含什么。我想我可以使用 map 内置函数,但仍然不确定要做什么。
以下是函数应该执行的示例:
accumulate_n(lambda x,y: x+y, 0, [[1,2],[3,4],[5,6]])
# [9, 12]
accumulate_n(lambda x,y: x+y, 0, [[1,4],[5,7],[9,10]])
# [15, 21]
accumulate_n(lambda x,y: x+y, 0, [[9,8],[7,6],[5,4]])
# [21, 18]
如果有人能提供帮助,我将不胜感激!谢谢!
请您参考如下方法:
看起来你想要得到:
- 每个序列的第一个元素的列表,可以是
[s[0] for s in sequences],和 - 每个序列剩余元素的列表,可以是
[s[1:] for s in sequences]。
总的来说:
def accumulate(op, init, seq):
if not seq:
return init
else:
return op(seq[0], accumulate(op, init, seq[1:]))
def accumulate_n(op, init, sequences):
if (not sequences) or (not sequences[0]):
return type(sequences)()
else:
heads = [s[0] for s in sequences]
tails = [s[1:] for s in sequences]
return ([accumulate(op, init, heads)]
+ accumulate_n(op, init, tails))
但为了它的值(value),我会按行而不是按列执行此操作,并且要求 init 本身就是一个序列:
def accumulate_n_(op, init, sequences):
try:
head = next(sequences)
except StopIteration:
return init
return accumulate_n_(
op,
[op(x, y) for x, y in zip(init, head)],
sequences,
)
def accumulate_n(op, init, sequences):
return accumulate_n_(op, init, iter(sequences))
更清洁的命令:
def accumulate_n(op, init, sequences):
for s in sequences:
init = [op(x, y) for x, y in zip(init, s)]
return init
最后,使用 functools.reduce:
def zipper(op):
return lambda xs, ys: [op(x, y) for x, y in zip(xs, ys)]
def accumulate_n(op, init, sequences):
return reduce(zipper(op), sequences, init)
