Skip to content

Instantly share code, notes, and snippets.

@rebekah
Created March 18, 2025 06:54
Show Gist options
  • Save rebekah/069f78919b08177a0d0a8e0b9a5dbf24 to your computer and use it in GitHub Desktop.
Save rebekah/069f78919b08177a0d0a8e0b9a5dbf24 to your computer and use it in GitHub Desktop.
def group_tweets_by_state(tweets):
"""Return a dictionary that aggregates tweets by their nearest state center.
The keys of the returned dictionary are state names, and the values are
lists of tweets that appear closer to that state center than any other.
tweets -- a sequence of tweet abstract data types
>>> sf = make_tweet("welcome to san francisco", None, 38, -122)
>>> ny = make_tweet("welcome to new york", None, 41, -74)
>>> two_tweets_by_state = group_tweets_by_state([sf, ny])
>>> len(two_tweets_by_state)
2
>>> california_tweets = two_tweets_by_state['CA']
>>> len(california_tweets)
1
>>> tweet_string(california_tweets[0])
'"welcome to san francisco" @ (38, -122)'
"""
state_centers_dict = state_centers()
state_tweets = {}
for tweet in tweets:
closest_state = ""
closest_distance = None
for state in state_centers_dict:
distance = geo_distance(state_centers_dict[state], tweet_location(tweet))
if(closest_distance == None):
closest_distance = distance
closest_state = state
elif(closest_distance > distance):
closest_distance = distance
closest_state = state
if(state_tweets[closest_state]):
state_tweets[closest_state] = state_tweets[closest_state] + [tweet]
else:
state_tweets[closest_state] = [tweet]
return state_tweets
def state_centers():
us_state_centers = {}
for state in us_states:
us_state_centers[state] = find_state_center(us_states[state])
return us_state_centers
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment