函数递归

函数递归

  • 函数递归:函数重复地调用自己,这叫递归。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    # 函数不断地内部调用
    def d():
        return '232'
     
    def c():
        r = d()
        return r
     
    def b():
        r = c()
        return r
     
    def a():
        r = b()
        print(r)
    a()
     
    -----
    232
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    #函数重复调用自己,叫做递归
    def func(n):
        n +=1
        if n >= 5:
            return 'a'
        return func(n)
     
    r = func(1)
    print(r)
     
    -----
    a

  • 使用递归 7*6*5*4*3*2*1​

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    #方法一
    def factorial(num):
      
        if num>1:
            return num*factorial(num-1)
        else:
            return 1
      
    sum =factorial(7)
    print(sum)
    ------
    5040
  • 阶乘变换(11*9*7*5*3*1)(12*10*8*6*4*2)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    def fa1(a):
     
        if a%2 == 0:
            if a > 2:
                return a*fa1(a-2)
            else:
                return 2
            pass
        else:
            if a > 1:
                return a*fa1(a-2)
            else:
                return 1
     
    b = fa1(11)
    c = fa1(12)
    print(b,c)
    -----
    10395 46080







posted @ 2016-11-20 21:58  Diligent小十  阅读(129)  评论(0编辑  收藏  举报