Python基础学习笔记-15.时间复杂度

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()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值