Count Frequency of Each Character

Medium ⏱ 12 min 55% acceptance ★★★★☆ 4.4
Write a function char_frequency(s) that returns a dictionary mapping each character in s to how many times it appears, built by iterating over the string with a for loop (do not use collections.Counter).

Examples

Example 1
Input
char_frequency("banana")
Output
{"b": 1, "a": 3, "n": 2}
Explanation

Counts of each letter.

Constraints

  • s is a string.
  • Must not use collections.Counter.

Topics

Loopsfor loopaccumulator

Companies

FlipkartWalmart

Hints

Hint 1

Start with an empty dict; for each character, increment its count or initialize it to 1.

Hint 2

`counts[ch] = counts.get(ch, 0) + 1` is a concise pattern.

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.