Sum of the main diagonal of a matrix in Python

Asked

Viewed 1,952 times

0

I’m making an array[3][3] in Python where I’m summing the main diagonal elements in the matrix plus it’s giving an error.

i = 0 # linha
j = 0 # coluna
soma = 0
matriz = int (input("Digite a matriz (%d,%d): ",[i],[j]))
for i in matriz:
    for j in matriz:
        soma = matriz[0][0] + matriz[1][1] + matriz[2][2]

for i in matriz:
    for j in matriz:
        print ("\t {}".format(matriz[i][j]))
    print ("\n")

print ("A soma da diagona principal é {}".format(soma))

Expected exit

5       4       6
7       5       4
3       2       3
A soma da diagonal principal e 13

Output produced:

TypeError: raw_input() takes from 1 to 2 positional arguments but 4 were given
  • If you are using the function input, as error in function raw_input?

3 answers

2


You have passed more arguments than necessary in input (raw_input is python 2.7 as I recall and I used 3.7), try using an input for i and another for j, however your code would culminate in more errors that I show below and a version "refactored".

YOUR VERSION:

i = 0 # linha
j = 0 # coluna
soma = 0
matriz = int (input("Digite a matriz (%d,%d): ",[i],[j])) #esse input funciona no C, mas não funciona no python

for i in matriz: # daria erro pois a matriz não foi criada

    for j in matriz: # mesmo erro de cima, entretando falta dizer qual lista da matriz você deseja percorrer

        soma = matriz[0][0] + matriz[1][1] + matriz[2][2] # caso estivesse correto ele percorreria várias vezes, assim fazendo com que a essa soma acabasse errada

for i in matriz: # o mesmo falado anteriormente
    for j in matriz:
        print ("\t {}".format(matriz[i][j]))#não está errada a sintaxe entretanto ele iria printar todos uma uma fila e não da maneira correta.

    print ("\n") # o \n seria meio inútil mas se quiser pode deixar.

print ("A soma da diagona principal é {}".format(soma)) # sem erros aqui

THE WAY WITHOUT THE MISTAKES WOULD BE SO:

i = int (input("Digite o número de linhas: "))# linha
j = int (input("Digite o número de colunas: ")) # coluna
soma = 0
matriz= []
#opcional, pois serve apenas para criar uma matriz
for linha in range(0,i):
    matriz.append([])
    for coluna in range(0,j):
        matriz[linha].append(int(input ("Digite o número de {}x{}: ".format(linha+1, coluna+1))))

ll = 0 #número de linhas
lc = 0 #número de colunas

for linha in matriz:
    for coluna in matriz[ll]: #pega a matriz linha e cara um de seus objetos
        if ll == lc: #caso o número de linhas seja igual ao de colunas ele soma
            soma += coluna
        print ("\t {}".format(coluna), end = "")#se não o print cria uma nova linha
        lc +=1
    print() #serve de espaço entre linhas
    ll+=1
    lc=0 #para poder resetar o número de colunas para o próximo teste
print ("A soma da diagona principal é {}".format(soma))

I believe it’s all clear now!

  • I believe that’s just the mistake.

  • I still don’t understand

  • Input is a function and you are passing more arguments than it needs, try using one input for i and another for j.

  • Type thus i = int(input("Enter number of rows: ")) and j = int(input("Enter number of columns: "))

  • There’s one more little mistake I’ve seen, your sum will add up multiple times.

  • I tried to do based on what I had in C code of this kind of algorithm, I think it’s a little different in Python.

  • ready now I think it’s complete because it had some errors in its original, I just did fix.

  • i = 0 # row j = 0 # column sum = 0 matrix = int (input("Type matrix (%d,%d): ",[i],[j])#gives error for i in matrix: # the matrix was not created/from error for j in matrix: # would only take lines if it was created sum = matrix[0][0] + matrix[1][1] + matrix[2][2]#unnecessary and sum multiple times for i in matrix: #same thing as before for j in matrix: print (" t {}". format(matrix[i][j])) print (" n") #you would be giving more than one line break because print already does it alone print ("The sum of the main diagonal is {}". format(sum))

  • It became clearer to me, thank you.

Show 4 more comments

2

How about using the numpy:

import numpy as np

def SomaDiagonal( m, invertida=False ):
    x = np.asarray( m )
    if( invertida ):
        x = np.fliplr(x)
    return np.trace(x)

matriz = [ [1,2,2], [4,1,6], [2,8,1] ]


print ("A soma da diagonal principal eh {}".format( SomaDiagonal( matriz, False ) ))
print ("A soma da diagonal invertida eh {}".format( SomaDiagonal( matriz, True ) ))
  • Face in the matter of Data Structure that I have in Python we do not import libraries, at least yet.

1

To resolve this issue we must:

  1. Capture the matrix elements;
  2. Assemble such a matrix;
  3. Calculate the sum of the main diagonal;
  4. Display the created matrix;
  5. Display the sum of the main diagonal widgets.

Well, to solve this question we can use the following algorithm:

m = int(input('Digite o número de linhas? '))
n = int(input('Digite o número de colunas? '))

soma = 0
matrizA = list()
for c in range(1, m + 1):
    linha = list()
    for i in range(1, n + 1):
        while True:
            try:
                valor = int(input(f'Digite o {i}º elemento da {c}ª linha: '))
                break
            except ValueError:
                print('\033[31mValor INVÁLIDO! Digite apenas valores inteiros!\033[m')
        if c == i:
            soma += valor
        linha.append(valor)
    matrizA.append(linha)

print('\033[32mA matriz gerada é:')
for j in matrizA:
    for k in j:
        print(k, end='  ')
    print()

print(f'A Soma da diagonal principal é: {soma}\033[m')

Note that first of all the algorithm captures the number of linhas and of colunas. With this data in hand, the algorithm executes the primeiro block nesting for. It is through this first nesting that the matrix will be mounted and, also, the sum will be calculated.

After typing the valor of each element, the block while treats the variable type. After approval, the block if checks whether in this interaction the order of c is equal to the order of i. If positive, the sum variable is incremented with valorand the variable valor is added to the list linha.

After the list linha is complete, it will be added to the list matrizA.

Once the list matrizA being complete, the algorithm is shifted to the second block nesting for. This, in turn, will go through the list matrizA displaying each of the elements in tabular form.

Later the sum of the main diagonal elements is displayed.

Now, if you want to use the library numpy, you can use the following algorithm:

import numpy as np

m = int(input('Digite o número de linhas? '))
n = int(input('Digite o número de colunas? '))

matrizA = list()
for c in range(1, m + 1):
    linha = list()
    for i in range(1, n + 1):
        while True:
            try:
                valor = int(input(f'Digite o {i}º elemento da {c}ª linha: '))
                break
            except ValueError:
                print('\033[31mValor INVÁLIDO! Digite apenas valores inteiros!\033[m')
        linha.append(valor)
    matrizA.append(linha)

matriz = np.array(matrizA)
soma = np.trace(matriz)
print(f'\033[32mA matriz gerada é:\n{matriz}')
print(f'A Soma da diagonal principal é: {soma}\033[m')

In this second algorithm the sum of the main diagonal elements is calculated by the method trace library numpy.

Browser other questions tagged

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