zoukankan      html  css  js  c++  java
  • python 基础11-递归

    1、递归特点:

      1、递归类似循环

      2、递归必须有一个明确的结束条件

      3、每次进入更深一层递归时,问题规模相比上次递归都应有所减少

      4、递归效率不高,递归层次过多会导致栈溢出

    2、递归的函数:

    # 处于死循环
    import time
    def a(n):
         print(n)
         time.sleep(1)
         a(n)
    a(10)
    
    
    # 打印10,5,2,1
    def calc(n):
        print(n)
        if int(n/2) == 0:
            return n
        return calc(int(n/2))  #相当于 内部调用函数
    calc(10)
    # ==
    def calc(n):
        print(n)
        if int(n/2) == 0:
            return n
        res = calc(int(n/2))  #相当于内部调用
        return res  #一直不执行
    calc(10)
    
    # 问路 A->B->C->D,D->C->B->A
    import time
    person_list=['alex','wupeiqi','yuanhao','linhaifeng']
    def ask_way(person_list):
        print('-'*60)
        if len(person_list) == 0:
            return '没人知道'
        person=person_list.pop(0)
        if person == 'linhaifeng':
            return '%s说:我知道,老男孩就在沙河汇德商厦,下地铁就是' %person
        print('hi 美男[%s],敢问路在何方' %person)
        print('%s回答道:我不知道,但念你慧眼识猪,你等着,我帮你问问%s...' %(person,person_list))
        time.sleep(3)
        res=ask_way(person_list)
        # print('%s问的结果是: %res' %(person,res))
        return res
    
    res=ask_way(person_list)
    print(res)
  • 相关阅读:
    HDU 5775 Bubble Sort
    HDU 5763 Another Meaning
    HDU 5773 The All-purpose Zero
    HDU 5768 Lucky7
    HDU 5769 Substring
    SPOJ 705 New Distinct Substrings
    POJ 3261 Milk Patterns
    HDU 1521 排列组合 指数型母函数
    HDU 1023 Traning Problem (2) 高精度卡特兰数
    HDU 2082 母函数模板题
  • 原文地址:https://www.cnblogs.com/zhuanfang/p/12547542.html
Copyright © 2011-2022 走看看