10/15 - count


#1
    def censor(text, word):
    words = text.split()
    result = ''
    stars = '*' * len(word)
    count = 0
    for i in words:
        if i == word:
            words[count] = stars
        count += 1
    result =' '.join(words)

    return result

I have trouble understanding ‘count’ here. ‘words’ refers to the text split up in words. The ‘for’ loop searches for an element in ‘words’. So far so good i suppose.

We want to find an element in ‘words’ that corresponds with whatever we assign ‘word’ to in calling the function. ‘words’ is a list? so we search for an index?

So…

words[count] = stars

explained means as much as the text split into elements, where we take index zero, because count equals zero, to equal the length of the word we want to censor in asterisks? In other words, [count] is performing the task of finding the element we want in the list? Im obvi confused and very new to coding, any input appreciated.

I guess what i dont understand is how ‘words[0]’ succeeds in finding the right element in the list?

Also, why can’t we simply say for every instance we find of ‘word’ in ‘text’ to equal ‘word’ with ‘stars’? Why do we need to make use of indices?

Thanks in advance


#2

yea, count is keeping track of the indexes so we can replace/censor the right element in words list.

there are two common ways to solve this problem, the one you posted, which is replacing words which require censoring.

the other is to construct a new list, and loop over words and see if the word (i) requires censoring, if so so append starts to the new list, else append i (the current word in sentence)

i am personally not a huge fan of this solution, we use both a for loop and a counter. We could use range() instead (to give us indexes) but then we get a lot of list lookups based on index, not ideal)

there is enumerate which gives us both indexes and item in list, but i can see why the exercise might not want to use that (hasn’t been taught)


#3

So it starts at index zero to check whether ‘i == word’ and the ‘count += 1’ makes it move to the next index to repeat the function?

Thanks, I’ll try to mess about with range and enumerate as well.


#4

repeat the function? No

The loop loops over all the elements, at the same time we also have a variable (count) which acts as a counter to keep track of the index we are at


#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.