### python基礎-遞歸、二分法查找（for\遞歸）、三級菜單、壓棧思想

#### 遞歸方法

``````
# age(1) n = 1 age(2)+2
# age(2) n = 2 age(3)+2
# age(3) n = 3 age(4)+2
# age(4) n = 4 40

def age(n):
if n == 4:
return 40
return age(n+1)+2

print(age(1))

``````

``````E:\python\python_sdk\python.exe E:/python/py_pro/1.初識遞歸.py
46

Process finished with exit code 0
``````

#### 二分法查找

##### 通過for循環實現

``````def method(mLis,mVal):
minIndex = 0
maxIndex = len(mLis) -1
while True:
centerIndex = (minIndex + maxIndex) // 2
centerValue = mLis[centerIndex]

if centerValue < mVal:#右邊
minIndex = centerIndex + 1
if centerValue > mVal:#左邊
maxIndex = centerIndex  - 1
if centerValue == mVal:
return centerIndex

print(method(l,18))``````

##### 通過遞歸實現
``````
def find_2(l,aim,start=0,end=None):  #[2,3,5,10,15,16,18,22,26,30,32,35,41,42,43,55,56,66,67,69,72,76,82,83,88]
if end == None:end = len(l) - 1  #start = 0,end = 24
if start <= end:
mid = (end-start) // 2  + start  #mid = 12
if l[mid] > aim:
ret = find_2(l,aim,start,mid-1)
return ret
elif l[mid] < aim:              #
ret = find_2(l,aim,mid+1,end)     #find_2(l,58,13,24)
return ret
else:
return aim,mid
else:
print('找不到這個值')
l = [2,3,5,10,15,16,18,22,26,30,32,35,41,42,43,55,56,66,67,69,72,76,82,83,88]
print(find_2(l,22))

``````

``(22, 7)``

#### 遞歸應用–三級菜單

``````menu = {
'北京': {
'海淀': {
'五道口': {
'soho': {},
'網易': {},
}
},
'昌平': {
'沙河': {
'北航': {},
},
'天通苑': {}
}
},
'上海': {
'閔行': {
"人民廣場": {
'炸雞店': {}
}
}
}
}

while True:
print(key)      #北京上海山東
choice = input('選擇 : ')   #北京
if choice == 'q' or choice == 'b':
return choice
if borq == 'q':
return 'q'

``````

``````E:\python\python_sdk\python.exe E:/python/py_pro/4.三級菜單.py

soho

Process finished with exit code 0
``````

#### 壓棧

``````fields = "fld2|fld5|fld6|fld19|fld7|fld46"
data={"time":"2016-08-05T13:13:05",
"some_id":"ID1234",
"grp1":{ "fld1":1,"fld2":2},
"xxx2":{ "fld3":0,"fld5":0.4},
"fld6":{"key":{ "fld19":1}},
"fld7":7,
"fld46":8}
#計算機思想:壓棧，Alex
def select(data,fields):
l = [data]
field_lst = fields.split('|')
result = {}
while l:

data = l.pop()     #data = { "fld1":1,"fld2":2}

for key in data:
if type(data[key]) == dict:
l.append(data[key])   # l = [{ "fld1":1,"fld2":2},{ "fld3":0,"fld5":0.4},{"key":{ "fld19":1}}]
elif key in field_lst:
result[key] = data[key]
print("-----",l)
return result

print(select(data,fields))``````

``````E:\python\python_sdk\python.exe E:/python/py_pro/python.py
----- [{'fld1': 1, 'fld2': 2}, {'fld3': 0, 'fld5': 0.4}, {'key': {'fld19': 1}}]
----- [{'fld1': 1, 'fld2': 2}, {'fld3': 0, 'fld5': 0.4}, {'fld19': 1}]
----- [{'fld1': 1, 'fld2': 2}, {'fld3': 0, 'fld5': 0.4}]
----- [{'fld1': 1, 'fld2': 2}]
----- []
{'fld7': 7, 'fld46': 8, 'fld19': 1, 'fld5': 0.4, 'fld2': 2}

Process finished with exit code 0
``````