zoukankan      html  css  js  c++  java
  • python--第六天练习题

    #1.正则表达式计算 origin = "1 - 2 * ( ( 60 - 30 + ( -40.0 / 5 ) * ( 9 - 2 * 5 / 3 + 7 / 3 * 99 / 4 * 2998 + 10 * 568 / 14 )) - ( - 4 * 3 ) / ( 16 - 3 * 2))"
    
    import re
    import functools
    
    def checkInput(formula):
        """检测输入合法与否,是否包含字母等非法字符"""
        return not re.search("[^0-9+-*/.()s]",formula)
    
    def formatInput(formula):
        """标准化输入表达式,去除多余空格等"""
        formula = formula.replace(' ','')
        formula = formula.replace('++', '+')
        formula = formula.replace('+-', '-')
        formula = formula.replace('-+', '-')
        formula = formula.replace('--', '+')
        return formula
    
    def mul_divOperation(s):
        """乘法除法运算"""
        # 1-2*-14969036.7968254
        s = formatInput(s)
        sub_str = re.search('(d+.?d*[*/]-?d+.?d*)', s)
        while sub_str:
            sub_str = sub_str.group()
            if sub_str.count('*'):
                l_num, r_num = sub_str.split('*')
                s = s.replace(sub_str, str(float(l_num)*float(r_num)))
            else:
                l_num, r_num = sub_str.split('/')
                s = s.replace(sub_str, str(float(l_num) / float(r_num)))
            #print(s)
            s = formatInput(s)
            sub_str = re.search('(d+.?d*[*/]d+.?d*)', s)
    
        return s
    
    
    def add_minusOperation(s):
        """加法减法运算
        思路:在最前面加上+号,然后正则匹配累加
        """
        s = formatInput(s)
        s = '+' + s
        #print(s)
        tmp = re.findall('[+-]d+.?d*', s)
        s = str(functools.reduce(lambda x, y:float(x)+float(y), tmp))
        #print(tmp)
        return s
    
    def compute(formula):
        """无括号表达式解析"""
        #ret = formula[1:-1]
        ret = formatInput(formula)
        ret = mul_divOperation(ret)
        ret = add_minusOperation(ret)
        return ret
    
    
    def calc(formula):
        """计算程序入口"""
        has_parenthesise = formula.count('(')
        if checkInput(formula):
            formula = formatInput(formula)
            while has_parenthesise:
                sub_parenthesise = re.search('([^()]*)', formula) #匹配最内层括号
                if sub_parenthesise:
                    #print(formula+"...before")
                    formula = formula.replace(sub_parenthesise.group(), compute(sub_parenthesise.group()[1:-1]))
                    #print(formula+'...after')
                else:
                    #print('没有括号了...')
                    has_parenthesise = False
    
            ret = compute(formula)
            print('结果为:')
            return  ret
    
        else:
            print("输入有误!")
    -------------------------------------------------------------------------------------------
    def add(args):  #加减
        args = args.replace(' ', '')
        args = args.replace('++', '+')
        args = args.replace('+-', '-')
        args = args.replace('-+', '-')
        args = args.replace('--', '+')
        tmp = re.findall("([+-]?d+.?d*)", args)
        ret = 0
        for i in tmp:
            ret = ret + float(i)
        return ret
    
    def mul(args):
        #乘除
        while True:
            ret = re.split("(d+.?d*[*/][+-]?d+.?d*)",args,1)
            if len(ret) == 3:
                a = ret[0]
                b = ret[1]
                c = ret[2]
                if "*" in b:
                    num1,num2 = b.split("*")
                    new_b = float(num1) * float(num2)
                    args = a + str(new_b) + c
                elif "/" in b:
                    num1, num2 = b.split("/")
                    new_b = float(num1) / float(num2)
                    args = a + str(new_b) + c
            else:
                return add(args)
    def calc(args):
        while True:
            args = args.replace(" ", "")
            ret = re.split("(([^()]+))",args,1)
            if len(ret) == 3:
                a,b,c = ret
                r = mul(b)      #调用乘除得到计算结果
                args = a + str(r) + c
            else:
                return mul(args)
    
    print(calc(origin))
    print(eval(origin))
    
    #2.将“我我我、、、我我、、我要、我要要、、、要要要、、要要、、学学学、、、、学学编、、、学编编编、、编编编程、、程程”还原成:我要学编程
    f = "我我我、、、我我、、我要、我要要、、、要要要、、要要、、学学学、、、、学学编、、、学编编编、、编编编程、、程程"
    
    c = ''
    import re
    a = re.sub(r'、','',f)
    for i in a:
        if i not in c:
            c += i
    print(c)
    
    #3.查找IP地址
    temp = "192.168.1.200 10.10.10.10 3.3.50.3 127.0.0.1 244.255.255.249 273.167.189.222"
    
    # sel = re.compile(r'((25[0-5]|2[0-4]d|((1d{2})|([1-9]?d))).){3}(25[0-5]|2[0-4]d|((1d{2})|([1-9]?d)))')
    # 参考:https://www.cnblogs.com/brogong/p/7929298.html
    f = re.compile(r"(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)")
    ip = f.findall(temp)
    print(ip)
    
    #4.读写用户的输入,根据用户输入,创建一个相应的目录
    improt os,sys
    os.mkdir(sys.argv[1])
    
    #5.进度条,显示百分比
    import sys,time,datetime
    #
    for i in range(1,101):
        if i == 100:
            b = '完成'
        else:
            b = '进度中'
        for a in ['\','|','/','=']:
            sys.stdout.write("
    ")
            sys.stdout.write(r'%s%s%s %s%% ' % (b,int(i/100*100)*'=',a,int(i/100*100)))
            sys.stdout.flush()
            time.sleep(0.3)
    
    #6.密码加密版,用户登录
    import hashlib
    def md5(pawd):
        hash = hashlib.md5(bytes('fana,*=',encoding='utf-8'))
        hash.update(bytes(pawd,encoding='utf-8'))
        return hash.hexdigest()
    
    def zhuce(user,pawd):
        with open('fana.db','a',encoding='UTF-8') as f:
            tmp = user + '|' + md5(pawd) + '
    '
            f.write(tmp)
    
    def denglu(user,pawd):
        with open('fan.db','r',encoding='UTF-8') as f:
            for line in f:
                u,p = line.strip().split('|')
                if u == user and p == md5(pawd):
                    return True
            return False
    
    i = input('登陆按1,注册按2:')
    if i == '2':
        user = input('用户名:')
        pawd = input('密码:')
        zhuce(user,pawd)
        print('注册成功')
    if i == '1':
        user = input('用户名:')
        pawd = input('密码:')
        re = denglu(user,pawd)
        if re:
            print('登陆成功')
        else:
            print('登陆失败')
    
  • 相关阅读:
    C/C++内存对齐
    Fibonacci
    Count 1 in Binary
    Hash Function
    Fast Power
    Update Bits
    Unique Binary Search Trees
    Java知识体系(持续更新)
    如何发现牛股
    OpenResty究竟解决了什么痛点
  • 原文地址:https://www.cnblogs.com/fan-gx/p/11512020.html
Copyright © 2011-2022 走看看