Generating random numbers within a range excluding a subrange

I’ve seen questions and answers for generating a set of numbers within one range but excluding specific numbers like here

https://stackoverflow.com/a/41643919/3259896

But I am wondering if there’s any computational efficiency for selecting a number from one range, but excluding a whole sub range.

So I would want to pick a number between 0 and 200, excluding numbers 75 to 130.

The obvious solution to declare whole lists for the entire possible ranges of 0 to 75 and 130 to 200, concatenate them, and select a number from that range.

import random
allowed_values = list(range(0, 75)) + list(range(130, 200))

# can be anything in {-5, ..., 5} \ {0}:
random_value = random.choice(allowed_values)

This seems a bit wasteful time-wise and space-wise. Is there a more efficient solution due to efficiencies of excluding a whole range instead of specific numbers?

>Solution :

It looks like you’re using Python range conventions to describe all of your ranges, i.e. they’re all inclusive of the lower bound and exclusive of the upper bound. So the desired numbers are in the range 0 through 74 inclusive, and 130 through 199 inclusive. That’s what the posted code does.

The following is compatible with that:

x = random.randrange(0, 145)
if x >= 75:
    x += 55

x is initially in the range 0 through 144, inclusive. If it’s >= 75, then it’s initially in the range 75 through 144, inclusive. In this case, it adds 55 to x, placing it in the range 130 through 199, inclusive. This is consistent with the behavior of the posted code.

If you in fact intended the original ranges to be inclusive of the upper bounds, rather than what the posted code does, then it’s easy to adjust this to accommodate the desired ranges.

Leave a Reply