Given a list of unique words. Find all pairs of distinct indices (i, j) in the given list so that the concatenation of the two words, i.e. words[i] + words[j] is a palindrome.

Examples:

Non-string inputs should be converted to strings.

Return an array of arrays containing pairs of distinct indices that form palindromes. Pairs should be returned in the order they appear in the original list.

Source: codewars | Difficulty: EASY
Tags: String algorithms

Fundamentals

Data structures

Starter code: def palindrome_pairs(words):
	

Solutions:
def palindrome_pairs(w):
	return [[i, j] for i in range(len(w)) for j in range(len(w)) if str(w[i]) + str(w[j]) == (str(w[i]) + str(w[j]))[::-1] and i != j]


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

def palindrome_pairs(words):
	words = [str(word) for word in words]
	return [[i, j] for (i, word_i) in enumerate(words) for (j, word_j) in enumerate(words) if i != j and is_palindrome(word_i + word_j)]


def palindrome_pairs(words):
	indices = []
	for i in range(len(words)):
		for j in range(len(words)):
			if i != j:
				concatenation = str(words[i]) + str(words[j])
				if concatenation == concatenation[::-1]:
					indices.append([i, j])
	return indices


from itertools import chain, permutations

def is_palindrome(w1, w2):
	return all((c1 == c2 for (c1, c2) in zip(chain(w1, w2), chain(reversed(w2), reversed(w1)))))

def palindrome_pairs(words):
	words = [str(word) for word in words]
	return [[i, j] for (i, j) in permutations(range(len(words)), 2) if is_palindrome(words[i], words[j])]


from itertools import permutations

def palindrome_pairs(words):
	result = []
	for (i, j) in permutations(list(range(len(words))), 2):
		concat = f'{words[i]}{words[j]}'
		if concat == concat[::-1]:
			result.append([i, j])
	return result


def palindrome_pairs(words):
	w = list(map(str, words))
	return [[i, j] for (i, a) in enumerate(w) for (j, b) in enumerate(w) if i != j and a + b == (a + b)[::-1]]


import itertools

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

def palindrome_pairs(words):
	words = list(map(str, words))
	return [[i, j] for (i, j) in itertools.permutations(range(len(words)), 2) if is_palindrome(words[i] + words[j])]


def palindrome_pairs(words):
	return [[words.index(i), words.index(j)] for i in words for j in words if str(i) + str(j) == (str(i) + str(j))[::-1] and i != j]


palindrome_pairs = lambda a: [[i, j] for (i, s) in enumerate(a) for (j, t) in enumerate(a) if i != j and str(s) + str(t) == (str(s) + str(t))[::-1]]


def palindrome_pairs(a):
	a = [str(x) for x in a]
	r = []
	for (k1, i) in enumerate(a):
		for (k2, j) in enumerate(a):
			if i != j and i + j == (i + j)[::-1]:
				r.append([k1, k2])
	return r