thumbtackthief
thumbtackthief

Reputation: 6211

What does this lambda function do?

I'm still struggling with lambdas. This code was submitted as an answer to Python: closest coordinate?. A lot of it confused me, but I've sorted through most of it. The float method's use of self is still a little tricky for me (I get self.x and self.y, but not really sure what self is in that context). Only mentioning that as it is likely involved in the main part I don't understand, which is the lambda function in the closest method. I see it's going to return the minimum item generated, and that it unpacks the points as args. Then I get a little lost. Are __sub__ and __pow__ redefining - and ** respectively, or are they just distinct 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))

Upvotes: 3

Views: 155

Answers (3)

SingleNegationElimination
SingleNegationElimination

Reputation: 156158

lambda args: expr is not a special magic feature, it's just nice shorthand for

def someFunc(args):
    return expr

which is mainly useful when you need a small function with a simple expression for its body and you don't care about the name. If we used familiar syntax, the closest() method would be:

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

that is, it creates a small, one off function which does a little bit of calculation depending on self and its argument x, and passes that into the min() builtin function. As Ostrea explains, min(seq, key=f) returns the item x in seq which minimizes f(x)

Upvotes: 2

Ostrea
Ostrea

Reputation: 289

Yes, __sub__ and __pow__ redefines - and ** respectively. In this example you just pass anonymous function to optional argument for min(). Here is what this optional argument does, as said in docs:

The optional keyword-only key argument specifies a one-argument ordering function like that used for list.sort().

In this anonymous function you just subtract point, on which closest was called from points, which was passed as arguments and then convert it to float (this conversion is overridden, see __float__)

Upvotes: 1

Karoly Horvath
Karoly Horvath

Reputation: 96258

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

It will be called when you substract the two points. In the example, self will be pt0.

Upvotes: 1

Related Questions