mardi 8 décembre 2020

Define new variable according to the range of the values of another variable

This is a python function, which set the value for variable cor depending on the value of another variable (num_heavy_atoms): if num_heavy_atoms is in range [1:10], cor=1.0, if num_heavy_atoms is in range [11:20], cor=2.0, etc.

def determine_cor(num_heavy_atoms):
    if num_heavy_atoms >= 1 and num_heavy_atoms <= 10:
        cor = 1.0
    elif num_heavy_atoms >= 11 and num_heavy_atoms <= 20:
        cor = 2.0
    elif num_heavy_atoms >= 21 and num_heavy_atoms <= 30:
        cor = 3.0
    elif num_heavy_atoms >= 31 and num_heavy_atoms <= 40:
        cor = 4.0
    elif num_heavy_atoms >= 41 and num_heavy_atoms <= 50:
        cor = 5.0
    elif num_heavy_atoms > 50:
        cor = 6.0
    return cor 

Is it possible to rewrite this function in more compact way to avoid all of those elif, and define at the beginning all of the possible range for the variable (num_heavy_atoms)?

Aucun commentaire:

Enregistrer un commentaire