Palindromizing the strings

Pyth (commit b93a874), 11 bytes

.VkI_IJ+zbB


Test suite

This code exploits a bug in the current version of Pyth, commit b93a874. The bug is that _IJ+zb is parsed as if it was q_J+zbJ+zb, which is equivalent to _I+zb+zb, when it should (by the design intention of Pyth) be parsed as q_J+zbJ, which is equivalent to _I+zb. This allows me to save a byte - after the bug is fixed, the correct code will be .VkI_IJ+zbJB. I'll explain that code instead.

Basically, the code brute forces over all possible strings until it finds the shortest string that can be appended to the input to form a palindrome, and outputs the combined string.

.VkI_IJ+zbJB
z = input()
.Vk             For b in possible strings ordered by length,
+zb      Add z and b,
J         Store it in J,
_I          Check if the result is a palindrome,
I            If so,
J     Print J (This line doesn't actually exist, gets added by the bug.
B     Break.


Python, 46 bytes

f=lambda s:s*(s==s[::-1])or s[0]+f(s[1:])+s[0]


If the string is a palindrome, return it. Otherwise, sandwich the first letter around the recursive result for the remainder of the string.

Example breakdown:

f(bonobo)
b  f(onobo) b
b o f(nobo) o b
b o n f(obo) n o b
b o n obo n o b


f s|s==reverse s=s|h:t<-s=h:f t++[h]


f s
|s==reverse s = s
|(h:t)<-s     = h:(f t)++[h]


If the string is a palindrome, return it. Otherwise, sandwich the first letter around the recursive result for the tail of the string.

The string s is split into h:t in the second guard, obviating a filler 1>0 for this case. This is shorter than doing s@(h:t) for the input.