Skip to content

Instantly share code, notes, and snippets.

@montycheese
Created October 20, 2015 13:47
Show Gist options
  • Save montycheese/54ab7b0973cea9764f79 to your computer and use it in GitHub Desktop.
Save montycheese/54ab7b0973cea9764f79 to your computer and use it in GitHub Desktop.
solves a word ladder given a dictionary
from string import ascii_lowercase as alphabet
d = {"dog","dig", "din", "dag","fog",
"god", "fig", "ape", "dot", "got",
"bog", "bag","bat","cat"
}
def transform(w1, w2):
frontier = [[w1]]
explored = set()
while(len(frontier) > 0):
curr_path = frontier.pop(0)
word = curr_path[-1]
if word == w2:
return curr_path
else:
explored.add(word)
neighbors = []
for i in range(len(word)):
for char in alphabet:
new_word = word[:i] + char + word[i+1:]
if new_word == w1:
continue
elif is_word(new_word) and new_word not in explored:
neighbors.append(curr_path[:] + [new_word])
for n in neighbors:
frontier.append(n)
return w1
def is_word(w):
return w in d
def main():
print transform("bob","cat")
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment