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)
Mad
  • 435
  • 2
  • 17
  • The first answer in that question would seem to work perfectly well for non-square matrices. – Nathan Pierson Aug 15 '20 at 05:40
  • 1
    I edited the question. See where I found it fails. – Mad Aug 15 '20 at 05: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. – Nathan Pierson Aug 15 '20 at 05:52

2 Answers2

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)])
mathfux
  • 5,759
  • 1
  • 14
  • 34
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]]
Akshay Sehgal
  • 18,741
  • 3
  • 21
  • 51