实例1:斐波那契数列
# 1 1 2 3 5 8 13 # 计算n位的数vi def fibo(n): if n <= 2: return 1 return fibo(n - 1) + fibo(n - 2) #计算比n小的最大数是数列中的第几位 print(fibo(n)) def func(m): n = 1 while True: # if fibo(n) > m and fibo(n - 1) < m: if fibo(n + 1) > m >= fibo(n): return n else: n += 1
def fib(n): f1 = f2 = 1 for i in range(2, n): f1, f2 = f2, (f2 + f1) return f2 def fib_n(n): if n <= 2: return 1 return fib_n(n-1) + fib_n(n-2)
实例二:计算路径中总文件的大小
递归
# 用递归方法计算文件夹的大小 def cal_size(file_path): file_size = 0 file_name = os.listdir(file_path) for name in file_name: name_path = os.path.join(file_path, name) if os.path.isdir(name_path): file_size += cal_size(name_path) else: file_size += os.path.getsize(name_path) return file_size print(cal_size("H:\GamePatch"))
循环方法:
lst = ["H:\GamePatch", ] file_size = 0 while lst: file_name = lst.pop() file_path = os.listdir(file_name) for name in file_path: name_new = os.path.join(file_name, name) if os.path.isdir(name_new): lst.append(name_new) else: file_size += os.path.getsize(name_new) print(file_size)