user5224720
user5224720

Reputation:

Create a combined list of random order from a fixed number of items

Say I have 3 different items being A, B and C. I want to create a combined list containing NA copies of A, NB copies of B and NC copies of C in random orders. So the results should look like this:

finalList = [A, C, A, A, B, C, A, C,...]

Is there a clean way to get around this using np.random.rand Pythonically? If not, any other packages besides numpy?

Upvotes: 2

Views: 182

Answers (3)

Sohaib Farooqi
Sohaib Farooqi

Reputation: 5666

You can define a list of tuples. Each tuple should contain a character and desired frequency. Then you can create a list where each element is repeated with specified frequency and finally shuffle it using random.shuffle

>>> import random
>>> l = [('A',3),('B',5),('C',10)]
>>> a = [val for val, freq in l for i in range(freq)]
>>> random.shuffle(a)
>>> ['A', 'B', 'A', 'B', 'B', 'B', 'C', 'C', 'C', 'C', 'C', 'C', 'C', 'C', 'A', 'C', 'B', 'C']

Upvotes: 3

cs95
cs95

Reputation: 402463

Yes, this is very much possible (and simple) with numpy. You'll have to create an array with your unique elements, repeat each element a specified number of times using np.repeat (using an axis argument makes this possible), and then shuffle with np.random.shuffle.

Here's an example with NA as 1, NB as 2, and NC as 3.

a = np.array([['A', 'B', 'C']]).repeat([1, 2, 3], axis=1).squeeze()
np.random.shuffle(a)

print(a)
array(['B', 'C', 'A', 'C', 'B', 'C'],
      dtype='<U1')

Note that it is simpler to use numpy, specifying an array of unique elements and repeats, versus a pure python implementation when you have a large number of unique elements to repeat.

Upvotes: 2

AndreyF
AndreyF

Reputation: 1838

I don't think you need numpy for that. You can use the random builtin package:

import random
na = nb = nc = 5
l = ['A'] * na + ['B'] *nb + ['C'] * nc
random.shuffle(l)

list l will look something like:

['A', 'C', 'A', 'B', 'C', 'A', 'C', 'B', 'B', 'B', 'A', 'C', 'B', 'C', 'A']

Upvotes: 3

Related Questions