Python – how to return from n dimensional function a 1 dimensional function? – answered

Question:

I’m trying to create a function that receives n variables and returns the same function with one veritable.
my intention is to make a multi-dimentional search within a function in order to find its max point.

lets say i have a function: f(x1,x2,x3) = x1x2+4x3

my first phase of the algorithem will be to randomly choose a start point: x0 = (1,2,6)

now i have for every phase 3 iterations (one for each variable)

for the first one: f(x0+theta*(1,0,0)) = f1(theta) = (1+thata)2+46

now in order to find the best direction i will apply golden slice on f1(theta) lets assume i recived theta = 2

my new x0 will be (1+2,2,6) and agein -> f(x0+thata*(0,1,0) -> golden slice-> optimum…

my question is how can i make a general function that recives multiple variables and returns function with one variable without knowing upfront which of the recived variables is with theta

Any ideas of how to realize it?

the soloution for the problem i presented is here:

def func(*args):
    x = []
    if args[0] == []:
        x.append(args[1])
        for i in args[2]:
            x.append(i)
    elif args[2] == []:
        for i in args[0]:
            x.append(i)
        x.append(args[1])
    elif args[2] == [] and args[0] == []:
        x.append(args[1])
    else:
        for i in args[0]:
            x.append(i)
        x.append(args[1])
        for i in args[2]:
            x.append(i)
    # write your target function
    h = (x[0] - 3) ** 2 + (x[1] - 2) ** 2 - x[0] * x[1] + x[2] + x[3]

    return h


def flatten(funci, *args, i,theta):
    lst1 = []
    lst2 = []
    for j in range(len(args[0])):
        if j < i:
            lst1.append(args[0][j])
        elif j > i:
            lst2.append(args[0][j])

    def inner(x):
        return funci(lst1, theta+x, lst2)

    return inner


p = [1.0, 4.0, 7.0, 6.0]
s = flatten(func, p, i=2,theta=4)
print(s(2.0))
Asked By: dor bar

||

Answers:

I tried to understand your intent rather than your very confused and confusing example. Here’s what I wrote:

def flatten(func, *args):
    def inner(x):
        return func(x,*args[1:])
    return inner

Example 1

def f(x,y,z):
    return x+y+z

f2 = flatten(f,1,2,3)
print(f2(10))

# 15

Example 2

def g(sta, stb):
    return sta+" says hello "+stb

g2 = flatten(g,"Max","Tom")
print(g2("Wanda"))

# Wanda says hello Tom

Example 3 (with a mutable flattened argument)

def h(x, list):
    return [x+i for i in list]

l = [1,2,3]
h2 = flatten(h,1,l)

print(h2(10))
[11, 12, 13]

l[0]=11
print(h2(10))
[21, 12, 13]
Answered By: Swifty
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.