
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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
- Related Articles
- Check if frequency of character in one string is a factor or multiple of frequency of same character in other string in Python
- Check if frequency of each digit is less than the digit in Python
- Java Program to check if the String contains any character in the given set of characters
- Program to check if a string contains any special character in Python
- Python program to check if a string contains any unique character
- Frequency of each character in String in Python
- Check whether the Average Character of the String is present or not in Python
- If an angle is $30^o$ more than one half of its complement, find the measure of the angle.
- Check if both halves of the string have at least one different character in Python
- Half the perimeter of a garden whose length is 4 m more than its width is 36 m. Find the dimensions of the garden.
- Check if the frequency of all the digits in a number is same in Python
- What happens if the length of the original string is greater than the length of the string returned after padding in LPAD() or RPAD() functions?
- Check if any anagram of a string is palindrome or not in Python
- Half the perimeter of a rectangular garden, whose length is 4 m more than its width, is 36 m. Find the dimensions of the garden.
- Program to check if a string contains any special character in C

Advertisements