I am trying to implement DFS Graph in python and I am newbie I am Python programming. I import defaultdict package in this code.I face this error and I was not figure out this error:
Traceback (most recent call last): File “/Users/abdullahsheikh/PycharmProjects/Implement_dfs/main.py”, line 26, in DFS_graph=DFS_() File “/Users/abdullahsheikh/PycharmProjects/Implement_dfs/main.py”, line 6, in init self.graphlist = defaultdict(self) TypeError: ‘module’ object is not callable
code sample is :
import defaultdict
class DFS_:
def __init__ (self):
self.graphlist = defaultdict(self)
def AddEdge(self,n,v):
self.graphlist[n].append(v)
def DFSfun(self,v,visited):
visited[v] = True
print(v,end= ' ')
for i in self.graphlist[v]:
if visited[i]==False:
self.DFSfun(i,visited)
def _dfs(self,v):
visited = [False] * (max(self.graphlist)+1)
self.DFSfun(v,visited)
DFS_graph=DFS_()
l = int(input("Enter total number of Edges"))
for i in range(l):
firstpoint = int(input("Enter first point"))
secondpoint = int(input("Enter Second point"))
DFS_graph.AddEdge(firstpoint,secondpoint)
startpoint = int(input("Enter starting point: "))
DFS_graph._dfs(startpoint)
Advertisement
Answer
There are multiple issues here.
from collections import defaultdict
instead ofimport defaultdict
self.graphlist = defaultdict()
instead ofself.graphlist = defaultdict(self)
Not sure what the methods are supposed to do. AddEdge should probably be something like:
JavaScript131def AddEdge(self, edge, first_point, second_point):
2self.graphlist.update({edge: [first_point, second_point]})
3
The other methods need a clean up, too.