+ 2

Python Number generator of multiple ranges.

How would I generate one random number from multiple ranges, example (0-10) and (20-30)

30th Sep 2020, 3:51 PM
Tom Klein
Tom Klein - avatar
8 Réponses
+ 7
A different approach, that is doing this: - in the inner choice(), the various ranges are stored in a list. choice() selects one of these range() objects and returns it to the outer choice - in the outer choice the selected object from the inner expression will give a number back that wil be the result: from random import choice print(choice(choice([range(0,15), range(30,45), range(60,75)]))) [edited] added an other version that has a better readabilty than the other ones. from random import choice rngs = [[0,15], [30,40], [90,110]] res = [range(*x) for x in rngs] print(choice(choice(res)))
30th Sep 2020, 6:02 PM
Lothar
Lothar - avatar
+ 7
Russ , may be you can shorten this by using: lst = list(range(10,20)) + list(range(35,50))
30th Sep 2020, 6:07 PM
Lothar
Lothar - avatar
+ 6
You could put all ranges into a list, then choose a number from the list at random. import random rand_list = [] rand_list += list(range(11)) rand_list += list(range(20, 31)) print(random.choice(rand_list))
30th Sep 2020, 4:02 PM
Russ
Russ - avatar
+ 6
Russ , you are absolutely right when ranges are too different in size. This was an issue i was not aware of. Thanks for you helpful comment. Also thanks for your last comment.
30th Sep 2020, 7:34 PM
Lothar
Lothar - avatar
+ 4
Lothar I had considered that before posting my answer but if the ranges are of different sizes, it would create an uneven distribution of probabilities over all the numbers. Great code though! 👍
30th Sep 2020, 6:04 PM
Russ
Russ - avatar
+ 4
Lothar Or this for more ranges..? lst = [] [lst.extend(range(*i)) for i in ((10,21), (30,45), (60,85))]
30th Sep 2020, 6:36 PM
Russ
Russ - avatar
+ 4
from random import randrange, randint print(randrange(8, 21, 2)) # (start, stop, step) # or print(randint(4, 17))
30th Sep 2020, 9:59 PM
Vitaly Sokol
Vitaly Sokol - avatar
0
Thank you!
30th Sep 2020, 5:11 PM
Tom Klein
Tom Klein - avatar