Recover array dimensions in Python

0

Can one help me write the "dimension (matrix)" function that receives an array as a parameter and prints the dimensions of the received array in iXj format?

def crie_matriz(n_linhas, n_colunas, valor):

    matriz = []

    for i in range(n_linhas):
        linha = []

        for j in range(n_colunas):
            linha.append(valor)
            matriz.append(linha)
    for n in matriz:
        print(''.join(map(str,matriz)))
    return matriz

a = crie_matriz(2,3)

print(a)

The above code I printed prints the output, but the question asks you to print the dimension as in the example below:

minha_matriz = [[1], [2], [3]]
dimensoes(minha_matriz)
3X1

minha_matriz = [[1, 2, 3], [4, 5, 6]]
dimensoes(minha_matriz)
2X3
    
asked by anonymous 05.02.2017 / 17:56

3 answers

0

The code looks like this:

def dimensoes(matriz):
tam_matriz = (len(matriz), len(matriz[0]))
print('{}X{}'.format(tam_matriz[0], tam_matriz[1]))

If the question asks to print, you have to use the 'print' command, if you ask to return or return, use the 'return' command

    
06.02.2017 / 00:15
1

You can do the following:

tam_matriz = (len(minha_matriz), len(minha_matriz[0]))

This will give a tuple, in this case: (2, 3)

You can print like this:

print('{} x {}'.format(tam_matriz[0], tam_matriz[1]))

Or with a function:

def dimensoes(m):
    return (len(m), len(m[0]))

print(dimensoes(minha_matriz)) # (2, 3)
    
05.02.2017 / 21:58
1

You can use the numpy library, which already comes with the method of returning the array / array dimensions

ex:

import numpy as np

np.array([[0, 1, 2],
          [3, 4, 5]]).shape

prints (2,3)

When stored in a variable you can always call .shape ex:

import numpy as np

x = np.array([[0, 1, 2],
              [3, 4, 5]])

print(x.shape)

If you want to take the transpose, eg:

print(x.T)

prints:

array([[0, 3],
       [1, 4],
       [2, 5]])

Good fun!

    
08.02.2017 / 14:38