Outline
Recursive function that is directly or indirectly calls itself a function and recursive process must have a clear recursive end condition, called recursive exports. Recursive extremely strong point is able to traverse arbitrary, unpredictable structure of the program, such as traversing complex nested list.
Recursive summation
We can implement a Python built-in functions use a recursive function sum()
recursive version.
# 递归
def d_sum(L):
if not L:
return 0
else:
return L[0] + d_sum(L[1:])
sum_l = d_sum(range(10))
print(sum_l)
复制代码
Sample results
45
复制代码
The recursive function is how to achieve it by adding a list of the elements? We know there is a local function scope, for each open when the function call, the call has its own copy of a local scope on the stack at run time, that is, L in each level is different, such as our You can add a print statement by each call, more intuitive to show the circumstances of each level L
# 递归
def d_sum(L):
# 打印该层级L
print(L)
if not L:
return 0
else:
return L[0] + d_sum(L[1:])
# 构建 0-10 数字元素列表
L = [i for i in range(10)]
sum_l = d_sum(L)
print(sum_l)
复制代码
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[2, 3, 4, 5, 6, 7, 8, 9]
[3, 4, 5, 6, 7, 8, 9]
[4, 5, 6, 7, 8, 9]
[5, 6, 7, 8, 9]
[6, 7, 8, 9]
[7, 8, 9]
[8, 9]
[9]
[]
45
复制代码
Deal with any structure
For example, we can use the sum of a calculated recursively nested sub-structure list of all the numbers
def dd_sum(L):
tot = 0
for x in L:
if not isinstance(x, list):
tot += x
else:
tot += dd_sum(x)
return tot
# 嵌套列表
L = [1,[2,3],[4,[5,6,7],8],9]
sum_l = dd_sum(L)
print(sum_l)
复制代码
Sample results:
45
复制代码
This approach may seem complicated, we might be more use of alternative loop, but using recursive function logic is clear and simple, this is a big advantage to use.
Reproduced in: https: //juejin.im/post/5cf8eb9351882570ad24ca0a