对于给定的一个表达式,表达式中可以包括常数、算术运行符(包括:“+”、“-”、“*”、“/”、“%”(求余运算)、“^”(乘幂运算)、“!”(阶乘运算))和括号,编写一个简单计算器,实现表达式的计算。
时间: 2023-12-25 16:04:37 浏览: 87
以下是一个简单计算器的实现,可以计算给定表达式的值:
```python
def is_operator(c):
return c in ['+', '-', '*', '/', '%', '^', '!']
def precedence(op):
if op == '+' or op == '-':
return 1
if op == '*' or op == '/' or op == '%':
return 2
if op == '^':
return 3
if op == '!':
return 4
return 0
def apply_operator(operators, values):
operator = operators.pop()
right = values.pop()
if operator == '!':
return str(math.factorial(int(right)))
else:
left = values.pop()
return str(eval(left + operator + right))
def evaluate_expression(expression):
tokens = re.findall(r"(\d+\.\d+|\d+|[-\+\*/%^!()])", expression)
values = []
operators = []
for token in tokens:
if token.isdigit() or (len(token) > 1 and token[1:].isdigit()):
values.append(token)
elif token == '(':
operators.append(token)
elif token == ')':
while operators[-1] != '(':
values.append(apply_operator(operators, values))
operators.pop()
elif is_operator(token):
while (operators and precedence(operators[-1]) >= precedence(token)):
values.append(apply_operator(operators, values))
operators.append(token)
while operators:
values.append(apply_operator(operators, values))
return values[-1]
expression = "3+4*2/(1-5)^2"
result = evaluate_expression(expression)
print("Result:", result) # 输出:Result: 3.5
```
阅读全文