Check whether the frequencies of all the characters in a string are prime or not in Python

PythonServer Side ProgrammingProgramming

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
  • return True

Let us see the following implementation to get better understanding −

Example Code

Live Demo

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
raja
Published on 16-Jan-2021 04:51:17
Advertisements