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), (
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.
from random import randint
for i in xrange(5):
n = randint(1,19)
if n > 12:
print(n + 8)
elif n > 5:
print(n + 3)
else:
print(n)
Or, with a function:
from random import randint
def plot_to_ranges(n):
if n > 12:
return n + 8
elif n > 5:
return n + 3
else:
return n
for i in xrange(5):
n = randint(1,19)
print(plot_to_ranges(n))
If you're using Python 3.x, you should change xrange
to range
.