Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does reduce function work?

Tags:

python

reduce

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 the list and then repeatedly calls the function f with the next list element and the previous result.

So, I define the following functions:

The following function computes the factorial.

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

Now, shouldn't this give me ((1! * 3!) * 1!) = 6? But, instead it gives 720. Why 720? It seems to take the factorial of 6 too. But, I need to understand why.

Can someone explains why this happens and a work-around?

I basically want to compute the product of factorials of all the entries in the list. The backup plan is to run a loop and compute it. But, I would prefer using reduce.

like image 961
Divya Avatar asked Feb 02 '12 07:02

Divya


People also ask

How do you use the reduce method?

Introduction to the JavaScript Array reduce() methodFirst, declare an array of three numbers 1, 2 and 3. Second, declare the sum variable and set its value to zero. Third, in the for loop, add up the elements of the numbers array to the sum variable. After the loop, the value of the sum variable is 6.

What is reduce () in JavaScript?

reduce() method in JavaScript is used to reduce the array to a single value and executes a provided function for each value of the array (from left-to-right) and the return value of the function is stored in an accumulator. Syntax: array.reduce( function(total, currentValue, currentIndex, arr), initialValue )

What is reduce () in Python?

Python's reduce() is a function that implements a mathematical technique called folding or reduction. reduce() is useful when you need to apply a function to an iterable and reduce it to a single cumulative value.


1 Answers

The other answers are great. I'll simply add an illustrated example that I find pretty good to understand reduce():

>>> reduce(lambda x,y: x+y, [47,11,42,13]) 113 

will be computed as follows:

enter image description here

(Source) (mirror)

like image 183
Franck Dernoncourt Avatar answered Sep 25 '22 21:09

Franck Dernoncourt