title: Longest word chain from a list of words
body: <p>So, this is a part of a function I'm trying to make.</p>
  
  <p>I don't want the code to be too complicated.</p>
  
  <p>I have a list of words, e.g. </p>
  
  <pre><code>words = ['giraffe', 'elephant', 'ant', 'tiger', 'racoon', 'cat', 'hedgehog', 'mouse']
  </code></pre>
  
  <p>The idea of the word chain sequence is for the next word to begin with the letter that the last word ended in.</p>
  
  <p>(Edit: Each word cannot be used more than once. Other than that there are no other constraints.)</p>
  
  <p>I want the output to give the longest word chain sequence, which in this case is:</p>
  
  <pre><code>['hedgehog', 'giraffe', 'elephant', 'tiger', 'racoon']
  </code></pre>
  
  <p>I'm not really sure how to do it, I had different attempts at trying this. One of them...</p>
  
  <p>This code finds the word chain correctly if we start with a specific word from the list, e.g. words[0] (so 'giraffe'):</p>
  
  <pre><code>words = ['giraffe', 'elephant', 'ant', 'tiger', 'racoon', 'cat', 'hedgehog', 'mouse']
  
  word_chain = []
  
  word_chain.append(words[0])
  
  for word in words:
      for char in word[0]:
  
         if char == word_chain[-1][-1]:
              word_chain.append(word)
  
  print(word_chain)
  </code></pre>
  
  <p>Output:</p>
  
  <pre><code>['giraffe', 'elephant', 'tiger', 'racoon']
  </code></pre>
  
  <p>BUT, I want to find the longest possible chain of words (explained above).</p>
  
  <p><strong>My method:</strong> So, I tried to use the above working code that I wrote and loop through, using each word from the list as the starting point and finding the word chain for each word[0], word[1], word[2] etc. Then I tried to find the longest word chain by using an if statement and compare the length to the previous longest chain, but I can't get it done properly and I don't really know where this is going.</p>
  
  <pre><code>words = ['giraffe', 'elephant', 'ant', 'tiger', 'racoon', 'cat', 'hedgehog', 'mouse']
  
  word_chain = []
  max_length = 0
  for starting_word_index in range(len(words) - 1):
  
      word_chain.append(words[starting_word_index])
  
      for word in words:
          for char in word[0]:
  
              if char == word_chain[-1][-1]:
                  word_chain.append(word)
  
      # Not sure
  
      if len(word_chain) &gt; max_length:
          final_word_chain = word_chain
          longest = len(word_chain)
          word_chain.clear()
  
  print(final_word_chain)
  </code></pre>
  
  <p>This is my nth attempt, I think this one prints an empty list, I had different attempts before this that failed to clear the word_chain list properly and ended up repeating words over again.</p>
  
  <p>Any help much appreciated. Hopefully I didn't make this too teedious or confusing... Thanks!</p>