Gavin
Gavin

Reputation: 113

3x3 Matrix not printing in correct format

I am trying to create a matrix that is 3x3 but it keeps returning as one line. This is the code I have tried so far.

def createSymmetricMat(n):
    m = []
    for i in range(n):
        r = []
        for j in range(n):
            r.append(3*i+j)
        print()
        m.append(r)
    return m

print(createSymmetricMat(3))

This returns

[[0, 1, 2], [3, 4, 5], [6, 7, 8]]

Any suggestions?

Upvotes: 1

Views: 77

Answers (2)

Yilun Zhang
Yilun Zhang

Reputation: 9008

I see no problem with this representation of a 3x3 matrix. If you want it visually correct after you created your matrix, you can do:

for r in createSymmetricMat(3):
    print(r)

which gives you:

[0, 1, 2]
[3, 4, 5]
[6, 7, 8]

Upvotes: 2

Harshal Parekh
Harshal Parekh

Reputation: 6017

def createSymmetricMat(n):
    m = []
    for i in range(n):
        r = []
        for j in range(n):
            r.append(3*i+j)
        m.append(r)

        # print m when updated
        print(m)
    return m

createSymmetricMat(3)

If you want to print each time m is updated, just add a print(m) whenever m is updated. Then you can print the entire matrix as:

for row in createSymmetricMat(3):
    print(row)

Upvotes: 1

Related Questions