Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class TreeNode(object):
- def __init__(self, prefix, parent=None):
- self.prefix = prefix
- self.branches = {}
- self.word = False
- self.parent = parent
- def add(self, item):
- if item == self.prefix: # done
- self.word = True
- return
- letter = item[len(self.prefix)]
- if letter not in 'abcdefghijklmnopqrstuvwxyz':
- return # not alphabet, nevermind
- if letter not in self.branches:
- self.branches[letter] = TreeNode(item[0:len(self.prefix) + 1], self)
- self.branches[letter].add(item)
- def dump(self, pad=''):
- print "%s%s %s" % (pad, self.prefix, self.word,)
- for letter in self.branches.iterkeys():
- self.branches[letter].dump(pad + ' ')
- class Dictionary(TreeNode):
- def __init__(self):
- super(Dictionary, self).__init__('')
- print "loading dictionary ..."
- for word in file('/usr/share/dict/american-english'):
- word = word[0:-1].lower()
- if len(word) > 1:
- self.add(word)
- print "loaded."
- def solvePuzzle(dictionary, puzzle):
- results = []
- visited = {}
- # recurse into puzzle, follow allong in tree-structure dictionary
- def searchPuzzle(wordsofar, x, y, treeloc):
- # off puzzle - return
- if x >= len(puzzle[0]) or x < 0:
- return
- if y >= len(puzzle) or y < 0:
- return
- # already used this letter - return
- if "%s-%s" % (x, y) in visited:
- return
- wordsofar = wordsofar + puzzle[y][x]
- treeloc = treeloc.branches.get(wordsofar[-1])
- # no words in dictionary from this stem, give up
- if not treeloc:
- return
- # new word found
- if treeloc.word and wordsofar not in results:
- results.append(wordsofar)
- pos = "%s-%s" % (x, y)
- visited[pos] = True
- searchPuzzle(wordsofar, x+1, y, treeloc)
- searchPuzzle(wordsofar, x-1, y, treeloc)
- searchPuzzle(wordsofar, x, y+1, treeloc)
- searchPuzzle(wordsofar, x, y-1, treeloc)
- del visited[pos]
- for x in range(0, len(puzzle[0])):
- for y in range(0, len(puzzle)):
- searchPuzzle('', x, y, dictionary)
- return results
- if __name__ == '__main__':
- print solvePuzzle(Dictionary(), ['xxdx', 'xxrt', 'xcax', 'xxxx'])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement