Add two matrices in python

Viewed 44773

I'm trying to write a function that adds two matrices to pass the following doctests:

  >>> a = [[1, 2], [3, 4]]
  >>> b = [[2, 2], [2, 2]]
  >>> add_matrices(a, b)
  [[3, 4], [5, 6]]
  >>> c = [[8, 2], [3, 4], [5, 7]]
  >>> d = [[3, 2], [9, 2], [10, 12]]
  >>> add_matrices(c, d)
  [[11, 4], [12, 6], [15, 19]]

So I wrote a function:

def add(x, y):
    return x + y

And then I wrote the following function:

def add_matrices(c, d):
    for i in range(len(c)):
        print map(add, c[i], d[i])

And I sort of get the right answer.

4 Answers
Related