递归和二分法

l=[1,[2,[3,[4,[5,[6,[7,[8,[9,[10,[11,]]]]]]]]]]]

def search(l):
     for item in l:
         if type(item) is not list:
             # 不是列表直接打印
             print(item)
         else:
             # 判断是列表则继续循环,判断...
             search(item)

 search(l)

nums=[13,15,17,23,31,53,74,81,93,102,103,201,303,403,503,777]
find_num=503


def binary_search(nums,find_num):
    print(nums)
    if len(nums) == 0:
        print('not exists')
        return
    mid_index=len(nums) // 2
    if find_num > nums[mid_index]:
        # in the right
        nums=nums[mid_index+1:]
        # 重新执行二分的逻辑
        binary_search(nums,find_num)
    elif find_num < nums[mid_index]:
        #in the left
        nums=nums[0:mid_index]
        # 重新执行二分的逻辑
        binary_search(nums,find_num)
    else:
        print('find it')

 

posted @ 2020-08-05 23:55  xuqidong  阅读(134)  评论(0编辑  收藏  举报