
- 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 whether the frequencies of all the characters in a string are prime or not in Python
Suppose we have a string s. We have to check whether the occurrences of each character in s is prime or not
So, if the input is like s = "apuuppa", then the output will be True as there are two 'a's, three 'p's and two 'u's.
To solve this, we will follow these steps −
- freq := a map containing all characters and their frequencies
- for each char in freq, do
- if freq[char] > 0 and freq[char] is not prime, then
- return False
- if freq[char] > 0 and freq[char] is not prime, then
- return True
Let us see the following implementation to get better understanding −
Example Code
from collections import defaultdict def isPrime(num): if num > 1: for i in range(2, num): if num % i == 0: return False return True return False def solve(s): freq = defaultdict(int) for i in range(len(s)): freq[s[i]] += 1 for char in freq: if freq[char] > 0 and isPrime(freq[char]) == False: return False return True s = "apuuppa" print(solve(s))
Input
"apuuppa"
Output
True
- Related Articles
- Python - Check if frequencies of all characters of a string are different
- Program to check whether elements frequencies are even or not in Python
- Check whether the given numbers are Cousin prime or not in Python
- Check whether the sum of prime elements of the array is prime or not in Python
- XOR of Prime Frequencies of Characters in a String in C++
- Check whether the given number is Wagstaff prime or not in Python
- Check whether the vowels in a string are in alphabetical order or not in Python
- Python - Check If All the Characters in a String Are Alphanumeric?
- Check whether N is a Dihedral Prime Number or not in Python
- Check if all the 1s in a binary string are equidistant or not in Python
- Check whether the Average Character of the String is present or not in Python
- Check whether the sum of absolute difference of adjacent digits is Prime or not in Python
- Check whether a string is valid JSON or not in Python
- Program to check whether every rotation of a number is prime or not in Python
- How to check whether a number is prime or not using Python?

Advertisements