Answer to Question #186373 in Python for phani

Question #186373
Palindrome Pairs

Given a list of unique words, write a program to print all the pairs of the distinct indices (i, j) in the given list, so that the concatenation of two words at indices i and j is a palindrome.

Input

The input will be a single line containing a sentence.

Output

The output should be printing each distinct pair of indices (i, j) each in a line in ascending order.
If there are no distinct pairs found, print "-1"
Note: Consider (i, j) and (j, i) as two different pairs.

Explanation

For example, if the given sentence is

was it a car or a cat I saw

The words that can be concatenated to make a palindrome are

Words	Indices
(was, saw)	(0, 8)
(a, a)	(2, 5)
(a, a)	(5, 2)
(saw, was)	(8, 0)

So the output should be

0 8
2 5
5 2
8 0
Sample Input 1
was it a car or a cat I saw
Sample Output 1
0 8
2 5
5 2
8 0

Sample Input 2
bat tac tab cat
Sample Output 2
0 2
1 3
2 0
3 1
1
Expert's answer
2021-04-27T20:33:00-0400
s = input('Enter your string: ')
words = s.split()
for i in range (len(words)):
    for j in range (len(words)):
        if i != j and words[i][::-1] == words[j]:
            print(i,j)

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS