Method analysis of MATRIX addition and multiplication implemented by Python

  • 2020-06-19 10:39:44
  • OfStack

An example of Python matrix addition and multiplication is presented in this paper. To share for your reference, specific as follows:

I thought that the matrix for python represented by list would be easy to do. In fact, found that there are universities asked.

Here is a counter example of the matrix addition I wrote which is not pythonic in particular.


def add(a, b):
   rows = len(a[0])
   cols = len(a)
   c = []
   for i in range(rows):
     temp = []
     for j in range(cols):
       temp.append(a[i][j] + b[i][j])
     c.append(temp)
   return c

Then I searched 1 data, and I decided that there was a great one, but I don't know if there was a better one.

Matrix addition


def madd(M1, M2):
  if isinstance(M1, (tuple, list)) and isinstance(M2, (tuple, list)):
    return [[m+n for m,n in zip(i,j)] for i, j in zip(M1,M2)]

Matrix multiplication


def multi(M1, M2):
  if isinstance(M1, (float, int)) and isinstance(M2, (tuple, list)):
    return [[M1*i for i in j] for j in M2]
  if isinstance(M1, (tuple, list)) and isinstance(M2, (tuple, list)):
    return [[sum(map(lambda x: x[0]*x[1], zip(i,j)))
         for j in zip(*M2)] for i in M1]

For more information about Python, please refer to Python Data Structure and Algorithm Tutorial, Python Encryption and Decryption Algorithm and Skills Summary, Python Coding skills Summary, Python Function Use Skills Summary, Python String Manipulation Skills Summary and Python Introductory and Advanced Classic Tutorial.

I hope this article has been helpful in Python programming.


Related articles: