I've run into confusion in generating X amount of random integers from different sets of (a,b). For example, I would like to generate 5 random integers coming from (1,5), (9,15),and (21,27). My code generates 5 random integers but only between 21 and 27 and not from the other two. Ideally I'd like to see something like 1,4,13,22,25 instead of 21,21,25,24,27.
My code:
from random import randint
n = 0
while n < 5:
n += 1
for i in (randint(1,5),randint(9,15),randint(21,27)):
x = i
print i
Not ideal
As Blender said - clearer version
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:
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:
Let's see it in action:
An added benefit of
randomPicker
is that it can deal with any number of ranges.Hope this helps.
There are some interesting answers here, though I think this problem can be solved with a bit less code, even if it is a little bit less readable.
The basic idea here is that you have a fixed number of choices so you can essentially have one range to do the job and then plot the result to the ranges you want. Or if you want to consider it another way, create a function
f(x) -> y
that boils down to the same thing.Or, with a function:
If you're using Python 3.x, you should change
xrange
torange
.This foor loop will generate 3 random numbers one from the first range supplied, another for second range and last one for last range and prints every one on output. Yours print is out of the foor loop and prints only the last random number from the last range given.
for non repeated numbers: