0

So, I'm trying to solve a task where I'm supposed to find if there is a cycle in the given graph using DFS. So what im strugguling with now is to match the nodes, since they are of type string I'm having some truble. The error message iI'm getting is the following:

TypeError: list indices must be integers or slices, not Graph

So I'm wondering how to solve this problem, or how to make it work for string and not just int?

    graph = dict()
    searched = []
   
    def add_edge(self, node, neighbour):
        if node not in self.graph:
            self.graph[node] = [neighbour]
        else:
            self.graph[node].append(neighbour)
            
   
                        
    
    
    def depth_first_search(self, node):
        if node not in self.searched:
            print("[", node, end= " ], ")
            
            self.searched.append(node)
            if node in self.graph:
                for neighbour in self.graph[node]:
                    self.depth_first_search(neighbour)
            
    def find_cycle(node):
        searched = [False]
        
        for i in searched[node]:
            if searched[i] == [False]*node:
                if(self.depth_first_search(i, node, neighbour)) == True:
                    return True
        return False
        
        
    def print_edges(self):
        for node in self.graph:
            for neighbour in self.graph[node]:
                print("(", node, "," , neighbour, ")")
    def print_graph(self):
        print(self.graph)
        

my_graph = Graph()
my_graph.add_edge('A', 'B')
my_graph.add_edge('B', 'C')
my_graph.add_edge('B', 'D')
my_graph.add_edge('D', 'E')
my_graph.add_edge('D', 'F')
my_graph.add_edge('C', 'E')
my_graph.add_edge('E', 'G')
my_graph.add_edge('F', 'H')
my_graph.print_graph()
my_graph.print_edges()
my_graph.depth_first_search('A')
result = my_graph.find_cycle()
print(result)
SonCOR
  • 63
  • 4
  • "TypeError: list indices must be integers or slices, not Graph" Okay, so, what do you think that *means*? Did you try to figure out which `list index` was a `Graph`, instead of being an `integer or slice` as requested? Did you try to figure out *why* it was a `Graph`? Did you look at the traceback in the error message, in order to figure out what part of the code it was complaining about? – Karl Knechtel Mar 24 '21 at 11:12
  • Where you have written `for i in searched[node]:`, what values do you expect `i` to take on? What kind of thing is `searched`, and what kind of thing is `node`? Does it make sense to do `searched[node]`, then? What should the result be? On the next line, where you do `if searched[i] == [False]*node:`, does that make sense to you? In particular, what do you expect the `searched[i]` part to do? – Karl Knechtel Mar 24 '21 at 11:15
  • Where you have `graph = dict()` and `searched = []` at the top, you do understand that these create *class* attributes, not instance attributes, yes? – Karl Knechtel Mar 24 '21 at 11:15

0 Answers0