Search This Blog

Tuesday, February 25, 2014

Write a program to find the longest word made of other words in a list of words.

__author__ = 'nitin'

   
EXAMPLE 
Input: test, tester, testertest, testing, testingtester
Output: testingtester

import sys

DEFAULT_FILE = 'words.txt'

def recsol(word, first=False):
    if not word or (not first and word in wordset): return True
    for i in range(1, len(word)):
        start = word[0:i]
        end = word[i:]
        if start in wordset and recsol(end):
            return True
    return False

filename = sys.argv[1] if len(sys.argv) > 1 else DEFAULT_FILE

header = '# Largest to Smallest Composable Strings #'
print '\n' + '#'*len(header) + '\n' + header + '\n' + '#'*len(header)
with open(filename, 'r') as f:
    wordstr = f.read()
wordlst = wordstr.split()
wordlst.sort(key=len, reverse=True)
wordset = set(wordlst)
cnt = 1
for s in wordlst:
    if recsol(s, True):
        print str(cnt) + '. ' + s
        cnt += 1

No comments:

My Profile

My photo
can be reached at 09916017317