2017-02-04 74 views
1

这是解决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 
+3

不要使用单独的变量,请使用将名称映射到列表的字典。然后你可以在字典中查找依赖关系。 – Barmar

+1

请小心使用可变默认参数! http://stackoverflow.com/questions/1132941/least-astonishment-and-the-mutable-default-argument –

+0

@Barmar即使我采取了一个字典,并推动每个列表项的关键,那么我也该如何告诉python将stack.peek元素作为字典的关键。 python相当新颖,请您详细说明如何实现这一目标。谢谢 – user1977867

回答

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')) 

版画

['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'] 

再次,测试各种不同场景来决定,如果它的工作原理为你的目的。

+0

感谢这个例子,它似乎对我很好,我正在考虑如何处理重启案例,例如,直到现在我们正在考虑启动进程,重新启动时,用'P5-> P1'给出,然后在重新启动P1之后,我们还需要启动P5,因为它依赖于P1并且由于P1将被重新启动,所以P5也应该重新启动。 – user1977867

相关问题