1

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.

Moun
  • 325
  • 2
  • 16
  • It depends on what is your input. If you're working with pandas dfs, maybe this is what you're looking for. [pd.cut answer](https://stackoverflow.com/questions/55677210/how-to-categorize-a-range-of-values-in-pandas-dataframe) – imburningbabe Oct 10 '22 at 12:31
  • What is the associated flag for *value == -1* ? In your implementation it would be 'C' but that doesn't fit with your description – DarkKnight Oct 10 '22 at 12:43
  • @OldBill i normalize the data between 0 and 1, so i'm sure to not get any value <0 – Moun Oct 10 '22 at 12:51

4 Answers4

1

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.

Nelfeal
  • 12,593
  • 1
  • 20
  • 39
1

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"
Schnitte
  • 1,193
  • 4
  • 16
0

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')
flyakite
  • 724
  • 3
  • 6
0

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'}
Mechanic Pig
  • 6,756
  • 3
  • 10
  • 31