Task: Teacup rim text





Java: import java.io.*;
import java.util.*;

public class Teacup {
    public static void main(String[] args) {
        if (args.length != 1) {
            System.err.println("usage: java Teacup dictionary");
            System.exit(1);
        }
        try {
            findTeacupWords(loadDictionary(args[0]));
        } catch (Exception ex) {
            System.err.println(ex.getMessage());
        }
    }

    
    private static Set<String> loadDictionary(String fileName) throws IOException {
        Set<String> words = new TreeSet<>();
        try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
            String word;
            while ((word = reader.readLine()) != null)
                words.add(word);
            return words;
        }
    }

    private static void findTeacupWords(Set<String> words) {
        List<String> teacupWords = new ArrayList<>();
        Set<String> found = new HashSet<>();
        for (String word : words) {
            int len = word.length();
            if (len < 3 || found.contains(word))
                continue;
            teacupWords.clear();
            teacupWords.add(word);
            char[] chars = word.toCharArray();
            for (int i = 0; i < len - 1; ++i) {
                String rotated = new String(rotate(chars));
                if (rotated.equals(word) || !words.contains(rotated))
                    break;
                teacupWords.add(rotated);
            }
            if (teacupWords.size() == len) {
                found.addAll(teacupWords);
                System.out.print(word);
                for (int i = 1; i < len; ++i)
                    System.out.print(" " + teacupWords.get(i));
                System.out.println();
            }
        }
    }

    private static char[] rotate(char[] ch) {
        char c = ch[0];
        System.arraycopy(ch, 1, ch, 0, ch.length - 1);
        ch[ch.length - 1] = c;
        return ch;
    }
}



Python: 

from itertools import chain, groupby
from os.path import expanduser
from functools import reduce



def main():
    
    print('\n'.join(
        concatMap(circularGroup)(
            anagrams(3)(
                
                lines(readFile('~/mitWords.txt'))
            )
        )
    ))



def anagrams(n):
    
    def go(ws):
        def f(xs):
            return [
                [snd(x) for x in xs]
            ] if n <= len(xs) >= len(xs[0][0]) else []
        return concatMap(f)(groupBy(fst)(sorted(
            [(''.join(sorted(w)), w) for w in ws],
            key=fst
        )))
    return go



def circularGroup(ws):
    
    lex = set(ws)
    iLast = len(ws) - 1
    
    
    (i, blnCircular) = until(
        lambda tpl: tpl[1] or (tpl[0] > iLast)
    )(
        lambda tpl: (1 + tpl[0], isCircular(lex)(ws[tpl[0]]))
    )(
        (0, False)
    )
    return [' -> '.join(allRotations(ws[i]))] if blnCircular else []



def isCircular(lexicon):
    
    def go(w):
        def f(tpl):
            (i, _, x) = tpl
            return (1 + i, x in lexicon, rotated(x))

        iLast = len(w) - 1
        return until(
            lambda tpl: iLast < tpl[0] or (not tpl[1])
        )(f)(
            (0, True, rotated(w))
        )[1]
    return go



def allRotations(w):
    
    return takeIterate(len(w) - 1)(
        rotated
    )(w)





def concatMap(f):
    
    def go(xs):
        return chain.from_iterable(map(f, xs))
    return go



def fst(tpl):
    
    return tpl[0]



def groupBy(f):
    
    def go(xs):
        return [
            list(x[1]) for x in groupby(xs, key=f)
        ]
    return go



def lines(s):
    
    return s.splitlines()



def mapAccumL(f):
    
    def go(a, x):
        tpl = f(a[0], x)
        return (tpl[0], a[1] + [tpl[1]])
    return lambda acc: lambda xs: (
        reduce(go, xs, (acc, []))
    )



def readFile(fp):
    
    with open(expanduser(fp), 'r', encoding='utf-8') as f:
        return f.read()



def rotated(s):
    
    return s[1:] + s[0]



def snd(tpl):
    
    return tpl[1]



def takeIterate(n):
    
    def go(f):
        def g(x):
            def h(a, i):
                v = f(a) if i else x
                return (v, v)
            return mapAccumL(h)(x)(
                range(0, 1 + n)
            )[1]
        return g
    return go



def until(p):
    
    def go(f):
        def g(x):
            v = x
            while not p(v):
                v = f(v)
            return v
        return g
    return go



if __name__ == '__main__':
    main()