'AttributeError: 'Graph' object has no attribute 'dfs'
I have below python code to build knn graph but I have an error:
AttributeError: 'Graph' object has no attribute 'dfs'.
It seems that the nx.Graph() has no node attribute but I don't know what should I replace with that.
import networkx as nx
def dfs(self,graph, node, visited):
if node not in visited:
visited.append(node)
for n in graph[node]:
self.dfs(graph,n, visited)
return visited
def BFS(self, s):
visited = [False] * (len(self.nodes))
queue = []
queue.append(s)
visited[len(queue)] = True
while queue:
s = queue.pop(0)
print (s, end = " ")
co=len(queue)
for i in self.adj[s]:
co+=1
print(visited[co])
if visited[co] == False:
queue.append(i)
visited[co] = True
DW=nx.DiGraph()
DW.add_nodes_from(['A','B','C','D','E','F','G','H','I','J','K','L','M','N',
'O','P','Q','R','S','T'])
DW.add_edge('A','B')
DW.add_edge('A','E')
DW.add_edge('B','F')
DW.add_edge('E','I')
DW.add_edge('F','J')
DW.add_edge('I','M')
DW.add_edge('M','Q')
DW.add_edge('M','N')
DW.add_edge('J','N')
DW.add_edge('N','R')
DW.add_edge('O','S')
DW.add_edge('O','P')
DW.add_edge('F','G')
DW.add_edge('G','K')
DW.add_edge('K','O')
DW.add_edge('G','H')
DW.add_edge('K','L')
DW.add_edge('C','D')
DW.add_edge('C','G')
DW.add_edge('P','T')
D =nx.Graph()
nx.draw(DW,with_labels=True)
visited = D.dfs(DW,'A', [])
print(visited)
Solution 1:[1]
The function dsf is not defined in any class, especially not in instance D of class Graph. That is the root cause of the issue you are seeing.
So you can either just use the function like so: (make sure to adjust all calls to dsf accordingly)
visited = dfs(DW,'A', [])
Or define everything in a class, e.g.:
class MyClass:
def dfs(self,graph, node, visited):
[...]
and call the function with:
myclass = MyClass()
visited = myclass.dfs(DW,'A', [])
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | mottek |
