I have the following problem: You are given a todo list, some items of which depend on others. Write a function that takes a subset of those todos and returns an ordered list of
Don't think of this as a topological sort. Think of this as "do dependencies first, do not do them twice." Which is simple recursive function as long as we keep track of what we will do, and what has been done.
The following Python solution may make this clearer.
def arrange_tasks(dependencies, todo, in_order=None, done=None):
if in_order is None:
in_order = []
if done is None:
done = set()
for item in todo:
# Do we need to?
if item not in done:
# Marking it done first avoids deep recursion on dependency loops!
done.add(item)
# Make sure that dependencies happened.
arrange_tasks(dependencies, dependencies[item], in_order, done)
# And now this can happen.
in_order.append(item)
return in_order
print(arrange_tasks(
{
'make a sandwich': ['buy groceries'],
'buy groceries': ['go to store'],
'go to store': []
},
['buy groceries']
))
Instead of taking a separate filtering pass, you should be able to check each task for addition to the output filteredTasks
as it is processed for addition to orderedTasks
.
Since the only other use of orderedTasks
is to check its length, you should then be able to replace it with a counter.
This might not make your function much faster, but it will simplify your code.