Codepath

Find Most Wasted Food Item

Unit 4 Session 2 Advanced (Click for link to problem statements)

U-nderstand

Understand what the interviewer is asking for by using test cases and questions about the problem.

  • Q: What is the goal of the problem?
    • A: The goal is to identify the food item that was wasted the most in total grams.
  • Q: What are the inputs?
    • A: The input is a dictionary where the keys are food items (strings) and the values are lists of integers representing the amounts of that food item wasted (in grams).
  • Q: What are the outputs?
    • A: The output is the name of the food item that has the highest total waste.
  • Q: How should the total waste be calculated?
    • A: For each food item, sum the values in the list associated with that food item to get the total waste. Then, determine which item has the maximum waste.
  • Q: Are there any assumptions about the input?
    • A: The dictionary is well-formed with non-negative integer values in the lists.

P-lan

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.

I-mplement

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
Fork me on GitHub