定义accumulate_n? (高阶函数)

时间:2017-03-19 05:32:17

标签: python python-3.x higher-order-functions accumulate

我想使用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]

如果有人可以提供帮助,我会非常感激!谢谢!

2 个答案:

答案 0 :(得分:1)

内置zip函数,结合使用*解压缩 参数列表,方便从a中选择第n个值 序列序列:

def accumulate_n(op, init, sequences):
    if (not sequences) or (not sequences[0]):
        return type(sequences)()
    else:
        return [accumulate(op, init, i) for i in zip(*sequences)]

答案 1 :(得分:1)

好像你想要得到:

  • 每个序列的第一个元素的列表,可以是[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))

但是对于它的价值,我会按行而不是按列进行,并且需要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)