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]])
sum_arr()function fails onsum_arr([])instead returning0, which seems more correct.sum_arrshould bereturn 0 if not arr else arr[0] + sum_arr(arr[1:])