ritualmagick ritualmagick - 1 year ago 80
Python Question

"Nested" anonymous functions/function handles in Python

Working on my Python these days, and I want to port a short Matlab code from a course I did a few years back into Python, but to be honest I can't figure out if it's possible to do it in the same manner, and if it is, how to do it.

The essential part here that I'm struggling with in Python is the following:

nk = @(x)1
for l=1:3 % calculate basis
nk = @(x)(nk(x).*(x-1));

How the code works in Matlab:

nk = @(x)1
creates a function handle
, which can be called by
where e.g.
, but as of now it will only return 1 since it doesn't depend on the variable
, yet.

In the for-loop,
is multiplied with
for every iteration (here
is considered a "symbolic" variable, or what to call it, similar to how you define a lambda function), and in the end it should turn out as
nk = (x-1)*(x-1)*(x-1)

It is still a function which I can call as
, where
is an array with whatever values I want it to have.

Answer Source

The following crude example of piecewise linear interpolation might give you an idea:

def interpolate(xs,ys):
    #assumes that xs and ys are same-length lists
    #of real numbers, with xs sorted
    def N(x):
        if x < min(xs) or x > max(xs): return False #we don't extrapolate
        if x == max(xs): return ys[-1]
        i = 0
        while xs[i] <= x:
            i+= 1
        m = (ys[i]-ys[i-1])/(xs[i]-xs[i-1])
        return ys[i-1] + m*(x - xs[i-1])
    return N

For example,

>>> f = interpolate([0,1,2],[1,2,4])
>>> f(0)
>>> f(0.7)
>>> f(1.9)
>>> f(2)
>>> f(2.1)

The key concept is that of closures. See this blog post for a nice discussion (especially the part that talks about function factories).

By the way, you can create closures with anonymous functions, though the resulting code isn't very readable:

>>> f = (lambda x: (lambda y: x+y))
>>> g = f(3)
>>> g(2)

Since you were mentioning function "handles", I don't think that you really want anonymous functions (especially given your original question that had more Matlab code).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download