Search code examples
pythonstring-comparisonlevenshtein-distance

Python: How to find the position of the character that makes the levenshtein distance


I'm calculating the levenshtein distance for some strings. Only the one with a distance of 1 I want to analyze further. What I'm interested in, above all, is the position of the character that makes the distance. So for example;

('rodange', 'redange', 1)  # position 2

I can think of a couple of ways to get there but they seem not very handy (like looping through all characters and comparing them one by one). Something out there already?


Solution

  • I don't think there's a better solution than what you already figured out. Either add code that returns the index of the first change to the levenshtein algorithm you are using. That should be a single line at the right place, and a modified return statement.

    Or loop through it like you say, not too difficult either:

    idx = next(i for (i, (a, b)) in enumerate(zip(w1, w2)) if a != b)
    

    If you prefer it shorter:

    from operator import eq
    idx = map(eq, w1, w2).index(False)