-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfunctional.txt
More file actions
38 lines (32 loc) · 1.02 KB
/
functional.txt
File metadata and controls
38 lines (32 loc) · 1.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
------------------------------------------------------------------------------
Python Functional Programming
FILTER
>>> def f(x): return x % 3 == 0 or x % 5 == 0
>>> filter(f, range(2, 25))
[3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24]
>>> [x for x in range(2,25) if x % 3 == 0 or x % 5 == 0]
[3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24]
------------------------------------------------------------------------------
MAP
>>> def cube(x): return x*x*x
>>> map(cube, range(1, 11))
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
>>> [x*x*x for x in range(1,11)]
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
------------------------------------------------------------------------------
REDUCE
>>> def add(x,y): return x+y
>>> reduce(add, range(1, 11))
55
>>> sum(range(1,11))
------------------------------------------------------------------------------
ZIP
>>> matrix= [[1,2,3],[4,5,6],[7,8,9]]
>>> zip(*matrix)
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
>>> x= [1,2,3]
>>> y=[4,5,6]
>>> zip(x,y)
[(1, 4), (2, 5), (3, 6)]
>>> [a+b for a,b in zip(x,y)]
[5, 7, 9]