day27 计算器加减乘除(去括号待完善)

#!/usr/bin/env python
# -*- coding:utf-8 -*-

import re


def cheng(suanshi):
try:
while 1:
x = re.search(r'-?\d+(\.\d+)?[*/]\d+(\.\d+)?', suanshi)
a, b, c = re.split(r'([*/])', x.group())
a = float(a)
c = float(c)
if b == '*':
res = a * c
elif b == '/':
res = float(a / c)
suanshi = suanshi.replace(x.group(), str(res), 1)
except Exception:
obj = re.search('\([^()]+\)', suanshi)
print(obj)
if not obj.group():
return suanshi[1:-1]
return suanshi


def jia(suanshi):
try:
while 1:
x = re.search(r'-?\d+(\.\d+)?[-+]\d+(\.\d+)?', suanshi)
lst = re.split(r'([-+])', x.group())
if len(lst) == 5:
q, w, a, b, c = lst
if b == '+':
res = - float(a) + float(c)
elif b == '-':
res = -(float(a) + float(c))
elif len(lst) == 3:
a, b, c = lst
if b == '+':
res = float(a) + float(c)
elif b == '-':
res = float(a) - float(c)
suanshi = suanshi.replace(x.group(), str(res), 1)
print(suanshi)
except Exception:
return suanshi


# user = input('请输入算式:')
user = '1-2*((60-30+(-40/5)*(9-2*5/4+7/2+10*14/7))-(-4*3)/(16-3*2))'
while 1:
lst = re.findall('\([^()]+\)', user)
print(lst)
if not lst:
res = jia(cheng(user))[1:-1]
user = user.replace('--', '+')
user = user.replace('+-', '-')
continue
for i in lst:
user = user.replace(i, cheng(i), 1)
print(user)
lst2 = re.findall('\([^()]+\)', user)
for j in lst2:
user = user.replace(j, jia(j), 1)
print(user)

猜你喜欢

转载自www.cnblogs.com/zjx1/p/10828176.html