【问题标题】:what does this <bound method Stack.pop of <__main__.Stack object at 0x03C74AB0>> mean?<__main__.Stack object at 0x03C74AB0>> 的 <bound method Stack.pop 是什么意思?
【发布时间】:2017-03-15 08:24:04
【问题描述】:
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):
        return (self.items ==[])
    def __str__(self):
        return str(self.items)

def postfixEval(postfixExpres):
         operandStack = Stack()
         tokenlist = postfixExpres.split()

         for token in tokenlist:
           if token in "0123456789":
             operandStack.push(int(token))
           else:
             operand2 = operandStack.pop
             operand1 = operandStack.pop
             result = doMath(token,operand1,operand2)
             operandStack.push(result)
         return operandStack.pop

def doMath(op,op1,op2):
       if op == "*":
        return op1*op2
       elif op == "/":
        return op1/op2
       elif op =="+":
        return op1 + op2
       elif op == "-":
        return op1 - op2

print(postfixEval('12+'))    

【问题讨论】:

    标签: python-3.x indexoutofboundsexception postfix-notation


    【解决方案1】:

    我相信这意味着您返回了pop 方法的函数对象,而不是postfixEval 末尾的值。将operandStack.pop 更改为operandStack.pop()(添加括号以应用pop 方法而不是返回它)。

    另外,如果我没记错的话,'12+'.split() 将在 python 中返回'123',因为split 使用空格作为默认分隔符。如果要将字符串转换为单个字符的列表,可以将字符串转换为列表,而不是 list('12+') 将返回 ['1', '2', '+']

    【讨论】:

      【解决方案2】:
      class stack():
          def __init__(self):
              self.items=[]
          def push(self,item):
              self.items.append(item)
          def pop(self):`
              self.items.pop()
          def get_stack(self):
              return self.items
          def emp(self):
              return self.items==[]
          def peek(self):
              if not self.emp():
                  return self.items[-1]
      
      s=stack()
      print("stack is empty: ",s.emp())
      s.push('a')
      s.push('b')
      print(s.get_stack())
      s.push(12)
      print(s.get_stack())
      s.pop()
      print(s.get_stack())
      s.push('c')
      print(s.get_stack())
      print('peek value is: ',s.peek())
      print("stack is empty: ",s.emp())        
      

      【讨论】:

        【解决方案3】:

        在这种情况下,这意味着您正在使用方法对象而不是调用它。在doMath 方法中,您应该像这样使用这两个变量:op1()*op2()

        【讨论】:

          猜你喜欢
          • 2019-05-16
          • 2015-05-06
          • 1970-01-01
          • 2020-04-29
          • 2017-02-27
          • 2017-06-08
          • 1970-01-01
          • 1970-01-01
          • 2013-10-21
          相关资源
          最近更新 更多