【问题标题】:Pop from Empty list error从空列表错误中弹出
【发布时间】:2013-06-11 10:19:21
【问题描述】:

我正在尝试将元素从列表推送到堆栈。代码如下:

#!/usr/bin/python

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

  def push(self, item) : 
    self.items.append(item) 

  def pop(self) : 
    return self.items.pop() 

  def isEmpty(self) : 
    if self.items == []:
     return true 

def InsertIntostacks(lst1):


    X = Stack() #for each expression a stack is defined
    Y = Stack()

    for words in lst1:

      if (ord(words) >= 48  and ord(words) <= 57) or (ord(words) >=65 and ord(words) <= 90):
          X.push(words)

      else:
          Y.push(words)

    print X.pop()



if __name__ == '__main__':
    a = open("testinput1.txt","r+")
    wordList = [line.strip() for line in a];

#print wordList[1]
    lst=list()
    for words in wordList:
      if words == '#':
       print "End of file"
      else:
          lst = list(words)
          lst1 = list()
          print lst
          for x1 in lst:
            if x1 != ' ':
             lst1.append(x1)
            InsertIntostacks(lst1)

所以 X 被填充,我需要 Y 来包含运算符,但显然没有任何元素进入 Y (输入如 A=B=C,所以 Y 应该包含 = = )。 如果我删除约束并将所有元素推送到一个堆栈中,则操作员就在那里。 我在这里做错了什么?

【问题讨论】:

  • 文件testinput1.txt长什么样子?

标签: python list debugging stack


【解决方案1】:

我怀疑InsertIntostacks(lst1) 的缩进可能是错误的,这就是问题所在。

尝试确保InsertIntostacks(lst1)for 循环正确对齐,这意味着它在循环之后执行,而不是在循环内。现在它在循环的每一次迭代中都执行,包括第一次,lst 确实是空的。

【讨论】:

  • 应该在for循环里面。 lst真的不空。我在每一步都检查了代码(读取:打印值),它工作正常。我怀疑运算符的 ASCII 值有问题。当我在没有任何 if ord(words) 语句的情况下推送元素时,堆栈会获取所有值。但是一旦遇到一个 ord 甚至像 words == '=' 这样的简单检查,它就会失败
猜你喜欢
  • 2014-04-04
  • 1970-01-01
  • 2015-09-21
  • 1970-01-01
  • 2020-01-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多