mr Mad
mr Mad

Reputation: 21

How to create a random matrix (without using numpy)?

I am trying to create an array. When the number of rows and columns are not same, an empty [] appears at the end.

I also want it to be displayed in correct matrix form of [m x n]

I am new to using Python language and this is my first question.

I hope to find a solution to the problem.

import random

m = int(input("Rows : "))
n = int(input("Columns : "))
Mat = []
for i in range(0,n):
    Mat.append([])
for i in range(0,m):
    for j in range(0,n):
        Mat[i].append(j)
        Mat[i][j] = 0
        Mat[i][j] = random.randint(1,100)
print(Mat)

Example:

Columns : 2
Rows : 3

Output:

[[7, 49, 61], [47, 2, 40], []]

I need it like this:

[[7, 49, 61],
 [47, 2, 40]]

Upvotes: 0

Views: 579

Answers (1)

Prune
Prune

Reputation: 77847

The problem is here, where you specifically add one row for every column the user requests:

for i in range(0,n):
    Mat.append([])

Instead, use the variable for rows:

for i in range(0, m):
    Mat.append([])

There are several places where you are doing extra work, such as setting a value and then immediately destroying it.

Upvotes: 2

Related Questions