Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading