text: Largest palindromic number by permuting digits | Python3 program to print the largest palindromic number by permuting digits of a number ; Function to check if a number can be permuted to form a palindrome number ; counts the occurrence of number which is odd ; if occurrence is odd ; if number exceeds 1 ; Function to print the largest palindromic number by permuting digits of a number ; string length ; map that marks the occurrence of a number ; check the possibility of a palindromic number ; string array that stores the largest permuted palindromic number ; pointer of front ; greedily start from 9 to 0 and place the greater number in front and odd in the middle ; if the occurrence of number is odd ; place one odd occurring number in the middle ; decrease the count ; place the rest of numbers greedily ; if all numbers occur even times , then place greedily ; place greedily at front ; 2 numbers are placed , so decrease the count ; increase placing position ; print the largest string thus formed ; Driver Code
code: from collections import defaultdict NEW_LINE def possibility ( m , length , s ) : NEW_LINE INDENT countodd = 0 NEW_LINE for i in range ( 0 , length ) : NEW_LINE INDENT if m [ int ( s [ i ] ) ] & 1 : NEW_LINE INDENT countodd += 1 NEW_LINE DEDENT if countodd > 1 : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def largestPalindrome ( s ) : NEW_LINE INDENT l = len ( s ) NEW_LINE m = defaultdict ( lambda : 0 ) NEW_LINE for i in range ( 0 , l ) : NEW_LINE INDENT m [ int ( s [ i ] ) ] += 1 NEW_LINE DEDENT if possibility ( m , l , s ) == False : NEW_LINE INDENT print ( " Palindrome ▁ cannot ▁ be ▁ formed " ) NEW_LINE return NEW_LINE DEDENT largest = [ None ] * l NEW_LINE front = 0 NEW_LINE for i in range ( 9 , - 1 , - 1 ) : NEW_LINE INDENT if m [ i ] & 1 : NEW_LINE INDENT largest [ l // 2 ] = chr ( i + 48 ) NEW_LINE m [ i ] -= 1 NEW_LINE while m [ i ] > 0 : NEW_LINE INDENT largest [ front ] = chr ( i + 48 ) NEW_LINE largest [ l - front - 1 ] = chr ( i + 48 ) NEW_LINE m [ i ] -= 2 NEW_LINE front += 1 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT while m [ i ] > 0 : NEW_LINE INDENT largest [ front ] = chr ( i + 48 ) NEW_LINE largest [ l - front - 1 ] = chr ( i + 48 ) NEW_LINE m [ i ] -= 2 NEW_LINE front += 1 NEW_LINE DEDENT DEDENT DEDENT for i in range ( 0 , l ) : NEW_LINE INDENT print ( largest [ i ] , end = " " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = "313551" NEW_LINE largestPalindrome ( s ) NEW_LINE DEDENT