1

I'm trying to generate random unique code with requirements :

  1. At least one number
  2. At least one string
  3. It should 8 characters
  4. 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

2
  • Generate a random number x between 1 and 8; that's the amount of numbers you'll draw from nums. Then 8-x is the amount of random strings you draw from chars. 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. Commented May 6, 2021 at 8:30
  • thank you Sanderjuth, it's work, but i like the way of Guy Commented May 6, 2021 at 8:54

2 Answers 2

3

Keep random.choice(rndstr) as a variable and decrease it from 8 when selecting random number

for i in range(total):
    str_len = random.choice(rndstr)
    selects = random.sample(chars, str_len) + random.sample(nums, 8 - str_len)
    random.shuffle(selects)
    unique_code = ''.join(selects)
    print(unique_code)
Sign up to request clarification or add additional context in comments.

2 Comments

thank's Guy, it's work, but how if requirements changes at least 2 numbers and at least 2 strings in a one line?
@here you can remove 1 and 7 from the rndstr list, you can use slice of it random.choice(rndstr[1:6]) and you can replace rndstr with range random.choice(range(2, 7)).
0

You can use randint to chose the number of digits, no need for list to choose from:

from string import ascii_uppercase as upp, digits as dig
from random import sample, shuffle, randint

for i in range(5):
    shuffle(s := sample(dig, n := randint(1, 7)) + sample(upp, 8-n))
    print("".join(s))

CYBOLN1K
3751NLIQ
05816R34
4012OC3E
GHWZB5SC

1 Comment

Okay thank you @schwobaseggl it works simple and fast, but i don't use all component in digits, but okay

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.