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.
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?
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”
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.
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.