Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Recursive function to find position of number within a matrix

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading