Advertisement
Geometrian

Word Chains

Feb 9th, 2015
373
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.26 KB | None | 0 0
  1. import os.path
  2.  
  3. try:    import cPickle as pickle #Only present in Python 2.*; Python 3 automatically imports the
  4. except: import  pickle as pickle #new equivalent of cPickle, if it's available.
  5. import zlib
  6.  
  7.  
  8. def dist(word0,word1):
  9.     if len(word0) == len(word1):
  10.         d = 0
  11.         for i in range(len(word0)):
  12.             if word0[i] != word1[i]:
  13.                 d += 1
  14.         return d
  15.     return False
  16.  
  17. class Word(object):
  18.     def __init__(self, index,word):
  19.         self.index = index
  20.         self.word = word
  21.        
  22.         self.path_parent = None
  23.  
  24.         self.connections = []
  25.     def find_neighbors(self, words):
  26.         for w in words:
  27.             if w.word == self.word: continue
  28.  
  29.             d = dist(w.word,self.word)
  30.             if d != False and d == 1:
  31.                 self.connections.append(w.index)
  32.  
  33.     def __repr__(self):
  34.         return "<" + self.word + ">"
  35.  
  36. p = "words.conn"
  37. if os.path.isfile(p):
  38.     print("Reading cached data . . .")
  39.     file = open(p,"rb")
  40.     data_str = file.read()
  41.     file.close()
  42.    
  43.     data_str = zlib.decompress(data_str)
  44.     words = pickle.loads(data_str)
  45. else:
  46.     print("Loading word data . . .")
  47.     file = open("dictionary.txt","r")
  48.     data = file.readlines()
  49.     file.close()
  50.  
  51.     print("Creating objects . . .")
  52.     words = {}
  53.     for line in data:
  54.         line = line.strip()
  55.         l = len(line)
  56.         if l not in words.keys(): words[l]=[]
  57.         words[l].append(Word( len(words[l]), line ))
  58.  
  59.     print("Finding neighbors . . .")
  60.     for wordset in words.values():
  61.         l = len(wordset[0].word)
  62.         print((l,len(wordset)))
  63.         #if l != 3: continue
  64.  
  65.         for word in wordset:
  66.             word.find_neighbors(wordset)
  67.  
  68.     print("Caching to file . . .")
  69.     data_str = pickle.dumps(words)
  70.     data_str = zlib.compress(data_str,9)
  71.  
  72.     file = open(p,"wb")
  73.     file.write(data_str)
  74.     file.close()
  75. print("Done!")
  76.  
  77.  
  78. def get_word(s):
  79.     wordset = words[len(s)]
  80.     for w in wordset:
  81.         if w.word == s:
  82.             return w
  83.     assert False
  84.  
  85. #List of strings excluded from search.  Add to as desired.
  86. ignore = []
  87. def print_path(src,dst):
  88.     l = len(src.word)
  89.     wordset = words[l]
  90.  
  91.     for word in wordset:
  92.         word.path_parent = None
  93.  
  94.     openset = [src]
  95.     while len(openset) > 0:
  96.         word=openset[0]; openset=openset[1:]
  97.         for iconnection in word.connections:
  98.             connection = wordset[iconnection]
  99.             if connection.word in ignore: continue
  100.             if connection.path_parent == None:
  101.                 connection.path_parent = word
  102.                 openset.append(connection)
  103.  
  104.         if word == dst: break
  105.  
  106.     if dst.path_parent == None:
  107.         print("No path found!")
  108.     else:
  109.         path = [dst]
  110.         current = dst
  111.         while current != src:
  112.             path.append(current.path_parent)
  113.             current = current.path_parent
  114.             assert current != None
  115.         for w in path[::-1]:
  116.             print(w)
  117.  
  118. ##print_path(get_word("aa"),get_word("ab"))
  119. ##print_path(get_word("bot"),get_word("car"))
  120. ##print_path(get_word("door"),get_word("hers"))
  121. ##print_path(get_word("hammer"),get_word("cheese"))
  122. print_path(get_word("under"),get_word("stand"))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement