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

near_palindromes.py 1014B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. """
  2. near_palindromes.py
  3. Donald Knuth, Art of Computer Programming, Volume 4 Facsimile 0
  4. Variation on Exercise #29
  5. Find SGB words that are near-palindromes
  6. (edit distance of one or two letters away from a palindrome).
  7. """
  8. from get_words import get_words
  9. from euclidean_distance import euclidean_distance
  10. from pprint import pprint
  11. def is_near_palindrome(word,lo,hi):
  12. d1 = euclidean_distance(word[0],word[4])
  13. d2 = euclidean_distance(word[1],word[3])
  14. if( (d1+d2) > lo and (d1+d2) <= hi ):
  15. return True
  16. return False
  17. if __name__=="__main__":
  18. words = get_words()
  19. knp = 0
  20. near_palindromes = []
  21. # Euclidean distance tolerance
  22. lo = 0.0
  23. hi = 1.0
  24. for i in range(len(words)):
  25. if(is_near_palindrome(words[i],lo,hi)):
  26. knp += 1
  27. near_palindromes.append(words[i])
  28. print("-"*40)
  29. print("Near Palindromes: \n")
  30. print(", ".join(near_palindromes))
  31. print("The number of near-palindromes is {0:d}".format(len(near_palindromes)))