[ Python

要求:禁止使用eval函数。参考网上代码如下:

#!_*_coding:utf-8_*_

"""用户输入计算表达式,显示计算结果"""

import re

a = '2+(6/3-2+(1*4))'
# 取最内层的括号
bracket = re.compile('([^()]+)')

# 加法
add = re.compile('(-?d+.?d*+d+.?d*)|(-?d+.?d*+-d+.?d*)')

# 减法
sub = re.compile('(d+.?d*-d+.?d*)|(d+.?d*--d+.?d*)')

# 乘法
mul = re.compile('(d+.?d**d+.?d*)|(d+.?d**-d+.?d*)')

# 除法
div = re.compile('(d+.?d*/-d+.?d*)|(d+.?d*/d+.?d*)')

# 检查括号内是否运算完毕
c_f = re.compile('(?+?-?d+)?')

# 去掉括号
strip = re.compile('[^(].*[^)]')


def Add(s):
    '''加法运算'''
    exp = re.split('+', add.search(s).group())
    return s.replace(add.search(s).group(), str(float(exp[0]) + float(exp[1])))

def Sub(s):
    '''减法运算'''
    exp = re.split('-', sub.search(s).group())
    return s.replace(sub.search(s).group(), str(float(exp[0]) - float(exp[1])))

def Mul(s):
    '''乘法运算'''
    exp = re.split('*', mul.search(s).group())
    return s.replace(mul.search(s).group(), str(float(exp[0]) * float(exp[1])))

def Div(s):
    '''除法运算'''
    exp = re.split('/', div.search(s).group())
    return s.replace(div.search(s).group(), str(float(exp[0]) / float(exp[1])))
def calc():
    while True:
        s = input('Please input the expression(q for quit):')
        if s == 'q':
            break
        else:
            s = ''.join([x for x in re.split('s+',s)]) # 将表达式按空格分割并重组
            if not s.startswith('('):   # 若用户输入的表达式首尾无括号,则统一格式化为:(表达式)
                s = str('(%s)' % s)
            while bracket.search(s):    # 若表达式s存在括号
                # print('---')
                s = s.replace('--', '+')    # 检查表达式,并将--运算替换为+运算
                # 获取最内层的表达式
                s_search = bracket.search(s).group()    # 将最内层括号及其内容赋给变量s_search
                # 括号里除法运算
                if div.search(s_search):    # 若除法运算存在(必须放在乘法之前)
                    s = s.replace(s_search, Div(s_search))  # 执行除法运算并将结果替换原表达式
                # 括号里乘法运算
                elif mul.search(s_search):  # 若乘法运算存在
                    s = s.replace(s_search, Mul(s_search))  # 执行乘法运算并将结果替换原表达式
                # 括号里减法运算
                elif sub.search(s_search):  # 若减法运算存在(必须放在加法之前)
                    s = s.replace(s_search, Sub(s_search))  # 执行减法运算并将结果替换原表达式
                # 括号里加法运算
                elif add.search(s_search):  # 若加法运算存在
                    s = s.replace(s_search, Add(s_search))  # 执行加法运算并将结果替换原表达式
                elif c_f.search(s_search):  # 若括号内无任何运算(类似(-2.32)除外)
                    s = s.replace(s_search, strip.search(s_search).group()) # 将括号脱掉,例:(-2.32)---> -2.32
            print(s)
            # print('The answer is: %.2f' %(float(s)))

if __name__ == '__main__':
    print(eval('1 - 2 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )'))
    calc()
View Code
原文地址:https://www.cnblogs.com/hukey/p/7095637.html