Skip to content

Commit 09d04c7

Browse files
bites 148 - grouping
1 parent fca53f7 commit 09d04c7

File tree

3 files changed

+85
-0
lines changed

3 files changed

+85
-0
lines changed

.gitignore

+2
Original file line numberDiff line numberDiff line change
@@ -67,3 +67,5 @@
6767
/140-pandas/README.md
6868
/118/README.md
6969
/116/README.md
70+
/187/README.md
71+
/148/README.md

148/grouping.py

+34
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
from itertools import groupby
2+
3+
cars = [
4+
# need mock data? -> https://www.mockaroo.com == awesome
5+
('Mercedes-Benz', '300D'), ('Mercedes-Benz', '600SEL'),
6+
('Toyota', 'Avalon'), ('Ford', 'Bronco'),
7+
('Chevrolet', 'Cavalier'), ('Chevrolet', 'Corvette'),
8+
('Mercedes-Benz', 'E-Class'), ('Hyundai', 'Elantra'),
9+
('Volkswagen', 'GTI'), ('Toyota', 'Highlander'),
10+
('Chevrolet', 'Impala'), ('Nissan', 'Maxima'),
11+
('Ford', 'Mustang'), ('Kia', 'Optima'),
12+
('Volkswagen', 'Passat'), ('Nissan', 'Pathfinder'),
13+
('Volkswagen', 'Routan'), ('Hyundai', 'Sonata'),
14+
('Kia', 'Sorento'), ('Kia', 'Sportage'),
15+
('Ford', 'Taurus'), ('Nissan', 'Titan'),
16+
('Toyota', 'Tundra'), ('Hyundai', 'Veracruz'),
17+
]
18+
19+
20+
def group_cars_by_manufacturer(cars):
21+
"""Iterate though the list of (manufacturer, model) tuples
22+
of the cars list defined above and generate the output as described
23+
in the Bite description (see the tests for the full output).
24+
25+
No return here, just print to the console. We use pytest > capfd to
26+
validate your output :)
27+
"""
28+
cars = sorted(cars, key=lambda x: x[0])
29+
for key, group in groupby(cars, lambda x: x[0]):
30+
cars_text = "\n- ".join(list(map(lambda x: x[1], group)))
31+
print(key.upper() + "\n- " + cars_text + "\n")
32+
33+
34+
# group_cars_by_manufacturer(cars)

148/test_grouping.py

+49
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
from grouping import cars, group_cars_by_manufacturer
2+
3+
expected_output = """
4+
CHEVROLET
5+
- Cavalier
6+
- Corvette
7+
- Impala
8+
9+
FORD
10+
- Bronco
11+
- Mustang
12+
- Taurus
13+
14+
HYUNDAI
15+
- Elantra
16+
- Sonata
17+
- Veracruz
18+
19+
KIA
20+
- Optima
21+
- Sorento
22+
- Sportage
23+
24+
MERCEDES-BENZ
25+
- 300D
26+
- 600SEL
27+
- E-Class
28+
29+
NISSAN
30+
- Maxima
31+
- Pathfinder
32+
- Titan
33+
34+
TOYOTA
35+
- Avalon
36+
- Highlander
37+
- Tundra
38+
39+
VOLKSWAGEN
40+
- GTI
41+
- Passat
42+
- Routan
43+
"""
44+
45+
46+
def test_group_cars_by_manufacturer(capfd):
47+
group_cars_by_manufacturer(cars)
48+
actual_output, _ = capfd.readouterr()
49+
assert actual_output.strip() == expected_output.strip()

0 commit comments

Comments
 (0)