Saturday, August 6, 2016

2. Functional programming in Python

1. Functional tools in python

  • map
    • apply an operation to each element in a list, return a list of results. (original list is never changed, map just creates a new list)
  • filter
    • select only certain elements from a list (based on a boolean list)
  • reduce
    • apply a function to all pairs (non-repeated) of elements in a list, return ONE value, not a list.
    • better for functions that are communicative, such as multiply/add, but not for divide/minus
  • lambda
    • allow us define a function with a value, without giving it a name
  • itertools
    • chain, chain.from_iterable
    • compress
    • accumulate
    • takewhile,  dropwhile
    • flatmap


additional reading about itertools:
https://docs.python.org/dev/library/itertools.html

2.  code examples
>>> map(lambda x: x+1, [1,2,3])
[2,3,4]
>>> filter(lambda x: x%2==1, range(1,10))
[1,3,5,7,9]
>>> reduce(lambda x, y: x+y, [1,2,3,4])
10

3. Exercises

(lambda x: x*2)(3) => ?
map(lambda x: x*2, [1,2,3]) =>?
map(lambda t: t[0], [(1,2), (3,4), (5,6)]) =>?
reduce(lambda x, y: x+y, [1,2,3]) =>?
reduce(lambda x, y: x+y,  map(lambda t: t[0], [(1,2), (3,4), (5,6)) =>?

Given a list of tuples: a=[(1,2), (3,4), (5,6)]
write an expression to get only the second element of each tuple.
write an expression to get the sum of second elements.



No comments:

Post a Comment