Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does this lambda function do?

Tags:

python

lambda

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))
like image 224
thumbtackthief Avatar asked Mar 21 '26 15:03

thumbtackthief


2 Answers

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)

like image 178
SingleNegationElimination Avatar answered Mar 24 '26 06:03

SingleNegationElimination


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.

like image 29
Karoly Horvath Avatar answered Mar 24 '26 07:03

Karoly Horvath



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!