Reputation: 1
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]])
Upvotes: 0
Views: 94
Reputation: 237
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]])
Upvotes: 1