Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there other ways to obtain a value from 2 ranges?

Tags:

python

range

pong

I am learning Python, and I would like to know if there are other functions, methods, or techniques to obtain a value from two ranges. I provide the only example I could came up with with my current knowledge. Any leads are quite appreciated:

import random

def choose_random_angle():
    range1 = list(range(1, 76))  
    range2 = list(range(120, 231)) 
    combined_ranges = range1 + range2  
    return random.choice(combined_ranges)  

I was expecting to be able to include both ranges, separated by ";" or something along the lines. However, after reviewing the documentation, range function can only contain start, end, and step. The solution I have works, but I am sure there is a more efficient way.

like image 771
Cristian Campos Avatar asked Nov 01 '25 02:11

Cristian Campos


1 Answers

For this specific example, you could use a single range, and skip the gap, e.g.:

import random

def choose_random_angle():
    a = random.randint(1, 186)
    return a if a < 76 else a + 44

So 1-75 returns 1-75, and 76-186 returns 120-230.

This would be more efficient then generating a large list of numbers.

like image 83
Mark Tolonen Avatar answered Nov 02 '25 15:11

Mark Tolonen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!