Find the sum of the elements of a matrix

Asked

Viewed 1,594 times

3

I was trying to create a code that would create a square matrix from the side n and then summed up each side to find out which has the different sum, in the sum part I was half locked.

I tried to make this code but it didn’t work. Can someone help me?

n = input()
y = []
while len(y) <= (n**2)-n:
    x = map(int,raw_input().split())
    for i in range(n):
        y.append(x[i])

matriz=[]
matriz1=[]
for i in range(n):
    arroz=[]
    for k in range(n):
        arroz.append (y[0])
        del (y[0])
    matriz.append(arroz)
matriz1.append(matriz[0])   

diferente=[]

Until this stretch worked, then I tried to make code find the different and go erasing the same

while True:

    if sum(matriz[0]) = sum(matriz[(len(matriz))-1]) and sum(matriz[(len(matriz))-2]) = sum(matriz[0]):
        del (matriz[0])
        del (matriz[len(matriz)-1]
        del (matriz[len(matriz)-2]
    elif sum(matriz[0]) != sum(matriz[len(matriz)-1]) and sum(matriz[0]) = sum(matriz[len(matriz)-2]):
           diferente.append(matriz[len(matriz)-1])
           del (matriz[0])
        del (matriz[len(matriz)-1]
        del (matriz[len(matriz)-2]
            break
    elif sum(matriz[0]) = sum(matriz[len(matriz)-1]) and sum(matriz[0]) != sum(matriz[len(matriz)-2]):
        diferente.append(matriz[len(matriz)-2])
        del (matriz[0])
        del (matriz[len(matriz)-1]
        del (matriz[len(matriz)-2]
            break
    elif sum(matriz[0]) != sum(matriz[len(matriz)-1]) and sum(matriz[len(matriz)-1]) = sum(matriz[len(matriz)-2]):
        diferente.append(matriz[0])
        del (matriz[0])
        del (matriz[len(matriz)-1]
        del (matriz[len(matriz)-2]
            break

print diferente
  • Modifying the input while trying to extract information from it is usually not a good idea.

1 answer

1

To add up the sides and identify which one is smaller, you can try something like:

superior = 0
direita = 0
esquerda = 0
inferior = 0

    for i in range(n):
        superior += [0][i]
        direita  += [i][n]
        esquerda += [i][0]
        inferior += [n][i]

Where n is the size of your matrix. Then just compare them.

Browser other questions tagged

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