Counting Character Frequency with Lambda

Write a lambda function that counts the number of times a character appears in a string.

Example 1:

Input: 'hello', 'l'
Output: 2

Example 2:

Input: 'world', 'o'
Output: 1

Use a lambda function and the count method of python strings.

# Define the lambda function
count_char = lambda s, c: s.count(c)

# Test the function
print(count_char('hello', 'l')) # Output: 2
print(count_char('world', 'o')) # Output: 1

© Let’s Data Science

LOGIN

Unlock AI & Data Science treasures. Log in!