在Python中使用堆栈计算表达式

2024-10-03 13:21:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我想编写一个Python代码,它将使用堆栈计算表达式。我有以下代码,其中numStk是一个包含数字的堆栈,optStk包含运算符。在表达式2+3*4-6中,在for循环的末尾,numStack包含{},12,和{};而{}包含{}和{}。现在我如何使我的setOps()函数从两个堆栈中弹出元素来计算表达式?在

def main():
      raw_expression = input("Enter an expression: ")
      expression = raw_expression.replace(" ", "")
      for i in expression:
          if (i in numbers):
              numStk.push(i)
          else:
              setOps(i)
              optStk.push(i)
      ## code needed to evaluate the rest of the elements in stackstack
      return valStk.top()

我的setOps(i)函数如下:

^{pr2}$

Tags: the函数代码inforraw表达式堆栈
1条回答
网友
1楼 · 发布于 2024-10-03 13:21:53

即使我填写了您遗漏的所有内容,您的代码也有问题:setOps()似乎被称为repeatOps()numStk有时被称为{};您的计算顺序错误,例如,“6-5”被计算为“5-6”;您调用的是eval()!在

以下是我为解决上述问题而填写和修改您的代码:

from collections import OrderedDict

DIGITS = "0123456789"

# position implies (PEMDAS) priority, low to high
OPERATORS = OrderedDict([  \
    ['+', lambda a, b: a + b], \
    ['-', lambda a, b: a - b], \
    ['*', lambda a, b: a * b], \
    ['/', lambda a, b: a / b], \
    ])

def operator_priority(character):
    return list(OPERATORS.keys()).index(character)

class Stack(list):
    """ minimalist stack implementation """

    def push(self, thing):
        self.append(thing)

    def top(self):
        return self[-1]

def evaluate(expression):
    numStk = Stack()
    optStk = Stack()

    def setOps(refOp):
        while numStk and optStk and operator_priority(refOp) <= operator_priority(optStk.top()):
            y = numStk.pop()
            x = numStk.pop()
            op = optStk.pop()
            print(x, op, y)  # debugging
            numStk.push(OPERATORS[op](x, y))

    for i in expression:
        if i in DIGITS:
            numStk.push(int(i))
        else:
            setOps(i)
            optStk.push(i)

    if optStk:
        # evaluate the rest of the elements in stacks
        setOps(list(OPERATORS.keys())[0])  # trigger using lowest priority operator

    return numStk.top()

if __name__ == "__main__":
    raw_expression = input("Enter an expression: ")
    expression = raw_expression.replace(" ", "")
    print(evaluate(expression))

远不是十全十美,但有些东西能让你前进:

示例

^{pr2}$

为了解决您最初的问题,完成评估的关键似乎是使用一个虚构的低优先级运算符运行setOps(),如果optStk中还剩下什么。在

相关问题 更多 >