Search code examples
pythonrandom

Creating a random list of 4 letters in which each letter appears 15 times and does not repeat twice in a row


I would like to create a random list of 4 letters, with the letters 'A', 'B', 'C' and 'D', where each letter appears 15 times and the same letter is not repeated twice in a row.

I tried the code below but the letters repeated twice in a row appear in the result:

import random

def create_random_list():
    try:
        letters = ['A', 'B', 'C', 'D']
        freq = 15
        
        lst = []
        for letter in letters:
            lst += [letter] * freq
        
        random.shuffle(lst)
        
        # Check that no letter appears twice in a row
        for i in range(1, len(lst)):
            if lst[i] == lst[i-1]:

                # If a letter appears twice in a row, shuffle the list again
                random.shuffle(lst)
                break
        
        return lst
    except Exception as e:
        print(f"Error: {e}")
        return []

print(create_random_list())

Solution

  • The issue with your current code is that you're checking for consecutive letters that are the same after shuffling the list, but you're not guaranteeing that the initial shuffled list satisfies the condition. To solve this, you can modify your code as follows:

    import random
    
    def create_random_list():
        try:
            letters = ['A', 'B', 'C', 'D']
            freq = 15
        
            lst = []
            for letter in letters:
                lst += [letter] * freq
        
            while True:
                random.shuffle(lst)
            
            # Check that no letter appears twice in a row
                for i in range(1, len(lst)):
                    if lst[i] == lst[i-1]:
                        break
                else:
                    # No consecutive letters found, so the list is valid
                    return lst
        
        except Exception as e:
            print(f"Error: {e}")
            return []
    
    print(create_random_list())
    

    This modified code uses a while loop to keep shuffling the list until a valid arrangement is found where no letter appears twice in a row. The for loop checks for consecutive letters, and if it finds any, it breaks out of the loop and shuffles the list again. If the loop completes without finding any consecutive letters, it means the list is valid, and it is returned