Matrix (Create 2 Matrices and Sums them up)

1

How could I build this array without using random / randit? Then I need to do the element-by-element sum function of the first two. The sum must be solved via subprogram written for this purpose. This subroutine should only take the two input arrays as parameters and return the resulting array if it is possible to evaluate the sum, or None, if this is not possible. After returning the subprogram, the main program must display the contents of the array obeying the format presented in the matrix construction. If None is returned, the main program should issue the message "Can not add arrays of different dimensions".

#Contrução da Matriz 1 e Matriz 2 - Programa Principal
import random
matriz1 = []
n = int(input("Informe a quantidade de linhas\n da matriz 1:" ))
m = int(input("Informe a quantidade de colunas\n da matriz 1:" ))
for i in range(n):
     matriz1.append([])
     for j in range(m):
        matriz1[i].append(random.randint(0,100))

for i in range(len(matriz1)):
    for j in range(len(matriz1[i])):
        print(matriz1[i][j], end=" ")
    print ("\n")


matriz2 = []
n = int(input("Informe a quantidade de linhas\n da matriz 2:" ))
m = int(input("Informe a quantidade de colunas\n da matriz 2:" ))

for i in range(n):
     matriz2.append([])
     for j in range(m):
        matriz2[i].append(random.randint(0,100))

for i in range(len(matriz2)):
    for j in range(len(matriz2[i])):
        print(matriz2[i][j], end=" ")
    print ("\n")
    
asked by anonymous 22.08.2016 / 15:29

1 answer

0

To add the arrays you can do:

def somarMatrizes(matriz1, matriz2):
    if(len(matriz1) != len(matriz2) or len(matriz1[0]) != len(matriz2[0])):
        return None
    result = []
    for i in range(len(matriz1)):   
        result.append([])
        for j in range(len(matriz1[0])):
            result[i].append(matriz1[i][j] + matriz2[i][j])
    return result

To make use of this in the last line of code you can do:

soma = somarMatrizes(matriz1, matriz2) # soma e o nosso retorno, result
if soma is not None:
    for i in soma:
        print(i)
else:
    print('Matrizes devem conter o mesmo numero de linhas e colunas')
    
22.08.2016 / 18:40