how not to calculate all results of functions in a list

Question:

I want to do a function who return a different result depending on the letter given in parameter.

I dont wan’t to do something like this because it’s not clean and really long with a lot of values :

def get_result(letter, value):

if letter == "a":
    return(get_result_a(value))
elif letter == "b":
    return(get_result_b(value))
elif letter == "c":
    return(get_result_c(value))
elif letter == "d":
    return(get_result_d(value))
elif letter == "e":
    return(get_result_e(value))

So I did this :

def get_result(letter, value):

results = [get_result_a(value), get_result_b(value), get_result_c(value), get_result_d(value), get_result_e(value)]

letters = ["a", "b", "c", "d", "e"]

for i in range(len(results)):
    if letter == letters[i]:
        return results[i]

The code is really shorter but the problem is that python calculate the result of all the functions even if I don’t need it, and it makes my code very slow with a lot of values.

Does someone know if there is a way to only calculate the result that I want ?

Asked By: Alexandre Boucard

||

Answers:

Use a dictionary to map your functions:

def get_result(letter, value):
    mapper = {'a': get_result_a,
              'b': get_result_b,
              'c': get_result_c,
              'd': get_result_d,
              'e': get_result_e,
             }
    if letter in mapper:
        return mapper[letter](value)
    # or
    # return mapper.get(letter, default_function)(value)
Answered By: mozway
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.