Modify array by replacing elements with the nearest power of its previous or next element | Python3 program for the above approach ; Function to calculate the power of y which is nearest to x ; Base Case ; Stores the logarithmic value of x with base y ; Function to replace each array element by the nearest power of its previous or next element ; Stores the previous and next element ; Traverse the array ; Calculate nearest power for previous and next elements ; Replacing the array values ; Print the updated array ; Given array
import math NEW_LINE def nearestPow ( x , y ) : NEW_LINE INDENT if y == 1 : NEW_LINE INDENT return 1 NEW_LINE DEDENT k = int ( math . log ( x , y ) ) NEW_LINE if abs ( y ** k - x ) < abs ( y ** ( k + 1 ) - x ) : NEW_LINE INDENT return y ** k NEW_LINE DEDENT return y ** ( k + 1 ) NEW_LINE DEDENT def replacebyNearestPower ( arr ) : NEW_LINE INDENT prev = arr [ - 1 ] NEW_LINE lastNext = arr [ 0 ] NEW_LINE for i in range ( len ( arr ) ) : NEW_LINE INDENT temp = arr [ i ] NEW_LINE if i == len ( arr ) - 1 : NEW_LINE INDENT next = lastNext NEW_LINE DEDENT else : NEW_LINE INDENT next = arr [ ( i + 1 ) % len ( arr ) ] NEW_LINE DEDENT prevPow = nearestPow ( arr [ i ] , prev ) NEW_LINE nextPow = nearestPow ( arr [ i ] , next ) NEW_LINE if abs ( arr [ i ] - prevPow ) < abs ( arr [ i ] - nextPow ) : NEW_LINE INDENT arr [ i ] = prevPow NEW_LINE DEDENT else : NEW_LINE INDENT arr [ i ] = nextPow NEW_LINE DEDENT prev = temp NEW_LINE DEDENT print ( arr ) NEW_LINE DEDENT arr = [ 2 , 3 , 4 , 1 , 2 ] NEW_LINE replacebyNearestPower ( arr ) NEW_LINE