I assume that you have a list of valid words, and you are not really looking for one way (why do you need to optimize it), but for many ways. This can be done quite easily with networkX :
from networkx import Graph from networkx.algorithms.shortest_paths import shortest_path, all_pairs_shortest_path from itertools import combinations WORDS = {'cat', 'hat', 'sat', 'car', 'cad', 'had', 'pad', 'pat', 'can', 'man'} def makeGraph(words): """ create a graph where nodes are words and two words are connected iff they have one different letter """ G = Graph()
Thanks @Ducan for examples of words.
If you really want to implement these algorithms yourself, you can find many descriptions in wikipedia . The classic Dijkstra's single-source shortest path algorithm and the classic Floyd-Warshall shortest path algorithm.
source share