How to create an array of functions that partially depend on external parameters? (Python)

I am interested in creating a list / array of functions "G" consisting of many small functions "g". This, essentially, should correspond to a series of “evolving” functions over time.

Each "g" takes two variables and returns the product of these variables with an external global variable indexed at the same step.

Assume that obs_mat(T x 1) is a predefined global array and tcorresponds to time steps

G = []

for t in range(T):
    # tried declaring obs here too.               
    def g(current_state, observation_noise):
        obs = obs_mat[t] 
        return current_state * observation_noise * obs 

G.append(g) 

Unfortunately, when I test the resulting functions, they do not seem to understand the difference in a constant that changes over time obs, i.e. (Got G[0](100,100)the same as G[5](100,100)). I tried to play with volume obs, but without much luck. Can anyone help me in the right direction?

+4
source share
3 answers

"getcha" , . , ( ). , , , , .

, :

def make_func(x):
    def func(a, b):
        return a*b*x
    return func

list_of_funcs = [make_func(i) for i in range(10)]

func x make_func. make_func, x.

, ( , ):

list_of_funcs = [lambda a, b, x=i: a*b*x for i in range(10)]

i x . , i, . , , , (, ).

+3

, , . , fuction, , , , ( , t, for)

, .

, . , , - ?

from functools import partial

def g(current_state, observation_noise, t):
    obs = obs_mat[t]
    return current_state * observation_noise * obs

g_maker = partial(g, current, observation)
results = list(map(g_maker, range(T)))

, , partial , . ( ), .

, , , , , (, , ).

+2

( , G.append ) , t , , range(T). g , t, , T - 1. , ( - t g):

G = []

for t in range(T):
    def g(current_state, observation_noise, t_kw=t):
        obs = obs_mat[t_kw] 
        return current_state * observation_noise * obs

    G.append(g)

This works because it creates a different name that points to the value that is treferenced during this iteration of the loop (you can still use t, not t_kw), and it will work anyway, because t g is bound to a value that is bound to t f - the value never changes, but t f is tied to another value at the next iteration, and t g still indicates the "original" value.

+2
source

All Articles