How does reduce function work?

前端 未结 9 1144
青春惊慌失措
青春惊慌失措 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:46

    From the Python reduce documentation,

    reduce(function, sequence) returns a single value constructed by calling the (binary) function on the first two items of the sequence, then on the result and the next item, and so on.

    So, stepping through. It computes reduce_func of the first two elements, reduce_func(1, 3) = 1! * 3! = 6. Then, it computes reduce_func of the result and the next item: reduce_func(6, 1) = 6! * 1! = 720.

    You missed that, when the result of the first reduce_func call is passed as input to the second, it's factorialized before the multiplication.

提交回复
热议问题