Hi, @wilest ,
range function is given one argument, as it is here ...
range(whole_string_len - sub_string_len + 1)
... the resulting sequence starts at
0, and ends at
1 less than the value of the argument. The ending value specified for a
range is exclusive.
Let's consider this function call as an example ...
print count_substring("reverberate", "er")
Here, the whole string is
"reverberate", and we are counting occurrences of the substring,
"er". The length of
11, and the length of
2. As we look at slices of the whole string for the substring, the last slice we look at needs to be the one that starts at the second-to-last character of the whole string. That is because it is the last place in the whole string where a slice can begin, and still have enough room to contain the substring, considering that our substring for this example is
2 characters in length.
For our example, that second-to-last character has an index of
9. Doing the math with the lengths of the whole string and the substring, we have
11 - 2, which is
9. So the index,
9, is where we want the final slice to begin. Consequently,
9 needs to be the value for
i during the final iteration of the
for loop. As we remember, in a
range, the ending value is exclusive, therefore, we need to use
10 as the ending value. That is why we have
whole_string_len - sub_string_len + 1 as the argument to
range. It evaluates to
10 in this example.
Here, we are looking at the slice of
whole_string that begins at index,
i, and runs for the number of characters in the substring ...
if whole_string[i: i + sub_string_len] == sub_string:
Each time that the slice is equivalent to the substring, we increment
res, which is the count.