您的位置:首页 > 编程语言 > Python开发

python之手撕代码

2019-03-21 11:42 37 查看

书读百遍,其意自见,代码亦如是,无他,唯熟练尔。

文章目录

装饰器之代码运行时间

1 # coding=utf8
2 # 使用装饰器实现统计一段代码的运行时间
3
4 import time
5
6 def w(func):
7     def inner():
8         s = time.time()
9         func()
10         e = time.time()
11         t = e-s
12         print('运行时间为%f'%t)
13     return inner()
14
15 @w
16 def f1():
17     n = 0
18     for i in range(101):
19         n += i
20     print(n)

运行结果

5050
运行时间为0.000068

文件路径

1 # coding=utf8
2 # 根据路径打印出路径下的文件夹以及文件的路径与名称
3 import os
4
5 def f1(p):
6     fs = os.listdir(p)
7     for f in fs:
8         temp_path = os.path.join(p,f)
9         if not os.path.isdir(temp_path):
10             print('文件:%s'%temp_path)
11         else:
12             print('文件夹:%s'%temp_path)
13             f1(temp_path)
14
15 path = '/home/python/Desktop/test'
16 f1(path)

运行结果

文件夹:/home/python/Desktop/test/03
文件:/home/python/Desktop/test/03/c.txt
文件:/home/python/Desktop/test/z.txt
文件夹:/home/python/Desktop/test/01
文件:/home/python/Desktop/test/01/a.txt
文件夹:/home/python/Desktop/test/02
文件:/home/python/Desktop/test/02/b.txt

两数之和之下标

1 # coding=utf8
2 # 给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。你可以假设每个输入只对应一种答案,且同
样的元素不能被重复利用。
3
4 # 求差值、把差值存进字典里作为键、索引作为值,第一次循环理解:d[7]=0 即字典d={7:0},表示为索引0需要数组里值为7的元素配对。 if 判断是否为前面元素所需要配对的值 , 是则返回两个索引值。(补充:nums[x] in d是判断值是否在字典某个key里面)
5
6 def f1():
7     l = [2,7,13,16]
8     t = 9
9     n = len(l)
10     d = {}
11     for x in range(n):
12         # 差值
13         a = t-l[x]
14         # 如果有需要我作为差值的元素
15         if l[x] in d:
16             # 返回需要我的元素的下标,我的下标
17             return d[l[x]],x
18         else:
19             # 否则,把我需要的差值和我的下标作为键值对存进去
20             d[a]=x
21
22 ret = f1()
23 print(list(ret))

运行结果

[0,1]

线程安全与互斥锁

1 import threading
2 import time
3
4 g = 0
5
6 def test1(n):
7     global g
8     for i in range(n):
9         mutex.acquire()
10         g += 1
11         mutex.release()
12     print('---test1---g=%d'%g)
13
14 def test2(n):
15     global g
16     for i in range(n):
17         mutex.acquire()
18         g += 1
19         mutex.release()
20     print('---test2---g=%d'%g)
21
22 mutex = threading.Lock()
23 p1 = threading.Thread(target=test1, args=(100000,))
24 p1.start()
25
26 p2 = threading.Thread(target=test2, args=(100000,))
27 p2.start()
28
29 while len(threading.enumerate()) != 1:
30     time.sleep(1)
31
32 print(g)

运行结果

---test2---187729
---test1---200000
200000

统计大小字母

1 with open('/home/python/Desktop/test/z.txt','r') as f:
2     uppers=0
3     lowers=0
4     digits=0
5     spaces=0
6     others=0
7     for i in f.read():
8         if i.isupper():
9             uppers += 1
10         elif i.islower():
11             lowers += 1
12         elif i.isdigit():
13             digits += 1
14         elif i.isspace():
15             spaces += 1
16         else:
17             others += 1
18     print('uppers=%d,lowers=%d,digits=%d,spaces=%d,others=%d'%(uppers,lowers,digits,spaces,others))

运行结果

uppers=5,lowers=31,digits=3,spaces=7,others=4

英文词频统计

1 def get_text():
2     f = open('en.txt','r')
3     text = f.read().lower()
4     for i in '!@#$%^&*()_¯+-;:`~\'"<>=./?,':
5         text = text.replace(i,'')
6     return text.split()
7
8 ls = get_text()
9 counts = {}
10 for i in ls:
11     counts[i] = counts.get(i,0)+1
12 iteams = list(counts.items())
13 iteams.sort(key=lambda x:x[1],reverse=True)
14 for i in iteams[0:5]:
15     print(i)

运行结果

('love', 27)
('i', 27)
('python', 27)
('haha', 2)
('name', 1)

Queue实例

from multiprocessing import Process, Queue
import os, time, random

# 写数据进程执行的代码:
def write(q):
for value in ['A', 'B', 'C']:
print('Put %s to queue...' % value)
q.put(value)
time.sleep(random.random())

# 读数据进程执行的代码:
def read(q):
while True:
if not q.empty():
value = q.get(True)
print('Get %s from queue.' % value)
time.sleep(random.random())
else:
break

if __name__=='__main__':
# 父进程创建Queue,并传给各个子进程:
q = Queue()
pw = Process(target=write, args=(q,))
pr = Process(target=read, args=(q,))
# 启动子进程pw,写入:
pw.start()
# 等待pw结束:
pw.join()
# 启动子进程pr,读取:
pr.start()
pr.join()
# pr进程里是死循环,无法等待其结束,只能强行终止:
print('')
print('所有数据都写入并且读完')

运行结果

冒泡排序

1 # coding:utf8
2 # 冒泡排序 相邻两位开始,大的放到后边
3 l = [1,2,5,4,3,6,9,7,8]
4
5 def pop_sort(alist):
6     n = len(alist)
7     # 确定冒泡的次数
8     for i in range(n-1):
9         for j in range(n-1-i):
10             # 排好之后的不需要再进行比较
11             # 两两比较,将最大的放到最右边
12             if alist[j] > alist[j+1]:
13                 alist[j],alist[j+1] = alist[j+1],alist[j]
14
15 pop_sort(l)
16 print(l)

运行结果

[1, 2, 3, 4, 5, 6, 7, 8, 9]

插入排序

1 # coding=utf8
2 # 插入排序 类似打牌 左边为有序列表,比要插入的元素大则往后排
3 def insert_sort(alist):
4     n = len(alist)
5
6     for i in range(1,n):
7         # 假如左手有一张牌,与其余的牌进行排序,从右向左
8         for j in range(i,0,-1):
9             # 将j和j-1这样的元素比较,大的放后,小的放前
10             # 新到手的牌和前面的牌比较,小的放前面
11             if alist[j] < alist[j-1]:
12                 alist[j],alist[j-1] = alist[j-1],alist[j]
13             else:
14                 break
15
16 l = [1,3,5,7,9,2,4,6,8]
17 insert_sort(l)
18 print(l)

运行结果

[1, 2, 3, 4, 5, 6, 7, 8, 9]

快速排序

1 # coding=utf8
2 # mid:基准值,以她为界限分为左右两个表,左边的小于它,右边的大于它
3 # low:低位游标, high:高位游标, start:其实下标,end:结尾下标
4 def quick_sort(alist,start,end):
5     if start>=end:
6         return
7
8     low = start
9     high = end
10
11     mid = alist[low]
12
13     # 当low>=high就退出循环
14     # 如果要保序: alist[high] >= mid 和 alist[low] <= mid 只取其中一种
15     while low < high:
16         while alist[high] >= mid and low < high:
17             # 如果最右边的值大于基准值,高位游标左移
18             high -= 1
19         # 跳出循环说明高位游标指向的值小于基准值,把该值放到低位
20         alist[low] = alist[high]
21
22         # 交换一次后高位游标不动,开始移动低位游标
23         while alist[low] < mid and low < high:
24             low += 1
25             alist[high] = alist[low]
26     # low == high
27     alist[low]=mid
28
29     # 以low下标为界, 分为左表和右表
30     #左表:[start,low-1]
31     quick_sort(alist, start, low-1)
32     #右表: [hight+1,end]
33     quick_sort(alist,high+1,end)
34
35 l = [1,3,5,7,9,8,6,4,2]
36 quick_sort(l,0,len(l)-1)
37 print(l)

运行结果

[1, 2, 3, 4, 5, 6, 7, 8, 9]

选择排序

1 # coding=utf8
2 # 选择排序 将其他元素与下标为0的元素逐一比较,小的放到0位上
3 def selection_sort(l):
4     n = len(l)
5     for i in range(n-1):
6         # 右边的元素与起始比较,小的放到前边
7         for j in range(i+1,n):
8             if l[j] < l[i]:
9                 l[i],l[j] = l[j],l[i]
10
11 li = [1,2,3,5,4,6,7,9,8,0]
12 selection_sort(li)
13 print(li)

运行结果

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: