首页 > 技术文章 > Python 大作业3:简单计算器

raygor 2020-07-20 20:22 原文

# 题目:利用Python实现一个计算器,可以计算小数复数等
import re
def calculator(string):
    # 去除括号函数
    def get_grouping(string):
        flag = False
        ret = re.findall('\(([^()]+)\)', string)
        for i in ret:
            temp = cal(i)
            if temp:
                string = re.sub('\(([^()]+)\)', temp[1], string)
                flag = True
        return flag, string
    # 将三个优先级集合,可以解决所有没有括号的问题,如果计算成功返回True和替换后的string,如果没有成功返回False
    def cal(string):
        flag = False
        func_box = [priority_1, priority_2, priority_3]
        for i in func_box:
            while True:
                ret = i(string)
                if ret == False: break
                else:
                    string = ret[1]
                    flag = True
        return flag, string
    # 第一优先级计算幂运算
    def priority_1(string):
        ret = re.findall('-?\d+(?:\.\d+)?\*\*-?\d+(?:\.\d+)?', string)
        if not ret: return False
        for i in ret:
            temp_li = i.split('**')
            res = float(temp_li[0]) ** float(temp_li[1])
            string = re.sub('-?\d+(\.\d+)?\*\*-?\d+(\.\d+)?', str(res), string, 1)
        return True, string
    # 第二优先级计算乘除
    def priority_2(string):
        ret = re.findall('-?\d+(?:\.\d+)?[*/]-?\d+(?:\.\d+)?', string)
        if not ret: return False
        for i in ret:
            if '/' in i:
                temp_li = i.split('/')
                res = float(temp_li[0]) / float(temp_li[1])
                string = string.replace(i, str(res))
            elif '*' in i:
                temp_li = i.split('*')
                res = float(temp_li[0]) * float(temp_li[1])
                string = string.replace(i, str(res))
        return True, string
    # 第三优先级计算加键
    def priority_3(string):
        ret = re.findall('-?\d+(?:\.\d+)?[+-]+?\d+(?:\.\d+)?', string)
        if not ret: return False
        for i in ret:
            if '+' in i:
                temp_li = i.split('+', 1)
                res = float(temp_li[0]) + int(temp_li[1])
                string = string.replace(i, str(res))
            else:
                temp_li = i.split('-', 1)
                res = float(temp_li[0]) - float(temp_li[1])
                string = string.replace(i, str(res))
        return True, string
    # 主逻辑
    string = string.replace(' ','')  # 去除输入过程中的所有空格
    res1, string_processed = get_grouping(string)  # 先按照优先级计算好所括号内的运算
    res2, result = cal(string_processed)  # 按照优先级计算去除括号后的运算
    if res1 == False and res2 == False:  # 如果没有进行字符串的改变,返回False,字符串输入格式有误
        print('ILLEGAL INPUT.')
    else: print(result)
    return

if __name__ == '__main__':
    string = input('INPUT:\n').strip()
    calculator(string)


推荐阅读