Python- How to generate random integers with multiple ranges?
Not ideal
from random import randint, choice
for _ in range(5):
print(choice([randint(1,5),randint(9,15),randint(21,27)]))
As Blender said - clearer version
from random import randint, choice
for _ in range(5):
r = choice([(1,5),(9,15),(21,27)])
print(randint(*r))
Hi!
This is an interesting question; it becomes interesting when you realize that to achieve true randomness, the probability of picking a particular range must be weighed by the length of that range.
Ranges of Equal Length:
If the three ranges are of equal length, say range(0, 10), range(20, 30) and range(40, 50); then, to pick a single random number, we may do the following:
- Pick a range at random.
- Pick a random number from that range.
Ranges of Unequal Length:
Now, consider three of unequally sized ranges, say range(0, 2), range(4, 6) and range(10, 100);
The third range is much larger than the first two. If we employ the same strategy we employed in dealing with equally long ranges, we will be biased towards picking numbers from the first two ranges.
In order to pick truly random numbers from the three unequally long ranges, there are two strategies.
Strategy 1: Using probability
The probability of picking a range should be such that the probability of picking a number remains the same. We could accomplish this by weighing down the probability of piking shorter ranges.
However, instead of computing probability weights; there's a better solution. See Strategy 2.
Strategy 2: Merging the ranges
We could simply merge the three ranges into a single single range. Then, randomly pick a number from the merged range. It's simple:
import random;
def randomPicker(howMany, *ranges):
mergedRange = reduce(lambda a, b: a + b, ranges);
ans = [];
for i in range(howMany):
ans.append(random.choice(mergedRange));
return ans;
Let's see it in action:
>>> randomPicker(5, range(0, 10), range(15, 20), range(40, 60));
[47, 50, 4, 50, 16]
>>> randomPicker(5, range(0, 10), range(70, 90), range(40, 60));
[0, 9, 55, 46, 44]
>>> randomPicker(5, range(0, 10), range(40, 60));
[50, 43, 7, 42, 4]
>>>
An added benefit of randomPicker
is that it can deal with any number of ranges.
Hope this helps.