Python全栈最全学习之路-Python基础(十一)

练习习题

	这节课主要是一些编程题,代码仅供参考,有不好的地方可以留言指点,感谢!!!

一、上节课作业
1、检查用户名是否是由字母数字下划线组成(字母或下划线开头

import re
st = input('请输入你的用户名:')
a = re.findall('^[a-zA-Z_]\w+$',st)
print(a)

在这里插入图片描述
2、检查用户输入的邮箱号是否符合规范

import re
st = input('请输入你的邮箱号:')
a = re.findall(r'^[A-z0-9]+@[0-9A-z]+\.[0-9A-z]+?$',st)
print(a)

在这里插入图片描述
3、检查用户输入的身份证号码是否符合规范

import re
st = input('请输入你的身份证号码:')
a = re.findall(r'^[1-8]\d{5}(?:19\d{2}|20[0-1]\d{2})(?:0[1-9]|1[0-2])(?:0[1-9]|2[0-9]|3[0-9])\d{3}[0-9X]$',st)
print(a)

在这里插入图片描述
4、检查用户输入的手机号码是否符合规范

import re
st = input('请输入你的手机号:')
a = re.findall(r'^1\d{10}$',st)
print(' '.join(a))

在这里插入图片描述
5、检查用户输入的密码是否符合规范(已字符或下划线开头长度8-10)

import re
st = input('请输入你的密码:')
a = re.findall(r'^[A-z_]\w{7,9}$',st)
print(' '.join(a))

在这里插入图片描述
6、模拟用正则获取爬虫爬取的数据

import re
st = """<ul class="fAl-loc" data-atp="2,{text},,,spu-toloc,20,toloc,">
 <li><a href="" code="110100">北京</a></li>
 <li><a href="" code="120100">天津</a></li>
 <li><a href="" code="310100">上海</a></li>
 <li><a href="" code="500100">重庆</a></li>
 <li class="fAll-cities"></li>
</ul>
<ul class="fAl-loc" data-atp="2,{text},,,spu-toloc,20,toloc,">
 <li><a href="" code="130000">河北</a></li>
 <li><a href="" code="140000">山西</a></li>
 <li><a href="" code="150000">内蒙古</a></li>
 <li><a href="" code="210000">辽宁</a></li>
 <li><a href="" code="220000">吉林</a></li>
 <li><a href="" code="230000">黑龙江</a></li>
 <li class="fAll-cities"></li>
 <li><a href="" code="320000">江苏</a></li>
 <li><a href="" code="330000">浙江</a></li>
 <li><a href="" code="340000">安徽</a></li>
 <li><a href="" code="350000">福建</a></li>
 <li><a href="" code="360000">江西</a></li>
 <li><a href="" code="370000">山东</a></li>
 <li class="fAll-cities"></li>
 <li><a href="" code="410000">河南</a></li>
 <li><a href="" code="420000">湖北</a></li>
 <li><a href="" code="430000">湖南</a></li>
 <li><a href="" code="440000">广东</a></li>
 <li><a href="" code="450000">广西</a></li>
 <li><a href="" code="460000">海南</a></li>
 <li class="fAll-cities"></li>
 <li><a href="" code="510000">四川</a></li>
 <li><a href="" code="520000">贵州</a></li>
 <li><a href="" code="530000">云南</a></li>
 <li><a href="" code="540000">西藏</a></li>
 <li><a href="" code="610000">陕西</a></li>
 <li><a href="" code="620000">甘肃</a></li>
 <li class="fAll-cities"></li>
 <li><a href="" code="630000">青海</a></li>
 <li><a href="" code="640000">宁夏</a></li>
 <li><a href="" code="650000">新疆</a></li>
 <li><a href="" code="710000">台湾</a></li>
 <li><a href="" code="810000">香港</a></li>
 <li><a href="" code="820000">澳门</a></li>
 <li class="fAll-cities"></li>
</ul>"""
a = re.findall(r'code="(.*?)">(.*?)<',st)
print(a)

在这里插入图片描述
二、练习题
1、 加密是日常生活中经常用到的保护信息内容的方法,比如非常简单的凯撒密码,利用字母移位来加密字母,比如让字母移动1位,比如a变成b,b变成c,最后z变成a,将内容整体移动一位来加密内容,现在要求实现这样的一个加密类,有一个加密的方法,也有一个解密到的方法,请实现这样的一个类
2、有两个长度一样列表a和b,它们里面的元素都是整形的数值,要求:通过交换两个列表的元素,使得sum(a) 和 sum(b)的差值最小
3、定义一个类,可以对输入的文章进行统计,要求实现以下几个方法:

统计出各个单词出现的次数和频率
查看出现频率最多的前10个单词
输入单词能够得到单词的出现次数和频率

string = “”"
There are moments in life when you miss someone so much that you just want to pick them from your dreams and hug them for real! Dream what you want to dream;go where you want to go;be what you want to be,because you have only one life and one chance to do all the things you want to do.
May you have enough happiness to make you sweet,enough trials to make you strong,enough sorrow to keep you human,enough hope to make you happy? Always put yourself in others’shoes.If you feel that it hurts you,it probably hurts the other person, too.
The happiest of people don’t necessarily have the best of everything;they just make the most of everything that comes along their way.Happiness lies for those who cry,those who hurt, those who have searched,and those who have tried,for only they can appreciate the importance of people
who have touched their lives.Love begins with a smile,grows with a kiss and ends with a tear.The brightest future will always be based on a forgotten past, you can’t go on well in lifeuntil you let go of your past failures and heartaches.
When you were born,you were crying and everyone around you was smiling.Live your life so that when you die,you’re the one who is smiling and everyone around you is crying.
Please send this message to those people who mean something to you,to those who have touched your life in one way or another,to those who make you smile when you really need it,to those that make you see the brighter side of things when you are really down,to those who you want to let them know that you appreciate their friendship.And if you don’t, don’t worry,nothing bad will happen to you,you will just miss out on the opportunity to brighten someone’s day with this message.
“”"

4、写一个函数实现将包含100个元素的列表随机分成12分,每份至少有2个元素
5、 给定一个列表和一个值,列表中数字两两相加如果有等于这个值的,就返回这两个值的索引,否则返回[-1, -1]
6、一个列表,里面都是整数,要求删除一个元素,使得剩余元素的乘积最大
现在要求找到这个待删除的元素

三、参考代码
1、加密是日常生活中经常用到的保护信息内容的方法,比如非常简单的凯撒密码,利用字母移位来加密字母,比如让字母移动1位,比如a变成b,b变成c,最后z变成a,将内容整体移动一位来加密内容,现在要求实现这样的一个加密类,有一个加密的方法,也有一个解密到的方法,请实现这样的一个类

分析一下:对字母进行加密,利用ascll码来移位并输出下一个,a变b,b边c,遇到z直接回到a,密码可能含其他的,比如数字,特殊字符等,他们可以不用变
class Encrypt():  # 定义类
    def encrypt(self,str):  # 类中的加密方法
        temp = ''
        for i in str:
            if i >= 'a' and i < 'z' or i >= 'A' and i < 'Z': #判断是字母的根据要求进行转化
                if i == 'z':
                    temp = temp + 'a'   #加密中z会成a,ASCII加1是不能直接到a的,所以我们直接进行转化
                elif i == 'Z':
                    temp = temp + 'A' # 加密直接转化Z
                else:
                    temp = temp + chr(ord(i)+1)  # 其他的就按ASCll码加1进行转换
            else:
                temp = temp + i #另外不属于字母的输出本身
        return temp  #返回加密的字符串
    def decrypt(self, str):
        temp = ''
        for i in str:
            if i >= 'a' and i < 'z' or i >= 'A' and i < 'Z':
                if i == 'a':
                    temp = temp + 'z'
                elif i == 'A':
                    temp = temp + 'Z'
                else:
                    temp = temp + chr(ord(i) - 1)
            else:
                temp = temp + i
        return temp
# 举例进行
b = Encrypt()
c = b.encrypt('abfjoiw13JHO12')
print(c)
d = b.decrypt('001AikjBk')
print(d)

在这里插入图片描述
2、有两个长度一样列表a和b,它们里面的元素都是整形的数值,要求:通过交换两个列表的元素,使得sum(a) 和 sum(b)的差值最小

分析一下:两个相同的列表,经过交换是的总和值得差值最小,可以这样做,
把两个列表合并到一起并排序,
找到最大的和次大的并在原先的列表中删除,这样就不会重复了
再找到最大的和最小的
分别和上面次大的和最大的放到一个新的列表中。并删除避免重复
接着计算两个新列表的和,谁的大然后从那个整合的列表中找到最小的放进去并删除,另外一个新列表中加入整合列表中最大的放进去并删除
重复上述的步骤知道分完就可以了。
def sum_min(list1,list2):   #定义类,参数有两个都是列表
    source = list1 + list2  # 合并列表
    source.sort()  # 列表排序
    l1 = []
    l2 = []
    l1.append(source.pop())  # 添加合并列表中最大值并删除避免重复
    l2.append(source.pop())  # 添加合并列表中次大值并删除避免重复
    l1.append(source.pop(0))  # 添加最小值并删除
    l2.append(source.pop())  # 添加最大值并删除
    while source:  # 循环判断合并列表是否为空
        if sum(l1) > sum(l2):   #判断新列表谁的和大
            l1.append(source.pop(0))   #和大的加入最小值
            l2.append(source.pop())	   #和小的加入最大值
        else:  # 相反
            l1.append(source.pop())
            l2.append(source.pop(0))
    return l1,l2  #返回列表
#举个例子
la = [10,20,30,40,50]
lb = [60,70,80,90,100]
a,b= sum_min(la,lb)
print(a)
print(b)

在这里插入图片描述
3、定义一个类,可以对输入的文章进行统计,要求实现以下几个方法:

统计出各个单词出现的次数和频率
查看出现频率最多的前10个单词
输入单词能够得到单词的出现次数和频率

string = “”"
There are moments in life when you miss someone so much that you just want to pick them from your dreams and hug them for real! Dream what you want to dream;go where you want to go;be what you want to be,because you have only one life and one chance to do all the things you want to do.
May you have enough happiness to make you sweet,enough trials to make you strong,enough sorrow to keep you human,enough hope to make you happy? Always put yourself in others’shoes.If you feel that it hurts you,it probably hurts the other person, too.
The happiest of people don’t necessarily have the best of everything;they just make the most of everything that comes along their way.Happiness lies for those who cry,those who hurt, those who have searched,and those who have tried,for only they can appreciate the importance of people
who have touched their lives.Love begins with a smile,grows with a kiss and ends with a tear.The brightest future will always be based on a forgotten past, you can’t go on well in lifeuntil you let go of your past failures and heartaches.
When you were born,you were crying and everyone around you was smiling.Live your life so that when you die,you’re the one who is smiling and everyone around you is crying.
Please send this message to those people who mean something to you,to those who have touched your life in one way or another,to those who make you smile when you really need it,to those that make you see the brighter side of things when you are really down,to those who you want to let them know that you appreciate their friendship.And if you don’t, don’t worry,nothing bad will happen to you,you will just miss out on the opportunity to brighten someone’s day with this message.
“”"

分析一下:统计一段字符串的词频,我们可以进行分割使用空格进行分割
首先全部转为小写
接着把不是字母的特殊字符全变成空格符使用字符串的替换
然后用空格进行分割变成一个列表
字典接受每个单词并计算出次数和频率就差不多了
class WordFrequency():  #定义类
    def __init__(self,string): # 初始化
        string = string.lower()  # 字符串转为小写
        import re
        all_word = re.split(r'\W',string)  # 正则分割
        all_word = [i for i in all_word if i != '']  # 列表推导式去掉空白符
        total = len(all_word)   # 列表总数
        self.word = {}  # 空字典
        for i in all_word:
            self.word[i] = {'items':all_word.count(i),'frequency':'%.3f'%(all_word.count(i)/total)}  # 字典套字典表示次数和频率
    def word_item(self):  
        word_list = list(self.word.items())  #转化为列表
        word_list.sort(key=lambda x:x[1]['items'],reverse=True)  # 推导式列出前十
        return word_list[:10]
    def get(self,key):  
        try:  # 使用异常进行输出
            values = self.word[key]   
        except:
            values = None
        return values
a = WordFrequency(string)
print(a.word_item())
print(a.get('women'))
print(a.get('you'))

在这里插入图片描述
4、写一个函数实现将包含100个元素的列表随机分成12分,每份至少有2个元素

分析一下:把一百个元素的列表分成12份,每份至少两个
12分每份两个元素,100个元素列表删除已经放进去的避免重复
12份里随机选把剩下的放进去
def divide_group(li):  # 定义个函数
    import random    
    dic = {}
    for i in range(12):   # 自动生成12份空列表
        dict_key = 'list' + str(i)
        dic[dict_key] = []
        for n in range(2):   # 每份列表随机加入两个元素
            value = random.choice(li)
            dic[dict_key].append(value)
            li.remove(value)
    vla = list(dic.values())  #转换类型为列表
    while li:  # 随机选取列表,随机加入元素直到添加完毕
        vl = random.choice(vla)
        v = random.choice(li)
        vl.append(v)
        li.remove(v)
    return list(dic.values())  # 返回字典中的值并转换为列表类型
# 举个例子
li = list(i for i in range(100))  #用列表推导式生成100个元素
b = divide_group(li)   # 调用函数
j = 1
for i in b:    # 输出每个列表的具体内容
    print(f'第{j}个列表为:{i},长度为:{len(i)}')
    j += 1

在这里插入图片描述
5、给定一个列表和一个值,列表中数字两两相加如果有等于这个值的,就返回这两个值的索引,否则返回[-1, -1]

分析一下:列表中两个索引的值加起来等于给定的值这返回对应的索引值
使用循环将列表第一个元素和后面每一个元素相加看是否等于给定的,如果有则返回对应的索引
使用循环将列表第二个元素和后面的每一个元素相加看是否等于给定的,如果有则返回对应的索引
重复上述知道最后第二个和最后一个相加看是否等有给定的值
如果都没有则直接返回【-1-1】
def judge_sum(li,number):  # 定义类
    global l1
    for i in range(len(li)):   # 判断索引值相加
        for j in range(i+1,len(li)):
            if li[i] + li[j] == number:  # 判断是否相等
                l1.append([i,j])
    if len(l1) == 0:
        return [-1,-1]
    else:
        return l1
# 举个例子
l1 = []
b = judge_sum([1,2,6,8],2)
print(b)
a = judge_sum([1,2,3,7,5,6,6],12)
print(a)

在这里插入图片描述
6、一个列表,里面都是整数,要求删除一个元素,使得剩余元素的乘积最大
现在要求找到这个待删除的元素

分析一下
全为整数包含0,则删除最小的
全为负数,如果是偶数个删除最小的,奇数个删除最大的
正负数都有,看负数的个数,奇数,删除最大,偶数,删除整数中最小
def search_del(li):  # 定义函数
    negative_number_li = list(filter(lambda x : x < 0,li)) # 列表推导式添加负数
    positive_number_li = list(filter(lambda x : x >= 0,li)) # 列表推导式添加整数包含0
    if len(negative_number_li) % 2 == 0:  # 判断负数的奇偶
        if len(positive_number_li) == 0: # 判断有没有正数
            return min(negative_number_li)
        else:
            return min(positive_number_li)
    else:
        return max(negative_number_li)
a = search_del([1,2,3,4,5])
b = search_del([-3,-7,-8,-8,-12])
c = search_del([0,3,-8,23,87,-8,-3])
print(a,b,c)

在这里插入图片描述

  • 7
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值