Count array elements whose highest power of 2 less than or equal to that number is present in the given array | Python program for the above approach ; Function to count array elements whose highest power of 2 is less than or equal to that number is present in the given array ; Stores the resultant count of array elements ; Stores frequency of visited array elements ; Traverse the array ; Calculate log base 2 of the element arr [ i ] ; Highest power of 2 whose value is at most arr [ i ] ; Increment the count by 1 ; Return the resultant count ; Driver Code
from math import log2 NEW_LINE def countElement ( arr , N ) : NEW_LINE INDENT count = 0 NEW_LINE m = { } NEW_LINE for i in range ( N ) : NEW_LINE INDENT m [ arr [ i ] ] = m . get ( arr [ i ] , 0 ) + 1 NEW_LINE DEDENT for i in range ( N ) : NEW_LINE INDENT lg = int ( log2 ( arr [ i ] ) ) NEW_LINE p = pow ( 2 , lg ) NEW_LINE if ( p in m ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 3 , 4 , 6 , 9 ] NEW_LINE N = len ( arr ) NEW_LINE print ( countElement ( arr , N ) ) NEW_LINE DEDENT