Generating Unique Random Numbers Within a Range
Generating a random number within a range in Python using random.randint() is a common task, as is creating a list of n such numbers. However, when each number in the list must be unique, a more sophisticated approach is required.
While using conditional statements to check for duplicates is an option, a simpler and more efficient solution exists. The random.sample() function can be employed to perform sampling without replacement. This function takes a population and a sample size k, and returns k random and unique members of the population.
import random population = range(1, 100) unique_random_numbers = random.sample(population, 3) print(unique_random_numbers) # Output: [77, 52, 45]
If k exceeds the length of the population, a ValueError will be raised. To handle this case gracefully, you can catch the exception and handle it appropriately.
try: random.sample(range(1, 2), 3) except ValueError: print('Sample size exceeded population size.')
By using random.sample(), you can effortlessly generate a set of unique random numbers within a specified range, eliminating the need for complex conditional checks.
The above is the detailed content of How to Generate Unique Random Numbers Within a Range in Python?. For more information, please follow other related articles on the PHP Chinese website!