generated from yandex-praktikum/hw_python_oop
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhomework.py
More file actions
146 lines (111 loc) · 4.52 KB
/
homework.py
File metadata and controls
146 lines (111 loc) · 4.52 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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
from dataclasses import dataclass, asdict, fields
from typing import Dict, Any
@dataclass
class InfoMessage:
"""Информационное сообщение о тренировке."""
training_type: str
duration: float
distance: float
speed: float
calories: float
MESSAGE: str = ('Тип тренировки: {training_type}; '
'Длительность: {duration:.3f} ч.; '
'Дистанция: {distance:.3f} км; '
'Ср. скорость: {speed:.3f} км/ч; '
'Потрачено ккал: {calories:.3f}.')
def get_message(self) -> str:
return self.MESSAGE.format(**asdict(self))
@dataclass
class Training:
"""Базовый класс тренировки."""
LEN_STEP = 0.65
M_IN_KM = 1000
M_IN_H = 60
action: int
duration: float
weight: float
def get_distance(self) -> float:
"""Получить дистанцию в км."""
return self.action * self.LEN_STEP / self.M_IN_KM
def get_mean_speed(self) -> float:
"""Получить среднюю скорость движения."""
training_mean_speed = self.get_distance() / self.duration
return training_mean_speed
def get_spent_calories(self) -> float:
"""Получить количество затраченных калорий."""
raise NotImplementedError('Определите get_spent_calories в %s'
% type(self).__name__)
def show_training_info(self) -> InfoMessage:
"""Вернуть информационное сообщение о выполненной тренировке."""
return InfoMessage(type(self).__name__, self.duration,
self.get_distance(), self.get_mean_speed(),
self.get_spent_calories())
@dataclass
class Running(Training):
"""Тренировка: бег."""
COEFF_MEAN_SPEED_1 = 18
COEFF_MEAN_SPEED_2 = 20
def get_spent_calories(self) -> float:
return ((self.COEFF_MEAN_SPEED_1 * self.get_mean_speed()
- self.COEFF_MEAN_SPEED_2)
* self.weight / self.M_IN_KM
* self.duration * self.M_IN_H)
@dataclass
class SportsWalking(Training):
"""Тренировка: спортивная ходьба."""
COEFF_WEIGHT_1 = 0.035
COEFF_WEIGHT_2 = 0.029
EXPONENT = 2
action: int
duration: float
weight: float
height: float
def get_spent_calories(self) -> float:
return (
(self.COEFF_WEIGHT_1 * self.weight
+ (self.get_mean_speed() ** self.EXPONENT
// self.weight)
* self.COEFF_WEIGHT_2 * self.weight)
* self.duration * self.M_IN_H)
@dataclass
class Swimming(Training):
"""Тренировка: плавание."""
LEN_STEP = 1.38
COEFF_MEAN_SPEED = 1.1
COEFF_WEIGHT = 2
action: int
duration: float
weight: float
length_pool: float
count_pool: int
def get_mean_speed(self) -> float:
return (self.length_pool * self.count_pool / self.M_IN_KM
/ self.duration)
def get_spent_calories(self) -> float:
return ((self.get_mean_speed() + self.COEFF_MEAN_SPEED)
* self.COEFF_WEIGHT * self.weight)
def read_package(workout_type: str, data: list) -> Training:
"""Прочитать данные полученные от датчиков."""
training_type: Dict[str, Any] = {
'SWM': (Swimming, len(fields(Swimming))),
'RUN': (Running, len(fields(Running))),
'WLK': (SportsWalking, len(fields(SportsWalking)))
}
if workout_type not in training_type:
raise KeyError(f'кода тренировки {workout_type} нет в списке')
if training_type[workout_type][1] != len(data):
raise ValueError(f'недопустимое количество значений. '
f'Пришло значений: {len(data)}, '
f'ожидается: {training_type[workout_type][1]}')
return training_type[workout_type][0](*data)
def main(training: Training) -> None:
"""Главная функция."""
print(training.show_training_info().get_message())
if __name__ == '__main__':
packages = [
('SWM', [720, 1, 80, 25, 40]),
('RUN', [15000, 1, 75]),
('WLK', [9000, 1, 75, 180])
]
for workout_type, data in packages:
main(read_package(workout_type, data))