Skip to content

Commit 92f945a

Browse files
committed
Add code used in presentation
1 parent 1539beb commit 92f945a

File tree

3 files changed

+43
-0
lines changed

3 files changed

+43
-0
lines changed
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
OperatorsFunctools
2+
==================
3+
4+
Python has a number of packages that are useful for functional style
5+
programming, some of these are illustrated here.
6+
7+
What is it?
8+
-----------
9+
1. `sort.py`: illustrates sorting a list of nested tuples using a lambda
10+
function, and `operator`'s `itemgetter` higher order function.
11+
1. `reduce.py`: illustrates `functools`'s `reduce` function by computing
12+
the factorial function.
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
#!/usr/bin/env python
2+
3+
import functools
4+
import operator
5+
6+
if __name__ == '__main__':
7+
for i in range(0, 11):
8+
print(i, functools.reduce(operator.mul, range(1, i + 1), 1))
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
#!/usr/bin/env python
2+
3+
from operator import itemgetter
4+
5+
data = [
6+
('c', (19, 1)),
7+
('b', (12, 2)),
8+
('d', (13, 4)),
9+
('a', (17, 3)),
10+
]
11+
12+
13+
def print_data(msg, data):
14+
print(msg)
15+
data_str = '\t' + '\n\t'.join([str(x) for x in data])
16+
print(data_str)
17+
18+
if __name__ == '__main__':
19+
print_data('original list', data)
20+
sorted_data = sorted(data, key=lambda x: x[1][0])
21+
print_data('lambda sort', sorted_data)
22+
sorted_data = sorted(data, key=itemgetter(1, 0))
23+
print_data('itemgetter sort', sorted_data)

0 commit comments

Comments
 (0)