I'm trying to implement the following "game" in python:
Given a start word, find the goal word with modifications allowed modification per step: remove or add any letter and permute
The task is to find the way from start to goal with the least steps.
My approach was to add/remove a letter, permute the resulting letters and look up each permutant in a dictionary.
This quickly results in long run times (for a 9-letter word and the first step approx 60sec).
Here is my code.
import time
from itertools import permutations
startword = 'croissant'
nodes = list()
nodes.append(startword)
dicts = set([line.rstrip('\n') for line in open('wordList.txt')])
alpha = set([chr(i) for i in range(ord('a'),ord('z')+1)])
def step(nodes):
nnodes = list()
for word in nodes:
for s in word:
new_word = word.replace(s, '', 1)
perms = [''.join(p) for p in permutations(new_word)]
for per in perms:
if per in dicts:
nnodes.append(per)
for s in alpha:
new_word = word + s
perms = [''.join(p) for p in permutations(new_word)]
for per in perms:
if per in dicts:
nnodes.append(per)
return set(nnodes)
btime = time.time()
step(nodes)
print time.time() - btime
How can I improve the performance/logic? We are specifically asked to use a breadth first search.