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
JavaScript
x
49
49
1
def max(a,b):
2
3
if a >b :
4
return a
5
else:
6
return b
7
8
9
def palindrome(str,k1):
10
11
l=0
12
r=len(str)-1
13
pl=str
14
k=int(k1)
15
while (l < r):
16
if str[l] != str[r] :
17
pl[l]=pl[r]=max(str[l],str[r])
18
l+=1
19
r-=1
20
21
if k<= 0:
22
return "can not able to make palin "
23
24
l=0
25
r=len(str)-1
26
27
while l<= r:
28
if l == r:
29
if k>0:
30
pl[l]='9'
31
32
33
if pl[l] < '9':
34
if k>=2 and str[l]==pl[l] and str[r]==pl[r]:
35
k-=2
36
pl[l]=pl[r]='9'
37
38
elif k>=1 and (str[l]!=pl[l] or str[r]!=pl[r]):
39
k-=1
40
pl[l]=pl[r]='9'
41
42
l+=1
43
r-=1
44
45
46
return pl
47
48
print "Your output "+ str("".join(palindrome(list("45611"),1)))
49
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))