递归、二分查找

#递归函数: 有最大递归深度,默认接近1000,各版本略有差异
count = 0
def F1(n):
    n += 1
    print(n)#1  2   3……996
    F1(n)

F1(count)

#修改递归深度
import sys

sys.setrecursionlimit(100)

count = 0

def F2(n):
    n += 1
    print(n)  # 1  2   3……96
    F2(n)

F2(count)


#二分查找:必须是无重复数字的有序序列
def binary_search(L, numb, start = 0, end = None):
    if end is None:
        end = len(L) - 1
    m_index = (end - start) // 2 + start
    if start < end:
        if numb < L[m_index]:
            return binary_search(L, numb, start = start, end = m_index)
        elif numb > L[m_index]:
            return binary_search(L, numb, start = m_index, end = end)
        elif numb == L[m_index]:
            return m_index
        else:
            return None
    else:
        return None


L1 = [1, 3, 5, 6, 7, 8, 11, 23, 44, 46, 53]
print(binary_search(L1, 7))#4


#

 

posted @ 2022-09-05 20:46  尐少  阅读(12)  评论(0编辑  收藏  举报