Nearest power of 2 of nearest perfect squares of non | Python3 program for the above approach ; Function to find nearest perfect square of num ; Calculate square root of num ; Calculate perfect square ; Find the nearest perfect square ; Function to find the power of 2 nearest to the number num ; Calculate log base 2 of num ; Highest power of 2 which is <= num ; Function to find the nearest perfect square and the nearest power of 2 of every array element whose occurrence is 1 ; Stores frequency of array elements ; Traverse the array and update frequency of current array element ; Traverse the map freq ; If the frequency is 1 ; Find nearest perfect square ; Print the nearest power of 2 ; If the any does not contain any non - repeating elements ; Driver Code
from math import sqrt , log2 , pow NEW_LINE def perfectSquare ( num ) : NEW_LINE INDENT sr = int ( sqrt ( num ) ) NEW_LINE a = sr * sr NEW_LINE b = ( sr + 1 ) * ( sr + 1 ) NEW_LINE if ( ( num - a ) < ( b - num ) ) : NEW_LINE INDENT return a NEW_LINE DEDENT else : NEW_LINE INDENT return b NEW_LINE DEDENT DEDENT def powerOfTwo ( num ) : NEW_LINE INDENT lg = int ( log2 ( num ) ) NEW_LINE p = int ( pow ( 2 , lg ) ) NEW_LINE return p NEW_LINE DEDENT def uniqueElement ( arr , N ) : NEW_LINE INDENT ans = True NEW_LINE freq = { } NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( arr [ i ] in freq ) : NEW_LINE INDENT freq [ arr [ i ] ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT freq [ arr [ i ] ] = 1 NEW_LINE DEDENT DEDENT res = [ ] NEW_LINE for key , value in freq . items ( ) : NEW_LINE INDENT if ( value == 1 ) : NEW_LINE INDENT ans = False NEW_LINE ps = perfectSquare ( key ) NEW_LINE res . append ( powerOfTwo ( ps ) ) NEW_LINE DEDENT DEDENT res . sort ( reverse = False ) NEW_LINE for x in res : NEW_LINE print ( x , end = " ▁ " ) NEW_LINE if ( ans ) : NEW_LINE INDENT print ( " - 1" ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 4 , 11 , 4 , 3 , 4 ] NEW_LINE N = len ( arr ) NEW_LINE uniqueElement ( arr , N ) NEW_LINE DEDENT