How does reduce function work?

前端 未结 9 1142
青春惊慌失措
青春惊慌失措 2020-12-01 04:25

As far as I understand, the reduce function takes a list l and a function f. Then, it calls the function f on first two elements of th

9条回答
  •  执笔经年
    2020-12-01 04:53

    The easiest way to understand reduce() is to look at its pure Python equivalent code:

    def myreduce(func, iterable, start=None):
        it = iter(iterable)
        if start is None:
            try:
                start = next(it)
            except StopIteration:
                raise TypeError('reduce() of empty sequence with no initial value')
        accum_value = start
        for x in iterable:
            accum_value = func(accum_value, x)
        return accum_value
    

    You can see that it only makes sense for your reduce_func() to apply the factorial to the rightmost argument:

    def fact(n):
        if n == 0 or n == 1:
            return 1
        return fact(n-1) * n
    
    def reduce_func(x,y):
        return x * fact(y)
    
    lst = [1, 3, 1]
    print reduce(reduce_func, lst)
    

    With that small revision, the code produces 6 as you expected :-)

提交回复
热议问题