Trying to exclude an elements in an array if it overlaps with another array in Python

I am writing code that pseudorandomises positions from an array:

centre_pos = ['A','B','C','D','E']
corner_pos = ['1','2','3','4']

def position_generator():
    #for centre, corner in zip(centre_pos, corner_pos):
    random_centre = random.choice(centre_pos)
    random_corner = random.choice(corner_pos)

    #if random_centre and random_corner in exclusion:

    #else:
    return random_centre, random_corner

However, I want to exclude certain combinations of centre_pos and corner_pos. For example if B and 1 occur in the same pseudorandomisation, then exclude this.
I want to exclude all these combinations:

exclusion = [('B', 1), ('C', 2), ('D', 3), ('E', 4)]

How do I get the ‘exclusion’ list to be excluded if any one of these positions occur?

>Solution :

You can generate the combinations with itertools.product, filter out the unwanted ones, then pick a random one with random.choice:

import random
from itertools import product

def position_generator():
    
    centre_pos = ['A','B','C','D','E']
    corner_pos = ['1','2','3','4']
    
    exclusion = set([('B', '1'), ('C', '2'), ('D', '3'), ('E', '4')])
    
    return random.choice([x for x in product(centre_pos, corner_pos)
                          if x not in exclusion])

position_generator()
# ('B', '3')

If you plan to generate several coordinates, you might want to create a generator instead:

import random
from itertools import product

def position_generator():
    
    centre_pos = ['A','B','C','D','E']
    corner_pos = ['1','2','3','4']
    
    exclusion = set([('B', '1'), ('C', '2'), ('D', '3'), ('E', '4')])
    
    pos = [x for x in product(centre_pos, corner_pos) if x not in exclusion]
    random.shuffle(pos)
    
    return iter(pos)

gen = position_generator()

next(gen)
# ('E', '3')

next(gen)
# ('D', '1')

Leave a Reply