Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def find_centroid(polygon):
- """Find the centroid of a polygon. If a polygon has 0 area, use the latitude
- and longitude of its first position as its centroid.
- http://en.wikipedia.org/wiki/Centroid#Centroid_of_polygon
- Arguments:
- polygon -- A list of positions, in which the first and last are the same
- Returns 3 numbers: centroid latitude, centroid longitude, and polygon area.
- >>> p1 = make_position(1, 2)
- >>> p2 = make_position(3, 4)
- >>> p3 = make_position(5, 0)
- >>> triangle = [p1, p2, p3, p1] # First vertex is also the last vertex
- >>> round_all = lambda s: [round(x, 5) for x in s]
- >>> round_all(find_centroid(triangle))
- [3.0, 2.0, 6.0]
- >>> round_all(find_centroid([p1, p3, p2, p1])) # reversed
- [3.0, 2.0, 6.0]
- >>> apply_to_all(float, find_centroid([p1, p2, p1])) # A zero-area polygon
- [1.0, 2.0, 0.0]
- """
- "*** YOUR CODE HERE ***"
- def polygon_area_fn(polygon):
- if len(polygon) == 1:
- return 0
- else:
- part_a = ((longitude(polygon[0])*latitude(polygon[1])) -
- (longitude(polygon[1])*latitude(polygon[0])))
- return (part_a + polygon_area_fn(polygon[1:]))
- def centroid_latitude_fn(polygon):
- if len(polygon) == 1:
- return 0
- else:
- part_x = ((latitude(polygon[0]) + latitude(polygon[1])) *
- (latitude(polygon[0])*longitude(polygon[1]) -
- latitude(polygon[1])*longitude(polygon[0])))
- return part_x + centroid_latitude_fn(polygon[1:])
- def centroid_longitude_fn(polygon):
- if len(polygon) == 1:
- return 0
- else:
- part_y = ((longitude(polygon[0]) + longitude(polygon[1])) *
- (latitude(polygon[0])*longitude(polygon[1]) -
- latitude(polygon[1])*longitude(polygon[0])))
- return part_y + centroid_longitude_fn(polygon[1:])
- polygon_area = polygon_area_fn(polygon) * (1/2)
- centroid_latitude = (1/(6*polygon_area)) * centroid_latitude_fn(polygon)
- centroid_longitude = (1/(6*polygon_area)) * centroid_longitude_fn(polygon)
- final_list = [centroid_latitude, abs(centroid_longitude), abs(polygon_area)]
- # Trying to do abs(centroid_latitude), centroid_latitude*-1, or
- # anything else gives a ZeroDivisionError.
- return final_list
Advertisement
Add Comment
Please, Sign In to add comment