Search code examples
pythonrandomfixed

Generate random strings of fixed length from given characters with equal occurance


I want to generate random strings from a list of characters C (e.g. C = ['A', 'B', 'C', 'D']). This random string shall have length N (e.g. N = 32). Every character should occur equally often - in that example 8 times.

How can I implement that each character occurs equally often in here:

''.join(random.choice(C) for i in range(N))

Or is there a better way?


Solution

  • I don't think you can guarantee that each item is picked with the same frequency if you use random.choice. Each choice is equally likely which isn't the same thing.

    The best way to do this would be to maintain a list of characters and shuffle it...

    characters = C * 8
    random.shuffle(characters)
    print(''.join(characters))
    

    Or, if you want a bunch of them:

    def get_random_strings(characters, count, N):
        """Yield `N` strings that contain each character in `characters` `count` times."""
        characters = list(characters) * count
        for _ in xrange(N):
            random.shuffle(characters)
            yield ''.join(characters)