下面是一個例子遞歸的,基於字典的方法:
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