metric_lcs.py 670 B

123456789101112131415161718192021
  1. from .string_distance import MetricStringDistance, NormalizedStringDistance
  2. from .longest_common_subsequence import LongestCommonSubsequence
  3. class MetricLCS(MetricStringDistance, NormalizedStringDistance):
  4. def __init__(self):
  5. self.lcs = LongestCommonSubsequence()
  6. def distance(self, s0, s1):
  7. if s0 is None:
  8. raise TypeError("Argument s0 is NoneType.")
  9. if s1 is None:
  10. raise TypeError("Argument s1 is NoneType.")
  11. if s0 == s1:
  12. return 0.0
  13. max_len = int(max(len(s0), len(s1)))
  14. if max_len == 0:
  15. return 0.0
  16. return 1.0 - (1.0 * self.lcs.length(s0, s1)) / max_len