将修改的并入上面的计算器代码中
时间: 2024-02-05 08:14:11 浏览: 21
好的,以下是修改后的完整代码:
```python
class Calculator:
def __init__(self):
self.operations = ['+', '-', '*', '/', '(', ')']
def evaluate(self, expression):
# Remove all whitespace
expression = ''.join(expression.split())
# Create a list of tokens
tokens = []
i = 0
while i < len(expression):
# If current character is an operation
if expression[i] in self.operations:
tokens.append(expression[i])
i += 1
# If current character is a digit
elif expression[i].isdigit():
j = i + 1
while j < len(expression) and expression[j].isdigit():
j += 1
tokens.append(int(expression[i:j]))
i = j
else:
raise ValueError('Invalid character: ' + expression[i])
# Evaluate expression using stack
stack = []
for token in tokens:
if isinstance(token, int):
stack.append(token)
elif token == '+':
b = stack.pop()
a = stack.pop()
stack.append(a + b)
elif token == '-':
b = stack.pop()
a = stack.pop()
stack.append(a - b)
elif token == '*':
b = stack.pop()
a = stack.pop()
stack.append(a * b)
elif token == '/':
b = stack.pop()
a = stack.pop()
stack.append(a / b)
elif token == '(':
stack.append(token)
elif token == ')':
while stack[-1] != '(':
operator = stack.pop()
b = stack.pop()
a = stack.pop()
if operator == '+':
stack.append(a + b)
elif operator == '-':
stack.append(a - b)
elif operator == '*':
stack.append(a * b)
elif operator == '/':
stack.append(a / b)
stack.pop()
return stack[0]
```
现在,我们可以使用这个计算器来求解任何简单的算术表达式了。例如:
```python
c = Calculator()
print(c.evaluate('2 + 3 * 4')) # Output: 14
print(c.evaluate('(2 + 3) * 4')) # Output: 20
print(c.evaluate('5 / (7 - 2)')) # Output: 1.0
```