Using slicing instead of a naive approach [solved]

def count_multi_char_x(word, x):
  count = 0
  i = word.find(x)
  while (i>=0) and (word != ""):
    count+=1
    word = word[i+1:]
    i = word.find(x)
  return count

Hi ! What do you think about this answer fellow community members ?

We can refactor your solution to simplify…

def count_multi_char_x(word, x):
    count = 0
    while word:
        i = word.find(x)
        if i < 0: break
        count += 1
        word = word[i+1:]
    return count

There is something not very naive about the solution since it uses a built-in with slicing, rather than plain iteration and testing of each position for a match. As learners we should have the basic approach under our belt before moving on to more sophisticated solution approaches.

1 Like

str.find stops when it finds a match meaning that it will in total visit each location only once (except for the first time you use it, that’s a bit inconsistent: you forgot to make the string smaller there)

There’s another problem though, the copies you make of the string does end up being more work than there should be. Rather than copying the string, you could tell str.find where it should start searching.