Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python filter numbers within optional bounds (use less if-else)

I want to select elements from list of numbers within lower and upper bounds, each of which is optional. I can write it as a series of if and else for all possible cases. Can we reduce these branching and write in a concise way?

def select_within_bounds(li, lower=None, upper=None):
    if lower is None:
        if upper is None:
            return li
        else:
            return [v for v in li if v <= upper]
    else:
        if upper is None:
            return [v for v in li if v >= lower]
        else:
            return [v for v in li if lower <= v <= upper]

#example:
my_list = [1, 4, 5, 3, 6, 9]
print(select_within_bounds(my_list))
print(select_within_bounds(my_list, 3, 8))
print(select_within_bounds(my_list, lower=3))
print(select_within_bounds(my_list, upper=8))
print(select_within_bounds(my_list, lower=3,upper=8))

#results in 
[1, 4, 5, 3, 6, 9]
[4, 5, 3, 6]
[4, 5, 3, 6, 9]
[1, 4, 5, 3, 6]
[4, 5, 3, 6]
like image 358
Yashoda Neupane Avatar asked May 25 '26 09:05

Yashoda Neupane


2 Answers

def select_within_bounds(li, lower=float('-inf'), upper=float('inf')):
    return [v for v in li if lower <= v <= upper]
like image 109
petabyte Avatar answered May 27 '26 23:05

petabyte


Yes you can, using python's filter built-in function. Like so:

def select_within_bounds(li, lower=None, upper=None):
    return filter(lambda x: (x if lower is None else lower) <= x <= (x if upper is None else upper), li)
like image 33
Chitharanjan Das Avatar answered May 27 '26 22:05

Chitharanjan Das



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!