Modify string by sorting characters after removal of characters whose frequency is not equal to power of 2 | Python3 program for the above approach ; Function to remove all the characters from a that whose frequencies are not equal to a perfect power of 2 ; Stores the frequency of each character in S ; Iterate over characters of string ; Update frequency of current character in the array freq [ ] ; Traverse the array freq [ ] ; Check if the i - th letter is absent from S ; Calculate log of frequency of the current character in the S ; Calculate power of 2 of lg ; Check if freq [ i ] is a power of 2 ; Print letter i + ' a ' freq [ i ] times ; Driver Code
from math import log2 NEW_LINE def countFrequency ( S , N ) : NEW_LINE INDENT freq = [ 0 ] * 26 NEW_LINE for i in range ( N ) : NEW_LINE INDENT freq [ ord ( S [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT for i in range ( 26 ) : NEW_LINE INDENT if ( freq [ i ] == 0 ) : NEW_LINE INDENT continue NEW_LINE DEDENT lg = int ( log2 ( freq [ i ] ) ) NEW_LINE a = pow ( 2 , lg ) NEW_LINE if ( a == freq [ i ] ) : NEW_LINE INDENT while ( freq [ i ] ) : NEW_LINE INDENT print ( chr ( i + ord ( ' a ' ) ) , end = " " ) NEW_LINE freq [ i ] -= 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = " aaacbb " NEW_LINE N = len ( S ) NEW_LINE countFrequency ( S , N ) NEW_LINE DEDENT