Skip to content

Commit 62d43af

Browse files
committed
更新了文档和静态资源
1 parent ea9adc6 commit 62d43af

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

73 files changed

+4142
-117
lines changed
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.

Day16-20/code-2/example01.py

+69
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
"""
2+
查找 - 顺序查找和二分查找
3+
算法:解决问题的方法(步骤)
4+
评价一个算法的好坏主要有两个指标:渐近时间复杂度和渐近空间复杂度,通常一个算法很难做到时间复杂度和空间复杂度都很低(因为时间和空间是不可调和的矛盾)
5+
表示渐近时间复杂度通常使用大O标记
6+
O(c):常量时间复杂度 - 哈希存储 / 布隆过滤器
7+
O(log_2 n):对数时间复杂度 - 折半查找
8+
O(n):线性时间复杂度 - 顺序查找
9+
O(n * log_2 n):- 对数线性时间复杂度 - 高级排序算法(归并排序、快速排序)
10+
O(n ** 2):平方时间复杂度 - 简单排序算法(冒泡排序、选择排序、插入排序)
11+
O(n ** 3):立方时间复杂度 - Floyd算法 / 矩阵乘法运算
12+
也称为多项式时间复杂度
13+
O(2 ** n):几何级数时间复杂度 - 汉诺塔
14+
O(3 ** n):几何级数时间复杂度
15+
也称为指数时间复杂度
16+
O(n!):阶乘时间复杂度 - 旅行经销商问题 - NP
17+
"""
18+
from math import log2, factorial
19+
from matplotlib import pyplot
20+
21+
import numpy
22+
23+
24+
def seq_search(items: list, elem) -> int:
25+
"""顺序查找"""
26+
for index, item in enumerate(items):
27+
if elem == item:
28+
return index
29+
return -1
30+
31+
32+
def bin_search(items, elem):
33+
"""二分查找"""
34+
start, end = 0, len(items) - 1
35+
while start <= end:
36+
mid = (start + end) // 2
37+
if elem > items[mid]:
38+
start = mid + 1
39+
elif elem < items[mid]:
40+
end = mid - 1
41+
else:
42+
return mid
43+
return -1
44+
45+
46+
def main():
47+
"""主函数(程序入口)"""
48+
num = 6
49+
styles = ['r-.', 'g-*', 'b-o', 'y-x', 'c-^', 'm-+', 'k-d']
50+
legends = ['对数', '线性', '线性对数', '平方', '立方', '几何级数', '阶乘']
51+
x_data = [x for x in range(1, num + 1)]
52+
y_data1 = [log2(y) for y in range(1, num + 1)]
53+
y_data2 = [y for y in range(1, num + 1)]
54+
y_data3 = [y * log2(y) for y in range(1, num + 1)]
55+
y_data4 = [y ** 2 for y in range(1, num + 1)]
56+
y_data5 = [y ** 3 for y in range(1, num + 1)]
57+
y_data6 = [3 ** y for y in range(1, num + 1)]
58+
y_data7 = [factorial(y) for y in range(1, num + 1)]
59+
y_datas = [y_data1, y_data2, y_data3, y_data4, y_data5, y_data6, y_data7]
60+
for index, y_data in enumerate(y_datas):
61+
pyplot.plot(x_data, y_data, styles[index])
62+
pyplot.legend(legends)
63+
pyplot.xticks(numpy.arange(1, 7, step=1))
64+
pyplot.yticks(numpy.arange(0, 751, step=50))
65+
pyplot.show()
66+
67+
68+
if __name__ == '__main__':
69+
main()

Day16-20/code-2/example02.py

+161
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,161 @@
1+
"""
2+
排序 - 冒泡排序、选择排序、归并排序、快速排序
3+
冒泡排序 - O(n ** 2):两两比较,大的下沉
4+
35, 97, 12, 68, 55, 73, 81, 40
5+
35, 12, 68, 55, 73, 81, 40, [97]
6+
12, 35, 55, 68, 73, 40, [81]
7+
12, 35, 55, 68, 40, [73]
8+
...
9+
选择排序 - O(n ** 2):每次从剩下元素中选择最小
10+
-----------------------------------------
11+
归并排序 - O(n * log_2 n) - 高级排序算法
12+
35, 97, 12, 68, 55, 73, 81, 40
13+
[35, 97, 12, 68], [55, 73, 81, 40]
14+
[35, 97], [12, 68], [55, 73], [81, 40]
15+
[35], [97], [12], [68], [55], [73], [81], [40]
16+
[35, 97], [12, 68], [55, 73], [40, 81]
17+
[12, 35, 68, 97], [40, 55, 73, 81]
18+
[12, 35, 40, 55, 68, 73, 81, 97]
19+
-----------------------------------------
20+
快速排序 - 以枢轴为界将列表中的元素划分为两个部分,左边都比枢轴小,右边都比枢轴大
21+
35, 97, 12, 68, 55, 73, 81, 40
22+
35, 12, [40], 68, 55, 73, 81, 97
23+
[12], 35, [40], 68, 55, 73, 81, [97]
24+
[12], 35, [40], 55, [68], 73, 81, [97]
25+
[12], 35, [40], 55, [68], 73, [81], [97]
26+
"""
27+
28+
29+
class Person(object):
30+
"""人"""
31+
32+
def __init__(self, name, age):
33+
self.name = name
34+
self.age = age
35+
36+
# def __gt__(self, other):
37+
# return self.name > other.name
38+
39+
def __str__(self):
40+
return f'{self.name}: {self.age}'
41+
42+
def __repr__(self):
43+
return self.__str__()
44+
45+
46+
def select_sort(origin_items, comp=lambda x, y: x < y):
47+
"""简单选择排序"""
48+
items = origin_items[:]
49+
for i in range(len(items) - 1):
50+
min_index = i
51+
for j in range(i + 1, len(items)):
52+
if comp(items[j], items[min_index]):
53+
min_index = j
54+
items[i], items[min_index] = items[min_index], items[i]
55+
return items
56+
57+
58+
# 函数的设计要尽量做到无副作用(不影响调用者)
59+
# 9 1 2 3 4 5 6 7 8
60+
# 9 2 3 4 5 6 7 8 1
61+
# *前面的参数叫位置参数,传参时只需要对号入座即可
62+
# *后面的参数叫命名关键字参数,传参时必须给出参数名和参数值
63+
# *args - 可变参数 - 元组
64+
# **kwargs - 关键字参数 - 字典
65+
def bubble_sort(origin_items, *, comp=lambda x, y: x > y):
66+
"""冒泡排序"""
67+
items = origin_items[:]
68+
for i in range(1, len(items)):
69+
swapped = False
70+
for j in range(i - 1, len(items) - i):
71+
if comp(items[j], items[j + 1]):
72+
items[j], items[j + 1] = items[j + 1], items[j]
73+
swapped = True
74+
if swapped:
75+
swapped = False
76+
for j in range(len(items) - i - 1, i - 1, -1):
77+
if comp(items[j - 1], items[j]):
78+
items[j], items[j - 1] = items[j - 1], items[j]
79+
swapped = True
80+
if not swapped:
81+
break
82+
return items
83+
84+
85+
def merge_sort(items, comp=lambda x, y: x <= y):
86+
"""归并排序"""
87+
if len(items) < 2:
88+
return items[:]
89+
mid = len(items) // 2
90+
left = merge_sort(items[:mid], comp)
91+
right = merge_sort(items[mid:], comp)
92+
return merge(left, right, comp)
93+
94+
95+
def merge(items1, items2, comp=lambda x, y: x <= y):
96+
"""合并(将两个有序列表合并成一个新的有序列表)"""
97+
items = []
98+
index1, index2 = 0, 0
99+
while index1 < len(items1) and index2 < len(items2):
100+
if comp(items1[index1], items2[index2]):
101+
items.append(items1[index1])
102+
index1 += 1
103+
else:
104+
items.append(items2[index2])
105+
index2 += 1
106+
items += items1[index1:]
107+
items += items2[index2:]
108+
return items
109+
110+
111+
def quick_sort(origin_items, comp=lambda x, y: x <= y):
112+
"""快速排序"""
113+
items = origin_items[:]
114+
_quick_sort(items, 0, len(items) - 1, comp)
115+
return items
116+
117+
118+
def _quick_sort(items, start, end, comp):
119+
"""递归调用划分和排序"""
120+
if start < end:
121+
pos = _partition(items, start, end, comp)
122+
_quick_sort(items, start, pos - 1, comp)
123+
_quick_sort(items, pos + 1, end, comp)
124+
125+
126+
def _partition(items, start, end, comp):
127+
"""划分"""
128+
pivot = items[end]
129+
i = start - 1
130+
for j in range(start, end):
131+
if comp(items[j], pivot):
132+
i += 1
133+
items[i], items[j] = items[j], items[i]
134+
items[i + 1], items[end] = items[end], items[i + 1]
135+
return i + 1
136+
137+
138+
def main():
139+
"""主函数"""
140+
items = [35, 97, 12, 68, 55, 73, 81, 40]
141+
# print(bubble_sort(items))
142+
# print(select_sort(items))
143+
# print(merge_sort(items))
144+
print(quick_sort(items))
145+
items2 = [
146+
Person('Wang', 25), Person('Luo', 39),
147+
Person('Zhang', 50), Person('He', 20)
148+
]
149+
# print(bubble_sort(items2, comp=lambda p1, p2: p1.age > p2.age))
150+
# print(select_sort(items2, comp=lambda p1, p2: p1.name < p2.name))
151+
# print(merge_sort(items2, comp=lambda p1, p2: p1.age <= p2.age))
152+
print(quick_sort(items2, comp=lambda p1, p2: p1.age <= p2.age))
153+
items3 = ['apple', 'orange', 'watermelon', 'durian', 'pear']
154+
# print(bubble_sort(items3))
155+
# print(bubble_sort(items3, comp=lambda x, y: len(x) > len(y)))
156+
# print(merge_sort(items3))
157+
print(merge_sort(items3))
158+
159+
160+
if __name__ == '__main__':
161+
main()

Day16-20/code-2/example03.py

+76
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
"""
2+
函数递归调用 - 函数直接或者间接的调用了自身
3+
1. 收敛条件
4+
2. 递归公式
5+
6+
n! = n * (n-1)!
7+
f(n) = f(n-1) + f(n-2)
8+
1 1 2 3 5 8 13 21 34 55 ...
9+
"""
10+
from contextlib import contextmanager
11+
from time import perf_counter
12+
13+
14+
def fac(num):
15+
"""求阶乘"""
16+
assert num >= 0
17+
if num in (0, 1):
18+
return 1
19+
return num * fac(num - 1)
20+
21+
22+
def fib2(num):
23+
"""普通函数"""
24+
a, b = 1, 1
25+
for _ in range(num - 1):
26+
a, b = b, a + b
27+
return a
28+
29+
30+
def fib3(num):
31+
"""生成器"""
32+
a, b = 0, 1
33+
for _ in range(num):
34+
a, b = b, a + b
35+
yield a
36+
37+
38+
# 动态规划 - 保存可能进行重复运算的中间结果(空间换时间)
39+
def fib(num, results={}):
40+
"""斐波拉切数"""
41+
assert num > 0
42+
if num in (1, 2):
43+
return 1
44+
try:
45+
return results[num]
46+
except KeyError:
47+
results[num] = fib(num - 1) + fib(num - 2)
48+
return results[num]
49+
50+
51+
@contextmanager
52+
def timer():
53+
try:
54+
start = perf_counter()
55+
yield
56+
finally:
57+
end = perf_counter()
58+
print(f'{end - start}秒')
59+
60+
61+
def main():
62+
"""主函数"""
63+
# for val in fib3(20):
64+
# print(val)
65+
# gen = fib3(20)
66+
# for _ in range(10):
67+
# print(next(gen))
68+
for num in range(1, 121):
69+
with timer():
70+
print(f'{num}: {fib(num)}')
71+
# print(fac(5))
72+
# print(fac(-5))
73+
74+
75+
if __name__ == '__main__':
76+
main()

Day16-20/code-2/example04.py

+43
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
"""
2+
贪婪法:在对问题求解时,总是做出在当前看来是最好的选择,
3+
不追求最优解,快速找到满意解。
4+
"""
5+
class Thing(object):
6+
"""物品"""
7+
8+
def __init__(self, name, price, weight):
9+
self.name = name
10+
self.price = price
11+
self.weight = weight
12+
13+
@property
14+
def value(self):
15+
"""价格重量比"""
16+
return self.price / self.weight
17+
18+
19+
def input_thing():
20+
"""输入物品信息"""
21+
name_str, price_str, weight_str = input().split()
22+
return name_str, int(price_str), int(weight_str)
23+
24+
25+
def main():
26+
"""主函数"""
27+
max_weight, num_of_things = map(int, input().split())
28+
all_things = []
29+
for _ in range(num_of_things):
30+
all_things.append(Thing(*input_thing()))
31+
all_things.sort(key=lambda x: x.value, reverse=True)
32+
total_weight = 0
33+
total_price = 0
34+
for thing in all_things:
35+
if total_weight + thing.weight <= max_weight:
36+
print(f'小偷拿走了{thing.name}')
37+
total_weight += thing.weight
38+
total_price += thing.price
39+
print(f'总价值: {total_price}美元')
40+
41+
42+
if __name__ == '__main__':
43+
main()

0 commit comments

Comments
 (0)