Skip to content

Instantly share code, notes, and snippets.

@msyvr
Last active December 31, 2024 04:16
Show Gist options
  • Save msyvr/111c8d2ba31dc62f43e596fdd63e812d to your computer and use it in GitHub Desktop.
Save msyvr/111c8d2ba31dc62f43e596fdd63e812d to your computer and use it in GitHub Desktop.
mit 6.0001 dictionaries - lyric frequencies: id the most frequent word
def lyric_frequencies(lyrics_db):
'''
create a dictionary with
keys = unique lyrics (words)
vals = number of occurrences in the lyrics db
'''
lyrics_dict = {}
# loop through lyrics_db elements
for lyric in lyrics_db:
if lyric in lyrics_dict:
lyrics_dict[lyric] += 1
else:
lyrics_dict[lyric] = 1
return lyrics_dict
def hi_freq(lyrics_dict):
'''
find the key(s) with the highest frequency value
'''
vals = lyrics_dict.values()
max_val = max(vals)
hi_vals = [k for k, v in lyrics_dict.items() if v == max_val]
return (max_val, hi_vals)
if __name__ == "__main__":
lyric_string = ('You\'re sublime, You\'re a turkey dinner, '
'You\'re the time of a Derby winner, '
'I\'m a toy balloon that\'s fated soon to pop - '
'But if, baby, I\'m the bottom - You\'re the top')
lyrics_db = list((lyric_string).lower().split(" "))
print(lyrics_db)
print(hi_freq(lyric_frequencies(lyrics_db)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment