Repository navigation
Expand file tree
/
Copy pathcode.py
More file actions
87 lines (54 loc) · 1.88 KB
/
Copy pathcode.py
File metadata and controls
87 lines (54 loc) · 1.88 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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
# A first class function just means that functions can be passed as arguments to functions.
def calculate(*values, operator):
return operator(*values)
def divide(dividend, divisor):
if divisor != 0:
return dividend / divisor
else:
return "You fool!"
# We pass the `divide` function as an argument
result = calculate(20, 4, operator=divide)
print(result)
def average(*values):
return sum(values) / len(values)
result = calculate(10, 20, 30, 40, operator=average)
print(result)
# -- searching with first-class functions --
def search(sequence, expected, finder):
for elem in sequence:
if finder(elem) == expected:
return elem
raise RuntimeError(f"Could not find an element with {expected}")
friends = [
{"name": "Rolf Smith", "age": 24},
{"name": "Adam Wool", "age": 30},
{"name": "Anne Pun", "age": 27},
]
def get_friend_name(friend):
return friend["name"]
print(search(friends, "Bob Smith", get_friend_name))
# -- using lambdas since this can be simple enough --
def search(sequence, expected, finder):
for elem in sequence:
if finder(elem) == expected:
return elem
raise RuntimeError(f"Could not find an element with {expected}")
friends = [
{"name": "Rolf Smith", "age": 24},
{"name": "Adam Wool", "age": 30},
{"name": "Anne Pun", "age": 27},
]
print(search(friends, "Bob Smith", lambda friend: friend["name"]))
# -- or as an extra, using built-in functions --
from operator import itemgetter
def search(sequence, expected, finder):
for elem in sequence:
if finder(elem) == expected:
return elem
raise RuntimeError(f"Could not find an element with {expected}")
friends = [
{"name": "Rolf Smith", "age": 24},
{"name": "Adam Wool", "age": 30},
{"name": "Anne Pun", "age": 27},
]
print(search(friends, "Rolf Smith", itemgetter("name")))