How to generate 3 no-digit repeated random integers, each with distinct digits in Python

1 Answer

0 votes
import random

# ------------------------------------------------------------
# Function: generate_number
# Purpose: Create one 3-digit integer with distinct digits,
#          drawn from a shared pool of available digits.
#          The first digit is never zero, so the result
#          is always a true 3-digit integer.
# ------------------------------------------------------------
def generate_number(available_digits, length=3):
    # Choose the first digit from the pool, excluding '0'
    non_zero_digits = [d for d in available_digits if d != '0']
    first_digit = random.choice(non_zero_digits)
    available_digits.remove(first_digit)

    # Choose the remaining digits from the updated pool
    remaining = random.sample(available_digits, length - 1)

    # Remove chosen remaining digits from the pool
    for d in remaining:
        available_digits.remove(d)

    # Build the number as a string, then convert to int
    digits_str = first_digit + "".join(remaining)
    return int(digits_str)


# ------------------------------------------------------------
# Function: generate_three_distinct_digit_numbers
# Purpose: Produce three integers, each with distinct digits,
#          and no digit repeated across all three numbers.
#          All numbers are guaranteed to be 3 digits long.
# ------------------------------------------------------------
def generate_three_distinct_digit_numbers():
    # Start with all digits 0–9 as strings
    digits = [str(i) for i in range(10)]

    # Generate three numbers, each 3 digits long
    n1 = generate_number(digits)
    n2 = generate_number(digits)
    n3 = generate_number(digits)

    return n1, n2, n3


# ------------------------------------------------------------
# Main execution
# ------------------------------------------------------------
if __name__ == "__main__":
    # Run the generator 5 times
    for _ in range(5):
        result = generate_three_distinct_digit_numbers()
        print(result)


"""
run:

(514, 860, 973)
(165, 934, 207)
(596, 743, 810)
(894, 720, 163)
(408, 279, 136)

"""

 



answered Jul 16 by avibootz
edited Jul 17 by avibootz

Related questions

...