0

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.

Abdullah
  • 23
  • 1
  • 7
  • 1
    Does this answer your question? [How to remove items from a list while iterating?](https://stackoverflow.com/questions/1207406/how-to-remove-items-from-a-list-while-iterating) – Kemp Mar 26 '21 at 19:44
  • Removing items from the list while iterating over it will cause you to skip over items. E.g. you look at item 1, remove it, then look at item 2. What you're actually looking at is the item that used to be in position 3 before you removed item 1. – Kemp Mar 26 '21 at 19:44
  • @Kemp makes sense. Alright, so, how do i do what i want to? – Abdullah Mar 26 '21 at 19:47
  • 1
    Note: if you want to be really lazy you can use python's in-built `count` function: `str1.count(str2)`. e.g `"Hello World".count("o")` would return `2`. – thornejosh Mar 26 '21 at 19:52
  • NICE! What if I dont want to be lazy? – Abdullah Mar 26 '21 at 19:59
  • @Abdullah I linked to a question that has a number of answers telling you different ways to do it – Kemp Mar 26 '21 at 20:35

2 Answers2

0

Not to undermine your work but using predefined libraries will go a long way.

from collections import Counter
def word_occurrences(string):
    words = string.split(" ")
    return Counter(words)

string.split(" ") splits the string into a list of "words". The Counter function simply returns a dictionary of the counts of these words.

thornejosh
  • 148
  • 8
0

You are removing items from the list while iterating over it

def word_occurrences(string):
    words = string.split(" ")
    word_freq = {}
    for word in words:
        if(word in word_freq):
            word_freq[word] += 1
        else:
            word_freq[word] = 1
    return word_freq
print(word_occurrences('Abdullah is Abdullah at work'))

The above code outputs

{'Abdullah': 2, 'is': 1, 'at': 1, 'work': 1}