Reputation: 69
I can sum the items in column zero fine. But where do I change the code to sum column 2, or 3, or 4 in the matrix? I'm easily stumped.
def main():
matrix = []
for i in range(2):
s = input("Enter a 4-by-4 matrix row " + str(i) + ": ")
items = s.split() # Extracts items from the string
list = [ eval(x) for x in items ] # Convert items to numbers
matrix.append(list)
print("Sum of the elements in column 0 is", sumColumn(matrix))
def sumColumn(m):
for column in range(len(m[0])):
total = 0
for row in range(len(m)):
total += m[row][column]
return total
main()
Upvotes: 5
Views: 78066
Reputation: 21
To get the sum of all columns in the matrix you can use the below python numpy code:
matrixname.sum(axis=0)
Upvotes: 2
Reputation: 1295
One-liner:
column_sums = [sum([row[i] for row in M]) for i in range(0,len(M[0]))]
also
row_sums = [sum(row) for row in M]
for any rectangular, non-empty matrix (list of lists) M
. e.g.
>>> M = [[1,2,3],\
>>> [4,5,6],\
>>> [7,8,9]]
>>>
>>> [sum([row[i] for row in M]) for i in range(0,len(M[0]))]
[12, 15, 18]
>>> [sum(row) for row in M]
[6, 15, 24]
Upvotes: 8
Reputation: 501
Here is your code changed to return the sum of whatever column you specify:
def sumColumn(m, column):
total = 0
for row in range(len(m)):
total += m[row][column]
return total
column = 1
print("Sum of the elements in column", column, "is", sumColumn(matrix, column))
Upvotes: 2
Reputation: 8205
This can be made easier if you represent the matrix as a flat array:
m = [
1,2,3,4,
10,11,12,13,
100,101,102,103,
1001,1002,1003,1004
]
def sum_column(m, n):
return sum(m[i] for i in range(n, 4 * 4, 4))
Upvotes: 0
Reputation: 113905
numpy could do this for you quite easily:
def sumColumn(matrix):
return numpy.sum(matrix, axis=1) # axis=1 says "get the sum along the columns"
Of course, if you wanted do it by hand, here's how I would fix your code:
def sumColumn(m):
answer = []
for column in range(len(m[0])):
t = 0
for row in m:
t += row[column]
answer.append(t)
return answer
Still, there is a simpler way, using zip:
def sumColumn(m):
return [sum(col) for col in zip(*m)]
Upvotes: 13