Created
September 27, 2022 14:30
-
-
Save codeboy/ba8d892aec725e04e2577386b7eb98f7 to your computer and use it in GitHub Desktop.
test common sortener
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# Please create a Python code that will write the 3 most common words from the | |
# given list to standard output. | |
# | |
# Preferred output format is a list of (word, count) tuples, e.g.: | |
# | |
# $ python words.py | |
# [('apple', 5), ('banana', 4), ('orange', 3)] | |
# | |
# Ideally, the list should be sorted by word frequency. | |
# | |
# Feel free to utilize features that are available in Python 3.9. | |
words = [ | |
'apple', | |
'foo', | |
'apple', | |
'bar', | |
'apple', | |
'baz', | |
'apple', | |
'frog', | |
'apple', | |
'toad', | |
'banana', | |
'video', | |
'banana', | |
'audio', | |
'banana', | |
'banana', | |
'orange', | |
'toad', | |
'orange', | |
'frog', | |
'orange', | |
] | |
def common_sortener(lst: list) -> list: | |
common_words: dict = {} | |
for word in lst: | |
if word not in common_words: | |
common_words[word] = 1 | |
else: | |
common_words[word] += 1 | |
sorted_list = [] | |
dicy_keys = sorted(common_words, key=common_words.get, reverse=True) | |
for w in dicy_keys: | |
sorted_list.append({w: common_words[w]}) | |
return sorted_list | |
final_list = common_sortener(words) | |
print(final_list) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment