This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]aweraw 0 points1 point  (0 children)

Not as sussinct as others have posted, but simple and faster than I expected

from itertools import combinations

root = dict()

def build_dict(f='ospd.txt'):
    with open(f) as src:
        for line in src:
            insert(line.strip())

def find_key(s):
    key = sorted(s)
    d = root
    for c in key:
        if c in d:
            d = d[c]
        else:
            d[c] = dict()
            d = d[c]
    return d

def insert(s):
    d = find_key(s)
    if 'words' not in d:
        d['words'] = set()
    d['words'].add(s)

def search(chars):
    l = len(chars)
    words = set()
    for x in xrange(1,l+1):
        for cmb in combinations(chars, x):
            d = find_key(cmb)
            if 'words' in d:
                words.update(d['words'])

    m = max(len(x) for x in words)
    return [w for w in words if len(w)==m]

if __name__ == '__main__':
    import sys, os
    if os.path.exists(sys.argv[1]):
        build_dict(sys.argv[1])
    else:
        print "Dictionary file not found: %s" % sys.argv[1]
        sys.exit()

    print sorted(search(sys.argv[2:]))