What does this lambda function do?

I am still struggling with lambdas. This code was submitted as Python's answer : nearest coordinate? ... A lot confused me, but I did most of it. Using the float method self

is still a bit tricky for me (I get self.x

and self.y

, but not sure what I am in this context). Just mentioning that, as it is probably related to the main part, I don't understand what is the lambda function in the method closest

. I can see that it is returning the minimum item it returns and that it is unpacking the points as arguments. Then I got a little lost. Are __sub__

both __pow__

overridden -

and **

respectively, or are they just different methods?

class Point:
    def __init__(self,x,y):
        self.x = x
        self.y = y
    def closest(self,*points):           
        return min(points,key=lambda x:float(x-self))
    def __sub__(self,other):
        return Point((self.x-other.x) , (self.y - other.y))
    def __pow__(self,powTo):
        return Point(self.x**powTo,self.y**powTo) 
    def __iter__(self):
        yield self.x
        yield self.y
    def __float__(self):
        return sum(self**2)**0.5
    def __str__(self):
        return "(%s,%s)"%(self.x,self.y)

pt0 = Point(9,2)
print pt0.closest(Point(0,0),Point(10,0),Point(10,10))

      

+3


source to share


3 answers


lambda args: expr

is not a special magic function, it is just a nice shorthand for

def someFunc(args):
    return expr

      

which is mostly useful when you need a small function with a simple expression for your body and you don't care about the name. If we were using familiar syntax, the method closest()

would be as follows:



def closest(self,*points):
    def keyFunc(x):
        return float(x-self)           
    return min(points,key=keyFunc)

      

that is, it creates a small, one function that computes a little depending on self

and its argument x

, and passes it to an inline function min()

. As Ostrea explains, min(seq, key=f)

returns an element x in seq

which minimizes f(

x)

+1


source


def __sub__

is one of the magic methods that you can define on an object.



It will be called when you select two points. The example self

will be pt0

.

+1


source


Yes, __sub__

and __pow__

overrides -

and **

accordingly. In this example, you are simply passing an anonymous function as an optional argument to min()

. This is what this optional argument does, as the docs says :

The optional keyword argument specifies a single argument ordering function, similar to the one used for list.sort ().

In this anonymous function, you simply subtract the point from which the point closest

was called, which was passed as arguments and then converted to float (this conversion is overridden, see __float__

)

+1


source







All Articles