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]
def select_within_bounds(li, lower=float('-inf'), upper=float('inf')):
return [v for v in li if lower <= v <= upper]
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With