已知:F(0) = 0, F(1) = 1, F(n) = F(n-1) + F(n-2) 其中(n≥2,n∈N*)函數
求:求10之內的函數值分別是多少spa
方法一:code
def F(n): if n <= 1: return 1 else: return F(n-1) + F(n-2) for i in range(100): print(i,"-->",F(i))
方法二:blog
def F(n): x,a,b=0,0,1 while x < n: a,b = b,a+b x += 1 return b for i in range(100): print(i,"-->",F(i))
說明二者都是循環語句是能夠替換遞歸邏輯的,且循環語句要比遞歸運行效率高!遞歸