Reputation:
This is my code to find the sum of all the elements of all columns in a given matrix:
row, col = map(int, input().split())
mat1 = [list(map(int, input().split())) for i in range(row)]
result = 0
j = 0
for i in range(row):
result += mat1[i][j]
print(result)
I am able to get the answer for the first column but I am unable to do it for other columns. Where should I increment j
to +1
to get the result for other columns?
This is the input:
2 2
5 -1
19 8
This is the output:
24
7
I got 24
as the answer. How should I get 7
now?
EDIT:
Can I insert the code in a function? After I got the first column's answer, I can increment j outside the loop and then call the function? I think it is known as recursion. I don't know I am new to programming
Upvotes: 2
Views: 515
Reputation: 1263
You should define loop on columns (you have used a fixed value j) and call your code for each column as this:
row, col = map(int, input().split())
mat1 = [list(map(int, input().split())) for i in range(row)]
def sum_column(mat1, row, j):
result = 0 #initialize
for i in range(row): #loop on rows
result += mat1[i][j]
return result
for j in range(col): #loop on columns
#call function for each column
print(f'Column {j +1} sum: {sum_column(mat1, row, j)}')
UPDATE:
please pay attention to the way you get input from user. Although the function is applied on col
but in your code user can define more columns than col
. You can ignore extra columns like this:
mat1 = [list(map(int, input().split()[:col])) for i in range(row)]
Upvotes: 0
Reputation: 48337
You should use another for loop for j
and reinitialize
the result when a new column started to be processed.
for j in range(col):
result = 0
for i in range(row):
result += mat1[i][j]
print(result)
Can I insert the code in a function? After I got the first column's answer, I can increment j outside the loop and then call the function? I think it is known as
recursion
.
Yes, you can do this with recursion.
matrix = [[5, -1], [19, 8]]
row = 2
column = 2
def getResult(j, matrix, result):
if j >= column:
return result
s = sum([matrix[i][j] for i in range(row)])
result.append(s)
return getResult(j + 1, matrix, result)
result = getResult(0, matrix, [])
Output
> result
[24, 7]
Upvotes: 2