Help understanding my own solution. String Methods - Count Multi X

Hi, so I was trying to write a solution using split as hinted. So I came up with this and it seems to work. I later realised looking at the solution given that I actually didn’t really need the “gap” variable. So now I’m confused. Do I actually need to use the split function to solve this problem or is it just for the practice? Cos it seems more complicated than it really needs to be. Also, does my solution actually work (usable) or was it just a fluke? I’d appreciate any feedback.
Btw I’m new and still learning how to copy codes in here. If the indentation comes out funny it’s because I didn’t know how to do it but it is indented in the correct place. :grin:

> def count_multi_char_x(word, x):
>    **gap = word.split(x)**
>     count = word.count(x) 
>     return count

print(count_multi_char_x(“mississippi”, “iss”))
should print 2
print(count_multi_char_x(“apple”, “pp”))
should print 1

Solution given:

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

There’s very often many ways to solve things. Sometimes solutions are given as optimal solutions, and sometimes they’re given as pedagogical solutions. Ideally they’re not given just for the sake of “convenience”.

Either way, this solution gives a good example of the split method which is a valuable tool to have when writing in python.

2 Likes