A palindrome is a word, phrase, or sequence that reads the same backwards as forwards. Given a palindrome write a program to print the sorted list of all palindromes that can be constructed from the alphabets of the given palindrome. All palindromes should start in a newline.Input Format:
One string (palindrome)
Output Format:
A sorted list of all palindromes constructed from the given string. Each line should contain one palindrome.
Example 1
Input
NITIN
Output
INTNI
NITIN
Explanation
There are only two palindromes that can be constructed from NITIN
Answers
Answered by
1
Language used : Python Programming
Program :
from itertools import permutations
st=str(input())
li=[]
if st==st[::-1]:
st=permutations(list(st))
for i in st:
x=''.join(i)
if x==x[::-1]:
if x not in li:
li.append(x)
li=sorted(li)
if len(li)==0:
print("The word you have entered is not a palindrome")
else:
for i in li:
print(i)
Inputs and outputs :
Input :
NITIN
Output :
INTNI
NITIN
Input : (2)
RACECAR
Output:
ACRERCA
ARCECRA
CARERAC
CRAEARC
RACECAR
RCAEACR
Input : (3)
BOB
Output :
BOB
Input : (4)
HAPPY
Output :
The word you have entered is not a palindrome
Explanation :
- Ask user to enter a string as an input. Take an empty list in which you are going to store the palindromes formed.
- Check if the word entered is palindrome or not. If not, length of the list with be the same, 0. i.e., if length of list is 0, print a statement that says "The word you have entered is not a palindrome".
- If it is a palindrome, enter the conditional statement block and make a list of permutations and store it in a variable.
- Write a for loop that checks for every permutation i, by joining the contents of i and checks if it is a palindrome or not. If it is, then append it to the list, else just continue.
- Once every permutation is checked, sort the list using sorted() that sorts the strings by dictionary order.
- If the length of list is zero, as we have discussed before, that statement prints. else, print the palindromes in a list using a for loop. That's it!
Learn more :
- Similar question with no.of test cases taken.
https://brainly.in/question/19151384
- Indentation is must in python. Know more about it at :
brainly.in/question/17731168
Attachments:
Similar questions