15.时间复杂度
编程建议:
Beautiful is better than ugly
整齐、易读胜过混乱、晦涩
Simple is better than complex
简约胜过复杂
Complex is better than complicated
复杂胜过晦涩
Flat is better than nested
扁平胜过嵌套
Now is better than never.
Although never is often better than right now.
理解一:先行动起来,编写行之有效的代码,不要企图一开始就编写完美无缺的代码
理解二:做比不做要好,但是盲目的不加思考的去做还不如不做
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
如果方案很难解释,很可能不是有一个好的方案,反之亦然
15.1.常见时间复杂度
求最大值和排序
import numpy as np
x = np.random.randint(100, size=10)
x
array([13, 14, 33, 79, 18, 26, 17, 65, 87, 63])
寻找最大值的时间复杂度为O(n)
选择排序时间复杂度O(n^2)
代数分析
def one(x):
"""常数函数"""
return np.ones(len(x))
def log(x):
"""对数函数"""
return np.log(x)
def equal(x):
"""线性函数"""
return x
def n_logn(x):
"""nlogn函数"""
return x*np.log(x)
def square(x):
"""平方函数"""
return x**2
def exponent(x):
"""指数函数"""
return 2**x
各时间复杂度对比
import matplotlib.pyplot as plt
plt.style.use("seaborn-whitegrid")
t = np.linspace(1, 20, 100)
methods = [one, log, equal, n_logn, square, exponent]
method_labels = ["$y = 1$", "$y = log(x)$", "$y = x$", "$y = xlog(x)$", "$y = x^2$", "$y = 2^x$"]
plt.figure(figsize=(12, 6))
for method, method_label in zip(methods, method_labels):
plt.plot(t, method(t), label=method_label, lw=3)
plt.xlim(1, 20)
plt.ylim(0, 40)
plt.legend()