递归
递归
-
递归的最大深度1000层 目的:为了节省内存空间,不要让用户无限次使用内存空间
-
递归比循环更占用内存
-
修改递归的深度
import sys sys.setrecursionlimit(100) count=0 def func(): global count count+=1 print(count) func() func()
-
停止递归 (写条件使用return停止)
#当count等于3的时候停止 count=0 def func(): global count count+=1 print(count) if count==3:return func() func() # 得:1 2 3
-
将内存函数的值,返回给外层函数的值
count=0 def func(): global count count+=1 if count==3:return count s1=func() return s1 print(func()) # 得:3
-
小练习
- 计算4的阶乘
def fact(n): if n==1: return 1 else: return n*fact(n-1) ret=fact(4) print(ret) #得 24 #过程 # 4*3 #4*(3*2) #4*(3*(2*1))
-
打印文件夹内所有的文件和计算文件的大小
- 方式一
import os # def inner(): count = 0 def baoli(n): nonlocal count list1 = os.listdir(n) for i in list1: s1 = os.path.join(n, i) if os.path.isfile(s1): s2 = os.path.getsize(s1) print(s1) count += s2 else: baoli(s1) return count return baoli s=inner() print(s('E://baoli')) #*****
- 方式二
import os count=1 s1=os.walk(r'E:\baoli', topdown=True, onerror=None, followlinks=False) for a,b,c in s1: print(a,b,c) for i in c: s2=os.path.join(a,i) count+=os.path.getsize(s2) print(count)
-
斐波那契
# 方式一: for 循环 a=1 b=1 c=0 for i in range(1,11): if i == 1: print(a,b,end=' ') #1,1 else: c=a+b #2,3,5,8,13 print(c, end=' ') a=b #1,2,3,5,8 b=c #2,3,5,8,13 # 方式二 :此方法不好,因为每次打印都需要重头开始循环 def a(n): a,b=0,1 for i in range(n+1): a,b=b,a+b return a for b in range(11): print(a(b),end=' ') # 方式三:while循环 a=0 b=1 while b<100: print(b,end=' ') a,b=b,a+b #方式四:递归 def fb(n): if n<=1: return 1 else: return fb(n-1)+fb(n-2) for i in range(10): print(fb((i)))