4

I have a function

def max_f(tup, val):
    max = tup[0](val)
    out = tup[0]
    for funz in tup:
        new = funz(val)
        if new > max: 
            max = new
            out = funz
    return out

and I would like to write it in a better way. I tried with

def max_f2(tup, val):
    return (max(funz(val) for funz in tup))

but I should return a function, not a value. How could I?

These are some examples of correct outputs

tupleFunz=(lambda x: x + 3 ,lambda x: x * 2,lambda x: x % 2)
max_f(tupleFunz,4)(8) #=> 16
max_f(tupleFunz,1)(8) #=> 11 
CDJB
  • 14,043
  • 5
  • 29
  • 55
Alberto
  • 83
  • 2
  • 7

1 Answers1

5

You can do this using max() and the key argument with a lambda function:

def max_f(tup, val):
    return max(tup, key=lambda x: x(val))

Output:

>>> tupleFunz=(lambda x: x + 3 ,lambda x: x * 2,lambda x: x % 2)
>>> max_f(tupleFunz,4)(8)
16
>>> max_f(tupleFunz,1)(8)
11
CDJB
  • 14,043
  • 5
  • 29
  • 55