0

I was wondering if there's a way of compacting this code:

foo = calculate() # 'calculate' is some kind of function which
                  # could return float values less than 0.0 or more than 1.0
                  # It's here only as a (hopefully) clarification
bar = foo * 5 
if bar < 0:
    bar = 0
elif bar > 1:
    bar = 1
else:
    pass # 'bar' has a good value within the "range"

I know I could do bar = max(foo * 5, 0) or bar = min(foo * 5, 1) but... Is there a way of doing this in only one line? Something like bar = ensure_between(0, foo * 5, 1) or something like that?

It's not a big deal, I'm just curious.

Thank you in advance :-)

Savir
  • 17,568
  • 15
  • 82
  • 136

1 Answers1

3

A one-liner using min and max, resulting in either a number between 0 and 1, is this what you're looking for?

foo = max(0, min(foo, 1))

More suited to the example is

bar = max(0, min(foo, 1))

EDIT: fixed by removing the lists as soon pointed out

Community
  • 1
  • 1
Jamtot
  • 119
  • 1
  • 4