Skip to content

Instantly share code, notes, and snippets.

@codeboy
Created September 27, 2022 14:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codeboy/ba8d892aec725e04e2577386b7eb98f7 to your computer and use it in GitHub Desktop.
Save codeboy/ba8d892aec725e04e2577386b7eb98f7 to your computer and use it in GitHub Desktop.
test common sortener
#!/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