Functional Programming
Map
map()
receive two params, a function and a sequence. Each element in the sequence will be passed to the function and return the results as a new sequence. It’s more readable than iteration. You can also use list comprehension if you like, and it’s the prefered way in python.
# default function
name_len = map(len, ["Sam", "John", "Ned Stark"])
print name_len
[3, 4, 9]
# lambda function
squares = map(lambda x: x * x, range(9))
print squares
[0, 1, 4, 9, 16, 25, 36, 49, 64]
# self defined function
def toUpper(item):
return item.upper()
upper_name = map(toUpper, ["sam", "john", "ned stark"])
print upper_name
['SAM', 'JOHN', 'NED STARK']
Reduce
reduce
applay a function to a sequence [x1, x2, x3…], the function must take two params, reduce
use the result returned by the function with the next element in the sequence. It looks like this:
reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)
# add
print reduce(lambda x, y: x+y, [1,2,3,4])
10
# multiply
print reduce(lambda x, y: x*y, [1, 2, 3,4])
24
# convert sequence [1,2,3,4] to integer 1234
print reduce(lambda x,y: 10*x + y, [1,2,3,4])
1234
Filter
filter
acts just like a real filter. The first param passed to filter is a bool_func
which return True or False for different element in the sequence, and only return those elements with True returned from bool_func.
Just like map()
, filter()
also receive a function and sequence. But different in that filter()
only keeps those with True value returned.
# remove even number
def is_odd(n):
return n % 2 == 1
filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15])
[1, 5, 9, 15]
All
When all elements in iterable object(like list) are True, return True. Just like and
operation on all elements. Note that when iterable is empty, it also return True.
def all(iterable):
for element in iterable:
if not element:
return False
return True
all(['a', 'b', 'c']) # list
True
all([0, 1, 2, 3]) # list,with one 0 element
False
all(('a', 'b', '', 'd')) #tuple,with one empty element
False
all([]) # empty list
True
Any
Where any of the iterable is True, return True; otherwise return False. When iterable is empty, return False.
def any(iterable):
for element in iterable:
if element:
return True
return False
any([0,1,2])
True
any([0, '', False]) # list,element with 0,'',false
False
Sorted
Python’s built in function sorted()
can sort a list
:
sorted(iterable, cmp=None, key=None, reverse=False)
lst = [36, 5, -12, 9, -21]
sorted(lst)
[-21, -12, 5, 9, 36]
sorted()
function also receive a key for sorting, like base on the absolute value of a number. You can think of that you pass the key to map()
for transformation and use the results for sorting.
sorted keys => [5, 9, 12, 21, 36]
=============|==|==|===|===|
actual order====> [5, 9, -12, -21, 36]
sorted(lst,key=abs)
[5, 9, -12, -21, 36]
# ignore case
sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower)
['about', 'bob', 'Credit', 'Zoo']
['about', 'bob', 'Credit', 'Zoo']
# reverse order
sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower, reverse=True)
['Zoo', 'Credit', 'bob', 'about']
['Zoo', 'Credit', 'bob', 'about']