Search code examples
pythonnumerical-methods

How do you pass arguments to a function within an array?


Suppose I have an array of functions, each with the same arguments, but each manipulating the arguments in a different way. I then want to iterate over a loop, using my array of functions over and over again to get updated values. How do I pass arguments to the functions?

def f_1(a, b, c):
    val = a + b + c
    return val

def f_2(a, b, c):
    val = a*b + c
    return val

# something like this?

fun_arr = [f_1, f_2]

val1 = [fun_arr[0](a1, b1, c1), fun_arr[1](a1, b1, c1)]
val2 = [fun_arr[0](a2, b2, c2), fun_arr[1](a2, b2, c2)]

I hope the psuedo code above makes sense. It's a simplified version of what I'm trying to do.

If the context helps, I'm trying to write an RK2 algorithm for a system of equations that could possibly be reused for a general set of ODEs. I think I could easily enough write some simple code that applies to my specific problem but I wanted to challenge myself to make my code reusable.


Solution

  • Like this:

    fun_arr = [f_1, f_2]
    
    args_list = [
        (a1, b1, c1),
        (a2, b2, c2),
    ]
    
    val1 = [f(*args_list[0]) for f in fun_arr]
    
    all_vals = [
        [f(*args) for f in fun_arr]
        for args in args_list
        ]