![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check if the frequency of any character is more than half the length of the string in Python
Suppose we have a string s with lowercase, uppercase, numeric and special characters. We have to check whether frequency of any one of character is more than the half of length of string or not.
So, if the input is like s = "CC*Ca5&CC", then the output will be True as frequency of 'C' is 5 and length of string is 9. (5 > 9/2).
To solve this, we will follow these steps −
- freq := a map containing frequencies of characters of s
- for each ch in freq, do
- if frequency of ch > (size of s / 2), then
- return True
- if frequency of ch > (size of s / 2), then
- return False
Let us see the following implementation to get better understanding −
Example Code
from collections import defaultdict def solve(s): freq = defaultdict(int) for ch in s: freq[ch] += 1 for ch in freq: if freq[ch] > len(s) // 2: return True return False s = "CC*Ca5&CC" print(solve(s))
Input
"CC*Ca5&CC"
Output
True
Advertisements