221k views
4 votes
A palindrome is a string that reads the same from left to right and from right to left. Design an algorithm to find the minimum number of characters required to make a given string to a palindrome if you are allowed to insert characters at any position

User Melessia
by
4.6k points

1 Answer

6 votes

Answer:

Step-by-step explanation:

The following code is written in Python. It is a recursive function that tests the first and last character of the word and keeps checking to see if each change would create the palindrome. Finally, printing out the minimum number needed to create the palindrome.

import sys

def numOfSwitches(word, start, end):

if (start > end):

return sys.maxsize

if (start == end):

return 0

if (start == end - 1):

if (word[start] == word[end]):

return 0

else:

return 1

if (word[start] == word[end]):

return numOfSwitches(word, start + 1, end - 1)

else:

return (min(numOfSwitches(word, start, end - 1),

numOfSwitches(word, start + 1, end)) + 1)

word = input("Enter a Word: ")

start = 0

end = len(word)-1

print("Number of switches required for palindrome: " + str(numOfSwitches(word, start, end)))

A palindrome is a string that reads the same from left to right and from right to-example-1
User Simon Pham
by
5.1k points