I apologize for the error in my previous response. It seems that I made a mistake in the implementation of the topological_sort method. The error message you received indicates that the DirectedGraph object doesn't have an attribute named topological_order.

To fix this issue, we need to define the topological_order list as an instance variable in the DirectedGraph class. Here's the corrected implementation:

class DirectedGraph:
    def __init__(self):
        self.graph = {}
        self.topological_order = []  # Define topological_order as an instance variable

    # Rest of the methods...

    def topological_sort(self):
        visited = set()

        def dfs(vertex):
            visited.add(vertex)
            neighbors = self.get_neighbors(vertex)
            if neighbors:
                for neighbor in neighbors:
                    if neighbor not in visited:
                        dfs(neighbor)
            self.topological_order.append(vertex)

        for vertex in self.graph:
            if vertex not in visited:
                dfs(vertex)

        self.topological_order.reverse()
        for index, vertex in enumerate(self.topological_order):
            print(f'Vertex: {vertex}, Topological Order: {index + 1}')

    # Rest of the methods...

Make sure to update your code with this corrected implementation, and the error should be resolved. Please let me know if you have any further questions!

Python Directed Graph Topological Sort Error: AttributeError: 'Directed_Graph' object has no attribute 'topological_order'

原文地址: https://www.cveoy.top/t/topic/ZNq 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录