酷代码 AI
菜单
服务商

设计一个python算法,利用栈计算算术表达式

以下是一个使用 Python 实现的利用栈计算算术表达式的算法示例: ```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): 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 calculate_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 precedence[operator_stack.peek()] >= precedence[char]: operand2 = operand_stack.pop() operand1 = operand_stack.pop() operator = operator_stack.pop() if operator == '+': operand_stack.push(operand1 + operand2) elif operator == '-': operand_stack.push(operand1 - operand2) elif operator == '*': operand_stack.push(operand1 * operand2) elif operator == '/': operand_stack.push(operand1 / operand2) operator_stack.push(char) while not operator_stack.is_empty(): operand2 = operand_stack.pop() operand1 = operand_stack.pop() operator = operator_stack.pop() if operator == '+': operand_stack.push(operand1 + operand2) elif operator == '-': operand_stack.push(operand1 - operand2) elif operator == '*': operand_stack.push(operand1 * operand2) elif operator == '/': operand_stack.push(operand1 / operand2) return operand_stack.pop() # 测试 expression = "2+3*4" result = calculate_expression(expression) print(result) ``` 这个算法的基本思路是: - 遍历表达式中的每个字符。 - 如果是数字,将其压入操作数栈。 - 如果是运算符,根据运算符的优先级进行处理。如果当前运算符的优先级低于或等于栈顶运算符的优先级,就先计算栈顶的运算,然后将结果压入操作数栈,再将当前运算符压入运算符栈。 - 遍历完表达式后,依次从运算符栈和操作数栈取出元素进行计算,直到运算符栈为空,最终操作数栈中的唯一元素就是计算结果。 [2024-10-22 23:05:28 | AI写代码神器 | 612点数解答]

相关提问
实用工具查看更多
今日油价 [生活类]
图片互转base64 [开发类]
时间转换器 [开发类]
数独游戏 [娱乐类]
经典推箱子 [娱乐类]
AI摸鱼五子棋 [娱乐类]