Help needed with "Count multi X" challenge

Hi everyone!
I would need your help to understand the solution of the “Count multi X” Python challenge (#3: https://www.codecademy.com/courses/learn-python-3/articles/python-code-challenges-strings).
I really don’t understand the meaning of that “-1”. Why does it need to be there?

def count_multi_char_x(word, x):
  splits = word.split(x)
  return(len(splits)-1)

Thanks a lot, I really appreciate your help.

Morning.
It’s working by splitting the word up into chunks whenever it finds ‘x’ and putting it into a list. This leaves a list of chunks of what’s left. The actual value is the amount of gaps in between.
e.g.
word = mississsippi
x = is
gives
[‘m’,‘s’,‘sippi’] which has a length of 3,

So, len would give us the length of the new list, but the answer we want is one less (we want to count the gaps to find out how many times we’ve taken the selected string out).
hope that helps

1 Like

Here the the task is to know how many times a word was split. for example if you split a word once , it is broken into TWO parts and these two parts are stored in a list. So we get the length of the list and “-1” to get the number of times the word was actually split

1 Like

Thanks guys, but what if the string “x” shows up at the beginning or at the end of the word?
For example, if we were looking for the string “pa” in the word “pappagallo” here the string gets split into 2 and 2-1 = 1 (although the correct number here would be 2, not 1):
[“p”, “gallo”]

Have you tested that one yet? It’s perfectly valid to return empty strings as elements in the newly formed list in which case the effective counting mentioned above would still make sense.

1 Like

@web5265208141
The problem you have is: you’re assuming that all occurrences of the string we pass to .split() are removed at once. I feel a better way to visualize this is in an iterative manner, that is we are gradually moving from left to right scanning the word string for occurrences of the split string and each time we find an occurrence, we split the word string.
so for “pappagallo”.split(“pa”).

we start from the left, we see “pa” so we first split the string into an empty " " and ppagallo. that is [" ', “ppagallo”].

we continue going through the remaining part of word string “ppagallo” we see another “pa”. so we split it a second time to “p” and “gallo” meaning out split array now becomes [" ", “p”, “gallo”].

There are no more “pa” occurrences so the split is complete. The split array length is 3 and the number of splits is 3- 1 = 2.

You can also test these things out yourself using a python IDE

1 Like

Thanks for clarifying, it actually makes sense to me now!

2 Likes

you’re right, it works even if the string is at the beginning of the word

1 Like