+ 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?

2nd Apr 2021, 12:02 PM
Carlos
Carlos - avatar
6 Antworten
+ 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. 👍
2nd Apr 2021, 1:39 PM
thequietprogrammer
thequietprogrammer - avatar
+ 1
thequietprogrammer Thanks very much I understood the code and the logic.
2nd Apr 2021, 2:07 PM
Carlos
Carlos - avatar
+ 1
Ipang Thankss
2nd Apr 2021, 2:08 PM
Carlos
Carlos - avatar
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.
2nd Apr 2021, 12:13 PM
Carlos
Carlos - avatar