Matrix in python

Asked

Viewed 201 times

0

I’m building a matrix in python, but I can’t make the right impression. Someone could help me. Follow the code:

 linhas = 4

 entrada = input()
 valor = entrada.split()
 matriz = []
 while (entrada != ''):
     for i in range(linhas):
           linha = []
          for j in range(len(valor)):
                valor[j] = int(valor[j])
                linha.append(valor[j])

   matriz.append(linha)
   entrada = input()
   print(*matriz, sep='\n')

When I type:

           1 2 3 4 

           5 5 6 7

The impression is:

           [1, 2, 3, 4] 

           [1, 2, 3, 4]

What am I doing wrong?

2 answers

0


Failed to update variable valor inside the loop:

linhas = 4

entrada = input()
valor = entrada.split()
matriz = []
while (entrada != ''):
    for i in range(linhas):
        linha = []
        for j in range(len(valor)):
            valor[j] = int(valor[j])
            linha.append(valor[j])
    matriz.append(linha)
    entrada = input()
    valor = entrada.split()

print(*matriz, sep='\n')

Because, as you are using the variable valor to create the matrix lines you need to update it after receiving the input user’s.

0

When we are working with matrices we must know the number of linhas and also the number of colunas.

If your intention is to assemble an array you can use the following algorithm below. Note that, in this algorithm, I used the repetition loop for instead of the while.

import numpy as np

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

matrizTemp = 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 de {c}ª linha: '))
                break
            except ValueError:
                print('\033[31mValor INVÁLIDO! Digite apenas inteiros!\033[m')
        linha.append(valor)
    matrizTemp.append(linha)

# Exibindo a matriz e suas dimensões.
matriz = np.array(matrizTemp)
print(f'\033[32mA matriz gerada é:\n{matriz}')

Note that when we run this algorithm we are asked the number of linhas and then the number of colunas.

After having inserted the number of rows and columns, we must enter each of the elements we wish to insert into the matrix. After you have entered all possible elements of the matrix and press enter, the algorithm will assemble and display such a matrix.

Browser other questions tagged

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