Could I just use .count()?

I see many people use split etc. but I thought of this solution:

def count_multi_char_x(word, x):
  return word.count(x)

would that be ok as well?

It depends… Does the exercise suggest an algorithm of our own creation, or does it ask us to use the builtt-in method? Not much to be learned using the the built-in since it does all the heavy lifting and we do nothing.

Can you devise an algo that performs the same task but which exposes its logic to the reader? That would be better practice, one expects.

Wow, I did not realize I needed to use split for this solution.

I’ll try at this again, but my solution without the .split() command was the one from below:

# Write your count_multi_char_x function here:  
def count_multi_char_x(word , x):
  counter = 0
  start = 0
  while len(x) + start < len(word):
    if word[(0 + start) : (len(x) + start)] == x :
      counter += 1
      start += 1
      start += 1

  return counter

# Uncomment these function calls to test your function:
print(count_multi_char_x("mississippi", "iss"))
# should print 2
print(count_multi_char_x("apple", "pp"))
# should print 1      

It was just one approach, and given a string is subscriptable and we are not attempting to mutate it, we don’t need a list, anyway. The string is the list.

The solution you have does not pull any methods out of thin air. That’s what an algorithm looks like.

Plus, Plus.

>>> def count_multi_char_x(word , x):
  counter = 0
  start = 0
  a, b = len(x), len(word)
  while a + start < b:
    if word[(0 + start) : (a + start)] == x :
      counter += 1
    start += 1
  return counter

>>> count_multi_char_x("mississippi", "iss")

Well, this is very nice solution and works for words in the exercise but it wont work when you have matching (X) on the end.
As example just putting some letters together (“hajpphahsppjasjdpp”,“pp”) your code would tell us it is only 2 uses while there are 3 uses of “pp”.
I do not want to be picky i just want to show that this is not complete solution.
I had found one that uses .count() which is build-in but as @mtf mention this is not showing work and understanding.

1 Like