Difference between revisions of "Reduce"

From CS 61A Wiki
Jump to: navigation, search
[checked revision][checked revision]
(Created page with "'''Reduce''' is a higher-order function that is either a [https://docs.python.org/2/library/functions.html#reduce built-in function in Python 2.7] or can be import|impor...")
 
m ({{C-class}})
Line 1: Line 1:
 +
{{C-class}}
 
'''Reduce''' is a [[higher-order function]] that is either a [https://docs.python.org/2/library/functions.html#reduce built-in function in Python 2.7] or can be [[import|imported]] from [https://docs.python.org/3.2/library/functools.html functools in Python 3.2+].
 
'''Reduce''' is a [[higher-order function]] that is either a [https://docs.python.org/2/library/functions.html#reduce built-in function in Python 2.7] or can be [[import|imported]] from [https://docs.python.org/3.2/library/functools.html functools in Python 3.2+].
  

Revision as of 09:57, 30 June 2014

Reduce is a higher-order function that is either a built-in function in Python 2.7 or can be imported from functools in Python 3.2+.

Given a two-argument function, an iterable, and (optionally) an initalizer, reduce applies the function to each item pair in the sequence cumulatively, and returns a single value.

Reduce will take the first two elements of the iterable, apply the function to them, and reach a result. It will then apply the function to this result and the third element, move on to the fourth element, and so on, until it reaches the end of the iterable. The final result will be the single return value.

Form

The most general form of the reduce function is as follows:

reduce(func, iter)

with func being the 2-argument function given, and iter being the iterable being processed.

Examples

add_together

For the most basic example, we will attempt to add all elements of a list together. We'll create a starter function, add_together, and the list my_list below.

def add_together(x, y):
   return x+y
my_list = [1, 2, 3, 4, 5]

If we apply reduce to the above and apply them as arguments, we can expect:

>>>reduce(add_together, my_list)
15