Neistow
Neistow

Reputation: 1244

Print index of row and column in adjacency matrix

I have a function to build adjacency matrix. I want to improve matrix readability for humans, so I decided to print row index like this: enter image description here

Now I want to print column index in the same way, but I can't do it properly. best result I get is this: enter image description here

Any Ideas and suggestions how i can print column indexes neatly?

Source code here.

def generate_adjacency_matrix(vertices):
    # Create empty Matrix
    matrix = [['.' for _ in range(len(vertices))] for _ in range(len(vertices))]
    # Fill Matrix
    for row in range(len(matrix)):
        for num in range(len(matrix)):
            if num in vertices[row]:
                matrix[row][num] = '1'
    # Print column numbers
    numbers = list(range(len(matrix)))
    for i in range(len(numbers)):
        numbers[i] = str(numbers[i])
    print('  ', numbers)

    #Print matrix and row numbers
    for i in range(len(matrix)):
        if len(str(i)) == 1:
            print(str(i) + ' ', matrix[i])
        else:
            print(i, matrix[i])

If it matters Parameter in my function is a dictionary that looks like:

{0:[1],
 1:[0,12,8],
 2:[3,8,15]
 ....
 20:[18]
}

Upvotes: 0

Views: 437

Answers (1)

michjnich
michjnich

Reputation: 3395

If you know you're only going to 20, then just pad everything to 2 chars:

For the header row:

numbers[i] = str(numbers[i].zfill(2))

For the other rows, set to ". " or ".1" or something else that looks neat.

That would seem to be the easiest way.

Alternative way is to have 2 column headers, one above the other, first one is the tens value, second is the unit value. That allows you to keep the width of 1 in the table as well, which maybe you need.

Upvotes: 1

Related Questions