Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6028065
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 23, 20262026-05-23T04:41:01+00:00 2026-05-23T04:41:01+00:00

I’m trying to write a function that adds two matrices to pass the following

  • 0

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.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-23T04:41:02+00:00Added an answer on May 23, 2026 at 4:41 am

    Matrix library

    You can use the numpy module, which has 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]])
    

    Home-grown solution: heavyweight

    Assuming you wanted to implement it yourself, you’d set up the following machinery, which would let you define arbitrary pairwise operations:

    from pprint import pformat as pf
    
    class Matrix(object):
        def __init__(self, arrayOfRows=None, rows=None, cols=None):
            if arrayOfRows:
                self.data = arrayOfRows
            else:
                self.data = [[0 for c in range(cols)] for r in range(rows)]
            self.rows = len(self.data)
            self.cols = len(self.data[0])
    
        @property
        def shape(self):          # myMatrix.shape -> (4,3)
            return (self.rows, self.cols)
        def __getitem__(self, i): # lets you do myMatrix[row][col
            return self.data[i]
        def __str__(self):        # pretty string formatting
            return pf(self.data)
    
        @classmethod
        def map(cls, func, *matrices):
            assert len(set(m.shape for m in matrices))==1, 'Not all matrices same shape'
    
            rows,cols = matrices[0].shape
            new = Matrix(rows=rows, cols=cols)
            for r in range(rows):
                for c in range(cols):
                    new[r][c] = func(*[m[r][c] for m in matrices], r=r, c=c)
            return new
    

    Now adding pairwise methods is as easy as pie:

        def __add__(self, other):
            return Matrix.map(lambda a,b,**kw:a+b, self, other)
        def __sub__(self, other):
            return Matrix.map(lambda a,b,**kw:a-b, self, other)
    

    Example:

    >>> a = Matrix([[1, 2], [3, 4]])
    >>> b = Matrix([[2, 2], [2, 2]])
    >>> b = Matrix([[0, 0], [0, 0]])
    
    >>> print(a+b)
    [[3, 4], [5, 6]]                                                                                                                                                                                                      
    
    >>> print(a-b)
    [[-1, 0], [1, 2]]
    

    You can even add pairwise exponentiation, negation, binary operations, etc. I do not demonstrate it here, because it’s probably best to leave * and ** for matrix multiplication and matrix exponentiation.


    Home-grown solution: lightweight

    If you just want a really simple way to map an operation over only two nested-list matrices, you can do this:

    def listmatrixMap(f, *matrices):
        return \
            [
                [
                    f(*values) 
                    for c,values in enumerate(zip(*rows))
                ] 
                for r,rows in enumerate(zip(*matrices))
            ]
    

    Demo:

    >>> listmatrixMap(operator.add, a, b, c))
    [[3, 4], [5, 6]]
    

    With an additional if-else and keyword argument, you can use indices in your lambda. Below is an example of how to write a matrix row-order enumerate function. The if-else and keyword were omitted above for clarity.

    >>> listmatrixMap(lambda val,r,c:((r,c),val), a, indices=True)
    [[((0, 0), 1), ((0, 1), 2)], [((1, 0), 3), ((1, 1), 4)]]
    

    edit

    So we could write the above add_matrices function like so:

    def add_matrices(a,b):
        return listmatrixMap(add, a, b)
    

    Demo:

    >>> add_matrices(c, d)
    [[11, 4], [12, 6], [15, 19]]
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm trying to decode HTML entries from here NYTimes.com and I cannot figure out
I am trying to understand how to use SyndicationItem to display feed which is
Basically, what I'm trying to create is a page of div tags, each has
link Im having trouble converting the html entites into html characters, (&# 8217;) i
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I'm using v2.0 of ClassTextile.php, with the following call: $testimonial_text = $textile->TextileRestricted($_POST['testimonial']); ... and
I'm new to using the Perl treebuilder module for HTML parsing and can't figure
Seemingly simple, but I cannot find anything relevant on the web. What is the
Does anyone know how can I replace this 2 symbol below from the string
this is what i have right now Drawing an RSS feed into the php,

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.