-
Notifications
You must be signed in to change notification settings - Fork 931
/
match_cities.py
92 lines (73 loc) · 1.84 KB
/
match_cities.py
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
88
89
90
91
92
"""
match_cities.py
"""
# tag::CITY[]
import typing
class City(typing.NamedTuple):
continent: str
name: str
country: str
cities = [
City('Asia', 'Tokyo', 'JP'),
City('Asia', 'Delhi', 'IN'),
City('North America', 'Mexico City', 'MX'),
City('North America', 'New York', 'US'),
City('South America', 'São Paulo', 'BR'),
]
# end::CITY[]
# tag::ASIA[]
def match_asian_cities():
results = []
for city in cities:
match city:
case City(continent='Asia'):
results.append(city)
return results
# end::ASIA[]
# tag::ASIA_POSITIONAL[]
def match_asian_cities_pos():
results = []
for city in cities:
match city:
case City('Asia'):
results.append(city)
return results
# end::ASIA_POSITIONAL[]
# tag::ASIA_COUNTRIES[]
def match_asian_countries():
results = []
for city in cities:
match city:
case City(continent='Asia', country=cc):
results.append(cc)
return results
# end::ASIA_COUNTRIES[]
# tag::ASIA_COUNTRIES_POSITIONAL[]
def match_asian_countries_pos():
results = []
for city in cities:
match city:
case City('Asia', _, country):
results.append(country)
return results
# end::ASIA_COUNTRIES_POSITIONAL[]
def match_india():
results = []
for city in cities:
match city:
case City(_, name, 'IN'):
results.append(name)
return results
def match_brazil():
results = []
for city in cities:
match city:
case City(country='BR', name=name):
results.append(name)
return results
def main():
tests = ((n, f) for n, f in globals().items() if n.startswith('match_'))
for name, func in tests:
print(f'{name:15}\t{func()}')
if __name__ == '__main__':
main()