1

I have to write a program that creates a square matrix by user defined dimensions. So if a user enters "3" as the dimension, I want my program to display a 3 by 3 matrix. I have to fill in the matrix with random numbers between 1 and 15. So far I have this:

dimension = int(input("Enter the number of rows and columns: \n")) 
import random
for i in range(1,dimension):
    randomMatrix = random.sample(range(1,16), dimension)
print(randomMatrix)

However, it just displays one row of the matrix and not all that the user specified. I don't know how to white the loop so that it loops the random list to create a random matrix by the dimensions specified by the user. Any help would be greatly appreciated.

Peter O.
  • 32,158
  • 14
  • 82
  • 96

3 Answers3

3

I suggest you to use numpy:

import numpy as np

dimension = int(input("Enter the number of rows and columns: \n")) 

randomMatrix = np.random.randint(0,16, size=(dimension,dimension))

print(randomMatrix)
godot
  • 3,422
  • 6
  • 25
  • 42
2

.append to the randomMatrix:

dimension = int(input("Enter the number of rows and columns: \n"))
import random
randomMatrix = []
for i in range(1,dimension):
     randomMatrix.append(random.sample(range(1,16), dimension))
print(randomMatrix)

This is not recommended if you are allowed to use numpy, then use the other answer.

Wasif
  • 14,755
  • 3
  • 14
  • 34
1

your code seems fine and in case you dont want use numpy as @godot suggested (which i totally agree with him) u just need to store each list in a outer list resulting in nested list :

dimension = int(input("Enter the number of rows and columns: \n")) 
import random
randomMatrix =[]
for i in range(1,dimension):
    randomMatrix.append(random.sample(range(1,16), dimension))
print(randomMatrix)

>>> Enter the number of rows and columns: 
 5
[[13, 2, 14, 4, 8], [7, 11, 4, 2, 8], [8, 15, 14, 13, 5], [10, 15, 2, 1, 12]]
adir abargil
  • 5,495
  • 3
  • 19
  • 29