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

euclidean_distance.py 1023B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import random, math, operator
  2. from pprint import pprint
  3. from get_words import get_words
  4. random.seed(1337)
  5. """
  6. euclidean_dist.py
  7. Compute euclidean distance between 5-letter words.
  8. """
  9. def euclidean_distance(word1, word2):
  10. v1 = word2vec(word1)
  11. v2 = word2vec(word2)
  12. return l2norm(v1,v2)
  13. def l2norm(vec1, vec2):
  14. radicand = [(v2-v1)*(v2-v1) for (v1,v2) in zip(vec1,vec2)]
  15. return math.sqrt(sum(radicand))
  16. def word2vec(word):
  17. charvec = []
  18. vec = []
  19. for c in word:
  20. charvec.append(c)
  21. vec.append(ord(c)-ord('a'))
  22. return vec
  23. def print_tuple(e):
  24. print("Distance between {0:s} and {1:s} = {2:f}".format(*e))
  25. if __name__=="__main__":
  26. words = get_words()
  27. eds = []
  28. for i in range(100):
  29. w1 = words[random.randint(1,5757)]
  30. w2 = words[random.randint(1,5757)]
  31. ed = euclidean_distance(w1,w2)
  32. eds.append((w1,w2,ed))
  33. sorted_eds = sorted(eds, key=operator.itemgetter(2))
  34. for e in reversed(sorted_eds):
  35. print_tuple(e)