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循環實現

思路是獲取頭尾index,取中間索引值,與要查找的值進行判斷,如果中間值大於要查找的值,那么就在列表的前半部分查找,如果中間值小於要查找的值,那么就在列表后半部分查找,折半查找時候,在更新要查找的切片的頭尾索引值

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))

輸出如下:6

通過遞歸實現

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': {},
                '網易': {},
            }
        },
        '昌平': {
            '沙河': {
                '北航': {},
            },
            '天通苑': {}
        }
    },
    '上海': {
        '閔行': {
            "人民廣場": {
                '炸雞店': {}
            }
        }
    }
}

def menu_3(menu):
    while True:
        for key in menu:
            print(key)      #北京上海山東
        choice = input('選擇 : ')   #北京
        if choice == 'q' or choice == 'b':
            return choice
        elif choice in menu and menu[choice]:        #北京 in menu
            borq =  menu_3(menu[choice])
            if borq == 'q':
                return 'q'

menu_3(menu)


測試如下:

E:\python\python_sdk\python.exe E:/python/py_pro/4.三級菜單.py
北京
上海
選擇 : 北京
海淀
昌平
選擇 : 海淀
五道口
選擇 : 五道口
soho
網易
選擇 : b
五道口
選擇 : b
海淀
昌平
選擇 : b
北京
上海
選擇 : b

Process finished with exit code 0

壓棧

從該數據結構中返回由指定的字段和對應的值組成的字典,如果指定字段不存在就跳過該字段

這道題使用了壓棧的做法

通過data = l.pop()取出最后一個棧內元素賦值變量,意味着將l清空了,如果data里面的鍵在列表field_lst里面,就添加進一個新的result 字典里面,如果data的鍵對應的值是字典,那么就添加進來到l列表,例如{ “fld1”:1,”fld2”:2}
循環完畢后,列表里面就包含了[{‘fld1’: 1, ‘fld2’: 2}, {‘fld3’: 0, ‘fld5’: 0.4}, {‘key’: {‘fld19’: 1}}]

然后開始一個個pop獲取鍵值對

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

注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
粤ICP备14056181号  © 2014-2020 ITdaan.com