Skip to content
Advertisement

How can I make this matrix in python without using numpy?

I have to make a matrix thats N by N and the example im given looks like this:

4 0 0 0
3 3 0 0
2 2 2 0
1 1 1 1

So what I get from the example is that its gonna take the number N is (4 in this example since its 4 by 4) and print the number on the top row first column then fill it with zeros and then go down one line and print N -1 in the first two columns and then zeros. My code looks like this atm:

def fill_matrix(n): #Fills the matrix with 0s
    # Llena la matriz
    for r in range(n):
        row = []
        for c in range(n):
            row.append(0)
        matrix.append(fila)
    return matrix

def print_matrix(matriz): #Prints the matrix
    rows = len(matriz)
    columns = len(matriz[0])
    for f in range(row):
        for c in range(columns):
            print ("%3d" %matrix[f][c], end="")
        print()
       
# Programa principal
side = int(input("Input the size of the matrix: ")) #Input of N by N
while side < 1:
    print("Size must be bigger than 0")
    side = int(input("Input the size of the matrix: "))
matrix = []
fill_matrix(side)
print_matrix(matrix)

How can I make this matrix look like the one in the exercise?

Advertisement

Answer

Use list comprehension:

N = 4
>>> [[N-i]*(i+1)+[0]*(N-i-1) for i in range(N)]
[[4, 0, 0, 0], [3, 3, 0, 0], [2, 2, 2, 0], [1, 1, 1, 1]]

In a function:

def fill_matrix(N):
    return [[N-i]*(i+1)+[0]*(N-i-1) for i in range(N)]

def print_matrix(m):
    print("n".join(["t".join(map(str, row)) for row in m]))

>>> fill_matrix(6)
[[6, 0, 0, 0, 0, 0],
 [5, 5, 0, 0, 0, 0],
 [4, 4, 4, 0, 0, 0],
 [3, 3, 3, 3, 0, 0],
 [2, 2, 2, 2, 2, 0],
 [1, 1, 1, 1, 1, 1]]

>>> print_matrix(fill_matrix(6))
6   0   0   0   0   0
5   5   0   0   0   0
4   4   4   0   0   0
3   3   3   3   0   0
2   2   2   2   2   0
1   1   1   1   1   1

The ith row consists of:

  1. The number N-i repeated i+1 times
  2. 0 repeated N-(i+1) times
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement