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.
The input will be a single line containing a sentence.
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.
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
WordsIndices(was, saw)(0, 8)(a, a)(2, 5)(a, a)(5, 2)(saw, was)(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
def polindroms(words:str):
words = words.lower().split()
l = len(words)
result = []
for i in range(l):
for j in range(l):
if i == j:
continue
else:
tmp = words[i] + words[j]
if tmp == tmp[::-1]:
result.append([i, j])
if len(result) == 0:
print(-1)
else:
for el in result:
print(*el)
while True:
polindroms(input())
Comments
Leave a comment