deque 在 Python 递归迭代期间发生了变异,用于拓扑排序

问题描述

我正在处理以下问题:

有“N”个任务,标记为“0”到“N-1”。每个任务可以有 一些先决任务需要完成才能完成 预定。给定任务数量和先决条件对列表, 编写一种方法来打印满足所有任务的所有可能的排序 先决条件。

样本如下:

Input: Tasks=4,Prerequisites=[3,2],[3,0],[2,1]
Output: 
1) [3,2,1]
2) [3,1,0]
Explanation: There are two possible orderings of the tasks meeting all prerequisites.

这个问题看起来像一个拓扑排序问题,所以我试着按如下方式解决它:

from collections import deque


class Solution:
    def print_orders(self,tasks,prerequisites):
        # corner case
        if tasks <= 0:
            return []
        # 1. set up the adjacency list and the in-degree
        # the incoming edge of each vertex
        inDegree = {i: 0 for i in range(tasks)}
        # the adjacency list
        graph = {i: [] for i in range(tasks)}

        # 2. assign values
        for parent,child in prerequisites:
            graph[parent].append(child)
            inDegree[child] += 1

        # 3. identify the source
        source = deque()
        for key,inDegreeCount in inDegree.items():
            if inDegreeCount == 0:
                source.append(key)

        # 4. find all list
        return self.finder(source,graph,inDegree,[],[])

    def finder(self,s,res,currentOrder):
        # source is not empty
        if s:
            for vertex in s:
                # take this vertex as root
                currentOrder.append(vertex)
                # remove the vertex from the source
                s.remove(vertex)
                # update the adjacency list
                for child in graph[vertex]:
                    inDegree[child] -= 1
                    if inDegree[child] == 0:
                        s.append(child)
                # recursion for the next vertex
                self.finder(s,currentOrder)
                # add the current vertex back
                currentOrder.remove(vertex)
                for child in graph[vertex]:
                    s.remove(child)
                    inDegree[child] += 1
        # complete searching all vertices
        if len(currentOrder) == len(inDegree):
            res.append(list(currentOrder))
        return res


def main():
    solution = Solution()
    print("Task Orders: ",solution.print_orders(3,[[0,1],[1,2]]))

    print("Task Orders: ",solution.print_orders(4,[[3,1]]))

    print("Task Orders: ",solution.print_orders(6,[[2,5],[0,4],3]]))


main()

错误如下:

Traceback (most recent call last):
line 32,in finder
    for vertex in s:
RuntimeError: deque mutated during iteration

Process finished with exit code 1

我相信错误是由我对 s 的操作引起的。但我不确定如何有效地解决这个问题。

感谢您的高级帮助。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)