0

Okay, I'm trying to generate a 10 character string containing specific characters. With the conditions being, the letters can NOT be repeats (but the numbers CAN), and the string can ONLY contain a total of TWO letters, no more, no less. The final string output MUST be 8 numbers, and 2 letters.

numbers = ["1", "2", "3"]
letters = ["X", "Y", "Z"]

i.e. the string output should be similar to

123X21Y213

The problem is, I don't know how to do this, elegantly. I did create a solution, but it was way too many lines, and it involved constantly checking the previous character of the string. I'm really bad at this, and need something simpler.

Any help would be appreciated.

1

1 Answer 1

5
numbers = ["1", "2", "3"]
letters = ["X", "Y", "Z"]

from random import sample, shuffle


samp = sample(letters,2)+sample(numbers*3,8)
shuffle(samp)

print("".join(samp))
113332X2Z2

Or use choice and range:

from random import sample, shuffle,choice

samp = sample(letters,2)+[choice(numbers) for _ in range(8)]
shuffle(samp)

print("".join(samp))
1212ZX1131
Sign up to request clarification or add additional context in comments.

2 Comments

How about numbers*8? As-is, the string 111111111XY cannot be generated (whereas it seems to be acceptable).
@ThomasOrozco, I added choice, that will allow 111111111XY.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.