0

I checked the solution in Creating a Matrix in Python without numpy but this only address square matrixes. That is 3x3 or 4x4.

For example, I tried the answer in those questions with the following lines and it gives list index out of range error.

random_list = random.sample(range(10,99), 10)
print(len(random_list))
mat = createMatrix(5,2,random_list)
print (mat)

My question is given a list with numbers, how to put it into a matrix.

e.g.

column = input("No of Column: ")
rows = input("No of Rows: ")
randomDataList = random.sample(range(10,99), int(column)* int(rows))
createMatrix(int(column), int(rows), randomDataList)
3
  • The first answer in that question would seem to work perfectly well for non-square matrices. Commented Aug 15, 2020 at 5:40
  • 1
    I edited the question. See where I found it fails. Commented Aug 15, 2020 at 5:45
  • Oh, yes, it looks like there's a bug. I commented on the original question, but repeating it here: Changing rowCount to colCount in the innermost portion of createMatrix's for loop should fix it. Commented Aug 15, 2020 at 5:52

2 Answers 2

1

Another way of list comprehension:

import random
column = input("No of Column: ")
rows = input("No of Rows: ")
n, m = int(rows), int(column)
randomDataList = random.sample(range(10,99), n*m)
print([[randomDataList[i+m*j] for i in range(m)] for j in range(n)])
Sign up to request clarification or add additional context in comments.

1 Comment

2 nested for loops too much of a stretch?
0

You can use a list comprehension to build a list of lists -

import random

r, c = 4, 5

l = random.sample(range(-10,10),r*c)

matrix = [l[i:i + int(r*c / c)] for i in range(0, len(l), int(r*c / c))]
print(matrix)
[[-10, -4, 7, 4], [1, 9, -5, 6], [-8, 5, 3, -9], [-2, 2, 8, -7], [0, -6, -1, -3]]

5 Comments

Cannot use Numpy
Numpy has not been used for the solution. Only to generate the random input list that has to be converted to a 'matrix'
np.random.random, unlike random.sample, does not return unique numbers here.
My bad. Yes, got it.
Updated my solution just because. @MarioIshac - So?

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.