Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for Popular Words by donnythelegend
def popular_words(text: str, words: list) -> dict:
# Initialize an empty dictionary.
freqs = {}
# Convert text to lowercase to match words.
text = text.lower()
# Split text into a list using whitespaces.
lst = text.split()
# Loop through words.
for i in words:
# Assign words element and frequency within the list to freqs.
freqs[i] = lst.count(i)
# Return freqs.
return freqs
if __name__ == '__main__':
print("Example:")
print(popular_words('''
When I was One
I had just begun
When I was Two
I was nearly new
''', ['i', 'was', 'three', 'near']))
# These "asserts" are used for self-checking and not for an auto-testing
assert popular_words('''
When I was One
I had just begun
When I was Two
I was nearly new
''', ['i', 'was', 'three', 'near']) == {
'i': 4,
'was': 3,
'three': 0,
'near': 0
}
print("Coding complete? Click 'Check' to earn cool rewards!")
April 18, 2021