使用给定深度优先搜索功能制作拓扑搜索功能

时间:2015-05-08 21:44:24

标签: python

我在拓扑排序后制作了一堆顶点。我认为我编写的代码是正确的,但我不知道如何打印出堆栈。 这是我的代码:

  def toposort (self):
    stack = Stack()
    top = []
    for i in range(0,len(self.Vertices)):
      self.Vertices[i].visited == False
    for i in range(0,len(self.Vertices)):
      if not (self.Vertices[i]).wasVisited():
        self.dffs(self.getIndex(i),stack)
    return stack

  def dffs(self, v, stack):
    self.Vertices[v].visited == True
    for i in range(0,len(self.Vertices)):
      if (self.adjMat[v][i] > 0) and (not (self.Vertices[i]).wasVisited()):
        self.dffs(self.getIndex(self.Vertices[i]), stack)
        print (self.Vertices[v])
    stack.push(v)

,我得到的输出是:< main .Stack对象位于0x104adf1d0> 我确定这很容易解决,但我不知道如何解决。我的图是一堆带有权重的顶点和标签。

class Stack (object):
  def __init__ (self):
    self.stack = []

  # add an item to the top of the stack
  def push (self, item):
    self.stack.append ( item )

  # remove an item from the top of the stack
  def pop (self):
    return self.stack.pop()

  # check what item is on top of the stack without removing it
  def peek (self):
    return self.stack[len(self.stack) - 1]

  # check if a stack is empty
  def isEmpty (self):
    return (len(self.stack) == 0)

  # return the number of elements in the stack
  def size (self):
    return (len(self.stack))

1 个答案:

答案 0 :(得分:0)

看起来您的实际问题是"如何打印我的Stack对象"。默认情况下,在自定义类上调用str()只会打印出类型名称及其id,这不是非常有用。要改为打印内容,请将__str__()方法添加到Stack:

def __str__(self):
   return str(self.stack)