This was the first kata I found hard so I wanted to ask about it. Any ways I could I have done it better?
here's the question -> Most frequently used words in a text
def check_alphabet(string): #checks if the given string contains at least one alphabet
for i in string:
if i.isalpha():
return True
return False
def top_3_words(text):
text += " " # the for loop ends before it can check the final word
text = text.lower() # given in the problem
current_word = ""
words = {
}
letter_index = 0
for letter in text:
if letter.isalpha() or letter == "'": # make the word
current_word += letter
letter_index += 1
elif letter_index == 0: # this happens if there is more than one whitespace
pass
else: # add the word into the dictionary
if not check_alphabet(current_word): # filter out words only made out of '
current_word = ""
continue
if current_word in words.keys(): # if the word has already come out before
words[current_word] += 1
else: #if the word is new
words.update({current_word : 1})
current_word = "" #reset
letter_index = 0
words = sorted(words.items(), key = lambda x: x[1], reverse= True) # sort the dictionary
if len(words) == 0:
return []
elif len(words) == 1:
return [words[0][0]]
elif len(words) == 2:
return [words[0][0], words[1][0]]
elif len(words) >= 3:
return [words[0][0], words[1][0], words[2][0]]
check_alphabets
needlessly reinventsany()
\$\endgroup\$