To understand this code, you first need to understand the list of concepts and expressions of the generator . The following is an example of a simple list comprehension:
>>> [str(i) for i in range(5)] ['0', '1', '2', '3', '4']
As you can see, this one line executes the equivalent of the following regular for loop:
lst = [] for i in range(5): lst.append(str(i))
Basically, this is a shorthand for creating lists. Generator expressions are similar, but instead of returning a list, they return a generator that gives the same values ββas understanding the list, without actually creating a complete list. This is more efficient when you are just going to iterate over the values.
Now that the background is not working, you can extend this code with regular for loops:
def convex_hull(pts): """Returns the points on the convex hull of pts in CCW order.""" for t in xrange(len(pts)): m = 2 ** (2 ** t) hulls = [] for i in xrange(0, len(pts), m): hulls.append(_graham_scan(pts[i:i + m]))
As for your comment, pts[i:i + m] takes a slice of the list from index i to index i + m , you can mostly read snippets like this:
[first index to include : first index to exclude : step]
This answer has a pretty good explanation with some examples.
Andrew Clark
source share