Modify array by sorting nearest perfect squares of array elements having their digits sorted in decreasing order | Python 3 program of the above approach ; Function to sort array in ascending order after replacing array elements by nearest perfect square of decreasing order of digits ; Traverse the array of strings ; Convert the current array element to a string ; Sort each string in descending order ; Convert the string to equivalent integer ; Calculate square root of current array element ; Calculate perfect square ; Find the nearest perfect square ; Sort the array in ascending order ; Print the array ; Driver Code
import math NEW_LINE def sortArr ( arr , N ) : NEW_LINE INDENT for i in range ( N ) : NEW_LINE INDENT s = str ( arr [ i ] ) NEW_LINE list1 = list ( s ) NEW_LINE list1 . sort ( reverse = True ) NEW_LINE s = ' ' . join ( list1 ) NEW_LINE arr [ i ] = int ( s ) NEW_LINE sr = int ( math . sqrt ( arr [ i ] ) ) NEW_LINE a = sr * sr NEW_LINE b = ( sr + 1 ) * ( sr + 1 ) NEW_LINE if ( ( arr [ i ] - a ) < ( b - arr [ i ] ) ) : NEW_LINE INDENT arr [ i ] = a NEW_LINE DEDENT else : NEW_LINE INDENT arr [ i ] = b NEW_LINE DEDENT DEDENT arr . sort ( ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 29 , 43 , 28 , 12 ] NEW_LINE N = len ( arr ) NEW_LINE sortArr ( arr , N ) NEW_LINE DEDENT