• Python中的递归函数


    函数递归:函数的递归调用,即在函数调用的过程中,又直接或间接地调用了函数本身

    # 直接调用
    # def foo():
    # print('from foo')
    # foo()
    #
    # foo()

    # 间接调用
    # def bar():
    # print('from bar')
    # foo()
    #
    # def foo():
    # print('from foo')
    # bar()
    #
    # foo()

    在使用递归时,需要注意以下几点:

    • 递归就是在过程或函数里调用自身
    • 必须有一个明确的递归结束条件,称为递归出口。

    注意: 切勿忘记递归出口,避免函数无限调用。

    递归的经典案例

    >>> def factorial(n):
    ...     if n == 1:
    ...         return 1
    ...     else:
    ...         return n * factorial(n - 1)
    ... 
    >>> 
    >>> factorial(1)
    1
    >>> 
    >>> factorial(5)
    120
    >>> 
    >>> factorial(10)
    3628800
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    当使用正整数调用 factorial() 时,会通过递减数字来递归地调用自己。

    为了明确递归步骤,对 5! 进行过程分解:

    factorial(5)                        # 第 1 次调用使用 5
    5 * factorial(4)                    # 第 2 次调用使用 4
    5 * (4 * factorial(3))              # 第 3 次调用使用 3
    5 * (4 * (3 * factorial(2)))        # 第 4 次调用使用 2
    5 * (4 * (3 * (2 * factorial(1))))  # 第 5 次调用使用 1 
    5 * (4 * (3 * (2 * 1)))             # 从第 5 次调用返回
    5 * (4 * (3 * 2))                   # 从第 4 次调用返回
    5 * (4 * 6)                         # 从第 3次调用返回
    5 * 24                              # 从第 2 次调用返回
    120                                 # 从第 1 次调用返回
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    当数字减少到 1 时,递归结束。

    二分法:

    二分查找

    
    
    nums=[1,3,7,11,22,34,44,55,66,77,88,99,111,222,333,444]

    # for item in nums:
    # if item == 10:
    # print('find it')
    # break
    # else:
    # print('not exist') #这种占用大量内存,不推荐,效率低下

    def search(search_num,nums):
    print(nums)
    if len(nums) == 0:
    print('not exists')
    return
    mid_index=len(nums) // 2
    if search_num> nums[mid_index]:
    nums=nums[mid_index+1:]
    search(search_num,nums)
    elif search_num<nums[mid_index]:
    nums=nums[:mid_index]
    search(search_num,nums)
    else:
    print('find it')
    search(31,nums) #二分法
    '''
     
  • 相关阅读:
    fiddler强大功能用法(二)
    fidder强大功能用法(一)
    fidder使用
    postman
    bug的一生:如何体现测试专业度?
    Fiddler无法抓到https的解决方法
    Fiddler工具安装下载使用
    z-index
    position:absolute
    ajax跨域,json,jsonp
  • 原文地址:https://www.cnblogs.com/huyingsakai/p/9182977.html
Copyright © 2020-2023  润新知