Iterating through word search with steps? [solved]

I thought I might approach it by iterating over the entire word by x length and look for match cases.

def count_multi_char_x(word, x):
    counter = 0
    stepper = len(x)
    #print(stepper)
    for index in range(len(word)):
        #print(index, word[index: stepper], stepper)
        if (word[index: stepper] == x):
            counter += 1
        stepper +=1
    return counter

The downside to stepping is we miss all the first letters between position one and position two. It makes sense to step past a found match, and continue from there, but until such match is found, the step should be one character over.

However, if we look back to the previous posts, we see that there are times when we would not want to jump, found match or not. The objectives need to be clear in order to choose a route to take.

Hi mtf, thank for the reply!

I am not sure I understand, because the step is one character over in word.

The function iterates over word by:
Starting at char 0 in the word and checking for matches from
Index 0 in word to len(x) in word then
Index 1 in word to len(x) in word then
Index 2 in word to len(x) in word

1 Like

For this exercise in order to get the expected result we must step one character at a time. It’s the only way we get 2 when counting issi in mississippi.

I thought that was what my function does?

1 Like

And so it does. I was letting the variable name (stepper) throw me off. My bad.

I think your code was fine, its just a bit tricky to understand what the stepper does at first glance.

Another way to do this in a bit more obvious way would be to just use slice by index + the length of x. This way you don’t have to build another counter:

  x_len = len(x)
  word_len = len(word)
  count = 0
  for index in range(word_len):
    if word[index:index+x_len] == x:
      count += 1
  return count