(二)遞歸code
遞歸須要知足三個條件:orm
(1)一個問題的解能夠分解成幾個子問題的解 (2)這個問題與分解以後的子問題,除了數據規模不一樣,求解思路徹底同樣 (3)存在遞歸終止條件
寫遞歸代碼的關鍵也是,找到遞推公式和終止條件遞歸
案例1 階乘ip
#循環實現 #時間O(n) #空間O(1) def factorial(n): result = 1 for i in range(1, n+1): result *= i return result #遞歸實現 #時間O(n) #空間O(n) ef factorial_recursive(n): if n == 1: return 1 return n * factorial_recursive(n - 1)
案例2 斐波那契數列ci
#遞歸實現 #時間O(2^n) def fibonacci1(n): assert(n>0) if (n <= 2): return 1 return fibonacci2(n-1) + fibonacci2(n-2) #循環實現 #時間O(n) def fibonacci2(n): assert(n>0) a,b=0,1 for i in range(1,n+1): a,b=b,a+b return a def fibonacci3(n): assert(n>0) if (n <= 1): return (n,0) (a, b) = fibonacci3(n-1) return (a+b, a)
案例3 打印尺子rem
(熱身)打印一下內容:it
1io
1 2 1form
1 2 1 3 1 2 1transform
1 2 1 3 1 2 1 4 1 2 1 3 1 2 1
#時間O(2^n) def ruler_bad(n): assert(n>=0) if (n==1): return "1" return ruler(n-1) + " " + str(n) + " " + ruler(n-1) #時間O(n) def ruler(n): assert(n>=0) if (n==1): return "1" t = ruler(n-1) return t + " " + str(n) + " " + t #循環實現 def ruler2(n): result = "" for i in range(1, n+1): result = result + str(i) + " " + result return result
畫尺子:
#畫橫線 def draw_line(tick_length, tick_label=''): line = '-' * tick_length if tick_label: line += ' ' + tick_label print(line) #畫每個大格子 def draw_interval(center_length): if center_length > 0: draw_interval(center_length - 1) draw_line(center_length) draw_interval(center_length - 1) #畫多個格子 def draw_rule(num_inches, major_length): draw_line(major_length, '0') for j in range(1, 1 + num_inches): draw_interval(major_length - 1) draw_line(major_length, str(j))
案例4 數字表達式
Given two integers a ≤ b, write a program that transforms a into b by a minimum sequence of increment (add 1) and unfolding (multiply by 2) operations.
For example,
23 = ((5 * 2 + 1) * 2 + 1)
113 = ((((11 + 1) + 1) + 1) * 2 * 2 * 2 + 1)
def intSeq(a, b): if (a == b): return str(a) if (b % 2 == 1): return "(" + intSeq(a, b-1) + " + 1)" if (b < a * 2): return "(" + intSeq(a, b-1) + " + 1)" return intSeq(a, b/2) + " * 2";
案例5 漢諾塔
def hanoi(n, start, end, by): if (n==1): print("Move from " + start + " to " + end) else: hanoi(n-1, start, by, end) hanoi(1, start, end, by) hanoi(n-1, by, end, start)