Replace all array elements with the nearest power of its previous element | Python3 program for the above approach ; Function to calculate log x for given base ; Function to replace all array elements with the nearest power of previous adjacent nelement ; For the first element , set the last array element to its previous element ; Traverse the array ; Find K for which x ^ k is nearest to arr [ i ] ; Find the power to x nearest to arr [ i ] ; Update x ; Return the array ; Driver Code ; Function Call
import math NEW_LINE def LOG ( x , base ) : NEW_LINE INDENT return int ( math . log ( x ) / math . log ( base ) ) NEW_LINE DEDENT def repbyNP ( arr ) : NEW_LINE INDENT x = arr [ - 1 ] NEW_LINE for i in range ( len ( arr ) ) : NEW_LINE INDENT k = LOG ( arr [ i ] , x ) NEW_LINE temp = arr [ i ] NEW_LINE if abs ( x ** k - arr [ i ] ) < abs ( x ** ( k + 1 ) - arr [ i ] ) : NEW_LINE INDENT arr [ i ] = x ** k NEW_LINE DEDENT else : NEW_LINE INDENT arr [ i ] = x ** ( k + 1 ) NEW_LINE DEDENT x = temp NEW_LINE DEDENT return arr NEW_LINE DEDENT arr = [ 2 , 4 , 6 , 3 , 11 ] NEW_LINE print ( repbyNP ( arr ) ) NEW_LINE