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.
"YYYY-MM-DD"
) and a list of integers representing the amount of food wasted on that date."YYYY-MM-DD"
allows for correct chronological ordering using string comparison.Plan the solution with appropriate visualizations and pseudocode.
General Idea: Use Python’s built-in sorting capabilities to sort the list of tuples by the date element in each tuple.
1) Use the `sorted()` function or the `sort()` method on the list `waste_records`.
2) Specify the sort key as the first element of each tuple (the date).
3) Return the sorted list.
**⚠️ Common Mistakes**
- Not realizing that the dates can be compared directly as strings due to their format.
- Overcomplicating the sort logic by attempting a manual implementation instead of using Python's efficient built-in sorting functions.
- Assuming the input might have duplicate dates, which is handled naturally by the sorting process.
def sort_waste_records_by_date(waste_records):
# Sort the list of waste records by the date (first element of each tuple)
return sorted(waste_records, key=lambda record: record[0])
Example Usage:
waste_records1 = [
("2024-08-15", [300, 200]),
("2024-08-13", [150, 100]),
("2024-08-14", [200, 250]),
("2024-08-12", [100, 50])
]
result = sort_waste_records_by_date(waste_records1)
print(result)
# Output: [('2024-08-12', [100, 50]), ('2024-08-13', [150, 100]), ('2024-08-14', [200, 250]), ('2024-08-15', [300, 200])]
waste_records2 = [
("2024-07-05", [400, 150]),
("2024-07-01", [200, 300]),
("2024-07-03", [100, 100]),
("2024-07-04", [50, 50])
]
result = sort_waste_records_by_date(waste_records2)
print(result)
# Output: [('2024-07-01', [200, 300]), ('2024-07-03', [100, 100]), ('2024-07-04', [50, 50]), ('2024-07-05', [400, 150])]