-1

I am trying to return a chained function

In the below I would like to give it a list of values that map to functions. For example from the code below

get_function([0,1,2])

returns the function

fun(x , [a,b,c]) = a*b/x**c = mult(div(pow(x,c),b),a)

What I have so far is close

def get_function(function_params):
    def fun(x,params):
        func = x
        for i in range(1,len(function_params)):
            if function_params[i] == 0:
                func = pow(func,params[-i])
            elif function_params[i] == 1:
                func = div(func,params[-i])
            elif function_params[i] == 2:
                func = mult(func,params[-i])
        return func
    return fun

Obviously I could use this giant list of if statements but I would like it to be faster so returning the function will give a decent performance boost. Note: this is a MRE

tjaqu787
  • 295
  • 2
  • 16
  • So, does `get_function()` work at the moment? Why do you test (eg): `if function_params == 0:`? – quamrana Oct 15 '22 at 15:54
  • @quamrana it works but it includes the if statements (benchmarked the 2 and ended up being the same). I have a list of functions to apply. Think of it like a case switch. where there will be a chain of cases to apply – tjaqu787 Oct 15 '22 at 15:57
  • It can't possibly work. You don't return func at the end. Please update your question with your real code. – quamrana Oct 15 '22 at 16:08
  • edit in fun: returned func but the outer block returning fun does return a function `.fun(x, params)>` – tjaqu787 Oct 15 '22 at 16:18
  • And what about `if function_params == 0:`? Surely this is never `True` since `function_params = [0,1,2]` – quamrana Oct 15 '22 at 16:18
  • @quamrana hahah i see my mistake I'll fix in the example – tjaqu787 Oct 15 '22 at 16:22

1 Answers1

1

Ok, I don't see why you can't just make a list of the functions to be applied at the time get_function() is called. You have all the information about those at that time.

The only thing missing is the values of the parameters, which are given later.

from operator import mul
from operator import truediv as div

def get_function(function_params):
    funcs = [lambda x,p: pow(x,p),lambda x,p: div(x,p),lambda x,p: mul(x,p)]
    funcs = [funcs[i] for i in function_params]
    def fun(x, params):
        func = x
        for f,p in zip(funcs, params):
            func = f(func, p)
        return func
    return fun

f = get_function([2,2])
print(f(5,[3,4]))

Output:

60

since 60 = (5*3)*4

quamrana
  • 37,849
  • 12
  • 53
  • 71