Unique Random Number Generation Within a Range
Given the ability to generate a random number within a range using random.randint, the task arises of generating a list of unique random numbers. While iterative conditional statements may serve as a solution, a more elegant approach exists for efficiently achieving this outcome.
Random Sampling
Python's random module provides a function named sample specifically designed for sampling without replacement. This function takes a population (e.g., a list of numbers) and a sample size as arguments and returns a list of randomly selected unique elements from the population.
For example, to generate a list of 3 unique random numbers within the range [1, 100], one can use the following code:
import random population = range(1, 100) # Initialize the population sample_size = 3 # Set the sample size random_sample = random.sample(population, sample_size)
random_sample will now contain a list of 3 unique random numbers within the specified range.
Handling Size Discrepancies
It is important to note that if the sample size exceeds the population size, sample will raise a ValueError. To handle this scenario, one can use a try-except block to catch the exception and handle it accordingly.
For instance, to attempt generating a sample of size 3 from a population of size 2, one can write the following code:
try: random.sample(range(1, 2), 3) except ValueError: print('Sample size exceeded population size.')
If the sample size is larger than the population size, this code will print an informative message rather than crashing.
The above is the detailed content of How Can I Generate a List of Unique Random Numbers Within a Range in Python?. For more information, please follow other related articles on the PHP Chinese website!