'moving through variables in matrix with recursion
I'm trying to write a function which got a kind of a matrix - a list that consists of sub-lists So I want to go through all the matrix members and print them out. Only in recursion! But I dont know how to create a good "stop conditions" for my function. So I get more numbers than I wanted.
def mission(mat):
def move(mat, i=0, j=0 ,k=0):
print(mat[i][j])
if j<(len(mat[0])-1):
move(mat,i,j+1)
if i<(len(mat)-1):
move(mat,i+1,0)
move(mat)
mat = [[1, 0, 0, 3, 0],
[0, 0, 2, 3, 0],
[2, 0, 0, 2, 0],
[0, 1, 2, 3, 3]]
mission(mat)
*edit I got another question - is there a way to decrease 2 list that looks like the mat function i did here (with the same length - just different numbers) without using numpy or for ?
Solution 1:[1]
You can test for end condition on function start, and check if you have already crossed the last item in the last sublist. If so, you return.
if(i == len(mat) - 1 and j == len(mat[0]) - 1):
return
Then, you check whether you are at the last item in your current sublist, and if so, increment the sublist index i and set the item index back to 0.
if(j == len(mat[0]) - 1):
i += 1
j = 0
If you are neither at the end of the whole 2d matrix (list), nor the end of any sublist, you just need to increment the item index j.
else:
j += 1
Then, you can safely call your function recursively. The whole code ends up looking like this.
def move(mat, i=0, j=0):
print(mat[i][j])
if(i == len(mat) - 1 and j == len(mat[0]) - 1):
return
if(j == len(mat[0]) - 1):
i += 1
j = 0
else:
j += 1
move(mat, i, j)
mat = [[1, 0, 0, 3, 0],
[0, 0, 2, 3, 0],
[2, 0, 0, 2, 0],
[0, 1, 2, 3, 3]]
move(mat)
Output::
1
0
0
3
0
0
0
2
3
0
2
0
0
2
0
0
1
2
3
3
Solution 2:[2]
as for the move function, simply change the 2nd if to elif
def move(mat, i=0, j=0):
print(mat[i][j])
if j<(len(mat[0])-1):
move(mat,i,j+1)
elif i<(len(mat)-1):
move(mat,i+1,0)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 |
