+ 2
Python Number generator of multiple ranges.
How would I generate one random number from multiple ranges, example (0-10) and (20-30)
8 Antworten
+ 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)))
+ 7
Russ , may be you can shorten this by using:
lst = list(range(10,20)) + list(range(35,50))
+ 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))
+ 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.
+ 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! 👍
+ 4
Lothar Or this for more ranges..?
lst = []
[lst.extend(range(*i)) for i in ((10,21), (30,45), (60,85))]
+ 4
from random import randrange, randint
print(randrange(8, 21, 2)) # (start, stop, step)
# or
print(randint(4, 17))
0
Thank you!