I wrote a topological sort alg and it's not returning an output

Viewed 63

I think my topological sort algorithm is correct, but perhaps my node class isn't working. This is my node class and my main function that creates the graph. When I run this, I get no output. I think it's my class or construction of my graph that went wrong because topSort() returns a list, so if it ran incorrectly, then I'd expect an empty list or a list with the wrong topological sort. This leads me to believe that the issue is in my construction.

class Node: 
    def __init__(self, val = 0, neighbors = None) -> None:
        self.val = val
        self.neighbors = neighbors
    def replaceNeighbors(self, neighbors):
        self.neighbors = neighbors

def dfs(vertex, stack, visited):
    #code

def topSort(graph):
    #code

def main():
    node1 = Node(1)
    node2 = Node(2)
    node3 = Node(3)
    node4 = Node(4)
    node1.replaceNeighbors([node2, node3])
    node2.replaceNeighbors([node4])
    node4.replaceNeighbors([node3])
    root = Node(0, [node1, node2])
    graph = [root, node1, node2, node3, node4]
    order = topSort(graph)
    print(order)
1 Answers

The reason your code is not returning a value is because you are not calling the main() method. You should use the strategy below to accomplish this. Also, a better technique to coming back to methods you declared, but haven't defined is using pass.

class Node:
    def __init__(self, val, neighbors=None) -> None:
        self.val = val
        self.neighbors = neighbors

    def replaceNeighbors(self, neighbors):
        self.neighbors = neighbors


def dfs(vertex, stack, visited):
    pass


def topSort(graph):
    pass


def main():
    node1 = Node(1)
    node2 = Node(2)
    node3 = Node(3)
    node4 = Node(4)
    node1.replaceNeighbors([node2, node3])
    node2.replaceNeighbors([node4])
    node4.replaceNeighbors([node3])
    root = Node(0, [node1, node2])
    graph = [root, node1, node2, node3, node4]
    order = topSort(graph)
    print(order)


if __name__ == '__main__':
    main()  # calls main method
Related