Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (16.4k points)

I'm attempting to compose a function which adds two matrices to pass the accompanying 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]]

Because of that, I wrote a function:

def add(x, y):

    return x + y

And I also wrote another function:

def add_matrices(c, d):

    for i in range(len(c)):

        print map(add, c[i], d[i])

Can anyone tell me, what would be the simplest way to add two matrices?

1 Answer

0 votes
by (26.4k points)

You can actually utilize numpy package, Which actually has a support for this

>>> import numpy as np

>>> a = np.matrix([[1, 2], [3, 4]])

>>> b = np.matrix([[2, 2], [2, 2]])

>>> a+b

matrix([[3, 4],

        [5, 6]])

Join the python online course fast, to learn python concepts in detail and get certified.

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...