from collections import defaultdict


def signature(s):
    """Returns the signature of this string.

    Signature is a string that contains all of the letters in order.

    s: string
    """
    t = list(s)
    t = ''.join(sorted(t))
    return t


def all_anagrams(filename):
    d = defaultdict(list)
    for line in open(filename):
        word = line.strip().lower()
        t = signature(word)

        # TODO: rewrite using defaultdict
        if t not in d:
            d[t] = [word]
        else:
            d[t].append(word)
    return d


def print_anagram_sets(d):

    """Prints the anagram sets in d.
    d: map from words to list of their anagrams

    """

    for v in d.values():
        if len(v) > 1:
            print(len(v), v)


def print_anagram_sets_in_order(d):

    """Prints the anagram sets in d in decreasing order of size.
    d: map from words to list of their anagrams
    """

    # make a list of (length, word pairs)
    t = []

    for v in d.values():
        if len(v) > 1:
            t.append((len(v), v))

    # sort in ascending order of length
    t.sort(reverse=True)

    # print the sorted list
    for x in t:
        print(x)

if __name__ == '__main__':
    anagram_map = all_anagrams('words.txt')
    print(type(anagram_map))
    #print_anagram_sets(anagram_map)
    print_anagram_sets_in_order(anagram_map)
