Condition python Matrices

Asked

Viewed 1,548 times

1

My Code:

 m1 = [[1, 2, 3],
      [4, 5, 6]]
 m2 = [[2, 3, 4],
       [5, 6, 7]]

def soma_matrizes(m1, m2):
       matriz_soma = []
       linhas = len(m1) 
       colunas = len(m1[0]) 
  for i in range(linhas):
       matriz_soma.append([])
       for j in range(colunas):
            soma = m1[i][j] + m2[i][j]
            matriz_soma[i].append(soma)
 return matriz_soma

Example 1:

 m1 = [[1, 2, 3], [4, 5, 6]]
 m2 = [[2, 3, 4], [5, 6, 7]]
 soma_matrizes(m1, m2) => [[3, 5, 7], [9, 11, 13]]

Example 2:

m1 = [[1], [2], [3]]
m2 = [[2, 3, 4], [5, 6, 7]]
soma_matrizes(m1, m2) => False

What I have to do to make my code meet the requirements of the exemplo1 and exemplo2?

1 answer

3


The simplest way is to use the Numpy, because there you can compare if the format (shape) of the matrices is different, and if it is to return False as you wish. Example code:

def soma_matrizes(m1, m2):
    import numpy as np
    m1 = np.array(m1)
    m2 = np.array(m2)
    if m1.shape != m2.shape:
        return False
    else:
        return (m1 + m2).tolist()

m1 = [[1, 2, 3],[4, 5, 6]]
m2 = [[2, 3, 4],[5, 6, 7]]  
print(soma_matrizes(m1, m2))

m1 = [[1], [2], [3]]
m2 = [[2, 3, 4],[5, 6, 7]]  
print(soma_matrizes(m1, m2))

Upshot:

[[3, 5, 7], [9, 11, 13]]
False

See working in Ideone.

Editing:

To do manually (considering only lists):

def sameShape(m1, m2):
    '''Verificação manual se duas listas têm o mesmo formato'''

    if type(m1) != type(m2):
        return False

    if type(m1) == list:
        if len(m1) != len(m2):
            return False

        for i in range(len(m1)):
            if not sameShape(m1[i], m2[i]):
                return False

    return True

In this case, remove the use of the Numpy library and change the line:

if m1.shape != m2.shape:

for:

if not sameShape(m1, m2):

But note that you can no longer simply do m1 + m2, because this operator concatenates the Python lists and does not add up. You can use your summation method either, or do so (see in Ideone):

def sameShape(m1, m2):
    '''Verificação manual se duas listas têm o mesmo formato'''

    if type(m1) != type(m2):
        return False

    if type(m1) == list:
        if len(m1) != len(m2):
            return False

        for i in range(len(m1)):
            if not sameShape(m1[i], m2[i]):
                return False

    return True

def soma_matrizes(m1, m2):
    if not sameShape(m1, m2):
        return False
    else:
        # Reduz a dimensão da matriz de 2 pra 1 (i.e. transforma em lista simples)
        # para facilitar a soma
        m1 = [i for j in m1 for i in j]
        m2 = [i for j in m2 for i in j]

        # Calcula a soma item a item das duas listas
        s = [sum(t) for t in zip(m1, m2)] # <= usa `sum` em cada tupla
        #s = [i + j for i, j in zip(m1, m2)] # <== alternativa (talvez mais fácil de entender)

        # Faz a lista de soma ter 2 dimensões antes de retornar
        k = int(len(s) / 2)
        return [s[:k], s[k:]]

m1 = [[1, 2, 3],[4, 5, 6]]
m2 = [[2, 3, 4],[5, 6, 7]]
print(soma_matrizes(m1, m2))

m1 = [[1], [2], [3]]
m2 = [[2, 3, 4],[5, 6, 7]]
print(soma_matrizes(m1, m2))

Finally, note that:

  1. This code is much bigger and harder to understand than the previous one, with Numpy.
  2. It is specific to a 2-dimensional matrix and would need to be adapted if its matrix had more dimensions. Numpy’s code is already in general use.

Therefore, I disagree of his understanding that without the use of the package is better (even for you). : ) It is not so difficult to install it and worth very sorry! Believe me.

  • a solution without module , would fit better

  • If by "module" you mean without using the bundle Numpy, I disagree that it would fit better. It is much easier and practical this way (besides working for any number of matrix dimensions), and this package is used for many other things and is very easy to install (installs with the same Pip). Anyway, you didn’t specify in your question that it wasn’t to use a package, so I consider the answer still valid.

  • Now, if you want to do it manually, just compare in each dimension if the type (use type) is the same and if the size (if a list) is the same (use len). The loop to check is the same as you already do to add.

  • would fit better me in the case ,because I have no module installed yet, but thanks Luiz

  • I edited to add a suggestion of how to do it manually.

  • 1

    Hi Luiz, yesterday I already gave my +1 yesterday morning (I had a few drinks and it was the only thing I could do), no doubt that it is better this way for serious things. However, I wanted to be entertained today by this: http://ideone.com/2dnmKc

  • @Miguel You’re also enjoying Carnival out there, then, aren’t you? :) hehehe Very good your solution. Post it too as an answer. Serves as a basis for comparison for AP and future readers.

  • 1

    @Luizvieira if you want to add it in your answer so are the two together. It was not for carnival, it was by lol :p Friday

  • @Miguel I think if it’s to add it makes more sense to be another answer. Still, thank you! :)

  • Luiz has nothing to do, I decided to spend an hour in this now lol: http://ideone.com/b5zNbr . For indefinite number of lists

Show 5 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.