user1790201
user1790201

Reputation: 159

Sum of a matrix, even or odd

This function receives a numeric matrix represented as a list of rows, where each row is in turn a list. Assume that it is a square matrix: all rows have the same length and there are as many rows as elements in each row. Also assume that the matrix is at least of dimension 2 by 2 (i.e. minimally the matrix has 2 rows with 2 elements each) The function should return a list with as many elements as number of rows. Element i in the resulting list should have the sum of the values in row i.

For example, if the matrix is

1   2   3
10  20  30
100 200 300

then this function should return the list [6,60,600]

That is, addValuesInAllRows( [ [1,2,3], [10,20,30], [100,200,300] ] ) should return [6,60,600]

Isn't this sort of similar but how would you sum up the list individually

Upvotes: 1

Views: 883

Answers (3)

Artsiom Rudzenka
Artsiom Rudzenka

Reputation: 29093

One more option:

from operator import itemgetter

matrix = [ [1,2,3], [10,20,30], [100,200,300] ]

def addValuesInAllCols(arr):
    return map(sum, [map(itemgetter(i), arr) for i in range(len(a))])

Where map is a build-in function that can be rewritten as a simple for. For ex:

[map(itemgetter(i), arr) for i in range(len(a))] is the same as:

result = []
for i in range(len(a)):
    tmp = []
    for row in a:
        tmp.append(row[i])
    result.append(tmp)

Edited per new tests:

def addValuesInAllCols(arr):
    return map(sum, arr)

Or without map:

def addValuesInAllCols(arr):
    return [sum(row) for row in arr]

Upvotes: 0

Aesthete
Aesthete

Reputation: 18850

Sum of columns

>>> def addValuesInAllCols(arr):
      return [sum(x) for x in zip(*arr)]

>>> addValuesInAllCols( [ [1,2,3], [10,20,30], [100,200,300] ] )
[111, 222, 333]

Sum of rows

>>> map(sum, [ [1,2,3], [10,20,30], [100,200,300] ] )
[6, 60, 600]

Upvotes: 2

Jun HU
Jun HU

Reputation: 3314

matrix = [ [1,2,3], [10,20,30], [100,200,300] ]
print [sum(row) for row in zip(*matrix)]

Upvotes: 4

Related Questions