函数的变量作用域
递归函数
1 # 2 # @author:浊浪 3 # @version:0.1 4 # @time: 2021/4/8 9:57 5 # 6 def fac(n): 7 if n == 1: 8 return 1 9 else: 10 return n * fac(n-1) 11 12 fac(6)
斐波那契数列
该数列的前两个都为1,其后的数都是前两项的和
1 # 2 # @author:浊浪 3 # @version:0.1 4 # @time: 2021/4/8 10:05 5 # 6 7 def fei(n): 8 if n == 1 or n == 2: 9 return 1 10 else: 11 return fei(n-1) + fei(n-2) 12 13 print(fei(17)) #1597 14 15 def xun(n): 16 i = 3 17 a,b,c = 1,1,0 18 x = [0,1,1] 19 while(i <= n): 20 x.append(x[i-1] + x[i-2]) 21 c = a + b 22 a = b 23 b = c 24 i = i+1 25 return c,x[n] 26 27 print(xun(17)) # (1597, 1597)
#
# @author:浊浪
# @version:0.1
# @time: 2021/4/8 10:05
#
def fei(n):
if n == 1 or n == 2:
return 1
else:
return fei(n-1) + fei(n-2)
print(fei(17)) #1597
def xun(n):
i = 3
a,b,c = 1,1,0
x = [0,1,1]
while(i <= n):
x.append(x[i-1] + x[i-2])
c = a + b
a = b
b = c
i = i+1
return c,x[n]
print(xun(17)) # (1597, 1597)