Function Decorator, Map/Filter/Reduce in Python

Function

Function Decorator

1
2
3
4
5
6
7
8
9
10
11
def track(fn):
def h(x):
print('the fn {} has x {}'.format(fn, x))
return fn(x)
return h

@track
def foo(x):
return x ** x

print(foo(3))

decorator equals to: foo = track(foo)

Lambda

1
2
     lambda            x            :          f(g(x))
"A function that takes x and returns f(g(x))"

Map

Map will apply the function on elements in the iterables one by one, and return a map object (iterable).

1
map(func, *iterables)
  • how many parameters the func require, how many iterables there are.
  • whenever one iterable reaches its end, the map will stop without an error.
  • map will return a map object. use list() to convert it to a list.

Filter

Filter passes each element in the iterable to the function, and if the function returns True, the element will be returned.

1
filter(func, iterable)
  • the func should require one parameter, and return boolean type.
  • unlike map, only one iterable is supported.
  • if the func doesn't return a boolean type, the filter simply returns the iterable itself.
  • also use list() to convert the filter object to a list.

Reduce

Reduce takes the 1st and 2nd elements in the iterable, put them into the func, and take the return of the func and the 3rd element in the iterable, put them into the func again...

1
2
from functools import reduce
reduce(func, interable[, initial])
  • initial is literally an initial input into the func.