Skip to content
Advertisement

Make largest palindrome by changing at most K-digits from given numerical string using python?

Make largest palindrome by changing at most K-digits from the given numerical string using the python programming.

Advertisement

Answer

“Hello, ALL..This program help you to make the numerical string as largest palindrome with ‘k’number of changes !”

!/usr/bin/python

def max(a,b):

if a >b :
    return a
else:
    return b


def palindrome(str,k1):

   l=0
   r=len(str)-1
   pl=str
   k=int(k1)
   while (l < r):
     if str[l] != str[r] :
           pl[l]=pl[r]=max(str[l],str[r])
           l+=1
           r-=1

     if k<= 0:
        return "can not able to make palin "

   l=0
   r=len(str)-1

  while l<= r:
     if l == r:
         if k>0:
           pl[l]='9'


    if pl[l] < '9':
        if k>=2 and str[l]==pl[l] and str[r]==pl[r]:
            k-=2
            pl[l]=pl[r]='9'

        elif k>=1 and (str[l]!=pl[l] or str[r]!=pl[r]):
            k-=1
            pl[l]=pl[r]='9'

    l+=1
    r-=1


return pl

print "Your output "+ str("".join(palindrome(list("45611"),1)))

I’ve used list instead of string so that we can manipulate using the index and join the list to give out as string

“”.join(palindrome(list(“45611”),1))

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement