Find the Semordnilaps

Pyth, 23 (18 code, 5 necessary STDIN)

J'f&qlTQ&}_TJ>_TTJ

This is a fairly straightforward solution.

J stores the list of words. Then we filter over the list of words (f J) on the length of the word being the input (qlTQ), the reversed word being in the list (}_TJ), and the reversal of the word being greater than the word (>_TT). The last condition ensures T is not palindromic, and that only one of the pair is printed. The resultant list is printed.

The way Pyth works, the only way to open a file is to receive its name on STDIN. This is why I have counted 5 of the STDIN bytes, w.txt, in my score.

Example run:

$ pyth -c "J'f&qlTQ&}_TJ>_TTJ" <<< '6
w.txt'
['animal', 'denier', 'diaper', 'drawer', 'pupils', 'recaps', 'redraw', 'sleets', 'snoops', 'sports']

Ruby, 74 bytes

f=->n{i=IO.read('w.txt').split
p *i&[f.reverse]if f.size==n while f=i.pop}

Iterates over the list by removing elements, which avoids both palindromes and outputting both "stressed" and "desserts". Using the same variable name for the function and the iterator gets around a Ruby syntax quirk: even though f=i.pop is evaluated before f.reverse, the line won't parse unless f already means something. I could also use p.


Python, 126 125 120 bytes

N=input()
J=open("w.txt").read().split()
for c in set(J):
 if N==len(c)and c!=c[::-1]and c[::-1]in J:print c;J.remove(c)

Pretty straightforward solution.

Tags:

Code Golf