0

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?

2
  • Could you please translate your code to English? There's also a Spanish-speaking site if you'd prefer: es.stackoverflow.com Commented Sep 23, 2021 at 21:31
  • Break the problem down a bit. Could you write a function that can be called like this: build_row(filled_with=3, count=2, empty_value=0), such that it returns [3, 3, 0, 0]? Commented Sep 23, 2021 at 21:33

3 Answers 3

3

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
Sign up to request clarification or add additional context in comments.

4 Comments

Do I have to replace the original fill_matrix function with this new one? or just make a new function with this?
You can replace it since your function just fills in zeros
Thanks I got it, can you explain to me how the print function works? Ive seen map, /n and /t but I didnt really understand when should I use them or whats the advantage of using them
You print function should work fine too. This is just a complicated list comprehension converting each row to a string separated by tabs, and then combining the rows to a string separated by newlines.
2

Similar to the excellent approach by @not_speshal, slight more readability can be achieved with reversed(range())

n = 4

[[i+1]*(n-i)+[0]*(i) for i in reversed(range(n))]
[[4, 0, 0, 0], 
 [3, 3, 0, 0], 
 [2, 2, 2, 0], 
 [1, 1, 1, 1]]

Comments

1

not_speshal has already given you the list-comprehension solution, but you might find it easier to understand the logic by writing a full loop. Let's analyze the matrix you want:

Row #   Value   Count
0       4       1
1       3       2
2       2       3
3       1       4
# General case:
i       (N - i) (i + 1)

So your ith row needs to contain the number N - i, i + 1 times, and then the rest should be zeros.

def fill_matrix(N):
    # First, let's create a matrix of zeros
    matrix = [ [0] * N for _ in range(N) ]
    
    # Now, iterate over rows
    for i in range(N):
        # Set the first (i + 1) values to (N - i)
        for j in range(i + 1):
            matrix[i][j] = N - i

    return matrix

To run this:

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

If you want to reduce the iterations by getting rid of the zeros-matrix creation, but you will have to append zeros to fill out each row after the for j in range(i + 1) loop.

def fill_matrix(N):
    # An empty list that will contain our rows
    matrix = []

    # Now, iterate over rows
    for i in range(N):
        row = []
        # Set the first (i + 1) values to (N - i)
        for _ in range(i + 1):
            row.append(N - i)
        # Set the remaining values to 0
        for _ in range(N - len(row)):
            row.append(0)
        matrix.append(row)
    return matrix

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.