Python conversion madness

I have python related code understanding problem:

def convex_hull(pts): """Returns the points on the convex hull of pts in CCW order.""" for m in (2 ** (2 ** t) for t in xrange(len(pts))): hulls = [_graham_scan(pts[i:i + m]) for i in xrange(0, len(pts), m)] //more code 

I can’t understand how these two β€œfor ”s should work.

Unfortunately, the link to the command does not display such an example of use, and I can’t say whether this really - really means that one for this is the purpose of the left side of the other?

Also, what could the lower appointment mean? The 'for' statement returns the value?!?!

Thanks and sorry for the newbie.

+7
source share
1 answer

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])) # more code 

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.

+11
source

All Articles