Python — Problem solving -101

Prasad
1 min readMay 16, 2023

--

String input from the user and counts the frequency of each character in the string. Display the character along with its frequency.

def count_frequency_dict(string):
frequency = {}
for char in string:
if char in frequency:
frequency[char] += 1
else:
frequency[char] = 1
return frequency

input_string = input("Enter a string: ")
character_frequency = count_frequency_dict(input_string)

count the frequency of characters in a string using a dictionary. The count_frequency_dict() function iterates over each character in the input string and checks if it already exists as a key in the frequency dictionary. If it does, the corresponding value (frequency) is incremented by 1. If it doesn't, a new key is added to the dictionary with an initial frequency of 1.

After calling the count_frequency_dict() function with the user input, the resulting dictionary character_frequency contains the character frequencies.

With Numpy :-

input_string = input("Enter a string: ")
characters, counts = np.unique(list(input_string), return_counts=True)

With Pandas

input_string = input("Enter a string: ")
character_frequency = pd.Series(list(input_string)).value_counts().to_dict()

With Counter

from collections import Counter

input_string = input("Enter a string: ")
character_frequency = Counter(input_string)

print("Character frequency:")
for char, freq in character_frequency.items():
print(f"{char}: {freq}")

--

--

Prasad
Prasad

Written by Prasad

I am a OpenSource Enthusiast|Python Lover who attempts to find simple explanations for questions and share them with others

No responses yet