python正则实现简单计算器

利用正则实现计算器

利用正则来实现简单计算器的功能,能够设计计算带括号的加减乘除运算。当然不使用eval等语句。

利用递归:

import re
from functools import reduce
def foo2(y):
    if '(' in y:
        t1 = re.search(r'\([^()]+\)',y)
        temp1 = t1.group().strip('()')
        res = foo1(temp1)
        y = y.replace(t1.group(),str(res))
        return foo2(y)
    else:
        return foo1(y)
def foo1(x):
    x = x.replace(' ','')
    if x.find('*') == -1 and x.find('/') == -1:
        res = str(foo3(x))
        return res
    else:
        t1 = re.search(r'(?P<x1>(-?\d+\.\d*)|(-?\d+))(?P<x2>\*|\/)(?P<x3>(-?\d+\.\d*)|(-?\d+))',x)
        t2 = re.search(r'((-?\d+\.\d*)|(-?\d+))(\*|\/)((-?\d+\.\d*)|(-?\d+))',x)
        y1 = float(t1.group('x1')) if '.' in t1.group('x1') else int(t1.group('x1'))
        y2 = float(t1.group('x3')) if '.' in t1.group('x3') else int(t1.group('x3'))
        temp = y1 * y2 if t1.group('x2') == '*' else y1 / y2
        tt = '+' + str(temp) if y1 < 0 and temp > 0 else str(temp)
        x = x.replace(t2.group(),tt)
        return foo1(x)
def foo3(z):
    z = z.replace(' ','')
    z = re.sub('\+\-|\-\+','-',z)
    z = re.sub('\-\-|\+\+','+',z)
    z = re.findall('-?\d+\.\d*|-?\d+',z)
    z = list(map(lambda x: float(x) if '.' in x else int(x), z))
    res = reduce(lambda x,y:x+y,z)
    return res
while True:
    s = input('please input :> ')
    print('the result is %s' %foo2(s))

利用循环:

import re
from functools import reduce
def foo2(y):
    while '(' in y:
        t1 = re.search(r'\([^()]+\)',y)
        temp1 = t1.group().strip('()')
        res = foo1(temp1)
        y = y.replace(t1.group(),str(res))
    return foo1(y)
def foo1(x):
    x = x.replace(' ','')
    while x.find('*') != -1 or x.find('/') != -1:
        t1 = re.search(r'(?P<x1>(-?\d+\.\d*)|(-?\d+))(?P<x2>\*|\/)(?P<x3>(-?\d+\.\d*)|(-?\d+))',x)
        t2 = re.search(r'((-?\d+\.\d*)|(-?\d+))(\*|\/)((-?\d+\.\d*)|(-?\d+))',x)
        y1 = float(t1.group('x1')) if '.' in t1.group('x1') else int(t1.group('x1'))
        y2 = float(t1.group('x3')) if '.' in t1.group('x3') else int(t1.group('x3'))
        temp = y1 * y2 if t1.group('x2') == '*' else y1 / y2
        tt = '+' + str(temp) if y1 < 0 and temp > 0 else str(temp)
        x = x.replace(t2.group(),tt)
    return str(foo3(x))
def foo3(z):
    z = z.replace(' ','')
    z = re.sub('\+\-|\-\+','-',z)
    z = re.sub('\-\-|\+\+','+',z)
    z = re.findall('-?\d+\.\d*|-?\d+',z)
    z = list(map(lambda x: float(x) if '.' in x else int(x), z))
    res = reduce(lambda x,y:x+y,z)
    return res
while True:
    s = input('please input :> ')
    print('the result is %s' %foo2(s))
posted @ 2017-07-01 12:50  村口王铁匠  阅读(447)  评论(0编辑  收藏  举报