Count Occurrences of a Character in a String
Quick Overview
`str.count()` scans the whole string, so counting one character is `O(n)`. Counting several in a loop repeats that scan each time, where `collections.Counter` walks it once for all of them.
Deep Dive
1. The Challenge: Character Counting
Create a function char_count(char, txt) that takes a character and a string text and returns the total number of times that character appears in the text.
2. Why It Matters
Character frequency counting is used in DNA sequence analysis, cryptography, and string parsing.
3. The Python Solution
Use Python's built-in txt.count(char) method:
def char_count(char, txt):
return txt.count(char)
# Testing our function
print(char_count("a", "edabit")) # Output: 1
print(char_count("c", "Chamber of secrets")) # Output: 1
print(char_count("b", "big fat bubble")) # Output: 4
4. Case Sensitivity in String Methods
String operations in Python are case-sensitive. "c" does not match "C". If case-insensitive counting is required, convert text to lowercase first: txt.lower().count(char.lower()).
5. Common Mistakes
- Manual Loop Overkill: Writing a
forloop to increment a counter variable manually is redundant whentxt.count(char)is built natively into Python.
6. Next Steps
Use txt.count() for frequency checks. Next, let's calculate the sum of cubes!
Next Up in Python Beginner Practice & Core Problem Solving
Return the Sum of Two Numbers
A function with no `return` hands back `None`, so a forgotten one surfaces as a `TypeError` at the call site rather than at the line that actually caused it.
Convert Minutes into Seconds
`minutes * 60` returns an `int` when given an `int`, while `/` always produces a float regardless of the operands. Multiplication preserves the type; division does not.
Calculate the Area of a Triangle
`base * height / 2` always yields a float in Python 3 because `/` never returns an int, even for whole numbers. `//` floors instead, which is almost never what an area wants.