I'm trying to generate random unique code with requirements :
- At least one number
- At least one string
- It should 8 characters
- No repeating strings and numbers in one line
here's my code
import random
chars = 'CDHKPQRVXY'
nums = '123456789'
total = 10
rndstr = [1,2,3,4,5,6,7]
rndint = [1,2,3,4,5,6,7]
random.choice(rndstr)
random.choice(rndint)
for i in range(total):
selects = random.sample(chars, random.choice(rndstr)) + random.sample(nums, random.choice(rndint))
random.shuffle(selects)
unique_code = ''.join(selects)
print(unique_code)
Expected Output :
1DXVQP7H
V3H6QP2K
R3562197
CDVQXHK9
The problem with the code above is that it doesn't meet the third point
xbetween 1 and 8; that's the amount of numbers you'll draw fromnums. Then 8-xis the amount of random strings you draw fromchars. For both you make a copy of both lists, and remove that item once you've drawn it. That way you'll have 8 characters, at least one string, at least one number, and no repeating characters/numbers.