algorithm:一個計算過程,解決問題的方法
程序設計=數據結構+算法
輸入→算法→輸出
數據結構就是關係python
用來估計算法運行時間的一個式子,通常來講時間複雜度高的算法比複雜度低的算法慢算法
print('hello') # O1 無循環 for i in range(n): # O(n) 一層循環 print('hello') for i in range(n): # O(n2) 2層循環 for j in range(n): print('hello') while n > 1: # O(logn) 每次循環減半 print(n) n = n//2
用來評估算法內存佔用大小的式子數據結構
遞歸的兩個特色函數
def func1(x): if x > 0: print(x) func1(x - 1) # 3 2 1 def func2(x): if x > 0: func2(x - 1) print(x) # 1 2 3
對上述結果的解釋設計
def hanoi(n, a, b, c): ''' 一共n層,盤子從a通過b移動到c ''' if n > 0: hanoi(n - 1, a, c, b) print('moving from %s to %s' % (a, c)) hanoi(n - 1, b, a, c) hanoi(3,'A','B','C') ''' moving from A to C moving from A to B moving from C to B moving from A to C moving from B to A moving from B to C moving from A to C '''