練習題解答(二)


1、現有列表alist = [3,1,-4,2,-6] 按照元素的絕對值大小進行排序(注意,內置函數中也有sorted方法,但是會開辟內存,所以盡量用list自帶方法sort)

alist = [3,1,-4,2,-6]
ret=sorted(alist,key=lambda x:abs(x))
print(ret)
View Code

2、5.輸入某年某月某日,判斷是這一年中的第幾天?(用內置模塊實現)

import time
input_ = input('請輸入年月日:')
time_local = time.strptime(input_,'%Y-%m-%d %X')
print(time_local.tm_yday)  # 結構化時間調用里面的參數
View Code

3、一行代碼實現[1,4,9,16,25,36,49,64,81,100]

print(list(map(lambda x: x**2,range(1,11))))
View Code

4、從0-99這個100個數中隨機取出10個不重復的數

import random
print(list(random.sample(list(range(0,100)),10)))
View Code

5、一行代碼,通過filter和lambda函數輸出以下列表索引為奇數對應的元素

lis = [12,13,14,151,5,16,17,117,133,144,177]
print(list(filter(lambda x:lis.index(x)%2!=0,lis)))
View Code  
print(list(filter(lambda x:x,(lis[i] for i in range(1,len(lis),2)))))
View Code

6、將下列數據轉成想要的結果,盡量用簡潔的方式實現:

  原數據lst =[[1,2,3],[4,5,6],[7,8,9]]
  轉換后 li = [1,2,3,4,5,6,7,8,9]

lst =[[1,2,3],[4,5,6],[7,8,9]]
li = [x for i in lst for x in i]
print(li)
View Code 

7、實現一個裝飾器,通過調用一次裝飾器使被裝飾的函數調用5次

def warpper(f):
    def inner(arg):
        for i in range(5):
            f(arg)
            arg += 1
    return inner
@warpper
def fun(num):
    print('我被執行了%s次了'%num)
fun(1)
View Code

8、將列表內的元素,根據位數被合並成字典(升級題)lst = [1,2,3,4,12,13,14,123,124,125,1234,1235,1236,1237,12345,12346,12347]

變成
{
1:[1,2,3,4],
2:[12,13,14],
3:[123,124,125],
4:[1234,1235,1236,1237],
5:[12345,12346,12347]
}

from collections import defaultdict
d = defaultdict(list)  # 這里里面的參數可以是任何可變數據類型,可以不斷往里面加值
for i in lst:
    d[len(str(i))].append(i)   # 不斷地給相應的加值
d = dict(d)   # 會根據最終值工廠化這個字典
print(d)
View Code 

9、12.輸入一個不是空的字符串,判斷這個字符串是不是由一個子字符重復多次組成,字符只包含小寫字母,且長度不超過1000(升級題)

示例一:
輸入:"abab"
這種就輸出True,因為輸入的是ab重復組成的字符串
示例二:
輸入:"abcabcabc"
這種就輸出True,因為輸入的是abc重復組成的字符串
示例三:
輸入:"abcdabcd"
這種就輸出True,因為輸入的是abcd重復組成的字符串
示例四:
輸入:'abc"
這種就輸出False,因為輸入的沒有重復組成字符串

法一 :
def func():
    cont = input('請輸入字符串:').strip()
    for i in range(1,len(cont)-1):
        for j in range(i,len(cont),i):
            if cont[0:0+i]==cont[j:j+i]:continue  # 迭代比較
            elif cont.replace(cont[0],'') =='':continue  # 排除單個字母重復奇數次
            else:break
        else:return True
    else:return False
print(func())

法一:
s = input("請輸入一個只包含小寫字母組成的字符串:").strip()
l=len(s)
for i in range(l//2):
    j=l//(i+1)    
    if s[0:i+1]*j==s:
        print(True)
        break
else:
    print(False)
View Code
num = input('請輸入一個字符:')
j = 1
while 1:
    print(num[:j])
    if (num[:j])*(num.count(num[:j])) == num and (num[:j] != num):
        print(True)
        break
    elif num[:j] == num:
        print(False)
        break
    else:
        j += 1
代碼補充

10、 求結果 v = [lambda :x for x in range(10)]

print(v)   #[<function <listcomp>.<lambda> at 0x02EE2F60>, ……
print(v[0])  #<function <listcomp>.<lambda> at 0x02EE2F60>
print(v[5]())  #9 全是9,應為最后一個x為9,所有的函數執行時都引用一個9的內存
View Code

11、求結果v = (lambda :x for x in range(10))

print(v)    #一個生成器地址  <generator object <genexpr> at 0x0382E870>
print(v[0])  # 注意生成器沒有索引 TypeError: 'generator' object is not subscriptable
print(v[0]())  # 生成器只能send或則next調用 TypeError: 'generator' object is not subscriptable
print(next(v))   #一內存地址 <function <genexpr>.<lambda> at 0x03182F60>
print(next(v)())  #1
View Code

12、有兩個字符串列表,a和b,每個字符是由逗號分隔的一些字符,(升級題)盡量做得支持擴展

a = [
'a,1',
'b,3,22',
'c,3,4',
'f,5',
]
b=[
'a,2,1',
'b,4',
'd,2',
'e,12',
'g,12,43',
'a,4354,6'
]
按每個字符串的第一個值,合並a和b到c
c = [
'a,1,2',
'b,3,22,4',
'c,3,4',
'd,2',
'e,12',
'f,5'
]
題目
法1:
c=[]
for i in a:
    flag = False
    removes = None
    i = i.strip()
    li=[i[0],i[2:],]
    for v in b:
        v=v.strip()
        if i[0]==v[0]:
            li.append(v[2:])
            flag,removes=True,v
            break
    print(li)
    c.append(','.join(li))
    if flag:
        b.remove(removes)
else:
    c.extend(b)
print(c)

法2:
g = { i[0]:i for i in a}
for i in b:
    if i[0] in g:
        g[i[0]]=g[i[0]][2:]+i[1:]
    else:
        g[i[0]]=i

print(list(g.values()))
View Code
dic=dict([(i[0],i) for i in a])
for v in b:
    if dic.get(v[0]):dic[v[0]]=dic[v[0]]+v[1:]
    else: dic[v[0]]=v[2:]
print(list(dic.values()))
優美版本

13、正則表達式例題

1、匹配整數或者小數(包括正數和負數)
        [-|+]?\d+(\.\d+)?
2、匹配年月日日期 格式2018-12-6
        \d{4}-\d+-\d+
3、匹配qq號
        ^[^0]\d{8}\d$
4、長度為8-10位的用戶密碼 : 包含數字字母下划線
        \w{8}(\w{2})?
5、匹配驗證碼:4位數字字母組成的
        [0-9A-z]{4}
6、匹配郵箱地址
        [^0]\d{9}@[qq|126|outlook]+\.[a-z]{3}        
View Code

14、 用hashlib模塊 寫函數來校驗兩個文件是否內容一致(要考慮到文件過大,如何處理)

import hashlib
md5=hashlib.md5(b'alex')
md4=hashlib.md5(b'alex')
def read_txt(first_file,second_file):
    with open(first_file,'r',encoding='utf-8') as f,\
        open(second_file,'r',encoding='utf-8') as f2:
        targt =True
        while targt:
            i=f.readline()
            i_2 =f2.readline()
            m_info =md5.update(i.encode('utf-8'))
            m_comp = md5.hexdigest()
            m_info_2 =md4.update(i_2.encode('utf-8'))  #update方法不能累加
            m_comp_2 = md4.hexdigest()
            if m_comp !=m_comp_2:
                return False
            elif i_2 =='':
                return True
ret=read_txt('1.txt','2.txt')
print(ret)
View Code 
# 在公司中很可能要驗證一些視頻文件,但是上面的代碼就不行了
import os
import hashlib

def file_md5(path):
    filesize = os.path.getsize(path)   # 先獲取文件大小
    md5 = hashlib.md5()      # 獲取對象
    with open(path,'rb') as f:
        while filesize >= 4096:   # 判斷大小,以便相減
            content = f.read(4096)
            md5.update(content)  # 每次更新對象內容
            filesize -= 4096
        else:
            content = f.read(filesize)
            if content:
                md5.update(content)
    return md5.hexdigest()  # 生成密文

def cmp_file(path1,path2):
    return file_md5(path1) == file_md5(path2)

path1 = r'D:\s20\day18\視頻\4.面向對象整理.mp4'
path2 = r'D:\s20\day18\視頻\tmp.mp4'
ret = cmp_file(path1,path2)
print(ret)
完善代碼

 15、用hashlib模塊做一個密文存儲密碼的注冊登陸程序。

import hashlib
def register():
    md5 = hashlib.md5()
    with open('register.txt','a+',encoding='utf-8') as f:
        print('歡迎注冊'.center(20,'='))
        new_usr = input('新用戶名:').strip()
        new_pw = input('新密碼:').strip()
        md5.update(new_pw.encode('utf-8'))
        hash_pw = md5.hexdigest()
        f.write('%s|%s\n'%(new_usr,hash_pw))
    return True

def warpper(func):
    def check(usr,func_2):
        tagert_2 =False
        while not tagert_2:
            print('歡迎登陸'.center(20,'='))
            md4 = hashlib.md5()
            with open('register.txt','r',encoding='utf-8') as f2:
                usr = input('用戶名:').strip()
                for i in f2:
                    i = i.strip().split('|')
                    if i[0]==usr:
                        pw = input('密碼:').strip()
                        md4.update(pw.encode('utf-8'))
                        md4_info = md4.hexdigest()
                        if i[1]==md4_info:
                            return func(i[0])
                else:
                    print('<<<用戶未注冊>>> '.center(20,'*'))
                    targt_2 = func_2()
    return check

@warpper
def logging(usr,re=None):
    print('%s登陸成功!'%usr)

logging(None,register)
View Code
import hashlib
def md5(username,password):
    md5 = hashlib.md5(username[::-1].encode('utf-8'))
    md5.update(password.encode('utf-8'))
    return md5.hexdigest()

def get_line():
    with open('userinfo', encoding='utf-8') as f:
        for line in f:
            user, pwd = line.strip().split(',')
            yield user,pwd   #生成器 

def register():
    flag = True
    while flag:
        username = input('user :')
        password = input('passwd :')
        for user,pwd in get_line():
            if user == username:
                print('您輸入的用戶名已經存在')
                break
        else:
            flag = False
    password = md5(username,password)
    with open('userinfo',encoding='utf-8',mode='a') as f:
        f.write('%s,%s\n'%(username,password))

def login():
    username = input('user :')
    password = input('passwd :')
    for user,pwd in get_line():
        if username == user and pwd == md5(username,password):
            return True


ret = login()
if ret:
    print('登陸成功')
完善代碼

16、拼手氣紅包,要求每個人的概率均等。

import random
def func(money,pople):
    lst=[0,2000]
    lst.extend(random.sample(list(range(0,money*10)),pople-1))
    lst.sort()
    lst =list(map(lambda x:x/10,lst))
    g=(round(lst[i+1]-lst[i],3) for i in range(len(lst)-1))
    return g
ret=list(func(200,10))
print(ret)
View Code
# 涉及到讀取文件,最好使用生成器
import random
def red_pac(money,num):
    ret = random.sample(range(1,money*100),num-1)
    ret.sort()
    ret.insert(0,0)
    ret.append(money*100)
    for i in range(len(ret)-1):
        value = ret[i+1] - ret[i]  #迭代器
        yield value/100

g = red_pac(200,10)
for i in g:
    print(i)
生成器寫法 

17、os模塊計算文件夾總大小:(注意要考慮文件中還有多個文件夾怎么辦)

    1、這個文件夾里面都是文件
    2、這個文件夾里還有文件

import os
def get_size(path):
    size = 0
    l = [path]
    while l:
        path = l.pop()
        lst = os.listdir(path)
        for name in lst:
            son_path = os.path.join(path,name)
            if os.path.isfile(son_path):
                size += os.path.getsize(son_path)
            else:
                l.append(son_path)
    return size

size = get_size(r'D:\s14\算法')
print(size)
必看

 

20、計算當前月1號 的時間戳時間

import time
shi_jian_chou = time.time()
strct_time=time.localtime(shi_jian_chou) # 轉化成結構化時間
new_time=shi_jian_chou-86400*strct_time.tm_mday # 打印天數
print(new_time)
print(time.localtime(new_time))
View Code
import time
現在是哪個月
def first_day():
    str_t = time.strftime('%Y-%m')
    tup_t = time.strptime(str_t,'%Y-%m')
    stamp_t = time.mktime(tup_t)
    return stamp_t
f = first_day()
print(f)
完善代碼

21、省、市、區三級菜單

menu = {
    '北京': {
        '海淀': {
            '五道口': {
                'soho': {},
                '網易': {},
                'google': {}
            },
            '中關村': {
                '愛奇藝': {},
                '汽車之家': {},
                'youku': {},
            },
            '上地': {
                '百度': {},
            },
        },
        '昌平': {
            '沙河': {
                '老男孩': {},
                '北航': {},
            },
            '天通苑': {},
            '回龍觀': {},
        },
        '朝陽': {},
        '東城': {},
    },
    '上海': {
        '閔行': {
            "人民廣場": {
                '炸雞店': {}
            }
        },
        '閘北': {
            '火車戰': {
                '攜程': {}
            }
        },
        '浦東': {},
    },
    '山東': {
        '聊城':{
            '耿家庄':{},
            '耿二庄':{},
        },
    },
}
li =[]
def func(menus,parent_palce=menu):
    current_place = list(menus.keys())
    for i,v in enumerate(current_place,1):
        print(i,v)
    if current_place ==[]:
        print('已經到最底層了!!!')

    usr_choose = input('請輸入相關城市(Q退出,B返回上一層)>>> ').strip()
    if usr_choose.lower()=='b':
            menus =parent_palce
            for i in range(len(li)-1,-1,-1):     # parent_palce在給了值之后要更改到上一級
                parent_palce=li[i]
            try:
                li.pop()
            except:pass
            func(menus,parent_palce)
    elif usr_choose.isdigit() and 0<int(usr_choose)<=len(current_place):
        sub_place = menus[current_place[int(usr_choose)-1]]
        li.append(menus)
        parent_palce = menus
        func(sub_place,parent_palce)
    elif usr_choose.upper() =='q':
        exit()
    else: print('輸入有誤!!!')
func(menu)
View Code
#遞歸
def threeLM(dic):
    while True:
        for k in dic:print(k)
        key = input('input>>').strip()
        if key == 'b' or key == 'q':return key
        elif key in dic.keys() and dic[key]:
            ret = threeLM(dic[key])
            if ret == 'q': return 'q'

threeLM(menu)

#壓棧
l = [menu]
while l:
    for key in l[-1]:print(key)
    k = input('input>>').strip()   # 北京
    if k in l[-1].keys() and l[-1][k]:l.append(l[-1][k])
    elif k == 'b':l.pop()
    elif k == 'q':break
遞歸和壓棧實現
l = [menu]
while l:
    for k in l[-1]:
        print(k)
    key = input('>>>')
    if key.upper() == 'B':
        l.pop()
    elif key.upper() == 'Q':
        l.clear()
    elif l[-1].get(key):  #判斷是否在內
        l.append(l[-1][key])
再次更新

 

22、1-2*((60-30+(-40/5)*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2))從上面算式中匹配出最內層小括號以及小括號內的表達式

import re
print(re.findall('\([^()]+\)','1-2*((60-30+(-40/5)*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2))'))
View Code

23、從類似9-2*5/3+7/3*99/4*2998+10*568/14的表達式中匹配出乘法或除法

import re
print(re.findall('\d+(?:\.\d+)?[*/]\d+(?:\.\d+)?','9-2*5/3+7/3*99/4*2998+10*568/14'))
View Code

24、從lianjia.html中匹配出標題,戶型和面積,結果如下:

[('金台路交通部部委樓南北大三居帶客廳 單位自持物業', '3室1廳', '91.22平米'),
('西山楓林 高樓層南向兩居 戶型方正 采光好', '2室1廳', '94.14平米')]

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div class="info clear">
    <div class="title">
        <a class="" href="https://bj.lianjia.com/ershoufang/101103186217.html" target="_blank" data-log_index="1"
           data-el="ershoufang" data-housecode="101103186217" data-is_focus="1" data-sl="">金台路交通部部委樓南北大三居帶客廳   單位自持物業</a>
        <span class="new tagBlock">新上</span></div>
    <div class="address">
        <div class="houseInfo">
            <a href="https://bj.lianjia.com/xiaoqu/1111027381816/" target="_blank" data-log_index="1" data-el="region">延靜西里 </a>
            <span class="divide">/</span>3室1廳<span class="divide">/</span>91.22平米<span class="divide">/</span>南 北<span class="divide">/</span>簡裝<span class="divide">/</span>有電梯
        </div>



上面是部分html文檔,正則出想要的結果:
法一(笨辦法):
import re
f = open('lianjia.html','r',encoding='utf-8')
info = f.read()
ret = re.compile(r'<div class="info clear">.*?div class="title">.*?<a class=.*?>(?P<id>\w+).*?</a>'
'.*?<span class="divide">/</span>(?P<area>\w+)<span.*?</span>(?P<mian>\d+(\.\d+)?\w+)<span.*?class',re.S)
print(ret.findall(info)


法二:
with open('lianjia.html', 'r', encoding='utf-8') as f:
    file_obj = f.read()
om = re.compile(
    '<div class="info clear">.*? data-sl="">(?P<title>.*?)</a>.*?<span class="divide">/</span>(?P<house>.*?)'
    '<span class="divide">/</span>(?P<area>.*?)<span class="divide">/</span>', re.S)
res = om.findall(file_obj)
print(res)
View Code

25、匹配年月日日期 類似 2018-12-06 2018/12/06 2018.12.06

import re
ret = re.findall('\w{1,4}[-|/|\.]\w{2}[-|/|\.]\w{2}',s)
ret1 = re.findall('\w{1,4}(?:[-/\.]?\w{2}){2}',s)
print(ret,ret1)
View Code

 26、匹配一篇英文章的標題 類似 The Voice Of China

import re
ret = re.search('([A-Z]\w+[ ]?)+','adfadfafdadfThe Voice Of China adfafafx')
print(ret.group())
View Code
([A-Z][a-z]*)( [A-Z][a-z]*)*
更新答案

27、用正則表達式對標簽進行匹配

import re

ret = re.search("<(?P<tag_name>\w+)>\w+</(?P=tag_name)>","<h1>hello</h1>")
#還可以在分組中利用?<name>的形式給分組起名字
#獲取的匹配結果可以直接用group('名字')拿到對應的值
print(ret.group('tag_name'))  #結果 :h1
print(ret.group())  #結果 :<h1>hello</h1>

ret = re.search(r"<(\w+)>\w+</\1>","<h1>hello</h1>")
#如果不給組起名字,也可以用\序號來找到對應的組,表示要找的內容和前面的組內容一致
#獲取的匹配結果可以直接用group(序號)拿到對應的值
print(ret.group(1))
print(ret.group())  #結果 :<h1>hello</h1>
View Code

28、對數字進行整數匹配(用到findall的優先級處理)

import re

ret=re.findall(r"\d+","1-2*(60+(-40.35/5)-(-4*3))")
print(ret) #['1', '2', '60', '40', '35', '5', '4', '3']
ret=re.findall(r"-?\d+\.\d*|(-?\d+)","1-2*(60+(-40.35/5)-(-4*3))")
print(ret) #['1', '-2', '60', '', '5', '-4', '3']  # 這里優先匹配整數,括號的用法
ret.remove("")
print(ret) #['1', '-2', '60', '5', '-4', '3']
View Code

29、對數字、年份等進行匹配

1、 匹配一段文本中的每行的郵箱
      http://blog.csdn.net/make164492212/article/details/51656638

2、 匹配一段文本中的每行的時間字符串,比如:‘1990-07-12’;

   分別取出1年的12個月(^(0?[1-9]|1[0-2])$)、
   一個月的31天:^((0?[1-9])|((1|2)[0-9])|30|31)$

3、 匹配qq號。(騰訊QQ號從10000開始)  [1,9][0,9]{4,}

4、 匹配一個浮點數。       ^(-?\d+)(\.\d+)?$   或者  -?\d+\.?\d*

5、 匹配漢字。             ^[\u4e00-\u9fa5]{0,}$ 
View Code 

30計算器

import re

count ='1-2*((60-30+(-9-2*5/3+7/3*99/4*2998+10*568/14)*(-40/5))-(-4*3)/(16-3*2))'
def atom_cal(atom_count):#計算乘除
    for i in atom_count:
        if i == '*':
            n1,n2 = atom_count.split('*')
            return float(n1)*float(n2)
        elif i == '/':
            n1,n2 = atom_count.split('/')
            return float(n1)/float(n2)
def atom_cal1(brack_ret):#計算加減
    sum = 0
    for i in brack_ret:
        sum += float(i)
    return sum
def dropbug(brack_ret):
    brack_ret = brack_ret.replace('--', '+')
    brack_ret = brack_ret.replace('-+', '-')
    brack_ret = brack_ret.replace('+-', '-')
    return brack_ret
def cal(brack_ret):
    while 1:
        brack_ret_count = re.search('\d+(\.\d+)?[*/]-?\d+(\.\d+)?',brack_ret) #匹配乘除
        if brack_ret_count:
            atom_count = brack_ret_count.group() #取值
            atom_result = atom_cal(atom_count)
            brack_ret = brack_ret.replace(atom_count,str(atom_result)) #替換新值
        else:
            break  #直到吧括號內都算完
    brack_ret = dropbug(brack_ret) #去符號
    brack_ret_2 = re.findall('(-?\d+(?:\.\d+)?)', brack_ret) # 匹配數進行加減
    if brack_ret_2:
        atom_count = brack_ret_2
        atom_result = atom_cal1(atom_count)
        brack_ret_3 = str(atom_result)
    return brack_ret_3
def main(count):
    while 1:
        ret = re.search('\([^()]+\)',count) #判斷還有無括號
            if ret:
            brack_ret = ret.group()  # 獲取值
            ret_1 = cal(brack_ret)  # 計算括號內值
            count = count.replace(ret.group(),ret_1.strip('()'))
        else:
            break
    return cal(count)
result_2 = main(count)
print(result_2)
View Code

 31、當前年月日的凌晨12點對應的時間戳時間是多少,當前年月日的凌晨12點對應限制的時間差了多少

import time
def now_day():
    today_time=time.strftime('%Y-%m-%d')  # 格式化時間
    locals_time=time.strptime(today_time,'%Y-%m-%d')  #  獲取到結構化時間,默認返回凌晨時間
    return time.mktime(locals_time)   # 獲取時間戳
ret=now_day()
print(ret)

# 當前年月日的凌晨12點對應限制的時間差了多少
def com_time(new_time):
     now_time = time.time()-now_day()
     return now_time
t=time.time()
print(com_time(t))
View Code

 32、獲取最大公約數和最小公倍數

a = 36
b = 21

def maxCommon(a, b):
    while b: a,b = b, a%b
    return a

def minCommon(a, b):
    c = a*b
    while b: a,b = b, a%b
    return c//a

if __name__ == '__main__':
    print(maxCommon(a,b))
    print(minCommon(a,b))
View Code

 

33、獲取中位數

def median(data):
    data.sort()  # [1, 2, 3, 4, 8, 42, 46, 53, 82]
    print(l[~3]) # 42
    print(l[:~5]) # [1, 2, 3]
    print(l[~1:3:2]) # []
    print(l[~1:3:-2]) # [53, 42]
    print(l[~1::-2]) # [53, 42, 4, 2]
    print(l[~1]) # 53  # 所以~ 再將會是倒着從0開始算索引
    half = len(data) // 2
    print(data)
    print(data[~half])
    print(data[half])
    return (data[half] + data[~half])/2

l = [1,3,4,53,2,46,8,42,82]

if __name__ == '__main__':
    print(median(l))
View Code

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM