0

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]])
3
  • What exactly do you want to ask us? Commented Oct 19, 2022 at 20:41
  • FWIW, it is probably better to use an empty array as the edge condition and return 0. Currently your sum_arr() function fails on sum_arr([]) instead returning 0, which seems more correct. Commented Oct 19, 2022 at 20:47
  • your sum_arr should be return 0 if not arr else arr[0] + sum_arr(arr[1:]) Commented Oct 19, 2022 at 21:26

1 Answer 1

1

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]])
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, you are correct, what a silly mistake I did :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.