Python Sort Longest English Word Chain of The last letter of the previous word in the list is the first letter of the next word

  • 2021-08-21 20:52:26
  • OfStack

Use recursive implementation


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']

It works like a breadth-first search because the get_results function continues to traverse the entire list as long as the current value has not been previously called. The value that the function has looked up is added to the _ seen list, and finally the recursive call flow is stopped. This solution also ignores duplicate results,


words = ['giraffe', 'elephant', 'ant', 'ning', 'tiger', 'racoon', 'cat', 'hedgehog', 'mouse',]
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:

['ant', 'tiger', 'racoon', 'ning', 'giraffe', 'elephant']


Related articles: