I am struggling to understand the ‘reduce’ call written below in python.
I have found several sources, both here and elsewhere, that state what the function does, and that there’s an equivalent ‘aggregate’ for lists in C#, but I am unable to understand what do the calls below actually -expect-… possibly because I can’t really figure what does ‘_keep_left’ returns?
So:
1- can anybody help telling me what does ‘_keep_left’ return?
2- what does , []) mean in the reduce call?
Many thanks.
TURN_LEFT, TURN_RIGHT, TURN_NONE = (1, -1, 0)
def turn(p, q, r):
"""Returns -1, 0, 1 if p,q,r forms a right, straight, or left turn."""
return cmp((q[0] - p[0])*(r[1] - p[1]) - (r[0] - p[0])*(q[1] - p[1]), 0)
def _keep_left(hull, r):
while len(hull) > 1 and turn(hull[-2], hull[-1], r) != TURN_LEFT:
hull.pop()
return (not len(hull) or hull[-1] != r) and hull.append(r) or hull
def _graham_scan(points):
"""Returns points on convex hull of an array of points in CCW order."""
points.sort()
lh = reduce(_keep_left, points, [])
uh = reduce(_keep_left, reversed(points), [])
return lh.extend(uh[i] for i in xrange(1, len(uh) - 1)) or lh
_keep_leftreturns a listhull, which is initially empty. Turns not going left are removed from it. The current point is added into it, unless it is already the last element on the list., [])is the third parameter to reduce. It is the initial accumulator value, which will be passed to_keep_left, thus makinghull(and, in the end,lhanduh) initially empty.It performs Graham scan by first sorting the points, then going through all the points twice (
lhanduhstand for lower half and upper half), and with each sweep the points are accumulated to the list. The points are accumulated withreduce, that is, the result is originally empty, and the points are passed to_keep_leftone by one (in the sorted order), and for each point the points causing a right turn are removed from the accumulated list. Then the current point is added to the accumulated list.The return value from
_keep_leftis a bit tricky:not len(hull)returns True if the list is empty.hull[-1] != rchecks ifr(the current point) is the last element in the list.hull.append(r)is in the boolean expression only for the side effect of appendingrto the list (looks a bit dirty to me), so that if the last element ofhullisr,hullwill be returned without appendingrto it.Put in other words, due to short circuiting
hullwill always be returned, butrwill be appended to it before returning it if it’s not the last element. The same logic should be easy to implement in a nicer, yet more verbose, way.