- 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 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
Advertisements