Advertisement
amigojapan

functional programming in python examples

Dec 18th, 2016
145
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.50 KB | None | 0 0
  1. def sumA(n):
  2.         if not n:#if n is empty list
  3.                 return 0
  4.         head, *tail = n
  5.         return head + sumA(tail)
  6. #print(sumA([1,2,3,4,5]))
  7.  
  8. print(list(map(sumA, [[1,1,1],[2,2,2],[3,3],[4,4],[5,5]])))
  9.  
  10. print(sumA(list(map(sumA, [[1,1,1],[2,2,2],[3,3],[4,4],[5,5]]))))
  11.  
  12. from functools import reduce
  13. import operator
  14. def product(xs):
  15.     return reduce(operator.mul, xs, 1)
  16.  
  17. print(product([1,2,3,4]))
  18.  
  19. def sumB(xs):
  20.     return reduce(operator.add, xs, 1)
  21.  
  22. print(sumB([1,2,3,4]))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement