Count letter differences of two strings

后端 未结 11 681
既然无缘
既然无缘 2020-12-09 17:11

This is the behaviour I want:

a: IGADKYFHARGNYDAA
c: KGADKYFHARGNYEAA
2 difference(s).
11条回答
  •  失恋的感觉
    2020-12-09 17:27

    With difflib.ndiff you can do this in a one-liner that's still somewhat comprehensible:

    >>> import difflib
    >>> a = 'IGADKYFHARGNYDAA'
    >>> c = 'KGADKYFHARGNYEAA'
    >>> sum([i[0] != ' '  for i in difflib.ndiff(a, c)]) / 2
    2
    

    (sum works here because, well, kind of True == 1 and False == 0)

    The following makes it clear what's happening and why the / 2 is needed:

    >>> [i for i in difflib.ndiff(a,c)]
    ['- I',
     '+ K',
     '  G',
     '  A',
     '  D',
     '  K',
     '  Y',
     '  F',
     '  H',
     '  A',
     '  R',
     '  G',
     '  N',
     '  Y',
     '- D',
     '+ E',
     '  A',
     '  A']
    

    This also works well if the strings have a different length.

提交回复
热议问题