第二章——算法分析

0. 目标

  • To understand why algorithm analysis is important.
  • To be able to use “Big-O” to describe execution time.
  • To understand the “Big-O” execution time of common operations on Python lists and dictionaries.
  • To understand how the implementation of Python data impacts algorithm analysis.
  • To understand how to benchmark simple Python programs.

1. 课程笔记

1.1 如何记录代码的运行时间

如何写好的代码:

  1. 可读性
  2. 考虑空间复杂度
  3. 考虑时间复杂度——可调用python的内置函数记录程序运行的时间
import time

def sumOfN3(n):
   start = time.time()
   theSum = (n * (n + 1)) / 2
   end = time.time()

   return theSum,end-start

for i in range(5):
       print("Sum is %d required %10.7f seconds"%sumOfN3(100000))

1.2 big-O (big order)

O(n^2)和O(n)的对比

### bad algorithm-find the smallest number O(n^2) ####
import time
from random import randrange

def find_min(list):
    n = len(list)
    for i in range(n):
        for j in range(n):
            if list[j] < list[i]:
                continue
    print('the smallest number is', list[i])

def mainA():
    list = [5, 4, 3, 2, 1, 0]
    find_min(list)

def mainB():
    for listsize in range(1000, 10001, 1000):
        list = [randrange(100000000) for x in range(listsize)]
        start = time.time()
        find_min(list)
        end= time.time()
        print ("size: %d time: %f " % (listsize, end-start))

mainB()

#### good algorithm O(n) ######

def Find_Min(list):
    flag = list[0]
    for i in list:      ##python很高级,可以直接循环list!
        if i < flag:
            flag = i
    return flag
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 悄悄的,把旧梦埋葬,合上薄厚不均的前尘往事,只在扉页镌刻着久违难忘的铭心,枕着一缕馨香恬然入眠。下一世,待伊蓦然回...
    镜时柘阅读 264评论 0 1
  • 好了,不计时的整套题做下来,你已经知道在实力全部发挥的前提下自己大概可能拿到多少分。 也许你是理工科学生,甚至和我...
    王滚滚打小怪兽阅读 173评论 2 1
  • 梦之殇 梦啊 犹如一个精灵 飘飘悠悠 溜进我的脑袋 为我编织 甜美的意境 使我沉醉 梦啊 犹如一杯美酒 幸福的味蕾...
    听风识音阅读 319评论 0 0
  • 喜欢独处的人,看似独来独往、沉默寡言,甚至有人还将这种性格的人称之为“独行侠”,其实却是一种优良的品性、一种难得的...
    韩小暖m阅读 704评论 0 1