+ 1
Logic to make a string palindrome?
Palindrome: A sequence that reads the same backwards as forwards, e.g. "madam" or "nurses run". I am looking forward to make a program that would convert any string to a palindrome with least characters removed and also track the chars removed. For example: "ekgdegfgh" changed to "eghge" And chars removed = "gkdf" "esuussjsj" to "jssueussj" no chars removed "shsjnwnjsj" to "jnswsnj" chars removed = "sjh" What can be the logic to make such program?
6 Answers
+ 4
Hi. I've tried some things, and the code below may help to goal the polindrome:
word = input()
ls = list(word)
aSingle = []
aDouble = []
This part set the variables we'll be using. "ls" is the main list, where the word chars are separated. "aSingle" and "aDouble" are the lists that contains the single and repeated chars respectively. Let's get going.
for i in ls:
if i == "": continue
if ls.count(i) // 2 >= 1:
aDouble.append(i)
for j in range(2):
index = ls.index(i)
ls.remove(i)
ls.insert(index, "")
else:
aSingle.append(i)
index = ls.index(i)
ls.remove(i)
ls.insert(index, "")
In resume, this middle part adds the single and repeated chars to their own lists (i.e. "aSingle" and "aDouble"). When doing this, we are taking one char from "ls" and replacing by a empty char "". This is to prevent mistakes in the "for" loop. The final part is this:
palindrome = "".join(aDouble) + aSingle[0] + "".join(aDouble[::-1])
charsRemoved = "".join(aSingle[1:])
print("Palindrome:", palindrome)
print("Chars removed:", charsRemoved)
And here, we manipulate que lists we've created concatenating the strings formed by it's chars (using the string method ".join()"). Them we output the results. Hope this helps. đ
+ 1
thequietprogrammer Thanks very much I understood the code and the logic.
+ 1
Ipang Thankss
0
See code and its explanation â€
https://www.google.com/amp/s/www.geeksforgeeks.org/JUMP_LINK__&&__python__&&__JUMP_LINK-program-check-string-palindrome-not/amp/
0
ê§àŒâŹBadâŹBoyâŹàŒê§ I saw but that only checks whether a string is a palindrome or not by comparing it to the reversed string.
I want to implement, the conversion to palindrome.
0
Carlos,
I searched the net and found these, code examples available
https://www.techiedelight.com/find-minimum-number-deletions-convert-string-into-palindrome/
https://iq.opengenus.org/minimum-deletions-to-make-string-palindrome/