Member-only story
Python Coding Question #5
Count Frequency of Letters in String
Question:
Write a python program to count the frequency of letters in a string
Lets see the first solution:
from collections import Counter
def count_letter_frequency(string):
# Convert the string to lowercase
lower_string = string.lower()
# Use Counter to efficiently count frequencies
letter_counts = Counter(lower_string)
# Remove non-alphabetic characters
for char in list(letter_counts.keys()):
if not char.isalpha():
del letter_counts[char]
return letter_counts
if __name__ == "__main__":
input_string = input("Enter a string: ")
frequencies = count_letter_frequency(input_string)
for letter, count in frequencies.items():
print(f"{letter}: {count}")
# Output
Enter a string: hello123@
h: 1
e: 1
l: 2
o: 1As you can see from the above solution, the function takes input string as parameter and then converts it to lowercase to ensure case-insensitive counting and uses the Counter class to provide an efficient way to count occurrences of elements in a sequence and the code removes non-alphabetic characters to provide accurate letter frequency counts.
Lets see the second solution using the Counter class
from collections import Counter…




