Guest User

Untitled

a guest
Jan 19th, 2019
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.34 KB | None | 0 0
  1. from sys import argv
  2. from string import ascii_lowercase
  3. lowercase = frozenset(ascii_lowercase)
  4.  
  5. if len(argv) > 1:
  6. dictionary_name = argv[1]
  7. else:
  8. dictionary_name = "/usr/share/dict/words"
  9.  
  10. dictionary = frozenset(
  11. word.rstrip()
  12. for word in file(dictionary_name)
  13. if lowercase.issuperset(word.rstrip())
  14. )
  15.  
  16. def test_word(word, candidates):
  17. if len(word) < 2:
  18. if word in "ia": # only interested in final 1-letter words "I" and "A"
  19. yield []
  20. else:
  21. for i in range(len(word)):
  22. check_word = word[:i] + word[i+1:]
  23. if check_word in candidates:
  24. for smaller_matches in test_word(check_word, candidates):
  25. yield [check_word] + smaller_matches
  26.  
  27. maxlen = 5 # default to something low
  28. longest_chains = set()
  29. for word in dictionary:
  30. if len(word) < maxlen: continue # don't look at lesser words
  31. for results in test_word(word, dictionary):
  32. results = [word] + results
  33. new_maxlen = len(results)
  34. if new_maxlen > maxlen:
  35. maxlen = new_maxlen
  36. longest_chains = set([tuple([word] + results)])
  37. elif new_maxlen == maxlen:
  38. longest_chains.add(tuple(results))
  39.  
  40. for result in sorted(longest_chains):
  41. print("%i: %s" % (
  42. len(result),
  43. ' '.join(w.upper() for w in result),
  44. ))
Add Comment
Please, Sign In to add comment