'''
非负数的带括号的简单四则运算
注意:
1.不用加=
2.输入的必须是对的式子
测试案例:
(111+(30-12)/2.5)*11-114.34
'''
operators = ['+', '-', '', '/', '(', ')']
priority = {'+': 1, '-': 1, '': 2, '/': 2}
def change_to(s):
print(f'原式:{s}')
res = list() # 逆波兰表达式
op = list() # 存放操作符
i = 0 # 下标
while i < len(s):
# 数字直接放进res
if s[i] >= '0' and s[i] <= '9':
num = ""
while i < len(s) and ((s[i] >= '0' and s[i] <= '9') or s[i] == '.'):
num += s[i]
i += 1
res.append(eval(num)) # eval函数真的方便
elif s[i] in operators:
if s[i] == '(':
op.append(s[i])
# 碰到右括号取出op的元素放入res
elif s[i] == ')':
while op:
temp = op.pop()
if temp == '(':
break
else:
res.append(temp)
else:
if len(op) == 0:
op.append(s[i])
i += 1
continue
while op:
temp = op.pop()
# 判断优先级,如果优先放进op里(取出的时候最先取出)
if temp == '(' or priority[s[i]] > priority[temp]:
op += [temp, s[i]]
break
else:
res.append(temp)
if not op:
op.append(s[i])
i += 1
# 加入op中多余的
while op:
res.append(op.pop())
return res
def calculation(res):
stack = list()
for i in res:
if i in operators:
nums1 = stack.pop()
nums2 = stack.pop()
if i == '+':
stack.append(nums2 + nums1)
if i == '-':
stack.append(nums2 - nums1)
if i == '*':
stack.append(nums2 * nums1)
if i == '/':
stack.append(nums2 / nums1)
else:
stack.append(i)
return stack.pop()
def run():
while True:
s = input("输入计算式:
")
if s == 'q':
break
res = change_to(list(s.replace(" ", "")))
print(f"转化成逆波兰表达式为:
{res}")
ans = calculation(res)
print("计算结果为:%s" % ans)
if name == 'main':
run()