Generating Unique Random Numbers within a Range
When generating random numbers, ensuring that each number is unique can be a challenge. While it's possible to use conditional statements to check for duplicates, this approach becomes cumbersome when dealing with large ranges or large numbers.
One straightforward method for generating a list of unique random numbers is to use Python's random.sample() function. This function takes two arguments: a population (the range of numbers within which to generate the random numbers) and a sample size (the number of unique numbers to generate).
For example, to generate three unique random numbers within the range 1 to 100, you would use the following code:
import random random_numbers = random.sample(range(1, 101), 3)
The random.sample() function will return a list of three unique random numbers from the specified range, such as:
[77, 52, 45]
This method is particularly useful when dealing with large ranges or large numbers of random numbers, as it avoids the need for complex conditional statements to check for duplicates. Additionally, the random.sample() function ensures a uniform distribution of the generated numbers, which is essential for many applications.
The above is the detailed content of How to Generate Unique Random Numbers within a Specific Range in Python?. For more information, please follow other related articles on the PHP Chinese website!