Home > Back-end >  Basic python, NxN matrix printing the terms being the sum of the term coordinates in the matrix
Basic python, NxN matrix printing the terms being the sum of the term coordinates in the matrix

Time:07-20

Hy guys, i'm new to python, i'm trying to make an NxN matrix, that print out a matrix that have the terms value's being the sum of the coordinates of it.

In this example i used N=5

    N = 5
    M = []
    linha = []
    for i in range (N):
      linha.append(0)
    for i in range(N):
      M.append(linha)
    print(f"{M}") # just to make sure it's printing the NxN matrix
    for i in range(N):
      for j in range(N):
        M[i][j] = i   j
    print(M) #returning the final matrix

I'm getting this:

[[4, 5, 6, 7, 8],

[4, 5, 6, 7, 8],

[4, 5, 6, 7, 8],

[4, 5, 6, 7, 8],

[4, 5, 6, 7, 8]]

While i was expecting:

[[0, 1, 2, 3, 4],

[1, 2, 3, 4, 5],

[2, 3, 4, 5, 6],

[3, 4, 5, 6, 7],

[4, 5, 6, 7, 8]]

Since, for example, the first term is the M[0][0], so 0 0=0

Sorry if i wrote things that may be not too clear, but that's my problem, if anyone can help i would appreciate!

CodePudding user response:

A concise way of getting the desired result, using a nested list comprehension:

N = 5
M = [[i j for j in range(N)] for i in range(N)]
print(M)

CodePudding user response:

Like what was said in a comment:

The code for i in range(N): M.append(linha) means that M[0], M[1] ...M[N] are all references to the same object linha. So after that, when you change (for example) M[1][0], you're changing element 0 of the same object which all the rows of your matrix contain.

This means you're always referencing the same variable. You could make a small change to your code, so the new list of zeroes is created independent of name using a list comprehension:

N = 5
M = []
for i in range(N):
    M.append([0 for i in range(N)])
print(f"{M}")

for i in range(N):
    for j in range(N):
        M[i][j] = i   j
print(M) #returning the final matrix
  • Related