#!/usr/bin/python
# vim:fileencoding=utf-8
class Vertex(object):
def __init__(self, depth, parent, CWR):
self.depth = depth
self.parent = parent
self.CWR = CWR
self.children = []
def create_vocabulary():
global vocabulary
with open('./words.txt', 'r') as f:
vocabulary = f.read().split()
def solve_CWR(vertex):
global vocabulary
depth = vertex.depth
if depth == 3:
return
elif depth == 0:
is_valid_extension = lambda cwr, word: cwr[0][2] == word[0]
elif depth == 1:
is_valid_extension = lambda cwr, word: cwr[1][2] == word[2]
elif depth == 2:
is_valid_extension = (lambda cwr, word: cwr[0][0] == word[0] and
cwr[2][0] == word[2])
for word in vocabulary:
if is_valid_extension(vertex.CWR, word):
CWR = vertex.CWR[:]
CWR.append(word)
newchild = Vertex(depth+1, vertex, CWR)
vertex.children.append(newchild)
solve_CWR(newchild)
def print_solutions(vertex):
if vertex.depth == 3:
print vertex.CWR
return
for child in vertex.children:
print_solutions(child)
if __name__ == '__main__':
import random
create_vocabulary()
CWR = [vocabulary[random.randint(0, len(vocabulary)-1)]]
root = Vertex(0, None, CWR)
solve_CWR(root)
pAdd a code snippet to your website: www.paste.org