forked from realpython/materials
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhigher_order_reduce.py
More file actions
38 lines (26 loc) · 779 Bytes
/
Copy pathhigher_order_reduce.py
File metadata and controls
38 lines (26 loc) · 779 Bytes
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
"""
Example implementations of using `reduce()` to create
functional versions of `map()` and `filter()`.
"""
from functools import reduce
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Compare `map()` to `custom_map()`.
def custom_map(function, iterable):
return reduce(
lambda items, value: items + [function(value)],
iterable,
[],
)
print(list(map(str, numbers)))
print(list(custom_map(str, numbers)))
# Compare `filter()` to `custom_filter()`.
def is_even(x):
return x % 2 == 0
def custom_filter(function, iterable):
return reduce(
lambda items, value: items + [value] if function(value) else items,
iterable,
[],
)
print(list(filter(is_even, numbers)))
print(list(custom_filter(is_even, numbers)))