Saturday, 20 June 2026

πŸš€ Day 71/150 – Find Frequency of Characters in Python

 


πŸš€ Day 71/150 – Find Frequency of Characters in Python

Finding the frequency of characters means counting how many times each character appears in a string. This is a common task in text processing, data analysis, and coding interviews.

✅ Example

text = "hello"

Output
{'h': 1, 'e': 1, 'l': 2, 'o': 1}


πŸ”Ή Method 1 – Using Dictionary

text = "hello" freq = {} for ch in text: freq[ch] = freq.get(ch, 0) + 1 print(freq)








✅ Output

{'h': 1, 'e': 1, 'l': 2, 'o': 1}

πŸ“Œ Uses a dictionary to store each character and its count.


πŸ”Ή Method 2 – Taking User Input

text = input("Enter a string: ") freq = {} for ch in text: freq[ch] = freq.get(ch, 0) + 1 print(freq)








✅ Example Output

Enter a string: python

{'p': 1, 'y': 1, 't': 1, 'h': 1, 'o': 1, 'n': 1}



πŸ“Œ Works with any string entered by the user.


πŸ”Ή Method 3 – Using count()

text = "hello" for ch in set(text): print(ch, ":", text.count(ch))





✅ Output

h : 1
e : 1
l : 2
o : 1

πŸ“Œ Simple approach using Python's built-in count() method.


πŸ”Ή Method 4 – Using Function

def char_frequency(text): freq = {} for ch in text: freq[ch] = freq.get(ch, 0) + 1 return freq print(char_frequency("hello"))





✅ Output

{'h': 1, 'e': 1, 'l': 2, 'o': 1}

πŸ“Œ Ideal when the same logic needs to be reused multiple times.


πŸ”₯ Key Takeaways

✅ Character frequency counts occurrences of each character.

✅ Dictionaries are the most efficient and commonly used solution.

✅ count() is easy to understand but less efficient for large strings.

✅ Functions make your code reusable and cleaner.

✅ Useful in text analysis, word processing, and interview problems.




0 Comments:

Post a Comment

Popular Posts

Categories

100 Python Programs for Beginner (119) AI (283) Android (25) AngularJS (1) Api (7) Assembly Language (2) aws (30) Azure (11) BI (10) Books (262) Bootcamp (11) C (78) C# (12) C++ (83) cloud (1) Course (87) Coursera (300) Cybersecurity (31) data (6) Data Analysis (36) Data Analytics (23) data management (15) Data Science (371) Data Strucures (22) Deep Learning (179) Django (16) Downloads (3) edx (21) Engineering (15) Euron (30) Events (7) Excel (21) Finance (10) flask (4) flutter (1) FPL (17) Generative AI (73) Git (12) Google (53) Hadoop (3) HTML Quiz (1) HTML&CSS (48) IBM (42) IoT (3) IS (25) Java (99) Leet Code (4) Machine Learning (318) Meta (24) MICHIGAN (5) microsoft (13) Nvidia (8) Pandas (14) PHP (20) Projects (34) Python (1380) Python Coding Challenge (1168) Python Mathematics (1) Python Mistakes (51) Python Quiz (545) Python Tips (13) Questions (3) R (72) React (7) Scripting (3) security (4) Selenium Webdriver (4) Software (20) SQL (52) Udemy (18) UX Research (1) web application (11) Web development (9) web scraping (3)

Followers

Python Coding for Kids ( Free Demo for Everyone)