Python 递归经典案例

阶乘和二分查找


def factorial1(n):
    """
    传统思维:使用循环求阶乘
    :param n:
    :return:
    """
    result = n
    for i in range(1, n):
        result *= i
    return result


def factorial2(n):
    """
    递归思维求阶乘
    :param n:
    :return:
    """
    if n == 1:
        result = 1
    else:
        result = n * factorial2(n-1)
    return result


def binary_search(sequence, number, lower, upper):
    """
    二分查找递归方法
    :param sequence:
    :param number:
    :param lower:
    :param upper:
    :return:
    """
    if number in sequence:
        if lower == upper:
            assert number == sequence[upper]
            return upper
        else:
            middle = (lower + upper) // 2
            if number > sequence[middle]:
                return binary_search(sequence, number, middle + 1, upper)
            else:
                return binary_search(sequence, number, lower, middle)
    else:
        print("列表中无此数字!")


def bin_search(data_list, val):
    """
    二分查找,传统思维
    :param data_list:
    :param val:
    :return:
    """
    low = 0                         # 最小数下标
    high = len(data_list) - 1       # 最大数下标
    while low <= high:
        mid = (low + high) // 2     # 中间数下标
        if data_list[mid] == val:   # 如果中间数下标等于val, 返回
            return mid
        elif data_list[mid] > val:  # 如果val在中间数左边, 移动high下标
            high = mid - 1
        else:                       # 如果val在中间数右边, 移动low下标
            low = mid + 1
    return  # val不存在, 返回None


if __name__ == '__main__':
    sequence = range(101)
    # index = binary_search(sequence, 200, 0, len(sequence)-1)
    index = bin_search(sequence, 200)
    print(index)



你可能感兴趣的:(Python 递归经典案例)