python-checkio/Elementary/popular-words.py

35 lines
980 B
Python
Raw Normal View History

2019-12-24 14:52:17 +01:00
def popular_words(text: str, words: list) -> dict:
result = {}
text = text.lower()
for word in words:
# print(text[0:len(word)+1])
result[word] = 1 if text[-(len(word)):] == word else 0
result[word] += 1 if text[0:len(word)+1] == word+" " else 0
result[word] += text.count(" "+word+" ")
result[word] += text.count(word+"\n")
result[word] += text.count("\n"+word+" ")
return result
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!")