""" 逆波兰表示法 逆波兰表示法(英语:Reverse Polish notation,缩写RPN, 或逆波兰记法、逆卢卡西维茨记法), 是一种由波兰数学家扬·卢卡西维茨于1920年引入的数学表达式形式。 在逆波兰记法中,所有操作符置于操作数的后面, 因此也被称为后缓示法、后序表示法。 逆波兰记法不需要括号来标识操作符的优先级。 计算'11 6 9 3 + -11 * / * 17 + 5 -'的结果。 """ import operator class Stack: """ 栈类,用于存储和操作数据。 """ def __init__(self): """ 初始化栈对象,设置空的items列表。 """ self.items = [] def push(self, item): """ 将元素压入栈顶。 参数: item - 要压入栈的元素。 """ self.items.append(item) def pop(self): """ 弹出并返回栈顶元素。 返回: 栈顶元素。 """ return self.items.pop() def eval_rpn(expr): """ 评估逆波兰表达式。 参数: expr - 逆波兰表达式的字符串表示。 返回: 表达式的计算结果。 """ operators = { '+': operator.add, '-': operator.sub, '*': operator.mul, '/': operator.truediv, } stack = Stack() for item in expr.split(" "): if item in '+-*/': num1 = stack.pop() num2 = stack.pop() stack.push(operators[item](num2, num1)) else: stack.push(int(item)) return round(stack.pop(), 2) print(eval_rpn('11 6 9 3 + -11 * / * 17 + 5 -'))
评论前必须登录!
注册