Issue
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
Solution
Not ideal but it works.
First it gets random numbers from all ranges and next it selects (randomly) one value.
from random import randint, choice
for _ in range(5):
print(choice([randint(1,5),randint(9,15),randint(21,27)]))
As Blender said - cleaner version - first it selects (randomly) one range and later it gets random value from this range.
from random import randint, choice
for _ in range(5):
r = choice([(1,5),(9,15),(21,27)])
print(randint(*r))
Answered By - furas Answer Checked By - Terry (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.