下面是一个例子递归的,基于字典的方法:
dependencies = { \
'p1': ['p2', 'p3'], \
'p2': ['p3', 'p4'], \
'p3': ['p4'], \
'p4': [], \
'p5': [] \
}
def run_order(process, order=None):
if order is None:
order = []
precursors = dependencies[process]
if precursors:
for precursor in precursors:
run_order(precursor, order)
if process not in order:
order.append(process) # should really be insert after right-most precursor
elif process not in order:
order.insert(0, process) # no dependencies, start ASAP
return order
print(run_order('p1'))
版画
['p4', 'p3', 'p2', 'p1']
这是否正确顺序你的目的的过程? (您需要测试各种不同场景。)另一种方法是让run_order()
采取的进程列表:
def run_order(processes, order=None):
if order is None:
order = []
for process in processes:
precursors = dependencies[process]
if precursors:
run_order(dependencies[process], order)
if process not in order:
order.append(process) # should really be insert after right-most precursor
elif process not in order:
order.insert(0, process) # no dependencies, start ASAP
return order
print(run_order(['p1']))
print(run_order(list(dependencies.keys())))
版画
['p4', 'p3', 'p2', 'p1']
['p5', 'p4', 'p3', 'p2', 'p1']
再次,测试各种不同场景来决定,如果它的工作原理为你的目的。
不要使用单独的变量,请使用将名称映射到列表的字典。然后你可以在字典中查找依赖关系。 – Barmar
请小心使用可变默认参数! http://stackoverflow.com/questions/1132941/least-astonishment-and-the-mutable-default-argument –
@Barmar即使我采取了一个字典,并推动每个列表项的关键,那么我也该如何告诉python将stack.peek元素作为字典的关键。 python相当新颖,请您详细说明如何实现这一目标。谢谢 – user1977867