如何用Python函数生成无重复数字的三位随机数(基于指定函数实现)
Solution for Generating Unique-Digit Three-Digit Random Number
Here's how you can implement the get_not_duplicated_random_number() function, with two practical approaches to choose from:
Approach 1: Reuse get_random_number() with Duplicate Check
This method leverages the existing function and adds a quick check to filter out numbers with repeated digits:
import random def get_random_number(): return random.randrange(100, 1000) def get_not_duplicated_random_number(): while True: num = get_random_number() # Convert to string to easily check digit uniqueness digit_str = str(num) # A set removes duplicates—if length is 3, all digits are unique if len(set(digit_str)) == 3: return num
How it works:
- We loop until we find a valid number (on average, this only takes 1-2 tries since 72% of three-digit numbers have unique digits).
- Converting the number to a string and using a set lets us quickly verify if any digits repeat.
Approach 2: Direct Generation (More Efficient)
If you want to avoid looping entirely, you can construct the number by generating unique digits one by one:
import random def get_not_duplicated_random_number(): # First digit: 1-9 (can't be 0 for a three-digit number) first_digit = random.randint(1, 9) # Second digit: any digit except the first second_digit = random.choice([d for d in range(10) if d != first_digit]) # Third digit: any digit except the first two third_digit = random.choice([d for d in range(10) if d != first_digit and d != second_digit]) # Combine digits into the final number return first_digit * 100 + second_digit * 10 + third_digit
This method skips the check entirely by ensuring each digit is unique from the start, making it slightly more efficient (though both approaches work perfectly for this use case).
内容的提问来源于stack exchange,提问作者Ihtiyor Abduazizov
相关产品推荐
相关产品推荐

