Should I use a loop based or method based solution?

Hello,

I realised that the solution given by the system is more of a loop-based solution than string method- based solution.

def count_char_x(word, x):
    occurrences = 0
    for letter in word:
        if letter == x:
            occurrences += 1
    return occurrences

Using the example method @mtf has shared in the first Code Challenge exercise:

def count_char_x(word, x):
  count = [ ]
  for letter in word:
    if letter == x:
      count.append(letter)
  return len(count)

This method could also generate the required function, using string methods.

3 Likes

Speaking of string methods, there is one called .count() which is what you need for this exercise.
https://docs.python.org/3/library/stdtypes.html#str.count

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

or just

print(word.count(x))
18 Likes

Again, judging by the solution the question is ambiguous. Are we supposed to work out a naive solution or are we supposed to reach for built in string methods? The title suggests string methods, of which str.count() is the most appropriate one to use.

Bottom line, there are a lot of built in methods that can save time and effort but we should be aware of the naive solutions and how to arrive at them before reaching for built-ins. Practice makes perfect.

16 Likes

Hence my increasing love for list comprehensions I wanted to share my solution:

def count_char_x(word, x):
  lst = [letter for letter in word if letter == x]
  return len(lst)
16 Likes

How does this one work? I cannot get which part of this code counts. I can see that your return handles the numbers but how does lst is going to grow? I think letter for letter but it’s guessing, since this is the only part I don’t understand (from what I know about syntax it’s like letter = letter from word if that letter is equal to the letter we’re looking for but it doesn’t make sense)

That’s because the solution above may be out of step with the lesson plan. If you have not yet learned list comprehensions then expect it will come up soon.

The code is building a list in place of only the letters that match x. The length of that list is the return value, a count of matching characters.

We had list comprehension but it was like “do stuff for element in list if something”, here is “element for element in list if something” which I don’t get. Is “element for element” basically "put this element from the list on the new list?

[
    value to append    (may be an expression with x)
    for x in iterable  (the internal loop)
    conditional        (which values get appended)
]

Eg.

a = "123432123454321234567"
b = [x for x in a if x == 5]
print (b)         #  ['5', '5']
print (len(b))    #  2
2 Likes

So the answer to my question:

Is yes? I’m sorru, but I really need to put stuff in my head in terms 5 year old could understand, I’m not smart. How does the "[x " is part telling my computer to make a new list out of what follows? Why not [b += x for x in a if x==5?] or [x in a if x==5]? I don’t get logic behind “x for x”

Basically, yes.

The comprehension cannot interact with the new list as it is not assigned until it is completely built. The build takes place within the square brackets, the defined delimiters of a list object.

[ ----------- list body --------- ]
[ x       for x in a     if x == 5]
  ^            ^             ^
value        loop        condition
  to
append

There is no loop (iteration over a). What is x? In a loop it is the iteration variable that takes on each character in turn, tests it against the condition, and if true, it gets into the allowed values (the ones to include in the list). The resulting list gets assigned to b.

3 Likes

You don’t have to. I did it without one and using the knowledge we already have. Wouldn’t recommend.

def count_char_x(word, x):
  lst = word.split(x)
  lst = ''.join(lst)
  return (len(word) - len(lst))
1 Like

So we could reduce this to a single return line…

>>> def count_char_x(word, x):
  return len(word) - len(''.join(word.split(x)))

>>> count_char_x('supercalifragilisticexpialidocious', 'e')
2
>>> 'supercalifragilisticexpialidocious'.count('e')
2
>>> 

Hi,
i think a line of code is always best , if we can…
so here it is
Please share your feedback

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

2 Likes

Yes, this solution is a good one if your goal is to use a built-in string method to solve the problem. legendsmith pointed this solution out earlier in this thread in April of last year.

Nothing to see, here. Mastery means being able to write algorithms that do what the built-in methods do using naive coding concepts such as iteration and comparison. It’s fine and good that the authors of the language have given us an indispensable range of useful methods and functions to aid in workflow and optimization, but that is not our concern at the moment.

Writing code algorithms is what gives us insight. Do the work now, and reach for the built-ins when you begin writing production code for the real world.

this exercise can be solved either way, i did it with a method, even tho i could probably break depending on the word because i didn’t use count

def count_char_x(word,x):
    return len(word.split(x))-1