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|((1\d{2})|([1-9]?\d)))\.){3}(25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))')
# 参考:https://www.cnblogs.com/brogong/p/7929298.html
f = re.compile(r"\b(?:(?: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]?)\b")
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("\r")
        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) + '\n'
        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('登陆失败')

转载于:https://www.cnblogs.com/fan-gx/p/11512020.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值