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

Sum matrix using recursion in python

I need to create a func that calculate the sum of 2d arr (matrix) for example sum of [[1,1,1],[2,2,2]] would give 9.
I tried solving it using two functions – one calls the other but had an error.
It seems that when it gets to the second arr and on, it passes an arr in arr like that [[]] so it iterates threw another arr not threw the numbers.
I prefer not to use libraries in this case.

This is my code:

def sum_arr(arr):
    s = 0
    if len(arr) == 1:
        s += arr[0]
    else:
        s += (arr[0] + sum_arr(arr[1:]))
    return s

def sum_mat(mtx):
    sm = 0
    if len(mtx) == 1:
        sm += sum_arr(mtx[0])
    else:
        sm += sum_arr(mtx[0]) + sum_arr(mtx[1:])

    return sm

sum_mat([[1, 2, 3],[1,2,4],[7,8,9]])

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 :

I think your problem is that you accidentally are not recursively calling sum_mat. You call sum_arr on arr[0] then call it again on arr[1:]. Try:

def sum_arr(arr):
    s = 0
    if len(arr) == 1:
        s += arr[0]
    else:
        s += (arr[0] + sum_arr(arr[1:]))
    return s

def sum_mat(mtx):
    sm = 0
    if len(mtx) == 1:
        sm += sum_arr(mtx[0])
    else:
        sm += sum_arr(mtx[0]) + sum_mat(mtx[1:]) #changed this line here to fix repeat sum_arr call

    return sm

sum_mat([[1, 2, 3],[1,2,4],[7,8,9]])
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