0

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?

2
  • 1
    I see nothing wrong with the way you are doing it. Commented Sep 16, 2016 at 17:24
  • Yup looks good the way it is Commented Sep 16, 2016 at 17:24

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.