zoukankan      html  css  js  c++  java
  • Python-递归

    一、使用递归的准则

    1、函数自己调用自己,且规模逐渐缩小

    2、要有递归终止条件,不然就会无限调用

    二、经典递归函数

    #求n的阶乘
    def fac(n):
        if n == 0 or n == 1: #递归终止条件
            return 1
        else: #否则,缩小规模,再次调用自己
            return n * fac(n-1) 

    三、统计文件夹中有多少个文件

    def filenums(path1, count=0): #count中保存文件个数
        list_path = os.listdir(path1) #取出当前目录下的所有文件和子文件夹
        for path_tmp in list_path:
            fw = os.path.join(path1, path_tmp) #取出每个文件和子文件夹的绝对路径
            if os.path.isfile(fw): #若是文件,则count+1
                count += 1
            elif os.path.isdir(fw):#若是文件夹,则把该文件夹和当前count作为输入,再次调用函数
                count = filenums(fw, count)
        return count
    path = r'D:python_trainingday5f'
    print('该目录下的文件个数为:', filenums(path))
    #将count定义为全局变量,作用和上一个程序相同
    def filenums(path1):
        count = 0
        list_path = os.listdir(path1)
        for path_tmp in list_path:
            fw = os.path.join(path1, path_tmp)
            if os.path.isfile(fw):
                count = count+1
            elif os.path.isdir(fw):
                count = count + filenums(fw)
        return count
  • 相关阅读:
    bzoj1009
    bzoj1576 3694
    bzoj3143
    bzoj1391
    bzoj2729
    bzoj2653
    bzoj3261
    bzoj2326
    人件
    优秀的产品
  • 原文地址:https://www.cnblogs.com/jessicaxu/p/7708034.html
Copyright © 2011-2022 走看看