简体   繁体   中英

Finding the sum of column of all the rows in a matrix without using numpy

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

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]

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)]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM