Skip to content

Instantly share code, notes, and snippets.

@bennuttall
Last active November 3, 2019 13:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bennuttall/29381f5818beea8bd8669293219ed459 to your computer and use it in GitHub Desktop.
Save bennuttall/29381f5818beea8bd8669293219ed459 to your computer and use it in GitHub Desktop.
import operator
from graphviz import Digraph
alphabet = 'qwertyuiopasdfghjklzxcvbnm'
with open('/usr/share/dict/british-english') as f:
WORDS = {
word.strip()
for word in f
if all(c in alphabet for c in word.strip())
}
print(len(WORDS), 'words')
def get_chain_words(word):
new_words = {}
for i in range(len(word)):
new_word = word[:i] + word[i+1:]
if new_word in WORDS:
new_words[new_word] = get_chain_words(new_word)
return new_words
def calc_depth(d, word, c=1):
if d[word]:
return max(calc_depth(d[word], k, c+1) for k in d[word])
else:
return c
def create_graph(chain, word, dot=None, base=None):
if dot is None:
dot = Digraph(format='png')
if base is None:
base = word
else:
base = f'{base}_{word}'
dot.node(base, word)
for w, words in chain[word].items():
node = f'{base}_{w}'
dot.node(node, w)
dot.edge(base, node)
dot = create_graph(chain[word], w, dot, base)
return dot
if __name__ == '__main__':
chain = {word: get_chain_words(word) for word in WORDS}
chain_lengths = {word: calc_depth(chain, word) for word in chain}
n = max(chain_lengths.items(), key=operator.itemgetter(1))[1]
print('max chain length:', n)
for word, length in chain_lengths.items():
if length == n:
print(word)
dot = create_graph(chain, word)
dot.render(word)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment