递归¶
递归就是函数调用本身,知道满足指定条件之后,一层层退出函数
利用函数编写一个斐波那契数列,斐波那契数列就是前面两个数相加得到后面一个数,依次往后
#!/usr/bin/env python
# _*_ coding:utf-8 _*_
def counter(n1,n2):
# 当要计算的值大于10000就退出
if n1 > 10000:
return
# 输出当前计算到的值
print("Counter: ",n1)
n3 = n1 + n2
counter(n2,n3)
counter(0,1)
执行结果
➜ python_test python3 014-exercise-1.py
Counter: 0
Counter: 1
Counter: 1
Counter: 2
Counter: 3
Counter: 5
Counter: 8
Counter: 13
Counter: 21
Counter: 34
Counter: 55
Counter: 89
Counter: 144
Counter: 233
Counter: 377
Counter: 610
Counter: 987
Counter: 1597
Counter: 2584
Counter: 4181
Counter: 6765
利用递归获取斐波那契数列中的第10个数,并将该值返回给调用者
#!/usr/bin/env python
# _*_ coding:utf-8 _*_
def counter(index,start,end):
print("times: %d, num 1st: %d ,num 2nd: %d" % (index,start,end))
if index == 10:
return start
N = start + end
Number = counter(index + 1,end,N)
return Number
result = counter(1,0,1)
print("num: ",result)
执行结果
➜ python_test python3 014-exercise-2.py
times: 1, num 1st: 0 ,num 2nd: 1
times: 2, num 1st: 1 ,num 2nd: 1
times: 3, num 1st: 1 ,num 2nd: 2
times: 4, num 1st: 2 ,num 2nd: 3
times: 5, num 1st: 3 ,num 2nd: 5
times: 6, num 1st: 5 ,num 2nd: 8
times: 7, num 1st: 8 ,num 2nd: 13
times: 8, num 1st: 13 ,num 2nd: 21
times: 9, num 1st: 21 ,num 2nd: 34
times: 10, num 1st: 34 ,num 2nd: 55
num: 34