酷代码 AI
菜单
服务商

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

下面是一个使用栈来计算算术表达式的Python算法: ```python # 定义运算符的优先级 precedence = {'+': 1, '-': 1, '*': 2, '/': 2, '^': 3} # 定义栈类 class Stack: def __init__(self): self.items = [] def is_empty(self): return self.items == [] def push(self, item): self.items.append(item) def pop(self): return self.items.pop() def peek(self): return self.items[-1] # 定义函数来判断一个字符是否是运算符 def is_operator(char): return char in ['+', '-', '*', '/', '^'] # 定义函数来计算两个操作数的结果 def apply_operator(operator, b, a): if operator == '+': return a + b elif operator == '-': return a - b elif operator == '*': return a * b elif operator == '/': return a / b elif operator == '^': return a b # 定义函数来计算算术表达式的值 def evaluate(expression): operand_stack = Stack() operator_stack = Stack() # 遍历表达式中的每个字符 for char in expression: # 如果是一个数字,则将它压入操作数栈 if char.isdigit(): operand_stack.push(int(char)) # 如果是一个左括号,则将它压入运算符栈 elif char == '(': operator_stack.push(char) # 如果是一个右括号,则执行栈中所有的运算符,直到遇到左括号 elif char == ')': while not operator_stack.is_empty() and operator_stack.peek() != '(': operator = operator_stack.pop() b = operand_stack.pop() a = operand_stack.pop() result = apply_operator(operator, b, a) operand_stack.push(result) operator_stack.pop() # 弹出左括号 # 如果是一个运算符,则执行栈中所有优先级更高或相等的运算符 elif is_operator(char): while not operator_stack.is_empty() and precedence[char] <= precedence[operator_stack.peek()]: operator = operator_stack.pop() b = operand_stack.pop() a = operand_stack.pop() result = apply_operator(operator, b, a) operand_stack.push(result) operator_stack.push(char) # 执行栈中剩余的运算符 while not operator_stack.is_empty(): operator = operator_stack.pop() b = operand_stack.pop() a = operand_stack.pop() result = apply_operator(operator, b, a) operand_stack.push(result) # 返回最终的结果 return operand_stack.pop() # 测试算术表达式计算 expression = "3+4*2/(1-5)^2" result = evaluate(expression) print("计算结果:", result) ``` 这个算法首先定义了一个`Stack`类,用于实现栈数据结构。然后定义了一个`precedence`字典,用于存储每个运算符的优先级。接着定义了几个工具函数,包括`is_operator()`用于判断一个字符是否是运算符,`apply_operator()`用于计算两个操作数的结果,以及`evaluate()`用于计算算术表达式的值。 在`evaluate()`函数中,先初始化了操作数栈和运算符栈。然后遍历表达式中的每个字符,如果是数字则压入操作数栈,如果是左括号则压入运算符栈,如果是右括号则执行栈中的运算符直到遇到左括号,并将结果压入操作数栈,如果是运算符则执行栈中优先级更高或相等的运算符,并将结果压入操作数栈。执行栈中剩余的运算符,并返回最终的结果。 使用这个算法,可以计算包括括号、加减乘除和乘方运算的复杂算术表达式。在给定的示例中,计算结果为-3.0。 [2024-10-22 23:01:03 | AI写代码神器 | 2208点数解答]

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