11_資料結構_遞迴_Python實現
阿新 • • 發佈:2018-12-18
#Created By: Chen Da """ 階乘函式就是典型的遞迴: def fact(n): if n == 0: return 1 else: return n * fact(n-1) 遞迴的特點: 遞迴必須包含一個基本的出口(base case),否則就會無限遞迴,最終導致棧溢位。比如這裡就是n==0時返回1. 遞迴必須包含一個可以分解的問題(recursive case)。想求得fact(n),就要用n*fact(n-1)。 遞迴必須要向著遞迴出口靠近(toward the base case)。這裡每次遞迴呼叫都會n-1,向著遞迴出口n==0靠近。 """ ''' #倒序列印 def print_new(n): if n > 0: print(n) print_new(n - 1) #尾遞迴 print_new(10) ''' #匯入內建雙端佇列 from collections import deque #計算機中是用棧來實現遞迴 #定義一個棧 class Stack(object): def __init__(self): self._deque = deque() def push(self,value): return self._deque.append(value) def pop(self): return self._deque.pop() def is_empty(self): return len(self._deque) == 0 def print_stack(n): s = Stack() while n > 0: #n不為0時持續入棧 s.push(n) n -= 1 while not s.is_empty(): #s不為空時,後進先出 print(s.pop()) print_stack(10)