Unit 4 Session 2 Advanced (Click for link to problem statements)
Understand what the interviewer is asking for by using test cases and questions about the problem.
Plan the solution with appropriate visualizations and pseudocode.
General Idea: Iterate through each food item in the dictionary, sum the waste amounts, and track which item has the maximum total waste.
1) Initialize an empty dictionary `total_waste` to store the total waste for each food item.
2) Iterate over each `item, waste_list` pair in the `waste_records` dictionary:
a) Calculate the sum of the `waste_list`.
b) Store the sum in `total_waste` with `item` as the key.
3) Identify the food item with the maximum waste using `max()` on the `total_waste` dictionary.
4) Return the food item with the highest waste.
**⚠️ Common Mistakes**
- Forgetting to correctly sum the values in the waste list, leading to inaccurate totals.
- Assuming that all food items will have waste records, not handling empty lists or missing items.
- Misunderstanding the input format, which could result in incorrect processing of the waste data.
def find_most_wasted_food_item(waste_records):
# Initialize a dictionary to store the total waste for each food item
total_waste = {}
# Iterate over each food item and its waste list
for item, waste_list in waste_records.items():
# Calculate the total waste for the current food item
total_waste[item] = sum(waste_list)
# Find the food item with the maximum waste
max_waste_item = max(total_waste, key=total_waste.get)
return max_waste_item
Example Usage:
waste_records1 = {
"Apples": [200, 150, 50],
"Bananas": [100, 200, 50],
"Carrots": [150, 100, 200],
"Tomatoes": [50, 50, 50]
}
result = find_most_wasted_food_item(waste_records1)
print(result)
# Output: Carrots
waste_records2 = {
"Bread": [300, 400],
"Milk": [200, 150],
"Cheese": [100, 200, 100],
"Fruits": [400, 100]
}
result = find_most_wasted_food_item(waste_records2)
print(result)
# Output: Bread