正则表达式,计算器,装饰器,冒泡排序,用户登录系统

1.冒泡排序

li=[33,10,2,1]
for j in range(1,len(li)):
    for i in range(len(li)-j):
        if li[i]>li[i+1]:
            temp=li[i]
            li[i]=li[i+1]
            li[i+1]=temp
print(li)

方法二:

# li=[33,10,2,1]
# for j in range(1,len(li)):
#     for i in range(len(li)-j):
#         if li[i]>li[i+1]:
#             li[i],li[i+1]=li[i+1],li[i]
# print(li)

2.装饰器

def f1(func):
    def inner():
        print('hello')
        func()
        print('end')
        return 1
    return inner
@f1
 #1.f2作为f1的参数   2.执行f1的返回值函数
def f2():
    print(123)
f2()

 带参数的装饰器:

def f1():
    print('hello')

def f0():
    print('end')

def f(*args,**kwargs):
    def f2(func):
        def inner(*args,**kwargs):
            f1()
            r=func(*args,**kwargs)
            f0()
            return r
        return inner
    return f2
@f(f1,f0)    #f1和f2分别为执行主函数前后的函数名
 #1.执行f1,f2作为f1的参数   2.f2被重新定义为f1的内层函数
def f2(a,b):
    print(123)
    return a+b
f2(0,1)

3.正则表达式

import re
# re.S使.包含换行符   re.I对大小写不敏感
# m=re.match('abc','abcdfgg')  #匹配正确,返回类,否则None,match 用固定方法从开头匹配
# m=re.match('[0-9]{1,10}','777555abcdfgg')     #内部只能接收字符串,匹配0-10次
# if m:
#     print(m.group())  #匹配上的打印

# m=re.findall('[0-9]{1,10}','777555abc8d4fg3g')   #把所有匹配结果以#列表#形式拿出来
# print(m)
# m=re.findall('[a-zA-Z]+','777555abc8d4fg3g')
# print(m)
# m=re.findall('.*','777555abc8d4fg3g') #匹配任意字符 0个或多个
# print(m)
# m=re.findall('.+','g777555abc8d4fg3') #匹配任意字符1个或多个
# print(m)
m=re.search('\d+','adgabcdfg') #匹配一个或多个数字,从左到右找,
if not m:

    print(1)


#替换sub,subn显示替换次数,span 显示出现的位置
# m=re.sub('\d+','|','adg777555abc8d4fg3',count=2)# 数字替换|,只替换前两个
# print(m)
#
# m=re.sub('^\d+','|','adg777555abc8d4fg3',count=2) #从数字开头
# print(m)
# m=re.sub('^\d+$','|','adg777555abc8d4fg3',count=2)# 从数字开头和结尾,数字必须连续
#  print(m)
#.通配符,可以代替一个普通元素
#^以什么开头
#$以什么结尾

#重复
#*,控制前面的一个字符,匹配0到多次{0,}  *? 0次  件若前后均有限定条,问号不起作用,有多少打印多少
#+,控制前面的一个字符,匹配1到多次{1,}  +? 1次  件若前后均有限定条,问号不起作用,有多少打印多少
#?,控制前面的一个字符,匹配0到1次{0,1}
# {3,5}控制前面的一个字符,匹配3到5次

# [bc],字符集,匹配b或c  #[.] .失去意义   [a-z]从a到z  [^1-9]除了1-9的数字  [\d]还是数字
#\跟元字符使失去意义,
#
#
#\d十进制 \D  ,\s空字符\S 非空  ,\w数字或字母\W 非数字字母 \b匹配单词边界
#\数字  引用组里的内容,  \b I \b匹配单词I
#search只拿一个,findall找所有,match从开头找
#findall有组的情况下,只匹配组里的情况
#group(0)所有组,group(1)第一组
#a=re.compile(字符串)  a.findall(第二个参数,即要匹配的字符串)
#a=re.compile(r’\d+‘)  p.split(one1two2three3four4)

3.1匹配示例

Ip地址

3.2 match

3.3 flags

3.4分组示例

注意:这种效果只有贪婪匹配才有,如果不是贪婪匹配,每个结果都会匹配出来

4.计算器程序

 

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import re
# 请计算表达式: 1 - 2 * ( (60-30 +(-40.0/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )
def bracket(s):  #去除括号
    ret=re.search('\([^()]+\)',s).group()
    return ret

def mul(s):                                                             #乘除法函数
    ret=re.search('[\-]?\d+\.?\d*([*/]|\*\*)[\-]?\d+\.?\d*',s).group()  #取出含有乘除法的字符串
    if len(ret.split('*'))>1:                                           #判断是否是乘法
        a,b=ret.split('*')
        if float(a)<0 and float(b)<0:
            a=abs(float(a))
            b=abs(float(b))
            c= '+'+str(float(a)*float(b))
        else:
            c= str(float(a)*float(b))
    else:
        a,b=ret.split('/')
        c= float(a)/float(b)
        if float(a)<0 and float(b)<0:
            a=abs(float(a))
            b=abs(float(b))
            c= '+'+str(float(a)/float(b))
        else:
            c= str(float(a)/float(b))
    return str(c)

def ad(s):                                                                           #加减法函数
    ret=re.search('[\-]?\d+\.?\d*[+-][\-]?\d+\.?\d*',s).group()                      #提取加减法字符串
    ret=ret.replace('--','+').replace('++','+').replace('-+','-').replace('+-','-')
    if len(ret.split('+'))>1:
        a,b=ret.split('+')
        c= float(a)+float(b)
    else:
        a,b=ret.split('-')
        c= float(a)-float(b)
    return str(c)

s='1 - 2 * ( (60-30 +(-40.0/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )'
# s='1*1'
s=s.replace(' ','')                                                                              #去除空格
l=eval(s)
while re.search('\([^()]+\)',s):                                                                 #有括号,就一直循环
    a=bracket(s).strip('(').strip(')')                                                           #去除字符串的括号
    print(a)
    while re.search('[\-]?\d+\.?\d*([*/]|\*\*)[\-]?\d+\.?\d*',a):                                #如果含有乘除法,则执行循环
        b=mul(a)
        a=re.sub(re.search('[\-]?\d+\.?\d*([*/]|\*\*)[\-]?\d+\.?\d*',a).group().replace('*','\*').replace('/','\/'),b,a)     #结果替换到原字符串
    while re.search('[\-]?\d+\.?\d*[+-][\-]?\d+\.?\d*',a):                                       #如果含有加减法,就执行循环
        b=ad(a)
        a=re.sub(re.search('[\-]?\d+\.?\d*[+-][\-]?\d+\.?\d*',a).group().replace('+','\+').replace('-','\-'),b,a)
    s=re.sub(re.search('\([^()]+\)',s).group().replace('(','\(').replace('*','\*').replace('/','\/').replace('+','\+').replace('-','\-').replace(')','\)'),a,s)  #最终结果替换到原字符串
    print(s)

print(s)

while re.search('[\-]?\d+\.?\d*([*/]|\*\*)[\-]?\d+\.?\d*',s):
    b=mul(s)
    s=re.sub(re.search('[\-]?\d+\.?\d*([*/]|\*\*)[\-]?\d+\.?\d*',s).group().replace('*','\*').replace('/','\/'),b,s)
print(s)
while re.search('[\-]?\d+\.?\d*[+-][\-]?\d+\.?\d*',s):
    b=ad(s)
    s=re.sub(re.search('[\-]?\d+\.?\d*[+-][\-]?\d+\.?\d*',s).group().replace('+','\+').replace('-','\-'),b,s)

print(s,l)

  

 

5..用户登录系统

#!/usr/bin/env python
# -*- coding: utf-8 -*-


def login(username,password):
    '''
    登陆
    :param username:登录名
    :param password:登陆密码
    :return:登陆成功返回True,登陆错误返回False
    '''


    with open('log','r',encoding='utf-8') as f:
        for line in f:
            line=line.strip()
            line_list=line.split(';')
            if username==line_list[0] and password==line_list[1]:
                return True
        return False

def exist(username,password):
    '''
    检测用户名是否存在
    :param username:用户名
    :param password:密码
    :return:存在返回True,不存在返回False
    '''

    with open('log','r',encoding='utf-8') as f:
        for line in f:
            line=line.strip()
            line_list=line.split(';')
            if username==line_list[0]:
                return True
        return False


def register(username,password):
    '''
    注册
    :param username:用户名
    :param password:用户密码
    :return:注册成功返回True,不成功返回False
    '''


    try:
        with open('log','a',encoding='utf-8') as f:
            new='\n'+username+';'+password
            f.write(new)
            return True
    except:
        return False

def change(username,password):
    '''
    改密码
    :param username:用户名
    :param password:用户密码
    :return:修改成功返回True,失败返回False
    '''

    try:
        with open('log','r+',encoding='utf-8') as f,open('t','w',encoding='utf-8') as f1:
            a=f.readlines()
            for i in a:
                b=i.strip().split(';')
                if username==b[0] and password==b[1]:
                    b[1]=input('newpwd:')
                    print(b)
                    i1=';'.join(b)+'\n'
                    # print(i1)
                    a[a.index(i)]=i1    #通过索引赋值
            f1.writelines(a)
            return  True


    except:
        return False


def del_name(username,password):
    '''
    删除用户
    :param username:
    :param password:
    :return:
    '''
    try:
        with open('log','r+',encoding='utf-8') as f,open('t','w',encoding='utf-8') as f1:
            a=f.readlines()
            for i in a:
                b=i.strip().split(';')
                if username==b[0] and password==b[1]:
                   del  a[a.index(i)]    #通过索引赋值
            f1.writelines(a)
            return  True
    except:
        return False
    pass

def main():
    '''
    定义两个文件log(源文件)、t(new文件)
    :return:
    '''
    inp=input('1,deng;2,zhu;3,del;4,xchange')  #1.登陆2.注册3.删除用户4.修改密码
    usr=input('yonghu:')
    pwd=input('mi:')
    if inp=='1':
        l=login(usr,pwd)
        if l:
            print('d ok')
        else:
            print('d no')

    elif inp=='2':
        if exist(usr,pwd):
            print('cunzai')
        else:
            r=register(usr,pwd)
            if r:
                print('z ok')
            else:
                print('z no')

    elif inp=='3':
        if del_name(usr,pwd):
            print('del ok')
        else:
            print('del no')

    elif inp=='4':
        if change(usr,pwd):
            print('change ok')
        else:
            print('change no')

main()

 

转载于:https://www.cnblogs.com/wanghzh/p/5484401.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值