Recursive functions can be used when the depth of the nested structure is uncertain. (When handling JSON file data, etc.)
To call yourself (function) in a function. └ Literally "recursive", return to yourself again.
--A termination condition is required. --If you don't, you will end up in an infinite loop. --The default limit is 1000 times.
python
def sum(n):
#Exit conditions
if n <= 0:
return n
#Call yourself(Recursive function)
return n + sum(n-1)
If n = 4, add the numbers 4,3,2,1 in order.
Function execution result
sum(4)
#output
10
If you enter an integer greater than or equal to 0
(1) The first thing to be executed is n + sum (n-1)
(2) After entering a numerical value in n, perform sum (n-1)
.
└ The argument becomes "n-1".
(3) If n-1 is greater than 0, repeat n + sum (n-1)
.
Data can be obtained from a multidimensional array by combining if statements, for statements, and recursive functions.
python
data0 = [1,[2]]
def number(arr):
#Prepare a list to put the result
result=[]
#If it is an integer, add it to result
if isinstance(arr, int):
result.append(arr)
#Processing in case of list type
if isinstance(arr, list):
for brr in arr:
#Recursive function. Execution result(result)To add
result += number(brr)
#Function return value
return result
number(data0)
#output
[1, 2]
Set a return value (return). * Be careful of the location
python
data1 = [1,[2],[[3]],[[[[4]]]],[[[[5,6,7],8,9]]],10]
def number(arr):
result=[]
if isinstance(arr, int):
result.append(arr)
if isinstance(arr, list):
for brr in arr:
result += number(brr)
return result
number(data1)
#output
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Recommended Posts