Python栈的应用:四则运算表达式求解

2023-04-10 00:00:00 表达式 运算 求解

Python栈可以用于四则运算表达式求解。其基本思路是将运算符和操作数分别压入栈,当遇到运算符时弹出相应数量的操作数进行计算并将结果压入栈中,直到整个表达式计算完成。以下是详细的代码演示:

class Stack:
    """
    实现栈的数据结构
    """
    def __init__(self):
        self.items = []

    def is_empty(self):
        return len(self.items) == 0

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

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

    def peek(self):
        return self.items[-1]

    def size(self):
        return len(self.items)


def operate(num1, num2, operator):
    """
    实现基本的四则运算函数
    """
    if operator == '+':
        return num1 + num2
    elif operator == '-':
        return num1 - num2
    elif operator == '*':
        return num1 * num2
    elif operator == '/':
        if num2 == 0:
            raise ValueError('Divisor cannot be zero')
        return num1 / num2


def calculate(expression):
    """
    计算四则运算表达式
    """
    operator_stack = Stack()
    operand_stack = Stack()
    for i in range(len(expression)):
        char = expression[i]
        if char.isdigit():
            # 如果是数字,则将其压入操作数栈
            operand_stack.push(int(char))
        elif char in '+-*/':
            # 如果是运算符,则将其压入运算符栈
            operator_stack.push(char)
        elif char == '(':
            # 如果是左括号,则继续扫描
            pass
        elif char == ')':
            # 如果是右括号,则弹出相应数量的运算符和操作数进行计算
            operator = operator_stack.pop()
            num2 = operand_stack.pop()
            num1 = operand_stack.pop()
            result = operate(num1, num2, operator)
            operand_stack.push(result)
        else:
            raise ValueError('Invalid character: {}'.format(char))

    # 处理剩余的运算符和操作数
    while not operator_stack.is_empty():
        operator = operator_stack.pop()
        num2 = operand_stack.pop()
        num1 = operand_stack.pop()
        result = operate(num1, num2, operator)
        operand_stack.push(result)

    return operand_stack.pop()


if __name__ == '__main__':
    expression = '2+3*(4+5)-6/2'
    result = calculate(expression)
    print('{} = {}'.format(expression, result))    # 输出:2+3*(4+5)-6/2 = 29.0

该演示代码实现了基本的四则运算表达式计算功能,包括加、减、乘、除和括号。在运行时,可以将表达式字符串作为参数传递给calculate函数,该函数将返回表达式的计算结果。在本例中,计算表达式2+3*(4+5)-6/2的结果为29.0。

相关文章