1
m,n=input()
a=[0]*n
for i in range(0,m):
      a[i]=[0]*m
for i in range(0,m):
     for j in range(0,n):
           a[i][j]=input()
print a

Consider the above piece of code written in Python 2.7.4 to accept a 2-D array and then print it. This code functions well but it should accept any 2-D array means for example the values of m and could be 3,2 respectively let's say but it only accepts a square matrix. We cannot create a rectangular matrix because it gives the error: index out of range if the values of m and n are not equal. Is there any way to create a rectangular matrix just like we can do in C/C++ easily?

vaultah
  • 44,105
  • 12
  • 114
  • 143

2 Answers2

1

Numpy is a great module for fast linear algebra operations. You can create a rectangular array with Numpy which is essentially a matrix. (Numpy also has matrix functions too but they are a little more tedious to work with).

As an example, create a 3x4 array as follows

import numpy as np

input = np.zeros((3, 4))  #This creates a 3x4 array. It is good practice to initialize your array with 0's

input[0][3] = 5           #Fill out your array. The 0,0 index is the top left corner

In [42]:input
Out[42]:
array([[ 0.,  0.,  0.,  5.],
       [ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.]])

Proceed to fill out the rest of your rectangular matrix as per normal.

BigH
  • 340
  • 4
  • 6
0

You can do something like this:

rows = input()
cols = input()

arr = [[None] * cols for _ in range(rows)]

for i in range(rows):
    for j in range(cols):
        print(arr)
        arr[i][j] = input()

print(arr)

You should see this similar question: How to initialize a two-dimensional array in Python?

As far as getting your exact code to work, you just have m and n switched on lines 2 & 4:

m = input()  # rows
n = input()  # cols

a = [0] * m  # Initialize rows
for i in range(0, m):  # For each row (must be n rows)
    a[i] = [0] * n  # Initialize a column
for i in range(0, m):  # For each row
    for j in range(0, n):  # For each column
        a[i][j] = input()  # Input a value

print a
Community
  • 1
  • 1
supermitch
  • 2,062
  • 4
  • 22
  • 28