forked from shnela/python_course
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathenum_exercise_solution.py
68 lines (49 loc) · 2.12 KB
/
enum_exercise_solution.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
from collections import defaultdict
from enum import Enum
from random import randint, choice
from typing import List, Dict
class Color(Enum):
red = 'RED'
green = 'GREEN'
class WeightCategory(Enum):
light = 'LIGHT'
heavy = 'HEAVY'
class Apple:
def __init__(self, color: Color, weight: int):
self.color = color
self.weight = weight
def __repr__(self):
return f'Apple(color={self.color.value}, weight={self.weight})'
@staticmethod
def getnerate_random_apple():
return Apple(color=choice(list(Color)), weight=randint(50, 150))
def get_weight_category(self) -> WeightCategory:
"""Return WeightCategory.light if weight is below 100"""
return WeightCategory.light if self.weight < 100 else WeightCategory.heavy
def group_apples_by_color(apples: List[Apple]) -> Dict[Color, List[Apple]]:
apples_by_color = defaultdict(list)
for apple in apples:
apples_by_color[apple.color].append(apple)
return apples_by_color
def group_apples_by_color_then_weight(apples: List[Apple]) -> Dict[Color, Dict[WeightCategory, List[Apple]]]:
apples_by_color_and_weight = defaultdict(lambda: defaultdict(list))
for apple in apples:
apples_by_color_and_weight[apple.color][apple.get_weight_category()].append(apple)
return apples_by_color_and_weight
if __name__ == '__main__':
light_apple = Apple(color=Color.red, weight=55)
assert light_apple.get_weight_category() == WeightCategory.light
random_apple = Apple.generate_random_apple()
print(random_apple)
# Exercise1: generate 100 random apples
apples = [Apple.generate_random_apple() for _ in range(100)]
print(apples)
# Exercise2: group apples by color
apples_by_color = group_apples_by_color(apples)
assert all(a.color == Color.red for a in apples_by_color[Color.red])
# Exercise3: group apples by color, then by WeightCategory
apples_by_color_and_weight = group_apples_by_color_then_weight(apples)
assert all(
a.color == Color.red and a.weight < 100
for a in apples_by_color_and_weight[Color.red][WeightCategory.light]
)