Replace array elements that contains K as a digit with the nearest power of K | Python3 program for the above approach ; Function to calculate the power of base nearest to x ; Stores logX to the base K ; Function to replace array elements with nearest power of K ; Traverse the array ; Convert integer into a string ; If K is found , then replace with the nearest power of K ; Print the array ; Given array ; Given value of K ; Function call to replace array elements with nearest power of K
import math NEW_LINE def nearestPow ( x , base ) : NEW_LINE INDENT k = int ( math . log ( x , base ) ) NEW_LINE if abs ( base ** k - x ) < abs ( base ** ( k + 1 ) - x ) : NEW_LINE INDENT return base ** k NEW_LINE DEDENT else : NEW_LINE INDENT return base ** ( k + 1 ) NEW_LINE DEDENT DEDENT def replaceWithNearestPowerOfK ( arr , K ) : NEW_LINE INDENT for i in range ( len ( arr ) ) : NEW_LINE INDENT strEle = str ( arr [ i ] ) NEW_LINE for c in strEle : NEW_LINE INDENT if int ( c ) == K : NEW_LINE INDENT arr [ i ] = nearestPow ( arr [ i ] , K ) NEW_LINE break NEW_LINE DEDENT DEDENT DEDENT print ( arr ) NEW_LINE DEDENT arr = [ 432 , 953 , 232 , 333 ] NEW_LINE K = 3 NEW_LINE replaceWithNearestPowerOfK ( arr , K ) NEW_LINE