Can I iterate through the word? [solved]

def count_multi_char_x(word, x):
  count = 0
  for w in range(len(word)):
    if word[w : w + len(x)] == x:
      count += 1
  return count

Accepted, but:

print(count_multi_char_x("mississippi", "issi"))          # 2

If you need to count only non-overlapping strings, you’ll need to advance your iteration variable by the length of the target string each time you reach it.

You can’t do that with for, but you can with while.

1 Like

while will reduce the number of iterations, but as a brute force approach,

makes perfect sense, even while it does have to completely iterate over the word string.

>>> def count_multi_char_x(word, x):
  count = 0; c = 0
  for w in range(len(word)):
    c += 1
    if word[w : w + len(x)] == x:
      count += 1
  return count, c

>>> count_multi_char_x("mississippi", "issi")
(2, 11)
>>> 

The target does overlap (they share last/first i) though your solution still finds both impressions, which makes sense given the criteria of the problem. If we advance the iteration variable as @patrickd314 suggests, only one impression of ‘issi’ will be found in your word.

Nobody is right or wrong here. Criteria dictates must always be carefully considered, and never assumed.

We can tweak your solution slightly to eliminate unneeded iterations…

>>> def count_multi_char_x(word, x):
  count = 0; c = 0
  for w in range(len(word) - len(x)):
    c += 1
    if word[w : w + len(x)] == x:
      count += 1
  return count, c

>>> count_multi_char_x("mississippi", "issi")
(2, 7)
>>> 
2 Likes

Yes, I guess I misunderstood @web5761085078’s question:

I thought that “but” implied that 2 was an incorrect answer, and that non-overlapping instances were required. However, as it happens, the assignment is mute on whether or not overlaps are accepted.

1. Write a function named count_multi_char_x that takes a string named word and a string named x . This function should do the same thing as the count_char_x function you just wrote - it should return the number of times x appears in word . However, this time, make sure your function works when x is multiple characters long.

For example, count_multi_char_x("Mississippi", "iss") should return 2

… shoulda looked first.

2 Likes