zoukankan      html  css  js  c++  java
  • 尾递归

    尾递归

    只返回递归函数自己, 而非表达式(不带有运算)

    """
    在内存里之开辟一块栈帧空间, 节省内存,
    cpython不支持
    尾递归使用参数来进行运算的
    """

    阶乘的尾递归

     1 # 阶乘的尾递归
     2 
     3 def jiecheng(n, val):
     4    if n == 1:
     5       return val
     6    return jiecheng(n-1, val*n)
     7 
     8 res = jiecheng(5, 1)
     9 print(res)
    10 
    11 """
    12 去的过程:
    13 n = 5  jiecheng(5-1, 1*5)
    14 n = 4  jiecheng(4-1, 1*5*4)
    15 n = 3  jiecheng(3-1, 1*5*4*3)
    16 n = 2  jiecheng(2-1, 1*5*4*3*2)
    17 n = 1  return val 1*5*4*3*2
    18 
    19 回的过程:
    20 retrun val 
    21 从最内层递归函数返回到最外层递归函数
    22 
    23 """

    斐波那契尾递归

     1 # 斐波那契_尾递归
     2 def fbnq(n, tem, total):
     3    if n == 1:
     4       return tem
     5    return fbnq(n-1, total, tem+total)
     6 
     7 
     8 print(fbnq(5, 1, 1))
     9 """
    10 去的过程:
    11 n = 5  fbnq(5-1, 1, 1+1)
    12 n = 4  fbnq(4-1, 1+1, 1+1+1)
    13 n = 3  fbnq(3-1, 1+1+1, 1+1+1+1+1)
    14 n = 2  fbnq(2-1, 1+1+1+1+1, 1+1+1+1+1+1+1+1)
    15 n = 1  return tem 1+1+1+1+1
    16 
    17 回的过程:
    18 从内层递归函数返回到顶层递归函数
    19 return temp
    20 """
    21 
    22 
    23 
    24 # 斐波那契_普通
    25 def fbnq(n):
    26    if n <= 2:
    27       return 1
    28    return fbnq(n-1) + fbnq(n-2)
    29 
    30 
    31 print(fbnq(6))
  • 相关阅读:
    javaee 第六周作业
    javaee 第五周作业
    javaee 第四周作业
    第三周作业
    第二周作业xml学习情况
    javaWeb 中http请求 get 与 post的区别
    第八周
    第七周
    第六周
    第五周
  • 原文地址:https://www.cnblogs.com/caihuajiaoshou/p/10611934.html
Copyright © 2011-2022 走看看