Print multi-dimensional matrix in Python

Asked

Viewed 15,955 times

1

I’m wondering how to create a function(imprime_matriz) which receives a matrix as a parameter and prints the matrix line by line. Obs: Spaces after the last element of each line should not be printed. Someone can help me?

The code I tried was this:

def cria_matriz(num_linhas, num_colunas):

    matriz = []
    for i in range(num_linhas):
        linha = []
        for j in range(num_colunas):
            valor = int(input("Digite o elemento [" + str(i) + "][" + str(j) + "]"))
            linha.append(valor)

        matriz.append(linha)
    return matriz


def le_matriz():
    lin = int(input("Digite o número de linhas da matriz: "))
    col = int(input("Digite o número de colunas da matriz: "))
    return cria_matriz(lin, col)

m = le_matriz()

Option 2: (shorter)

def imprime_matriz(matriz):

linhas = len(matriz)
colunas = len(matriz[0])

for i in range(linhas):
    for j in range(colunas):
        if(j == colunas - 1):
            print("%d" %matriz[i][j], end = "")
        else:
            print("%d" %matriz[i][j], end = "")
print()
  • If you can give the dimension of the matrix would be better. Even if you can post the code you tried and the matrix you are using.

  • @Wilker put my code in the question.

  • I updated the answer.

2 answers

2


According to its code, its matrices will be two-dimensional, since it is requested to enter the size of two dimensions only. So you can use the code below.

for linha in m:
    for val in linha:
        print '{:4}'.format(val),
    print

He’s got a way out.

Digite o numero de linhas da matriz:2
Digite o numero de colunas da matriz: 2
Digite o elemento [0][0]1
Digite o elemento [0][1]2
Digite o elemento [1][0]3
Digite o elemento [1][1]4
   1    2
   3    4

You can see the code working on ideone or here.

Note that the code depends on the size of the matrix, the more dimensions, the more loops will be needed.

For printing matrices independent size, use the library NumPy

As in the example below

import numpy as np

m1 = [[1], [2], [3]]
m2 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print (np.matrix(m))
print
print (np.matrix(m2))

which generates the following output

[[1]
 [2]
 [3]]

[[1 2 3]
 [4 5 6]
 [7 8 9]]

EDIT Add below image with output by testing the step code and the 3 test impressions.

Teste IDE

.

  • didn’t work. gave error: ***** [1.0 points]: testing die imprints ([[1, 2, 7], [3, 4, 8], [1, 2, 3]]) - Failed ***** Timeout /////////// ****** [1.0 points]: testing die imprints ([[1, 2], [3, 4]]) - Failed *****Timeout ////////////////// [1.0 points]: testing matrix printing ([[1], [2]]) - Failed ***** Timeout

  • Which attempt gave error? Can post the error you received? Because in the two online links I posted to you is working correctly.

  • I added an image that shows the test done here. Maybe you might be having trouble in some other part of the code.

  • the broker aq of the course I do, is not recognizing this module, presents the following error: ***** [1.0 points]: testing matrix printing ([[1], [2]]) - Failed ***** Import: No module named 'numpy' ***** [1.0 points]: testing matrix printing ([[1, 2], [3, 4]]) - Failed ***** Import: No module named 'numpy' ***** [1.0 points]: Testing matrix printing ([[1, 2, 7], [3, 4, 8], [1, 2, 3]]) - Failed ***** Import: No module named 'numpy'. How can I redo this code to make it shorter and more efficient?

  • Add the expected output format to the question. It is easier to give an ad,equada response. By this error, it seems that your course does not have the Numpy package. So you will have to manually print.

  • I was able to make the code shorter because the other one was confusing me. How do I generate the expected output, which is like a table?

  • Try to specify exactly as you wish so that we can help. The question about how to print is solved. The problem of not being accepted by the validator of your course should about formatting the final result.

  • my doubt is another way to resolve the issue without using the Numpy package so that the course validator accepted.

  • Up there I gave you two forms that you can use to print the matrix. One without using the Numpy library and the other using. Add all the information the course gives about the question. Like the statement, expected result. Etc.

Show 4 more comments

1

Good afternoon, I used your own example to solve your problem. I hope I helped.

Example

Input: matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

Exit:

1 2 3

4 5 6

7 8 9

Function:

def imprime_matriz(matriz):

    linhas = len(matriz)
    colunas = len(matriz[0])

    for i in range(linhas):
        for j in range(colunas):
            if(j == colunas - 1):
                print("%d" %matriz[i][j])
            else:
                print("%d" %matriz[i][j], end = " ")
    print()

Browser other questions tagged

You are not signed in. Login or sign up in order to post.