zoukankan      html  css  js  c++  java
  • (一)Python入门-5函数:08递归函数

    递归函数:

      递归函数指的是:自己调用自己的函数,在函数体内部直接或间接的自己调用自己。递归类 似于大家中学数学学习过的“数学归纳法”。

      每个递归函数必须包含两个部分:

        1. 终止条件 表示递归什么时候结束。一般用于返回值,不再调用自己。

        2. 递归步骤 把第 n步的值和第 n-1步相关联。

      递归函数由于会创建大量的函数对象、过量的消耗内存和运算能力。在处理大量数据时,谨 慎使用。

    【操作】测试递归函数基本原理

    #测试递归函数基本原理
    
    def test01(n):
        print("test01:",n)
        if n == 0:
            print('over')
        else:
            test01(n-1)
        print("test01***",n)
    
    test01(3)

    运行结果:

      test01: 3
      test01: 2
      test01: 1
      test01: 0
      over
      test01*** 0
      test01*** 1
      test01*** 2
      test01*** 3

    【操作】 使用递归函数计算阶乘(factorial)

    #使用递归函数计算阶乘
    def factorial(n):
        if n == 1:return 1
        return n*factorial(n-1)
    
    print(factorial(5))
    
    for i in range(1,6):
        print(i,"!=",factorial(i))

    运行结果:

      120
      1 != 1
      2 != 2
      3 != 6
      4 != 24
      5 != 120

  • 相关阅读:
    微信分享
    angular 2
    angular 2
    angular 2
    angular 2
    ionic android升级检查
    ionic andorid apk 签名, 查看签名MD5
    微信支付 python版
    CSS3
    ionic 常见问题
  • 原文地址:https://www.cnblogs.com/jack-zh/p/10841583.html
Copyright © 2011-2022 走看看