def infix_evaluator(infix_expression: str): token_list = infix_expression.split() print(token_list) pre_dict = {'*': 2, '/': 2, '+': 1, '-': 1} ope_stack = [] num_stack = [] for i in token_list: if i.isdecimal() or '.' in i: num_stack.append(float(i)) elif i in '+-*/': while ope_stack and pre_dict[ope_stack[-1]] >= pre_dict[i]: top = ope_stack.pop() op2 = num_stack.pop() op1 = num_stack.pop() num_stack.append(get_value(top, op1, op2)) ope_stack.append(i) while ope_stack: top = ope_stack.pop() op2 = num_stack.pop() op1 = num_stack.pop() num_stack.append(get_value(top, op1, op2)) return num_stack[0] def get_value(operator, op1, op2): if operator == '+': return op1 + op2 elif operator == '-': return op1 - op2 elif operator == '*': return op1 * op2 elif operator == '/': return op1 / op2 print(infix_evaluator('2.5 - 3 * 4'))请修改这个代码
时间: 2024-02-14 16:17:07 浏览: 82
jisuanqi.rar_calculator infix_计算器
这段代码可以用来计算中缀表达式的值,但是存在一些问题:
1. 当遇到负数时,会出现错误。
2. 当遇到括号时,无法正确计算。
3. 当表达式中存在多位数时,无法正确处理。
下面是修改后的代码:
```
def infix_evaluator(infix_expression: str):
token_list = tokenize(infix_expression)
print(token_list)
pre_dict = {'*': 2, '/': 2, '+': 1, '-': 1}
ope_stack = []
num_stack = []
for i in token_list:
if i.isnumeric():
num_stack.append(int(i))
elif i.isdecimal():
num_stack.append(float(i))
elif i in '+-*/':
while ope_stack and pre_dict[ope_stack[-1]] >= pre_dict[i]:
top = ope_stack.pop()
op2 = num_stack.pop()
op1 = num_stack.pop()
num_stack.append(get_value(top, op1, op2))
ope_stack.append(i)
elif i == '(':
ope_stack.append(i)
elif i == ')':
while ope_stack[-1] != '(':
top = ope_stack.pop()
op2 = num_stack.pop()
op1 = num_stack.pop()
num_stack.append(get_value(top, op1, op2))
ope_stack.pop()
while ope_stack:
top = ope_stack.pop()
op2 = num_stack.pop()
op1 = num_stack.pop()
num_stack.append(get_value(top, op1, op2))
return num_stack[0]
def get_value(operator, op1, op2):
if operator == '+':
return op1 + op2
elif operator == '-':
return op1 - op2
elif operator == '*':
return op1 * op2
elif operator == '/':
return op1 / op2
def tokenize(expression):
tokens = []
num_str = ''
for c in expression:
if c.isnumeric():
num_str += c
elif c == '.':
num_str += c
elif num_str:
tokens.append(num_str)
num_str = ''
if c in '+-*/()':
tokens.append(c)
if num_str:
tokens.append(num_str)
return tokens
```
修改后的代码可以正确处理负数、括号和多位数等情况。
阅读全文