practice_repin_1/zadanie_1.py

68 lines
2.1 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import os
# 1. Загрузка заказов из файла
def load_orders(filepath: str) -> list[dict]:
"""
Читает файл с заказами.
Формат строки: user_id, item_name, quantity, price_per_item
"""
orders = []
with open(filepath, 'r', encoding='utf-8') as file:
for line in file:
line = line.strip()
if not line:
continue
parts = line.split(',')
if len(parts) != 4:
continue
user_id = int(parts[0].strip())
item_name = parts[1].strip()
quantity = int(parts[2].strip())
price = float(parts[3].strip())
total = quantity * price
orders.append({
'user_id': user_id,
'item_name': item_name,
'quantity': quantity,
'price': price,
'total': total
})
return orders
# 2. Валидация заказов (удаление некорректных)
def validate_orders(orders: list[dict]) -> list[dict]:
"""
Отбрасывает заказы с quantity <= 0, price <= 0 или пустым item_name.
"""
valid_orders = []
for order in orders:
if (order['quantity'] > 0 and
order['price'] > 0 and
order['item_name'].strip() != ''):
valid_orders.append(order)
return valid_orders
# 3. Группировка заказов по пользователям
def group_by_user(orders: list[dict]) -> dict[int, list[dict]]:
"""
Группирует заказы по user_id.
"""
grouped = {}
for order in orders:
uid = order['user_id']
if uid not in grouped:
grouped[uid] = []
grouped[uid].append(order)
return grouped
# 4. Расчет общей суммы трат пользователя
def calculate_user_total(user_orders: list[dict]) -> float:
"""
Суммирует все значения 'total' для одного пользователя.
"""
return sum(order['total'] for order in user_orders)