def calc(n):
print(n)
if int(n / 2) == 0:
return n
res = calc(int(n / 2))
print("res::",res)
print("返回值:",n)
return res
ret = calc(10)
print(ret)
輸出:
10
5
2
1
res:: 1
返回值: 2
res:: 1
返回值: 5
res:: 1
返回值: 10
1html
畫個圖理解:數據結構
import time person_list=['alex','wupeiqi','yuanhao','linhaifeng'] def ask_way(person_list): print('-'*60) if len(person_list) == 0: return '沒人知道路。。。' person=person_list.pop(0) if person == 'linhaifeng': return '%s說:我知道,老男孩就在沙河匯德商廈,下地鐵就是' %person print('hi 美男[%s],敢問路在何方' %person) print('%s回答道:我不知道,但念你慧眼識豬,你等着,我幫你問問%s...' %(person,person_list)) time.sleep(3) res=ask_way(person_list) print('%s問的結果是: %res' %(person,res)) return res res=ask_way(person_list) print(res)
#打印結果 #------------------------------------------------------------ # hi 美男[alex],敢問路在何方 # alex回答道:我不知道,但念你慧眼識豬,你等着,我幫你問問['wupeiqi', 'yuanhao', 'linhaifeng']... # ------------------------------------------------------------ # hi 美男[wupeiqi],敢問路在何方 # wupeiqi回答道:我不知道,但念你慧眼識豬,你等着,我幫你問問['yuanhao', 'linhaifeng']... # ------------------------------------------------------------ # hi 美男[yuanhao],敢問路在何方 # yuanhao回答道:我不知道,但念你慧眼識豬,你等着,我幫你問問['linhaifeng']... # ------------------------------------------------------------ # yuanhao問的結果是: 'linhaifeng說:我知道,老男孩就在沙河匯德商廈,下地鐵就是'es # wupeiqi問的結果是: 'linhaifeng說:我知道,老男孩就在沙河匯德商廈,下地鐵就是'es # alex問的結果是: 'linhaifeng說:我知道,老男孩就在沙河匯德商廈,下地鐵就是'es # linhaifeng說:我知道,老男孩就在沙河匯德商廈,下地鐵就是
1. 必須有一個明確的結束條件ide
2. 每次進入更深一層遞歸時,問題規模相比上次遞歸都應有所減小函數
3. 遞歸效率不高,遞歸層次過多會致使棧溢出(在計算機中,函數調用是經過棧(stack)這種數據結構實現的,每當進入一個函數調用,棧就會加一層棧幀,每當函數返回,棧就會減一層棧幀。因爲棧的大小不是無限的,因此,遞歸調用的次數過多,會致使棧溢出)優化
堆棧掃盲http://www.cnblogs.com/lln7777/archive/2012/03/14/2396164.html spa
尾遞歸優化:http://egon09.blog.51cto.com/9161406/1842475code
data = [1, 3, 6, 7, 9, 12, 14, 16, 17, 18, 20, 21, 22, 23, 30, 32, 33, 35] def binary_search(dataset,find_num): print(dataset) if len(dataset) >1: mid = int(len(dataset)/2) if dataset[mid] == find_num: #find it print("找到數字",dataset[mid]) elif dataset[mid] > find_num :# 找的數在mid左面 print("\033[31;1m找的數在mid[%s]左面\033[0m" % dataset[mid]) return binary_search(dataset[0:mid], find_num) else:# 找的數在mid右面 print("\033[32;1m找的數在mid[%s]右面\033[0m" % dataset[mid]) return binary_search(dataset[mid+1:],find_num) else: if dataset[0] == find_num: #find it print("找到數字啦",dataset[0]) else: print("沒的分了,要找的數字[%s]不在列表裏" % find_num) binary_search(data,66)