How to flag a given value based on a range rule

Question:

I’ve flags, each range of value has a flag.
for ex :

  • value = 0 is D
  • value > 0 and < 0.2 is C
  • value >=0.2 and <=0.8 is B
  • value > 0.8 is A

flag = ["A", "B", "C", "D"]

def get_flag(value) : 
            if value == 0: return "D"
            elif value > 0.8: return "A"
            elif value <=0.8 and value >= 0.2: return "B"  
            else: return "C"

i think this implementation is annoying and not algorthmically pretty to see, any suggestions so i can get the correct index in python, i thought about modulo and div but values are floats between 0 and 1.

Asked By: Moun

||

Answers:

Reorder your conditions:

def get_flag(value) : 
    if value == 0: return "D"
    elif value < 0.2: return "C"
    elif value <= 0.8: return "B"
    else: return "A"

It looks pretty clear to me what the ranges are now.

Answered By: Nelfeal

Yet another option to improve readability:

def get_flag(value):
    if value >= 0.8:
        return('A')

    elif value >= 0.2:
        return('B')
    
    elif value > 0:
        return('C')
    
    else:
        return('D')
Answered By: flyakite

You don’t need elif and else here, since return ends the execution of the function (so that lines after a return are not executed if the preceding return is triggered):

def get_flag(value) : 
    if value == 0: return "D"
    if value < 0.2: return "C"
    if value <= 0.8: return "B"
    return "A"
Answered By: Schnitte

Using the same idea as @aa_nador (his answer has been deleted), store the separation points and flags in the list, and determine the index through binary search. Here, the second separation point is the next floating point number in the negative direction of 0.2 instead of 0.2 so that 0.2 can be distributed to index 2:

>>> seps = [0, math.nextafter(0.2, -math.inf), 0.8]
>>> flags = list('DCBA')
>>> {i / 10: flags[bisect.bisect_left(seps, i / 10)] for i in range(10)}
{0.0: 'D',
 0.1: 'C',
 0.2: 'B',
 0.3: 'B',
 0.4: 'B',
 0.5: 'B',
 0.6: 'B',
 0.7: 'B',
 0.8: 'B',
 0.9: 'A'}
Answered By: Mechanic Pig