python中的重写功能-优化

时间:2019-04-18 03:23:43

标签: python function optimization

有没有一种方法可以优化此功能?原始版本在元组中具有更多参数,因此无法使用更多if和elif进行缩放。

from statistics import median

rule=[1,2,3]
direction=['up','down']

def function_db(mount,rule,direction):

        item=range(1,10)

        # --------------------------------------------------------------------------------
        # Porcentajes
        # --------------------------------------------------------------------------------
        if rule==1 and direction == 'up' :
            final_item = min(item)*(1+mount/100)

        elif rule==2 and direction == 'up' :
            final_item = max(item)*(1+mount/100)

        elif rule==3 and direction == 'up' :
            final_item = median(item)*(1+mount/100)

        elif rule==1 and direction == 'down' :
            final_item = min(item)*(1-mount/100)

        elif rule==2 and direction == 'down' :
            final_item = max(item)*(1-mount/100)

        elif rule==3 and direction == 'down' :
            final_item = median(item)*(1-mount/100)

        return final_item


function_db(10,3,"up")

3 个答案:

答案 0 :(得分:1)

实际上这甚至可以是单线的:

def function_db(mount,rule,direction):
     items = [0, 9, 5]
     directions = {"up": 1, "down": -1}

     return items[rule-1]*(1+ directions[direction]*mount/100)

答案 1 :(得分:1)

from statistics import median

rule=[1,2,3]
direction=['up','down']

def function_db(mount,rule,direction):
        dic={1:min,2:max,3:median}
        direct = {'up':1,'down':-1}
        item=range(1,10)
        final_item = dic[rule](item)*(1+(mount/100)*direct[direction])
        return final_item

答案 2 :(得分:1)

我试图优化代码的布局(减少if-elses的数量),但仍保持可读性。我认为规则将比指示更多,因此选择将规则放入功能列表中。因此,添加新规则只需将函数名称附加到rules中即可。

显然可以排除multiplicand的某些功能恒定部分,但我认为这大大牺牲了可读性。

我还认为值得检查(并提出)错误。

from statistics import median

def function_db( mount, rule, direction ):

    item  = range( 1, 10 )
    rules = [ min, max, median ]

    if ( direction == 'up' ):
        multiplicand = ( 1+mount/100 )
    elif ( direction == 'down' ):
        multiplicand = ( 1-mount/100 )
    else:
        raise( ValueError( 'Unknown direction [' + str( direction ) + ']' ) )

    if ( rule == 0 or rule > len( rules ) ):
        raise( ValueError( 'Unknown rule-code [' + str( rule ) + ']' ) )


    # Compute the result
    multiplier = rules[ rule-1 ]( item )

    final_item = multiplier * multiplicand
    return final_item



print( "RESULT=%f" % ( function_db( 10, 3, "up" ) ) )