In: Computer Science
Write a recursive function in python called make_palindrome that takes a sequence as a parameter and returns a new sequence that is twice the length of the parameter sequence but that contains the contents of the original in palindrome form. For example, if the sequence "super" is passed into the function, the function will return "superrepus".
The way I implemented the function is by using nested function in python.
The parent function will be the make_palindorme which takes the parameter passed to it by the main function.
In this function there is a child function named rev which takes in the parameter string which will be passed to it by the function make_palindrome.
The string gets reversed by using recursive method and is added to the original string.
And this string is returned and printed.
The python code for this program is provided below:
def make_palindrome(string):
def rev(string):
if len(string)==0:#using the build in function len() to find length of string and compare
#Checking whether it is the final element of string passed, if yes it returned
return string
else:
#It is the recursive way and until the last element is reached and returned it keeps on recursing
return rev(string[1:])+string[0]
string=string+rev(string)
#string now contains the required string
return string
ch='y'
while(ch!='n' or ch=='N'):
string=input("Enter the string of your choice:")
print(make_palindrome(string))
ch=input("Do you want to enter more?(y/n)")
The screenshot of the program and the output generated is attached for your reference:
Hope it helps!!!