使用python实现evaluate函数
时间: 2023-06-10 12:06:10 浏览: 438
evaluate函数的实现需要根据具体的应用场景而定,以下是一个简单的示例代码,用于计算一个表达式的值:
```python
def evaluate(expression):
"""
计算表达式的值
:param expression: 表达式字符串
:return: 计算结果
"""
# 去除空格
expression = expression.replace(' ', '')
# 定义操作数栈
operands = []
# 定义操作符栈
operators = []
# 定义优先级字典
priority = {'+': 1, '-': 1, '*': 2, '/': 2}
# 遍历表达式
i = 0
while i < len(expression):
# 如果当前字符是数字,提取整个数
if expression[i].isdigit():
j = i
while j < len(expression) and expression[j].isdigit():
j += 1
operands.append(int(expression[i:j]))
i = j
# 如果当前字符是操作符,判断是否需要进行运算
elif expression[i] in priority:
# 如果操作符栈为空,或者当前操作符优先级大于栈顶操作符优先级,直接入栈
if not operators or priority[expression[i]] > priority[operators[-1]]:
operators.append(expression[i])
# 否则,弹出栈顶操作符和两个操作数进行运算,将结果入栈
else:
operator = operators.pop()
operand2 = operands.pop()
operand1 = operands.pop()
if operator == '+':
result = operand1 + operand2
elif operator == '-':
result = operand1 - operand2
elif operator == '*':
result = operand1 * operand2
else:
result = operand1 / operand2
operands.append(result)
continue
i += 1
else:
i += 1
# 遍历完表达式后,对剩余的操作符和操作数进行运算,直到操作符栈为空
while operators:
operator = operators.pop()
operand2 = operands.pop()
operand1 = operands.pop()
if operator == '+':
result = operand1 + operand2
elif operator == '-':
result = operand1 - operand2
elif operator == '*':
result = operand1 * operand2
else:
result = operand1 / operand2
operands.append(result)
# 返回最终结果
return operands[0]
```
该函数使用了栈来存储操作符和操作数,根据操作符的优先级进行运算。需要注意的是,该函数只适用于简单的四则运算表达式,对于更复杂的表达式,需要进行相应修改。
阅读全文