day17 python递归案例(二分查找,三级菜单)

递归函数与三级菜单

day17 python递归案例(二分查找,三级菜单)
menu = {
    '北京': {
        '海淀': {
            '五道口': {
                'soho': {},
                '网易': {},
                'google': {}
            },
            '中关村': {
                '爱奇艺': {},
                '汽车之家': {},
                'youku': {},
            },
            '上地': {
                '百度': {},
            },
        },
        '昌平': {
            '沙河': {
                '老男孩': {},
                '北航': {},
            },
            '天通苑': {},
            '回龙观': {},
        },
        '朝阳': {},
        '东城': {},
    },
    '上海': {
        '闵行': {
            "人民广场": {
                '炸鸡店': {}
            }
        },
        '闸北': {
            '火车战': {
                '携程': {}
            }
        },
        '浦东': {},
    },
    '山东': {},
}
menu day17 python递归案例(二分查找,三级菜单)
def caidan(dic):
    if dic:
        for k in dic:
            print(k)
        city = input('>>>')
        if city in dic:
            return caidan(dic[city])
        else:
            return '没找到啊'
    else:
        return "传入的字典是空的"
print(caidan(menu))
答案一 day17 python递归案例(二分查找,三级菜单)
def threeLM(dic):
    while True:
        for k in dic: print(k)
        key = input('input>>').strip()
        if key == 'b' or key == 'q': return key
        elif key in dic.keys() and dic[key]:
            ret = threeLM(dic[key])
            if ret == 'q': return 'q'

threeLM(menu)
答案二

二分查找算法

二分查只能用在排序过得序列中

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]
def search(num,l,start=None,end=None):
    start = start if start else 0
    end = end if end is None else len(l) - 1
    mid = (end - start)//2 + start
    if start > end:
        return None
    elif l[mid] > num :
        return search(num,l,start,mid-1)
    elif l[mid] < num:
        return search(num,l,mid+1,end)
    elif l[mid] == num:
        return mid

 

上一篇:day17


下一篇:python day17