how do I make an Nxn matrix, where N is a variable (acquired in input), in python. Because the example below cannot change the values in the indices?

Asked

Viewed 106 times

-3

E1 = input(). split()

E2 = input(). split()

Matri, numj = E1

name, idj = E2

matrix = [[0,0,0],[0,0,0],[0,0,0]] # I cannot make the matrix that is the user’s choice, that is a variable..

for l in range(0,3):

for c in range (0,3):
    matriz[l][c] = 0

for l in range(0,3):

for c in range(0,3):
    print(f'[{matriz[l][c]:^5}]',end='')    
print()

jg1 = input('Move 1:'). split() jgl, jgc = jg1 matrix[jgl][jgc] print(matrix)

jg2 = input('Move 2:'). split() jgl2, jgc2 = jg2 print(jgl2)

in this case I am not managing to change a certain Dice. For example, I want to change 2x1 inidice from 0 to 2, I cannot... ?

1 answer

0


If you really want to use lists, you can create two nested loops to add sublists inside another list and zeros inside sublists.

N = input("Digite o valor de N: ")
N = int(N)

mat = []
for i in range(N):
    mat.append([])
    for j in range(N):
        mat[i].append(0)

print(mat)

To access and/or modify the indexes, use matriz[linha][coluna] normally:

entrada = input("Digite os indices: ").split()
linha, coluna = entrada
linha = int(linha)
coluna = int(coluna)
print(f"Linha: {linha}")
print(f"Coluna: {coluna}")

entrada = float(input("Digite o novo valor: "))
mat[linha][coluna] = entrada

print(mat)

I hope I helped. If not, try to explain your doubt better ;)

  • Thank you R.Pinho, it worked, and it was really what I needed!!

Browser other questions tagged

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