Print characters having prime frequencies in order of occurrence | Python 3 implementation of the approach ; Function to create Sieve to check primes ; false here indicates that it is not prime ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p , set them to non - prime ; Function to print the prime frequency characters in the order of their occurrence ; Function to create Sieve to check primes ; To store the frequency of each of the character of the string ; Update the frequency of each character ; Traverse str character by character ; If frequency of current character is prime ; Driver code
SIZE = 26 NEW_LINE from math import sqrt NEW_LINE def SieveOfEratosthenes ( prime , p_size ) : NEW_LINE INDENT prime [ 0 ] = False NEW_LINE prime [ 1 ] = False NEW_LINE for p in range ( 2 , int ( sqrt ( p_size ) ) , 1 ) : NEW_LINE INDENT if ( prime [ p ] ) : NEW_LINE INDENT for i in range ( p * 2 , p_size , p ) : NEW_LINE INDENT prime [ i ] = False NEW_LINE DEDENT DEDENT DEDENT DEDENT def printChar ( str , n ) : NEW_LINE INDENT prime = [ True for i in range ( n + 1 ) ] NEW_LINE SieveOfEratosthenes ( prime , len ( str ) + 1 ) NEW_LINE freq = [ 0 for i in range ( SIZE ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT freq [ ord ( str [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT if ( prime [ freq [ ord ( str [ i ] ) - ord ( ' a ' ) ] ] ) : NEW_LINE INDENT print ( str [ i ] , end = " " ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str = " geeksforgeeks " NEW_LINE n = len ( str ) NEW_LINE printChar ( str , n ) NEW_LINE DEDENT