tusing

doomed?

Oct 6th, 2014
239
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.37 KB | None | 0 0
  1. def find_centroid(polygon):
  2.     """Find the centroid of a polygon. If a polygon has 0 area, use the latitude
  3.    and longitude of its first position as its centroid.
  4.  
  5.    http://en.wikipedia.org/wiki/Centroid#Centroid_of_polygon
  6.  
  7.    Arguments:
  8.    polygon -- A list of positions, in which the first and last are the same
  9.  
  10.    Returns 3 numbers: centroid latitude, centroid longitude, and polygon area.
  11.  
  12.    >>> p1 = make_position(1, 2)
  13.    >>> p2 = make_position(3, 4)
  14.    >>> p3 = make_position(5, 0)
  15.    >>> triangle = [p1, p2, p3, p1] # First vertex is also the last vertex
  16.    >>> round_all = lambda s: [round(x, 5) for x in s]
  17.    >>> round_all(find_centroid(triangle))
  18.    [3.0, 2.0, 6.0]
  19.    >>> round_all(find_centroid([p1, p3, p2, p1])) # reversed
  20.    [3.0, 2.0, 6.0]
  21.    >>> apply_to_all(float, find_centroid([p1, p2, p1])) # A zero-area polygon
  22.    [1.0, 2.0, 0.0]
  23.    """
  24.     "*** YOUR CODE HERE ***"
  25.     def polygon_area_fn(polygon):
  26.         if len(polygon) == 1:
  27.             return 0
  28.         else:
  29.             part_a = ((longitude(polygon[0])*latitude(polygon[1])) -
  30.                       (longitude(polygon[1])*latitude(polygon[0])))
  31.         return (part_a + polygon_area_fn(polygon[1:]))
  32.  
  33.     def centroid_latitude_fn(polygon):
  34.         if len(polygon) == 1:
  35.             return 0
  36.         else:
  37.             part_x = ((latitude(polygon[0]) + latitude(polygon[1])) *
  38.                       (latitude(polygon[0])*longitude(polygon[1]) -
  39.                        latitude(polygon[1])*longitude(polygon[0])))
  40.         return part_x + centroid_latitude_fn(polygon[1:])
  41.  
  42.     def centroid_longitude_fn(polygon):
  43.         if len(polygon) == 1:
  44.             return 0
  45.         else:
  46.             part_y = ((longitude(polygon[0]) + longitude(polygon[1])) *
  47.                       (latitude(polygon[0])*longitude(polygon[1]) -
  48.                        latitude(polygon[1])*longitude(polygon[0])))
  49.         return part_y + centroid_longitude_fn(polygon[1:])
  50.  
  51.     polygon_area = polygon_area_fn(polygon) * (1/2)
  52.     centroid_latitude = (1/(6*polygon_area)) * centroid_latitude_fn(polygon)
  53.     centroid_longitude = (1/(6*polygon_area)) * centroid_longitude_fn(polygon)
  54.     final_list = [centroid_latitude, abs(centroid_longitude), abs(polygon_area)]
  55.          # Trying to do abs(centroid_latitude), centroid_latitude*-1, or
  56.          # anything else gives a ZeroDivisionError.
  57.     return final_list
Advertisement
Add Comment
Please, Sign In to add comment