Skip to content

Instantly share code, notes, and snippets.

@gladson
Created November 15, 2025 00:50
Show Gist options
  • Select an option

  • Save gladson/fd9852342bc1a9fd61ecaa8f747f470b to your computer and use it in GitHub Desktop.

Select an option

Save gladson/fd9852342bc1a9fd61ecaa8f747f470b to your computer and use it in GitHub Desktop.
algorithms
# Design a computer program, in the Python programming language, that
# reads a text file and outputs to the screen the 5 most common words
# and their frequency of occurrences, ordered from most frequent to least
# frequent. Talk through your process and explain your decisions.
# Use this paragraph as the input to your program.
# Ground truth:
# 4 the
# 3 your
# 3 to
# 3 and
# 2 program
# ...
import re
paragraph = '''Design a computer program, in the Python programming language,
that reads a text file and outputs to the screen the 5 most common words and their
frequency of occurrences, ordered from most frequent to least frequent.
Talk through your process and explain your decisions.
Use this paragraph as the input to your program. '''
collection_words = {}
def find_words():
list_words = re.findall(r'\w+', paragraph.lower())
for word in list_words:
if word in collection_words:
collection_words[word] += 1
else:
collection_words[word] = 1
filter_words = {
word: times
for word, times in collection_words.items()
if times > 1
}
sorted_items = sorted(
filter_words.items(),
key=lambda item: item[1],
reverse=False
)
sorted_dictionary = dict(sorted_items)
print(sorted_dictionary)
return sorted_dictionary
find_words()
# result:
# {'the': 4, 'and': 3, 'to': 3, 'your': 3, 'a': 2, 'program': 2, 'most': 2, 'frequent': 2}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment