me again here. I am taking a small Python exercise to see how well can I do. (I am a beginner btw). So I got a question that asked me to tell how many times a word was present in a given string. Seemed pretty easy. I wrote down the code. Here it is:
# Question 12:
# Write a Python program to count the occurrences of each word in a given sentence.
def word_occurrences(string):
words = string.split(sep=' ')
words_len = {}
for each_word in words:
counter = 1
words_len[each_word] = counter
words.remove(each_word)
if each_word in words:
while each_word in words:
counter += 1
words_len[each_word] = counter
words.remove(each_word)
continue
return words_len
print(word_occurrences('Abdullah is Abdullah at work'))
My approach was to make a list using words of the sentence and then for each word, count up, remove that word, and if that word is still found in that list, it means that the word is appearing again. So I keep removing the word if it's still in there and counting up for each removal until there are no other occurrences of that word and I move on to the next word. But this code, particularly the for loop, seems to jump between elements. It gives me this output:
{'Abdullah': 2, 'at': 1}
When the desired or expected output was:
{'Abdullah': 2, 'is': 1, 'at': 1, 'work': 1}
I have no idea why is this happening. Any help/explanation will be deeply appericiated.