【问题标题】:Module object is not callable when using defaultdict package not working in PyCharm [closed]使用在 PyCharm 中不起作用的 defaultdict 包时,模块对象不可调用 [关闭]
【发布时间】:2021-06-22 13:26:59
【问题描述】:

我正在尝试在 python 中实现 DFS Graph,我是新手,我是 Python 编程。我在此代码中导入 defaultdict 包。我遇到了这个错误,但我没有弄清楚这个错误:

Traceback(最近一次调用最后一次): 文件“/Users/abdullahsheikh/PycharmProjects/Implement_dfs/main.py”,第 26 行,在 DFS_graph=DFS_() init 中的文件“/Users/abdullahsheikh/PycharmProjects/Implement_dfs/main.py”,第 6 行 self.graphlist = defaultdict(self) TypeError: 'module' 对象不可调用

代码示例是:

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)



【问题讨论】:

  • 导入看起来错误。你在使用collections.defaultdict 类吗?
  • 是的,我使用 defaultdict,我使用 Pycharm IDE。

标签: python python-3.x list graph pycharm


【解决方案1】:

这里有多个问题。

  1. from collections import defaultdict 而不是import defaultdict

  2. self.graphlist = defaultdict() 而不是self.graphlist = defaultdict(self)

  3. 不确定这些方法应该做什么。 AddEdge 应该是这样的:

     def AddEdge(self, edge, first_point, second_point):
         self.graphlist.update({edge: [first_point, second_point]})
    

    其他方法也需要清理。

【讨论】:

  • 非常感谢。 self.graphlist = defaultdict(self) 是个问题。
猜你喜欢
  • 2022-08-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-01
  • 1970-01-01
  • 2020-06-27
  • 1970-01-01
  • 2017-09-24
相关资源
最近更新 更多