微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决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 举报,一经查实,本站将立刻删除。