How to refer a function variable as a parameter of another function?

72 Views Asked by At

I want to write a function (function_A) to optimize the parameters of a another function (function_B) through iteration. The function whose parameters to be optimized is:

 def function_B(a=10, b=12, c=14, d= 18):
    value = (...)
    return value

Now I want to find the combinations of parameter a,b,c,d that would optimize the results based on certain criteria. So I write the following function - for example - user can specify which parameter to optimize, in this case, we choose to optimize parameter a:

def function_A(variable = a, min = 10, max = 20):

    value = np.zeros((max - min + 1)) # initialize an empty vector to store results
    count = 0

    for i in np.linspace(1, 20, 20, endpoint=True):
        ans = function_B(variable = i)
        value[count] = ans
        count = count + 1

    return value

The problem is, I don't know how to specify a in function_A. I tried to use:

function_A(variable = a, ...)

function_A(variable = 'a', ...)

but neither works...how to specify 'a' is the parameter I want to iterate through?

1

There are 1 best solutions below

2
On

Here is a very simplified example:

def A(a=5, b=4):
    return a, b

def B(var):
    x = {var:'numberyouwant'}
    return A(**x)

So in your case pass the variable as string and pass this into a dictonary and finally using keyworded variable update your function with the paremeter you want to optimize.

def function_A(variable = 'a', min = 10, max = 20):

    value = np.zeros((max - min + 1)) # initialize an empty vector to store results
    count = 0

    for i in np.linspace(1, 20, 20, endpoint=True):
        temp_dict = {variable: i}
        ans = function_B(**temp_dict)
        value[count] = ans
        count = count + 1

return value