【问题标题】:Python MS Project Predecessor Recursion with for loopPython MS项目前身递归与for循环
【发布时间】:2017-03-13 08:51:38
【问题描述】:

我已将 MS 项目文件提取为 CSV。它相当大(40 000 行),我正在尝试创建一个 Python 脚本,该脚本可以打印出任务/里程碑/依赖项之前的所有任务。

问题在于具有多个前置任务的任务。我已经存储了这些以“~”分隔的内容。

#Starting ID
MSid = 80329

#Subroutine FindPredesessors(MSid)
def FindPred(MSid):
#Get element[id] from the array                
    print(MSid)
    #Predecessors of task
    preds = arrMAX[MSid][1]
    #List of split milestones
    spID = spad.split('~')

    #Attempt to loop through Function for each milestone in the split list
    for h in range(len(spID)):         
        print(spID[h])
        print(h)
        FindPred(int(spID[h]))

FindPred(MSid)

我能做的最好的就是下面的输出

80329
['80326', '83171']
['80324', '80432']
['80323']
''

我可以得到最左边的路径,但我似乎无法返回并在拆分列表的其余部分循环该函数

【问题讨论】:

  • 您肯定会多次遇到一些前任任务,因此请存储您已经搜索过的 ID,并在每次搜索之前检查这些 ID。

标签: python loops recursion tree ms-project


【解决方案1】:

看来您需要Breadth First Search。这个想法是:

  1. 将所需的事件ID放入queue
  2. 当队列不为空时
    • get() current id 来自它
    • current的所有前辈放入队列中

因此,您将首先访问所选事件的所有前辈,然后访问其所有前辈,依此类推。

#!/usr/bin/env python3
from queue import Queue

size = 6
# in assumption you have devided strings to lists of ids
# -1 means that event has no predecessor.
preds = [[-1], [-1], [-1], [0], [1, 2], [3, 4]]

def bfs(start):
    """ Prints path of Depth first search given predecessors for all events"""
    q = Queue()
    q.put(start)

    while not q.empty():
        current = q.get()
        currentPreds = preds[current]
        print(current, end=' ')
        # or you can print them with predecessors
        # print(currentId =', current, '| preds:', currentPreds)

        for c in currentPreds:
            if not visited[c] and c != -1:
                q.put(c)
    print()

bfs(5)

【讨论】:

  • 我现在已经尝试过了,我得到了类似的结果。我似乎无法让函数返回到完成 for 循环的位置。
  • @codderz 我已经改变了答案,希望现在它会有所帮助。如果您只寻找递归版本,请查看深度优先搜索,但对于此类任务,您不需要。
  • 这是我目前为止最好的。谢谢你。但由于某种原因,即使我已经用 -1 替换了所有空白字段,我仍然坐在列表中得到 ' ' 并且它以错误终止
  • 刚刚清理了我的 CSV 文件,它就可以工作了。万岁!非常感谢!
猜你喜欢
  • 2016-07-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-12
  • 1970-01-01
  • 1970-01-01
  • 2011-02-09
相关资源
最近更新 更多