How to Pass Every Combination of Multiple Sets to Function

70 Views Asked by At

I come from a programming background, and I need to be able to formulate a mathematical function wherein I need to pass every combination of items in three sets to another function then return the maximum value returned by this other function. For example, I have a function $f(l,n)$, where 'l'is a list of numbers and 'n' is a number. I have another function that $g(a,i)$ takes a number and another number, and returns a number. It does not matter what $g$ does, just that it returns a number. $f(l,n)$ must find every combination of passing numbers $0$ to $n$ and each element in list $l$ to $g(a,i)$, where each element is then summed together and the maximum number out of those values is ultimately returned by $f$. I have written out an example in pythonic pseudocode to help define this:

def f(l,n):
    max = 0
    for i in [0..n]:
        for j in [0..n]:
            for k in [0..n]:
                x = g(l[0],i) + g(l[1],j) + g(l[2],k)
                if x > max:
                    max = x
    return max

In this example the three sets would be g(l[0],[0..n]), g(l[1],[0..n]), g(l[2],[0..n]). My ultimate question would be how would I express 'f' as a formalised mathematical function? I am struggling to find notation to describe this, any help given would be much appreciated. If anyone needs clarification/ I have poorly defined my requires, please do ask!

1

There are 1 best solutions below

1
On BEST ANSWER

I would write it as $\max\{g(l_0,i)+g(l_1,j)+g(l_2,k)\mid 0\leq i,j,k\leq n\}$.

However, note that your calculation is unnecessarily longwinded: since the three terms in the sum don't depend on each other, this is the same as finding the maximum values of $g(l_0,i)$, $g(l_1,j)$ and $g(l_2,k)$ separately, then adding. This can be done in linear time (instead of cubic with the nested loops).

Also, if you do need nested loops like this, it can be done more succinctly using itertools and list comprehension:

from itertools import product
def f(l,n):
    return max(sum(g(l[_],m[_]) for _ in range(3)) for m in product(range(n+1), repeat=3))