sixwords = open('sixwords.txt', 'r') words = sixwords.readlines() sixwords.close() words = [x.strip() for x in words] worddict = {} for w in words: for x in range(1,7): y = w[0:x] try: worddict[y].append(w) except KeyError: worddict[y] = [w] counter = 0 def solve(currentwords, depth): global counter counter += 1 if counter % 1000 == 0: print counter, if len(currentwords) == 6: print depth, counter, currentwords for q in currentwords: print q print "\n\n" dummy = raw_input() return True else: print "\n\ncurrentwords", currentwords, counter big = ''.join(currentwords) prefixes = [ big[0::6] ] nextletterset = list( set( [x[len(currentwords)] for x in worddict[prefixes[0]]] ) ) for letter in nextletterset: for maybefuture in worddict[letter]: futurezip = zip(*currentwords+[maybefuture]) futureprefixes = [''.join(z) for z in futurezip] validprefixes = [f in worddict for f in futureprefixes] if not False in validprefixes: solve( currentwords + [maybefuture], depth + 1 ) return False seed=['banana'] import cProfile cProfile.run('print solve(seed, 1)')