Home > Software engineering >  Recursive function to find position of number within a matrix
Recursive function to find position of number within a matrix

Time:06-14

I have to make this small recursion exercise where, given a matrix and a number I have to return the position of the number in the matrix. For example:

matrix = [[2,0,1],[3,5,3],[5,1,4,9],[0,5]]
numberToFind = 5

The expected result would be this one:

[(1,1),(2,0),(3,1)]

Could anyone pint me on how to start or what I have to do to create the code? I'm new to recursion.

CodePudding user response:

Here is one approach using a recursive generator:

matrix = [[2,0,1],[3,5,3],[5,1,4,9],[0,5]]
numberToFind = 5

def find(m, n, prev=tuple()):
    for i,x in enumerate(m):
        if isinstance(x, list):
            yield from find(x, n, prev=prev (i,))
        elif x==n:
            yield prev (i,)
            
list(find(matrix, numberToFind))

output: [(1, 1), (2, 0), (3, 1)]

other example:

matrix = [[2,0,1],[3,5,3],[5,1,4,5],[0,5],[[[2,5,[1,5]]]]]
list(find(matrix, numberToFind))

# [(1, 1), (2, 0), (2, 3), (3, 1), (4, 0, 0, 1), (4, 0, 0, 2, 1)]

CodePudding user response:

you can use just a single for loop as below. Way more efficient than a recursion

matrix = [[2,0,1],[3,5,3],[5,1,4,9],[0,5]]

my_list = []

for x in range(0,len(matrix)):
  try:
    a = matrix[x].index(5)
    my_list.append((x,a))
  except ValueError:
    pass
  • Related