1

I'm attempting a problem which asks me to define a func() that generates 4 unique random integers from 2-8 (inclusive). I've got everything working so far, except that I can't figure out if it's even possible to ensure that the next randomly generated integer isn't a repeat from the given range (2-8)

Code so far:

def get_unique_code():
    code_str = ""

    while len(code_str) != 4:
        x = str(random.randint(2,8))
        code_str += x
    return code_str

Expected output: 6842

Got: 6846

greg-449
  • 109,219
  • 232
  • 102
  • 145

2 Answers2

2

You can generate a list of random numbers, map to string and join them together. Don't forget to add +1 to your upper bound to make it inclusive.

import random


def get_unique_code():
    return ''.join(map(str, random.sample(range(2, 8 + 1), 4)))


print(get_unique_code())

See:

Henry Ecker
  • 34,399
  • 18
  • 41
  • 57
1

We can check if the character is already in the string:

def get_unique_code():
    code_str = ""

    while len(code_str) != 4:
        cont = False
        while not cont:
            x = str(random.randint(2,8))
            if x not in code_str:
                cont=True
        code_str += x
    return code_str
Star
  • 131
  • 3
  • 18