Condition Arrays python

0

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 do I have to do to get my code to meet the requirements of example1 and example2?

    
asked by anonymous 24.02.2017 / 20:16

1 answer

2

The simplest way is to use Numpy , because then you can compare if the format ( shape ) of the arrays is different , and if it returns False as desired. Code sample:

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))

Result:

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

See working on Ideone .

Issue:

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:

by:

if not sameShape(m1, m2):

However, note that you can not simply m1 + m2 because this operator concatenates the Python lists and does not sum. You can use your same sum method, or do so (see on 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:

  • This code is much bigger and harder to understand than the previous one, with Numpy.
  • It is specific to a 2-dimensional array and would need to be adapted if its array had more dimensions. The Numpy code is already commonly used.
  •   

    So I disagree from your understanding that without the use of the package   It's better (even for you). :) It's not that hard to install it and it's worth   very worth it! Believe me.

        
    24.02.2017 / 20:39