You can download this code by clicking the button below.
This code is now available for download.
This function returns a dictionary containing each word from the input list and its corresponding palindrome pairs and their indices.
Technology Stack : String operations, list comprehensions, dictionaries
Code Type : Function
Code Difficulty : Intermediate
def get_palindrome_pairs(words):
def is_palindrome(s):
return s == s[::-1]
palindrome_pairs = {}
for i, word in enumerate(words):
for j in range(len(word) + 1):
prefix, suffix = word[:j], word[j:]
if is_palindrome(prefix) and suffix in words:
if suffix not in palindrome_pairs:
palindrome_pairs[suffix] = []
palindrome_pairs[suffix].append(i)
if is_palindrome(suffix) and prefix in words and i != words.index(prefix):
if prefix not in palindrome_pairs:
palindrome_pairs[prefix] = []
palindrome_pairs[prefix].append(words.index(prefix))
return palindrome_pairs