简体   繁体   中英

Creating a random number block of 0s and 1s

        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! :)

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 , ie 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.

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

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]]

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM