Reputation: 105
import random
a = [0]
b = [1]
for row in range(1):
for colum in range(5):
random.shuffle(a and b)
print (" ".join( repr(e) for e in a + b[:5]))
Hey guys,
So I'm trying to create a 5 x 5 matrix filled with either 1s or 0s, however, having a bit of a hard time trying to achieve it. I gave it a go using the code above but no use. I'm new to python programming so be gentle haha.
This is the desired outcome: (There needs to be a MINIMUM of at least 10 1's within the matrix. Any idea of how to do that?
0 1 1 1 1
0 1 1 0 0
0 1 1 0 1
1 1 0 1 1
1 1 1 1 1
Any advice would be much, much appreciated. Thank you! :)
Upvotes: 2
Views: 354
Reputation: 780724
You can start by getting a random number between 10 and 25, and create a list with that many 1's followed by enough 0's to get to 25.
import random
ones = random.randint(10, 25)
l = [1] * ones + [0] * (25-ones)
[1] * ones
creates a list with ones
1's. [0] * (25-ones)
creates a list with the remaining 0's. These are then concatenated using the +
to produce a list with 25 total items.
Then shuffle this list:
random.shuffle(l)
and finally copy the values into the 5x5 matrix:
matrix = [l[i:i+5] for i in range(0, 25, 5)]
range(0, 25, 5)
iterates from 0
to 25
by 5
, i.e. 0
, 5
, 10
, etc. Then l[i:i+5]
takes a slice of 5 elements starting at each of those indexes. The list comprehension combines these all into a 2-dimensional list.
Upvotes: 4
Reputation: 660
In fact, my dear friend there is a simple approach for this problem, and you should put all your code after "if name == "main":".
import random
def log_matrix(matrix):
for r in range(len(matrix)):
print(" ".join([str(i) for i in matrix[r]]))
def sum_matrix(matrix):
return sum(map(sum, matrix))
def gen_matrix(row, col, minimum):
random_matrix = [[random.choice([0, 1]) for _ in range(row)]
for _ in range(col)]
while sum_matrix(random_matrix) < minimum:
random_matrix[random.choice([0, row - 1])][random.choice(
[0, col - 1])] = 1
return random_matrix
if __name__ == "__main__":
random_matrix = gen_matrix(5, 5, 10)
log_matrix(random_matrix)
Upvotes: 0
Reputation: 92440
random.choices
combined with a list comprehension is a quick way to do this. More often than not you will have 10 ones, but you can loop until you're certain:
from random import choices
total = 0
while total < 10:
matrix = [choices((0, 1), k=5) for i in range(5)]
total = sum(map(sum, matrix))
print(matrix)
[[1, 1, 1, 0, 0],
[1, 0, 0, 1, 0],
[1, 1, 0, 0, 0],
[0, 0, 1, 1, 0],
[1, 0, 1, 0, 0]]
Upvotes: 0
Reputation: 1362
You can use numpy.random.randint
>>> import numpy as np
>>> np.random.randint(0, 2, (5, 5))
array([[1, 1, 1, 0, 0],
[1, 0, 1, 1, 1],
[0, 1, 1, 0, 0],
[1, 0, 0, 0, 0],
[1, 0, 0, 0, 0]])
and then discard the solutions with less than 10 ones
For counting number of ones (as you only have 0s and 1s)
>>> data = np.random.randint(0, 2, (5, 5))
>>> data.sum()
13
Upvotes: 2