Transforming source word into target word

I need some help with my code. I need to convert one input word into another, changing one letter at a time. currently my program does this but very inefficiently and does not find the shortest route. Any help would be appreciated.

import re
def same(item, target):
  return len([c for (c, t) in zip(item, target) if c == t])

def build(pattern, words, seen, list):
  return [word for word in words
                 if, word) and word not in seen.keys() and
                    word not in list]

def find(word, words, seen, target, path):
  list = []
  for i in range(len(word)):
    list += build(word[:i] + "." + word[i + 1:], words, seen, list)
  if len(list) == 0:
    return False
  list = sorted([(same(w, target), w) for w in list])
  for (match, item) in list:
    if match >= len(target) - 1:
      if match == len(target) - 1:
      return True
    seen[item] = True
  for (match, item) in list:
    if find(item, words, seen, target, path):
      return True

fname = 'dictionary.txt'
file = open(fname)
lines = file.readlines()
while True:
  start = input("Enter start word:")
  words = []
  for line in lines:
    word = line.rstrip()
    if len(word) == len(start):
  target = input("Enter target word:")

count = 0
path = [start]
seen = {start : True}
if find(start, words, seen, target, path):
  print(len(path) - 1, path)
  print("No path found")

Powered by Zordis

Share This Post
Have your say!

Leave a Reply