Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import json
- from collections import defaultdict
- from datetime import datetime
- import requests
- # -----------------------------
- # Load JSON
- # -----------------------------
- def load_data(url=None, raw_json=None):
- if url:
- return requests.get(url).json()
- elif raw_json:
- return json.loads(raw_json)
- else:
- raise ValueError("Provide URL or raw JSON")
- # -----------------------------
- # 1) Highest protein meal on 1 Nov 2022
- # -----------------------------
- def highest_protein_meal(data):
- target_date = "2022-11-01"
- max_protein = -1
- meal_name = None
- for item in data:
- if item["date_consumed"] == target_date:
- protein = float(item["protein"])
- if protein > max_protein:
- max_protein = protein
- meal_name = item["name"]
- return meal_name or "No Result"
- # -----------------------------
- # 2) Users exceeding 30k calories per month
- # -----------------------------
- def users_exceeding_calories(data):
- monthly_user_calories = defaultdict(lambda: defaultdict(float))
- for item in data:
- date_obj = datetime.strptime(item["date_consumed"], "%Y-%m-%d")
- month = date_obj.strftime("%Y-%m")
- user_id = item["user_id"]
- monthly_user_calories[month][user_id] += float(item["calories"])
- result = {}
- for month, users in monthly_user_calories.items():
- count = sum(1 for cal in users.values() if cal > 30000)
- result[month] = count
- return result
- # -----------------------------
- # 3) 3 Cheapest foods and their consumers
- # -----------------------------
- def cheapest_foods(data):
- food_min_price = {}
- for item in data:
- name = item["name"]
- price = float(item["price"])
- user_id = item["user_id"]
- if name not in food_min_price or price < food_min_price[name][0]:
- food_min_price[name] = (price, user_id)
- sorted_foods = sorted(food_min_price.items(), key=lambda x: x[1][0])
- return sorted_foods[:3]
- # -----------------------------
- # Runner
- # -----------------------------
- def run_all(data):
- print("1) No Result (just reading file)")
- print("2) No Result (just parsing JSON)")
- # 3
- print("3)", highest_protein_meal(data))
- # 4
- print("4)")
- monthly = users_exceeding_calories(data)
- for month in sorted(monthly):
- print(f"{month}: {monthly[month]}")
- # 5
- print("5)")
- for name, (price, user_id) in cheapest_foods(data):
- print(f"{name}, {price:.2f}, {user_id}")
- # -----------------------------
- # MAIN
- # -----------------------------
- if __name__ == "__main__":
- URL = "https://topt.al/r6cvQM"
- try:
- data = load_data(url=URL)
- except:
- print("Paste JSON manually if URL fails")
- data = []
- run_all(data)
Advertisement
Add Comment
Please, Sign In to add comment