Experiments with Knuth's 5,757 five letter words. https://charlesreid1.com/wiki/Five_Letter_Words
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

64 lines
1.6 KiB

  1. """
  2. palindromes.py
  3. Donald Knuth, Art of Computer Programming, Volume 4 Facsimile 0
  4. Exercise #29
  5. Find all SGB words that are palindromes (kayak)
  6. or that are palindrome pairs (regal lager)
  7. """
  8. from get_words import get_words
  9. from pprint import pprint
  10. def is_palindrome(word):
  11. test1 = word[0]==word[4]
  12. test2 = word[1]==word[3]
  13. if(test1 and test2):
  14. return True
  15. return False
  16. def is_palindrome_pair(word1,word2):
  17. test0 = word1[0]==word2[4]
  18. test1 = word1[1]==word2[3]
  19. test2 = word1[2]==word2[2]
  20. test3 = word1[3]==word2[1]
  21. test4 = word1[4]==word2[0]
  22. if(test0 and test1 and test2 and test3 and test4):
  23. return True
  24. return False
  25. if __name__=="__main__":
  26. words = get_words()
  27. kp = 0
  28. palindromes = []
  29. kpp = 0
  30. palindrome_pairs = []
  31. # Check for palindromes
  32. for i in range(len(words)):
  33. if(is_palindrome(words[i])):
  34. kp += 1
  35. palindromes.append(words[i])
  36. print("-"*40)
  37. print("Palindromes: \n")
  38. print(", ".join(palindromes))
  39. print("There are {0:d} palindromes.".format(kp))
  40. # Check for palindrome pairs
  41. for i in range(len(words)):
  42. for j in range(i,len(words)):
  43. if(is_palindrome_pair(words[i],words[j])):
  44. # Palindromes shouldn't count as palindrome pairs
  45. if(words[i] is not words[j]):
  46. kpp += 1
  47. palindrome_pairs.append((words[i],words[j]))
  48. print("-"*40)
  49. print("Palindrome Pairs: \n")
  50. for pair in palindrome_pairs:
  51. print(", ".join(pair))
  52. print("There are {0:d} palindrome pairs.".format(kpp))