Скелет программы

This commit is contained in:
Danil 2026-04-09 20:09:25 +03:00
parent ebffaf9ceb
commit ba88486d55

145
main.py
View File

@ -1,35 +1,158 @@
import json
def load_orders(file_path):
return
with open(file_path, "r", encoding="utf-8") as f: # получаем список словарей orders
return json.load(f)
def validate_order(order):
return
if not isinstance(order, dict): # проверка что order это словарь (dict)
return False
for field in ["id", "customer", "items", "total_price"]:
if field not in order: # проверка что есть все элементы
return False
if not isinstance(order["items"], list):
return False
for item in order["items"]:
if not isinstance(item, dict):
return False
for field in ["name", "price", "quantity"]:
if field not in item:
return False
if not isinstance(item["price"], (int, float)):
return False
if not isinstance(item["quantity"], int):
return False
return True
def filter_orders_by_customer(orders, customer_name):
return
for order in orders:
if order["customer"] == customer_name:
return order
def calculate_order_total(order):
return
total = 0
for item in order["items"]:
total += item["price"] * item["quantity"]
return total
def update_order_totals(orders):
return
for order in orders:
order["total_price"] = calculate_order_total(order)
return orders
def get_top_expensive_orders(orders, n):
return
return sorted(orders, key=lambda x: x["total_price"], reverse=True)[:n]
def group_orders_by_customer(orders):
return
grouped = {}
for order in orders:
customer = order["customer"] # сравниваем по именам, или лучще по id
if customer not in grouped:
grouped[customer] = []
grouped[customer].append(order)
# id = order["id"]
# if id not in grouped:
# grouped[id] = []
# grouped[id].append(order)
return grouped
def calculate_customer_spending(orders):
return
spending = {}
for order in orders:
customer = order["customer"]
spending[customer] = spending.get(customer, 0) + order["total_price"]
return spending
def find_most_popular_product(orders):
return
product_counts = {}
for order in orders:
for item in order["items"]:
name = item["name"]
product_counts[name] = product_counts.get(name, 0) + item["quantity"]
if not product_counts:
return None
return max(product_counts, key=product_counts.get)
def generate_report(orders):
return
report = []
report.append(f"Общее количество действительных заказов: {len(orders)}")
spending = calculate_customer_spending(orders)
sorted_customers = sorted(spending.items(), key=lambda x: x[1], reverse=True)
report.append("\nТоп клиентов:")
for customer, amount in sorted_customers[:5]:
report.append(f"{customer}: {amount}")
popular_product = find_most_popular_product(orders)
report.append(f"\nСамый популярный продукт: {popular_product}")
return "\n".join(report)
def main():
print("Hello")
file_path = "data/orders.txt"
try:
orders = load_orders(file_path)
except Exception as e:
print("Ошибка загрузки файла:", e)
return
# Валидация
valid_orders = []
invalid_count = 0
for order in orders:
if validate_order(order):
valid_orders.append(order)
else:
invalid_count += 1
print(f"Пропущенные недействительные заказы: {invalid_count}")
# Пересчет сумм
valid_orders = update_order_totals(valid_orders)
# Пример фильтрации
example_customer = "Alice"
customer_orders = filter_orders_by_customer(valid_orders, example_customer)
# Аналитика
grouped = group_orders_by_customer(valid_orders)
spending = calculate_customer_spending(valid_orders)
top_orders = get_top_expensive_orders(valid_orders, 3)
# Отчет
report = generate_report(valid_orders)
print("\n=== ОТЧЕТ ===")
print(report)
print("\n=== ТОП 3 ДОРОГИХ ЗАКАЗОВ ===")
for order in top_orders:
print(order)
print(f"\n{example_customer} приобрел(а) {len(customer_orders)} заказов")
print(f"Общее количество клиентов: {len(grouped)}")
if __name__ == "__main__":
main()