Reputation: 75
I am new to programming and python. I am trying to create a matrix(6, 6) with random numbers within a certain range. Each number must be twice. Should I use matrix, multi dimensional array or list of lists? I'd like to know what is the easiest way to achieve this.
This is what I have right now:
rows = 6
columns = 6
range(0, 18)
matrix = [[0 for x in range(rows)] for y in range(columns)]
# Loop into matrix to fill with random numbers withing the range property.
# Matrix should have the same number twice.
for row in matrix:
print(row)
Upvotes: 1
Views: 899
Reputation: 6132
Assuming you're looking for integers, it's as easy as this:
import numpy as np
import random
number_sample = list(range(18))*2 #Get two times numbers from 0 to 17
random.shuffle(number_sample) #Shuffle said numbers
np.array(number_sample).reshape(6,6) #Reshape into matrix
array([[ 1, 0, 5, 1, 8, 15],
[ 9, 3, 15, 17, 0, 14],
[ 7, 9, 11, 7, 16, 13],
[ 4, 10, 8, 12, 5, 6],
[ 6, 11, 4, 14, 3, 13],
[10, 16, 2, 17, 2, 12]])
Edit: Changed answer to reflect changes in your question
Upvotes: 3
Reputation: 124648
You could:
2 * list(range(18))
The result will be a matrix that meets your requirements, using only the standard library.
Something like this:
import random
nums = 2 * list(range(18))
random.shuffle(nums)
matrix = [nums[i:i+6] for i in range(0, 36, 6)]
Upvotes: 3