Hello, I have a task at hand and would like to discuss with you what you think of my solution and whether would you do it completely differently or just change a thing here and there. Problem: Imagine you have a to-do list including tasks like the one below:
to_do_list = [
{priority: 2, name: "Take out trash"},
{priority: 1, name: "Go running"},
{priority: 20, name: "Do homework"},
{priority: 5, name: "Feed a dog"},
{priority: 20, name: "Water plants"},
]
where priority >= 0
.
Your task is to reduce priority
values to minimum while persisting their priority order. eg: Right now, there are 5 tasks with priorities 1, 2, 5, 20
. The goal is to reduce these numbers to look like 0, 1, 2, 3
without changing the order of tasks in the to_do_list
.
Expected outcome:
to_do_list = [
{priority: 1, name: "Take out trash"},
{priority: 0, name: "Go running"},
{priority: 3, name: "Do homework"},
{priority: 2, name: "Feed a dog"},
{priority: 3, name: "Water plants"},
]
My solution:
- Create a dictionary for unique priority values
- Store all tasks of the same priority in a list under its corresponding section(key) in the dictionary
- Create a list of sorted keys(priorities) from the dictionary in ascending order
- Initialise
new priority
to 0 - Iterate for each priority in the sorted keys(priorities)
- access list of tasks with the same priority
- change all the tasks’ priority attribute to
new priority
- increase
new priority
by 1
# Step 1
tasks_by_priority = dict()
# Step 2 - start
for task in to_do_list:
priority = task['priority']
# if first occurance of task's priority in the dictionary
# initialise it with empty list
if priority not in tasks_by_priority:
tasks_by_priority[priority] = []
# add item to the list
tasks_by_priority[priority].append(item)
# Step 3
sorted_priorities = sorted(tasks_by_priority.keys())
# Step 4
new_priority = 0
# Step 5
for priority in sorted_priorities:
for task in tasks_by_priority[priority]:
task['priority'] = new_priority
new_priority += 1
Thank you for you feedback