Search code examples
pythonlist

Choices Without Side By Side Duplicates


Hi! I am trying to print a list of letters (this list will never change) where duplicates are allowed but just not side by side that start with the same letter, but I need a set number of results, let's say 14 for this example. The below is what I have.

letters = ["A", "AAA", "B", "BBB", "C", "CCC", "D", "DDD", "E", "EEE"]                                                      groups = random.choices(letters, k = 14)                                                                                                print(groups)

Example return: ['B', 'CCC', 'AAA', 'A', 'EEE', 'D', 'DDD', 'B', 'B', 'A', 'C', 'E', 'AAA', 'BBB']                   Which is not great due to having 'AAA', 'A'--'D', 'DDD'---'B', 'B' next to each other.

Hope for something like this: ['B', 'CCC', 'A', 'BBB', 'EEE', 'D', 'AAA', 'B', 'E', 'B', 'CCC', 'E', 'AAA', 'BBB']    Where each string starts with a letter different than the one to the right / left of it.


Solution

  • Choose the strings one by one, and check each time if the first letter is different from the first letter of the last chosen string - if it isn't, just keep on trying other random choices.

    import random
    
    letters = ["A", "AAA", "B", "BBB", "C", "CCC", "D", "DDD", "E", "EEE"]                 
    
    expected_length = 14
    out = []
    for _ in range(expected_length):
        while True:
            new = random.choice(letters)
            if not out or new[0] != out[-1][0]:
                out.append(new)
                break
    print(out)
    #  ['C', 'AAA', 'EEE', 'D', 'CCC', 'D', 'AAA', 'DDD', 'C', 'E', 'A', 'BBB', 'EEE', 'AAA']