xFunKy

Containing_state_ex7

Dec 18th, 2013
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.62 KB | None | 0 0
  1. def find_containing_state(states):
  2.     """Returns a function that takes a tweet and returns the name of the state
  3.    containing the given tweet's location.
  4.  
  5.    Use the geo_distance function (already provided) to calculate distance
  6.    in miles between two latitude-longitude positions.
  7.  
  8.    Arguments:
  9.    tweet -- a tweet abstract data type
  10.    us_states -- a dictionary from state names to positions.
  11.  
  12.    >>> sf = Tweet("Welcome to San Francisco", None, 38, -122)
  13.    >>> ny = Tweet("Welcome to New York", None, 41.1, -74)
  14.    >>> find_state = find_containing_state(us_states)
  15.    >>> find_state(sf)
  16.    'CA'
  17.    >>> find_state(ny)
  18.    'NY'
  19.    """
  20.     def find_state(tweet):
  21.         for state in states:
  22.             polygon = states[state]
  23.             collisions = 0
  24.             for i in range(len(polygon)-1):
  25.                 point_a = min(polygon[i], polygon[i+1],
  26.                               key=lambda position: position.latitude())
  27.                 point_b = max(polygon[i], polygon[i+1],
  28.                               key=lambda position: position.latitude())
  29.  
  30.                 if not point_a.latitude() <= tweet.lat < point_b:
  31.                     continue
  32.  
  33.                 slope = (point_a.longitude() - point_b.longitude()) /\
  34.                         (point_a.latitude() - point_b.longitude())
  35.  
  36.                 y = slope*(tweet.lat - point_a.latitude()) +\
  37.                     point_a.longitude()
  38.  
  39.                 is_collision = y > tweet.lon
  40.                 collisions += is_collision
  41.  
  42.             if collisions%2 == INSIDE_MODULU:
  43.                 return state
  44.         return None
  45.  
  46.     return find_state
Advertisement
Add Comment
Please, Sign In to add comment