Search code examples
pythonlistfunctiontuples

Python function with variable number of arguments *arg


I have a function in python that takes the form f(t1, t2, t3, *theta). And I would like to define a new function g(t1, t3, *theta) defined by

enter image description here

So for example, g(1,2,3,4,5) = f(1,2,3,4,5) + f(1,4,3,2,5) + f(1,5,3,4,2)

Here is what i have tried:

def g(t1, t3, *theta):
  S = 0
  list_i = list(theta)
  for ti in theta:
    list_i.remove(ti)
    tuple_i = tuple(list_i)
    S += f(t1, ti, t3, tuple_i)
  return S

but it gives the error TypeError: unsupported operand type(s) for -: 'float' and 'tuple'


Solution

  • The error happens because you're passing a tuple instead of separate arguments to f. To fix it, unpack the tuple like this:

    def g(t1, t3, *theta):
        S = 0
        for i, ti in enumerate(theta):
            remaining = theta[:i] + theta[i+1:]
            S += f(t1, ti, t3, *remaining)
        return S