Answer to Question #217920 in Python for srikanth

Question #217920
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-07-17T01:30:07-0400
sentence = input("Enter sentence: ")
sentence = sentence.lower().split()
lentgth = len(sentence)
result = []
for i in range(lentgth):
    for j in range(lentgth):
        if i == j:
            continue
        else:
            tmp = sentence[i] + sentence[j]
            if tmp == tmp[::-1]:
                result.append([i, j])
if len(result) == 0:
    print(-1)
else:
    for every in result:
        print(*every)

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