计算器

测试好久,终于把计算器做出来了,还是简易版,哭哭,太难了。

import re

#定义一个格式化输出
def format(s):
    s = s.replace(" ","")
    s = s.replace("++", "+")
    s = s.replace("+-", "-")
    s = s.replace("-+", "-")
    s = s.replace("--", "+")
    return s

#定义一个输入检测函数
def check(s):
    flag = True
    if re.findall("[a-z]", source):
        print ("Invalid")
        flag = False
    if s.count("(") !=s.count(")"):
        print ("括号不匹配")
        flag = False
    return flag

#定义乘除计算
def mul_div_cal(string):
    regular = "[\-]?\d+\.?\d*[*/][\-]?\d+\.?\d*"
    while re.findall(regular,string) :
        expression = re.search(regular, string).group()
        if expression.count("*") ==1:
            x,y = expression.split("*")
            mul_reason = str(float(x) *float(y))
            string = string.replace(expression, mul_reason)
            string = format(string)
        if expression.count("/") == 1:
            x, y = expression.split("/")
            div_reason = str(float(x) / float(y))
            string = string.replace(expression,div_reason)
            string = format(string)
    return string

#定义加减计算
def add_sub_cal(string):
    regular = "[\-]?\d+\.?\d*[+-][\-]?\d+\.?\d*"
    while re.findall(regular,string) :
        expression = re.search(regular, string).group()
        if expression.count("+") ==1:
            x,y = expression.split("+")
            add_reason = str(float(x) + float(y))
            string = string.replace(expression, add_reason)
            string = format(string)
        if expression.count("-") == 1:
            x, y = expression.split("-")
            sub_reason = str(float(x) - float(y))
            string = string.replace(expression,sub_reason)
            string = format(string)
    return string



#主程序
source = input("输入一个计算方式>>>>>>:")
if check(source):
    source = format(source)
    while source.count("(") > 0:
        strs = re.search("\([^()]+\)",source).group()
        replace_str = mul_div_cal(strs)
        replace_str = add_sub_cal(replace_str)
        source = format(source.replace(strs,replace_str[1:-1]))
    else:
        replace_str = mul_div_cal(source)
        replace_str = add_sub_cal(replace_str)
        source = source.replace(source, replace_str)
    print("my result:",source)
else:
    print("invalid input")

 

posted @ 2017-11-01 21:53  阿秋秋秋秋  阅读(284)  评论(0)    收藏  举报