1. 程式人生 > >遞歸與循環

遞歸與循環

urn patch .get style ron list cal 大數 pop

實例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 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)

遞歸與循環