使用python实现简易计算器-支持加减乘除和括号
priority_dict = { # 操作符优先级字典
"+": 1,
"-": 1,
"*": 2,
"/": 2
}
operands_dict = { # 操作符函数字典
"+": lambda x, y: x + y,
"-": lambda x, y: x - y,
"*": lambda x, y: x * y,
"/": lambda x, y: x / y,
}
def calculator(expression):
suffix = _infix2suffix(expression)
return _calsuffix(suffix)
def _calsuffix(suffix):
'''
计算后缀表达式
:param suffix: 后缀表达式
:return:
'''
stack = []
for item in list(suffix):
'''
是数字,入栈
是操作符,出栈2个,计算,入栈
'''
if item.isdecimal():
stack.append(item)
elif item in operands_dict.keys():
num2 = float(stack.pop())
num1 = float(stack.pop())
stack.append(operands_dict[item](num1, num2))
else:
raise KeyError("illegal expression")
if len(stack) != 1:
raise KeyError("illegal expression")
return stack.pop()
def _infix2suffix(expression):
'''
中缀表达式转后缀表达式
:param expression: 中缀表达式
:return: 后缀表达式
'''
result = [] # 结果列表
stack = [] # 栈
for item in expression:
'''
是数字,直接添加到结果列表
是左括号,入栈
是右括号,依次出栈,直到左括号
是操作符,栈为空或栈顶为左括号或当前操作符比栈顶操作符优先级高,直接入栈
其他情况,依次出栈,直到栈为空或栈顶为左括号或当前操作符比栈顶操作符优先级高,当前操作符入栈
'''
if item.isdecimal():
result.append(item)
else:
if item == "(":
stack.append(item)
elif item == ")":
while True:
if len(stack) == 0:
raise KeyError("illegal expression")
pop_item = stack.pop()
if pop_item == "(":
break
result.append(pop_item)
elif item in priority_dict.keys():
if len(stack) == 0 or \
stack[len(stack) - 1] == "(" or \
priority_dict[item] > priority_dict[stack[len(stack) - 1]]:
stack.append(item)
else:
while True:
if len(stack) == 0 or \
stack[len(stack) - 1] == "(" or \
priority_dict[item] > priority_dict[stack[len(stack) - 1]]:
break
result.append(stack.pop())
stack.append(item)
else:
raise KeyError("illegal expression")
while len(stack) > 0:
result.append(stack.pop())
return "".join(result)
if __name__ == "__main__":
print(calculator("1+2/(3*3-5)*3")) # 1233*5-/3*+