find_words.py 998 B

12345678910111213141516171819202122232425262728
  1. if __name__ == '__main__':
  2. with open('word_list_2.txt') as all_words_raw:
  3. all_words = all_words_raw.read().split()
  4. all_words.sort(key = len) # sort word list by length
  5. print("Number of words = ", len(all_words))
  6. truncation_chains = []
  7. for cur_word in all_words:
  8. if len(cur_word) == 1:
  9. truncation_chains.append([cur_word])
  10. else:
  11. truncation = cur_word[:-1]
  12. for previous_chain in truncation_chains:
  13. if previous_chain[-1] == truncation:
  14. truncation_chains.append(previous_chain + [cur_word])
  15. break
  16. truncation_chains.sort(key = len, reverse=True)
  17. if len(truncation_chains) > 0:
  18. print("Longest found = ", truncation_chains[0])
  19. output_string = '\n'.join([' > '.join(chain) for chain in truncation_chains])
  20. with open('sorted_truncation_chains_2.txt', "w") as output_file:
  21. output_file.write(output_string)
  22. output_file.close()