Generating Palindromic Word Pairs from a List

  • Share this:

Code introduction


This function takes a list of words as input and returns a dictionary containing pairs of indices that point to words in the input list that can form palindromic pairs.


Technology Stack : List comprehension, string slicing, string reversal, dictionary, tuple

Code Type : Function

Code Difficulty : Intermediate


                
                    
def get_palindrome_pairs(words):
    def is_palindrome(word):
        return word == word[::-1]

    palindrome_pairs = {}
    for i, word in enumerate(words):
        for j, char in enumerate(word):
            prefix, suffix = word[:j], word[j:]
            if is_palindrome(prefix):
                for w in words:
                    if w != word and w.startswith(suffix) and is_palindrome(suffix):
                        palindrome_pairs[(i, len(w))] = (j, len(w))
            if is_palindrome(suffix):
                for w in words:
                    if w != word and w.endswith(prefix) and is_palindrome(prefix):
                        palindrome_pairs[(len(w), i)] = (len(w), j)
    return palindrome_pairs