Experiments with Knuth's 5,757 five letter words. https://charlesreid1.com/wiki/Five_Letter_Words

reverse_lexico.py 1.3KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. """
  2. reverse_lexico.py
  3. Donald Knuth, Art of Computer Programming, Volume 4 Facsimile 0
  4. Variation on Exercise #30
  5. Each letter of the word "spied" appears in reversed lexicographic order.
  6. Find more words whose letters appear in reverse lexicographic order.
  7. """
  8. from get_words import get_words
  9. def in_reverse_sorted_order(word):
  10. chars = list(word)
  11. # Note: reversed returns a generator,
  12. # so we have to pass it to list()
  13. # to explicitly enumerate the reversed results.
  14. if(str(chars)==str(list(reversed(sorted(chars))))):
  15. return True
  16. else:
  17. return False
  18. if __name__=="__main__":
  19. words = get_words()
  20. words = sorted(words)
  21. count = 0
  22. print("-"*40)
  23. print("ALL lexicographically reversed words:")
  24. for word in words:
  25. if(in_reverse_sorted_order(word)):
  26. print(word)
  27. count += 1
  28. print("{0:d} total.".format(count))
  29. print("-"*40)
  30. for word in words:
  31. if(in_reverse_sorted_order(word)):
  32. print("First reverse lexicographically sorted word:")
  33. print(word)
  34. break
  35. words.reverse()
  36. print("-"*40)
  37. for word in words:
  38. if(in_reverse_sorted_order(word)):
  39. print("Last lexicographically sorted word:")
  40. print(word)
  41. break