Sort Waste Records by Date - 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 sort a list of waste records by date in ascending order.
- Q: What are the inputs?
- A: The input is a list of tuples where each tuple contains a date (as a string in the format
"YYYY-MM-DD"
) and a list of integers representing the amount of food wasted on that date.
- A: The input is a list of tuples where each tuple contains a date (as a string in the format
- Q: What are the outputs?
- A: The output is the same list of tuples, but sorted by date in ascending order.
- Q: How should the dates be compared?
- A: Dates should be compared as strings because the format
"YYYY-MM-DD"
allows for correct chronological ordering using string comparison.
- A: Dates should be compared as strings because the format
- Q: Are there any assumptions about the input?
- A: The input list 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: 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.
I-mplement
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])]