practice_repin_1/zadanie_1.py

101 lines
3.5 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)
# 5. Поиск самого дорогого товара (по цене за единицу)
def find_most_expensive_item(orders: list[dict]) -> tuple[str, float]:
"""
Возвращает (название, цена) товара с максимальной price.
"""
if not orders:
return ('', 0.0)
most_expensive = max(orders, key=lambda x: x['price'])
return (most_expensive['item_name'], most_expensive['price'])
# 6. Применение скидки ко всем заказам (возвращает новый список)
def apply_discount(orders: list[dict], discount_percent: float) -> list[dict]:
"""
Уменьшает поле 'total' на discount_percent.
Возвращает новый список заказов, не изменяя исходный.
"""
discounted_orders = []
for order in orders:
new_order = order.copy()
new_order['total'] = order['total'] * (1 - discount_percent / 100.0)
discounted_orders.append(new_order)
return discounted_orders
# 7. Фильтрация товаров по минимальной цене за единицу
def filter_by_price_threshold(orders: list[dict], min_price: float) -> list[dict]:
"""
Возвращает заказы, у которых price >= min_price.
"""
return [order for order in orders if order['price'] >= min_price]