Python Find the longest word chain in English word list of list

  • 2021-08-28 20:32:24
  • OfStack

This paper mainly introduces the list of word strings in Python (list), and finds out the longest word chain method code in which the first letter of the first word and the last letter of the last word are the same, and each word cannot be used many times.

For example:


words = ['giraffe', 'elephant', 'ant', 'tiger', 'racoon', 'cat', 'hedgehog', 'mouse']

List of the longest word chains:


['hedgehog', 'giraffe', 'elephant', 'tiger', 'racoon']

1. Use recursive method to find


words = ['giraffe', 'elephant', 'ant', 'tiger', 'racoon', 'cat', 'hedgehog', 'mouse']
def get_results(_start, _current, _seen):
 if all(c in _seen for c in words if c[0] == _start[-1]):
  yield _current
 else:
   for i in words:
    if i[0] == _start[-1]:
     yield from get_results(i, _current+[i], _seen+[i])

new_d = [list(get_results(i, [i], []))[0] for i in words]
final_d = max([i for i in new_d if len(i) == len(set(i))], key=len)

Output:

['hedgehog', 'giraffe', 'elephant', 'tiger', 'racoon']

2. Use networkx to find


import networkx as nx
import matplotlib.pyplot as plt
words = ['giraffe', 'elephant', 'ant', 'tiger', 'racoon', 'cat',
     'hedgehog', 'mouse']
G = nx.DiGraph()
G.add_nodes_from(words)
for word1 in words:
  for word2 in words:
    if word1 != word2 and word1[-1] == word2[0]:
      G.add_edge(word1, word2)
nx.draw_networkx(G)
plt.show()
print(nx.algorithms.dag.dag_longest_path(G))


Related articles: