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.
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.
Character frequency counting is used in DNA sequence analysis, cryptography, and string parsing.
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
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()).
for loop to increment a counter variable manually is redundant when txt.count(char) is built natively into Python.Use txt.count() for frequency checks. Next, let's calculate the sum of cubes!
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.
`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.
`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.