lundi 25 janvier 2021

Sum two lists of lists

Taking the following lists

matrix1 = [[1, 1], [2, 3]]
matrix2 = [[1, 1], [2, 3]]

How does return, without using additional libraries (such as pandas, numpy,...), the sum of the various lists of lists, in these case 2, as

[[2, 2], [4, 6]]

With the following

def addMatrix(m1, m2):

    if len(m1) == len(m2):
        return [x[0] + x[1] for x in zip(m1, m2)]
    else:
        raise ValueError("Given matrices are not the same size.")

It returns

>>> addMatrix(matrix1, matrix2)
[[1, 1, 1, 1], [2, 3, 2, 3]]

Which is not what one wants and would only work for lists, not lists of lists.

One has tried the following as well, but gives the same output as above

new = [] 

def add(m1, m2):
    for i, value in enumerate(m1):
        if len(m1) == len(m2):
            additional = m2[i]
            new.append(value + additional)
        else:
            raise ValueError("Given matrices are not the same size.")

One knows how to do it with numpy, but an approach without using any libraries is what one wants.

Here is a working solution with numpy

import numpy as np

matrix1_np = np.asarray(matrix1)
matrix2_np = np.asarray(matrix2)
add = matrix1_np + matrix2_np
add.tolist()

Aucun commentaire:

Enregistrer un commentaire