python random number generator for long list of numbers

Viewed 47

I was wondering if anyone could help me write a better program. My goal is to make a random number generatorm but it has very specific perameters. I need to find a random number that looks for a random number for unit numbers in a housing compley. the parameters are between 101-112, 114-125, 128-149, 201-230, 232-263, 265-280 and 300-305. I made a list with every number and then called the random number function, but I was just wondering if there was an easier way or a more concise way to make this program. Thank you!

2 Answers

I think you should use

flat_num = random.choise(flats) 

if you have your number in some Iterable struct

or

you can random range and then select from selected range if you have just a numbers like this:

flat_num = random.randint(
  *random.choice(
    [(101,112),(114,125),(128,149),(201-230),(232-263),(300-305)]
  )
)

In order to make sure that your choice is equiprobable, your could start by choosing among your ranges with weights equal to the number of values in each range. random.choices allows you to specify weights.

You can then simply choose any value in the selected range:

import random

def random_in_ranges(ranges):
    weights = [end - start + 1 for start, end in ranges]
    range_ = random.choices(ranges, weights=weights)[0]
    return random.randint(*range_)




ranges = [(101,112), (114,125), (128,149), (201,230), (232,263), (265,280), (300,305)]
print(random_in_ranges(ranges))
# 262
Related