0

Let's say I have the following function that is in 2 variables -

def banana(x,y):
    return exp(((-x**2/200))-0.5*(y+0.05*(x**2) - 100*0.05)**2)

and I would like to write it as -

def banana(x):

where x here is a vector of two variables; if that's possible?

Thanks for your help!

shx2
  • 61,779
  • 13
  • 130
  • 153
tattybojangler
  • 1,003
  • 3
  • 15
  • 25

6 Answers6

3

Unpack the args in the beginning of your function:

def banana(args):
    x, y = args
    return exp(((-x**2/200))-0.5*(y+0.05*(x**2) - 100*0.05)**2)

or directly in the definition line:

def banana((x, y)):
    return exp(((-x**2/200))-0.5*(y+0.05*(x**2) - 100*0.05)**2)
shx2
  • 61,779
  • 13
  • 130
  • 153
2

Yes, this is possible:

def _banana(x):
    return banana(*x)
ForceBru
  • 43,482
  • 10
  • 63
  • 98
2

You could write:

def banana(vector):
    x, y = vector
    return exp(((-x**2/200))-0.5*(y+0.05*(x**2) - 100*0.05)**2)
Simeon Visser
  • 118,920
  • 18
  • 185
  • 180
1

may be something like

def banana(x):
    return exp(((-x[0]**2/200))-0.5*(x[1]+0.05*(x[0]**2) - 100*0.05)**2)
Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
Entro
  • 76
  • 1
  • 5
0

Yeah of course it's possible. You can use either a list or a tuple. Put you two variables into a list or a tuple

x = [5, 7] # A list
x = (5, 7) # A tuple

And you function should then be like that:

def banana(x):
    x, y = x # Unpacking
    return exp(((-x**2/200))-0.5*(y+0.05*(x**2) - 100*0.05)**2)

See more at https://docs.python.org/3.6/tutorial/datastructures.html

Zcode
  • 425
  • 3
  • 7
-1

you can write with lists

def banana(x):
    return exp(((-x[0]**2/200))-0.5*(x[1]+0.05*(x[0]**2) - 100*0.05)**2)
hicay
  • 78
  • 1
  • 2
  • 8