Nearest power of 2 of frequencies of each digit of a given number | Python3 program for the above approach ; Function to find the nearest power of 2 for all frequencies in the Map freq ; Traverse the Map ; Calculate log of the current array element ; Find the nearest power of 2 for the current frequency ; Function to find nearest power of 2 for frequency of each digit of num ; Length of string ; Stores the frequency of each character in the string ; Traverse the string S ; Function call to generate nearest power of 2 for each frequency ; Driver Code
from math import log2 , pow NEW_LINE def nearestPowerOfTwoUtil ( freq ) : NEW_LINE INDENT temp = { } NEW_LINE for key , value in freq . items ( ) : NEW_LINE INDENT lg = int ( log2 ( value ) ) NEW_LINE a = int ( pow ( 2 , lg ) ) NEW_LINE b = int ( pow ( 2 , lg + 1 ) ) NEW_LINE if ( ( value - a ) < ( b - value ) ) : NEW_LINE INDENT temp [ ( int ( a ) ) ] = key NEW_LINE DEDENT else : NEW_LINE INDENT temp [ ( int ( b ) ) ] = key NEW_LINE DEDENT DEDENT for key , value in temp . items ( ) : NEW_LINE INDENT print ( value , " - > " , key ) NEW_LINE DEDENT DEDENT def nearestPowerOfTwo ( S ) : NEW_LINE INDENT N = len ( S ) NEW_LINE freq = { } NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( S [ i ] in freq ) : NEW_LINE INDENT freq [ S [ i ] ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT freq [ S [ i ] ] = 1 NEW_LINE DEDENT DEDENT nearestPowerOfTwoUtil ( freq ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = "16333331163" NEW_LINE nearestPowerOfTwo ( N ) NEW_LINE DEDENT