# -*- coding: utf-8 -*-
import re
Parentheses = re.compile(r'\([^()]*\)') # find out the expression with parentheses but no parentheses inside
Mul_Dev = re.compile(r'(\d+\.?\d*)[*/]([+-]?\d+\.?\d*)') # find out the expression with '*' or '/' only
Add_Sub = re.compile(r'(\d+\.?\d*)[+-](\d+\.?\d*)') # find out the expression with '+' or '-' only
def compute_mul_dev(arg):
"""
calculate the subexpression which has '*' or '/'
"""
exp = Mul_Dev.search(arg[0])
if not exp:
return
else:
sub_exp = exp.group()
if len(sub_exp.split('*')) > 1:
n1, n2 = sub_exp.split('*')
ret = str(float(n1) * float(n2))
elif len(sub_exp.split('/')) > 1:
n1, n2 = sub_exp.split('/')
ret = str(float(n1) / float(n2))
arg[0] = Mul_Dev.sub(ret, arg[0], 1)
compute_mul_dev(arg)
def compute_add_sub(arg):
"""
calculate the expression only has '+' or '-'
"""
while True:
if arg[0].__contains__('--') \
or arg[0].__contains__('+-') \
or arg[0].__contains__('-+') \
or arg[0].__contains__('++'):
arg[0] = arg[0].replace('--', '+')
arg[0] = arg[0].replace('-+', '-')
arg[0] = arg[0].replace('+-', '-')
arg[0] = arg[0].replace('++', '+')
else:
break
if arg[0].startswith('-'):
arg[1] += 1
arg[0] = arg[0].replace('-', '&')
arg[0] = arg[0].replace('+', '-')
arg[0] = arg[0].replace('&', '+')
arg[0] = arg[0][1:]
exp = Add_Sub.search(arg[0])
if not exp:
return
sub_exp = exp.group()
if len(sub_exp.split('+')) > 1:
n1, n2 = sub_exp.split('+')
ret = float(n1) + float(n2)
elif len(sub_exp.split('-')) > 1:
n1, n2 = sub_exp.split('-')
ret = float(n1) - float(n2)
arg[0] = Add_Sub.sub(str(ret), arg[0], 1)
compute_add_sub(arg)
def compute(expression):
"""
calculate the expression not has parentheses
"""
exp = [expression, 0]
compute_mul_dev(exp)
compute_add_sub(exp)
cnt = divmod(exp[1], 2)
result = float(exp[0])
if (cnt[1] == 1):
result = -1 * result
return result
def execute(expression):
"""
calculate the expression in parentheses
"""
if not Parentheses.search(expression):
return expression
sub_exp = Parentheses.search(expression).group()
compute_exp = sub_exp[1:-1]
ret = compute(compute_exp)
new_exp = Parentheses.sub(str(ret), expression, 1)
return execute(new_exp)
if __name__ == "__main__":
exp = '-1-4*(3-10*(3*2-1*9/(3-4*5+ 4/2))) + 10.5 - (4+7)'
no_space_exp = re.sub(' ', '', exp)
ret = execute(no_space_exp)
fnl = compute(ret)
print('fnl result: ', fnl)
网友评论