user14748664
user14748664

Reputation:

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)?

Upvotes: 1

Views: 40

Answers (2)

uditha
uditha

Reputation: 47

You can use the following function.

def determine_cor(num_heavy_atoms):
    heavy_atoms = [10,20,30,40,50]
    for i , val in enumerate(heavy_atoms, start=1):
        if num_heavy_atoms <= val :
            return i    
    return 6

Upvotes: 0

a_guest
a_guest

Reputation: 36329

You can use a dictionary and compute the key from num_heavy_atoms:

cor_values = {i: i+1 for i in range(5)}
cor = cor_values.get((num_heavy_atoms-1) // 10, 6)

This assumes num_heavy_atoms >= 1 which seems reasonable for your application.

Alternatively you can compute cor directly from num_heavy_atoms in the following way:

cor = (num_heavy_atoms-1) // 10 + 1
cor = min(cor, 6)

Upvotes: 1

Related Questions