以下是使用栈求解简单表达式的完整代码:

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):
        if not self.is_empty():
            return self.items.pop()
        else:
            return None

    def peek(self):
        if not self.is_empty():
            return self.items[-1]
        else:
            return None

def evaluate_expression(expression):
    operand_stack = Stack()
    operator_stack = Stack()
    precedence = {'+': 1, '-': 1, '*': 2, '/': 2}

    for char in expression:
        if char.isdigit():
            operand_stack.push(int(char))
        elif char in ['+', '-', '*', '/']:
            while (not operator_stack.is_empty() and operator_stack.peek() != '('
                   and precedence[char] <= precedence[operator_stack.peek()]):
                operand2 = operand_stack.pop()
                operand1 = operand_stack.pop()
                operator = operator_stack.pop()
                result = calculate(operator, operand1, operand2)
                operand_stack.push(result)
            operator_stack.push(char)
        elif char == '(': 
            operator_stack.push(char)
        elif char == ')':
            while not operator_stack.is_empty() and operator_stack.peek() != '(': 
                operand2 = operand_stack.pop()
                operand1 = operand_stack.pop()
                operator = operator_stack.pop()
                result = calculate(operator, operand1, operand2)
                operand_stack.push(result)
            if not operator_stack.is_empty() and operator_stack.peek() == '(': 
                operator_stack.pop()

    while not operator_stack.is_empty():
        operand2 = operand_stack.pop()
        operand1 = operand_stack.pop()
        operator = operator_stack.pop()
        result = calculate(operator, operand1, operand2)
        operand_stack.push(result)

    return operand_stack.peek()

def calculate(operator, operand1, operand2):
    if operator == '+':
        return operand1 + operand2
    elif operator == '-':
        return operand1 - operand2
    elif operator == '*':
        return operand1 * operand2
    elif operator == '/':
        return operand1 / operand2

expression = '(56-20)/(4+2)'
result = evaluate_expression(expression)
print(f'The value of the expression {expression} is: {result}')

在这个示例中,我们定义了一个栈类(Stack),以及相关的操作方法。使用栈类,我们实现了求解简单表达式的算法。evaluate_expression函数对表达式进行求值,calculate函数执行运算操作。最后,我们调用evaluate_expression函数来求解给定表达式的值,并输出结果。在本例中,表达式为'(56-20)/(4+2)',求得的结果为6.0。

使用栈求解简单表达式 - Python 代码示例

原文地址: http://www.cveoy.top/t/topic/DUZ 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录