Search code examples
pythonarraysrandom

Python: How to generate a random array only consisting of a specific number of -1, 0, 1?


Is there a standard way in Python to generate an array (of size 15), where precisely three 1s and four -1s are placed randomly and the remaining array entries are 0?

An example for such an array would be

0 0 0 0 1 1 0 -1 1 -1 -1 0 0 0 -1

Solution

  • Using random.sample:

    from random import sample
    array = sample([1, -1, 0], 15, counts=[3, 4, 8])
    print(array)
    

    Note that counts argument requires Python 3.9.

    Using random.shuffle:

    from random import shuffle
    array = 3 * [1] + 4 * [-1] + 8 * [0]
    shuffle(array)
    print(array)
    

    Example output:

    [0, -1, 0, 0, 1, -1, -1, 0, 0, 0, -1, 1, 0, 0, 1]