Commit 7c1dcbf5 authored by Dave Lane's avatar Dave Lane

initial commit of working solver

parents
#!/home/dave/.pyenv/shims/python
import sys
#import
WORDS_PATH = '/usr/share/dict/british-english'
# accept 2 arguments, two valid dictionary words of the same length.
start = sys.argv[1]
end = sys.argv[2]
if len(start) != len(end):
print 'Words are not the same length. Cannot form a wordchain.'
exit(0)
WORDS = []
with open(WORDS_PATH) as f:
for line in f:
l = line.strip()
if "'s" not in l and len(l) == len(start):
WORDS.append(l)
if start not in WORDS:
print '%s is not in dictionary. Cannot find a wordchain.' %start
exit(0)
if end not in WORDS:
print '%s is not in dictionary. Cannot find a wordchain.' %end
exit(0)
def get_distance(word1, word2):
differences = 0
for i, j in zip(word1, word2):
if i != j:
differences += 1
return differences
FOUND_NEIGHBOURS = {}
def all_neighbours(word):
if word in FOUND_NEIGHBOURS:
return FOUND_NEIGHBOURS[word]
else:
ret = []
for other_word in WORDS:
if get_distance(word, other_word) == 1:
ret.append(other_word)
FOUND_NEIGHBOURS[word] = ret
return ret
working_chain = []
to_choose = [[start]]
itercount = 0
while to_choose and end not in working_chain:
while to_choose[-1]:
working_chain.append(to_choose[-1].pop())
new_neighbours = [i for i in all_neighbours(working_chain[-1]) if i not in working_chain]
new_neighbours.sort(key = lambda x: get_distance(end, x), reverse = True)
if new_neighbours and new_neighbours[-1] == end:
working_chain.append(end)
break
else:
itercount += 1
to_choose.append(new_neighbours)
else:
if end not in working_chain:
working_chain.pop()
to_choose.pop()
else:
break
for i in working_chain:
print i
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment