To resolve this issue we must:
- Capture the matrix elements;
- Assemble such a matrix;
- Calculate the sum of the main diagonal;
- Display the created matrix;
- 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 valor
and 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
.
If you are using the function
input
, as error in functionraw_input
?– Woss