Track Daily Food Waste - codepath/compsci_guides GitHub Wiki

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 calculate the total amount of food waste for each day based on the provided waste records and return a dictionary with dates and their corresponding total waste amounts.
  • Q: What are the inputs?
    • A: The input is a dictionary where the keys are dates (strings in the format "YYYY-MM-DD") and the values are lists of integers representing the amounts of food waste (in grams) recorded on those dates.
  • Q: What are the outputs?
    • A: The output is a dictionary where the keys are the same dates and the values are the total amount of food waste for those dates.
  • Q: How should the total waste be calculated?
    • A: For each date, sum the values in the list associated with that date to get the total waste.
  • Q: Are there any assumptions about the input?
    • A: The dictionary is well-formed with valid date strings and lists of non-negative integers.

P-lan

Plan the solution with appropriate visualizations and pseudocode.

General Idea: Iterate through each date in the dictionary, sum the waste amounts for that date, and store the result in a new dictionary.

1) Initialize an empty dictionary `total_waste` to store the total waste for each date.
2) Iterate over each `date, waste_list` pair in the `waste_records` dictionary:
   a) Calculate the sum of the `waste_list`.
   b) Store the sum in `total_waste` with `date` as the key.
3) Return `total_waste`.

**⚠️ Common Mistakes**

- Forgetting to correctly sum the values in the waste list, leading to inaccurate totals.
- Assuming that all dates will have waste records, not handling empty lists or missing dates.
- Misunderstanding the input format, which could result in incorrect processing of the waste data.

I-mplement

def track_daily_food_waste(waste_records):
    # Initialize an empty dictionary to store total waste for each day
    total_waste = {}

    # Iterate over each date in the waste_records dictionary
    for date, waste_list in waste_records.items():
        # Calculate the total waste for the current date
        daily_total = sum(waste_list)

        # Store the total waste in the total_waste dictionary
        total_waste[date] = daily_total

    return total_waste
Example Usage:

waste_records1 = {
    "2024-08-01": [200, 150, 50],
    "2024-08-02": [300, 400],
    "2024-08-03": [100]
}

result = track_daily_food_waste(waste_records1)
print(result)  
# Output: {'2024-08-01': 400, '2024-08-02': 700, '2024-08-03': 100}

waste_records2 = {
    "2024-07-01": [120, 80],
    "2024-07-02": [150, 200, 50],
    "2024-07-03": [300, 100]
}

result = track_daily_food_waste(waste_records2)
print(result)  
# Output: {'2024-07-01': 200, '2024-07-02': 400, '2024-07-03': 400}