Skip to content
Advertisement

How to make sure a pair of items in np.random.choice don’t appear together in a loop?

I’m currently trying to run a MonteCarlo simulation without replacement, using np.random.choice, but there are certain items in the list which cannot appear together. For example, if I have a list of five items: RO, MI, VE,NA, SI, and each loop produces a group of four items, RO can appear with VE, MI, or NA, but it cannot appear with SI, on each iteration. So a loop like: [RO,MI,VE,NA] is correct But not: [RO,MI,SI,NA] as SI appears in the same group as RO. This is the code I’m currently using (which is producing the incorrect grouping):

JavaScript

I’m at a loss as to what would do and any help would be appreciated. Thanks!

Advertisement

Answer

I present two solutions, both of which make use of the random module from the standard library. I recommend this approach over using numpy since you can’t really take advantage of numpy here in any way, and especially because you’re not even ending up with a numpy array at the end (you’re only using numpy for random number generation).

Solution 1: every sample has exactly one city from the “exclusive cities” group

Something you could do is have your cities which don’t play nice in a separate group from the others:

JavaScript

Here’s a contrived example:

JavaScript

Output:

JavaScript

Now something to be aware of is that this will guarantee that every sample has exactly one city from the exclusive_cities group:

JavaScript

Output:

JavaScript

Solution 2: every sample has at most one city from the “exclusive cities” group

If that’s not your desired behavior, you can use an additional “coin flip” to determine if 1 or 0 exclusive cities show up in a given sample with this minor modification to the above logic:

JavaScript

Now your samples may or may not include an exclusive city, but still only ever one max:

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement