Too many elif statements: return ()?

I have a function that passed two arguments:

def function(a, b):
    if   a == 'd' : return(4*b)
    elif a == '!' : return(5)
    elif a == 'k' : return(1-2*k+k**2)
    elif a == 'Z' : return(1/k)
    (...)

achecks its equality by one character, and is balways a number; the function always returns a number. Sometimes this is not always a simple comeback.

def function(a, b):
    (...)
    elif a == '2':
        temp_b = foo(b)
        if b == 2 : temp_b += 2
        return(temp_b)

I have a very long list of elif statements, is there a better way to do this?

+4
source share
2 answers

Actually yes. First, Python does not have a signed operator switchthat provides a binary search when the operator becomes long enough, which is much faster than a linear search.

Python , :

def other_case(x):
    '''We can store non-lambdas too'''

    return 8

functions = {
    'd': lambda x: 4*x,
    '!': lambda x: 5,
    'k': lambda x: (1-2*x+x**2),
    'Z': lambda x: (1/x),
    '*': other_case,
}

, :

def call(a, x):
    return functions[a](x)

O (1) , , , .

Edit

, , . , - 2000 5000 ( ), 100 . 500 , 30 .

from __future__ import division         # for //, floor division

def mass2000(x):
    '''Do something for mass of 2000'''

    return 1/x

def mass2100(x):
    '''Do something for mass of 2100'''

    return x

def mass2200(x):
    '''Do something for mass of 2200'''

    return x**2


lookup = [
    mass2000,
    mass2100,
    mass2200,
    # ....
]


def call(mass, x):
    if (mass < 2000 or mass > 5000):
        raise ValueError("Mass out of range")

    return lookup[(mass - 2000) // 100](x)
+8

- -, , /- .

:

def function_2(b):
    temp_b = foo(b)
    if b == 2 : temp_b += 2
    return(temp_b)

fp = {
    2 : function_2
}

, , b .

for element in fp:
    if element == a:
        fp[element](b)
+1

Source: https://habr.com/ru/post/1680378/


All Articles