Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Help me lambda-nize this

Tags:

python

lambda

To help me better understand lambda I wrote this short snippet that rotates and transforms a quad (I hope I got the math right). Now, I want to replace the three steps below with one liner lambdas, possibly in conjunction with map().

Im using a vector class but hopefully, the functions are clear as to what they do.

self.orientation = vector(1,0)
self.orientation.rotate(90.0)

#the four corners of a quad
points = (vector(-1,-1),vector(1,-1),vector(1,1),vector(-1,1))
print points

#apply rotation to points according to orientation
rot_points = []
for i in points:
    rot_points.append(i.rotated(self.orientation.get_angle()))
print rot_points

#transform the point according to world position and scale
real_points = []
for i in rot_points:
    real_points.append(self.pos+i*self.scale)
print real_points

return real_points
like image 623
Mizipzor Avatar asked May 24 '26 18:05

Mizipzor


1 Answers

You could use map, reduce, et al, but nowadays list comprehensions are the preferred way to do things in Python:

rot_points  = (i.rotated(self.orientation.get_angle()) for i in points)
real_points = [self.pos+i*self.scale for i in rot_points]

Notice how I used (parentheses) instead of [brackets] in the first line. That is called a generator expression. It allows rot_points to be constructed on the fly as the points are used in the second line rather than constructing all of the rot_points in memory first and then iterating through them. It could save some unnecessary memory usage, basically, if that's a concern.

like image 150
John Kugelman Avatar answered May 26 '26 08:05

John Kugelman



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!