猜数游戏
1-100,猜一个我心中的数字?
第一次猜多少? 50
最多猜几次? 7次 2^7 = 128
1- 1000 猜几次? 2^10 = 1024
1 - 1000000猜几次 2 ^20 > 1000000
100 - 1000 - 1000000 变化很大; 7 - 10 - 20 变化很小
import timeimport randomimport matplotlib.pyplot as pltimport math%matplotlib inlinedef random_list(l):return [[int( 1000*random.random()) for i in range(l*n)] for n in range(1,20)]
O(1)-Constant (常数级别)
def squre(x):return x *xsqure(3)
def first(x): # x is a liststart = time.time()r = x[0] # 取列表起始元素t = time.time - startreturn r, len(x), tdef midle(x):start = time.time()r = x[len(x)//2] # 取列表中间元素t = time.time() - startreturn r, len(x), tdef last(x):start = time.time()r = x[-1] # 取列表最后一个元素t = time.time() - startreturn r, len(x), t
random_list = random_list(10000)rst = [last(l) for l in random_list]len(rst)rst

x = list(zip(*rst))[1]y = list(zip(*rst))[2]plt.plot(x,y)

随着次数的增加的增加,时间基本此平在0.00。
O(log)-logarithm(对数级别)
二分查找就是log
import bisectdef bs(nums,target): # 二分查找sorted(nums)start = time.time()i = bisect.bisect_left(nums,target)if i != len(nums) and nums[i] == target:t = time.time() - startreturn i, len(nums), tt = time.time() - startreturn -1, len(nums), t
random_lists = random_list(1000)rst = [bs(l,100) for l in random_lists]len(rst)rst

x = list(zip(*rst))[1]y = list(zip(*rst))[2]plt.plot(x,y)

随着次数的增加的增加,时间基本也此平在0.00,**但是和O(1)还是有区别的。
O(n)- linear (线性级别)
def find_max(l): # 找最大的数start = time.time()if l == None:return Nonemx = l[0]for n in l:if n > mx:mx = nt = time.time() - startreturn mx, len(l), t
random_lists = random_list(20000)rst = [find_max(l) for l in random_lists]len(rst)rst

x = list(zip(*rst))[1]y = list(zip(*rst))[2]plt.plot(x,y)

O(nlgn)- linear logarithmic(线性对数级别)
def mysort(l): # 排序start = time.time()l.sort()t = time.time() - startreturn l[0], len(l), t
random_lists = random_list(20000)rst = [mysort(l) for l in random_lists]len(rst)rst

x = list(zip(*rst))[1]y = list(zip(*rst))[2]plt.plot(x,y)

O(n)- square (平方级别)
def has_duplicate(l): # 查看数组中是否有重复的数字start = time.time()rst = Falsefor i in range(len(l)):for j in range(i+1, len(l)):if l[i] == l[j]:rst = Truet = time.time() - startreturn rst, len(l), t
random_lists = random_list(100)rst = [ has_duplicate(l) for l in random_lists]len(rst)rst

x = list(zip(*rst))[1]y = list(zip(*rst))[2]plt.plot(x,y)
评估算法运行时间

分析处算法的最差情况:比如1-100 最好猜1次中,一般猜4-5次,最差猜7次中,研究4, 5,7更有意义。

核心就是:根据多项式快速求出时间复杂度
例如: 5(N**2)-22NlogN + 5N + 2 —-> O(N2**)
3**NlogN + 5N —-> O(NlogN )
**
主项定理


**

