这是解决this问题时代码中的一小段代码。我想将列表中的项目推送到堆栈中,但在传递给run
函数时,应使用相同的项目名称作为列表名称。我的意图是接近深度优先搜索和基本情况以阻止递归将很快包含在我的代码中。
有没有办法将cast
项弹出作为列表名称参数。
#Below is dependency list
p1-['p2','p3']
p2=['p3','p4']
p3=['p4']
p4=[]
p5=[]
def run(pro=[])
if pro: #process has a dependency, push its items dependency into stack
for dependency in pro:
stack.push(dependency)
run(stack.peek) #I need to pass top item of stack as a list
答案 0 :(得分:2)
这是一个递归的,基于字典的方法示例:
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'))
<强> PRINTS 强>
['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())))
<强> PRINTS 强>
['p4', 'p3', 'p2', 'p1']
['p5', 'p4', 'p3', 'p2', 'p1']
再次,测试各种场景以确定它是否适合您的目的。