Skip to content

Instantly share code, notes, and snippets.

@fanjin-z
Created May 15, 2019 19:54
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fanjin-z/b01ad4588520aa01bd93002053611d8d to your computer and use it in GitHub Desktop.
Save fanjin-z/b01ad4588520aa01bd93002053611d8d to your computer and use it in GitHub Desktop.
Python Implementation of Myers Diff Algorithm
'''
MIT License
Copyright (c) 2019 Fanjin Zeng
This work is licensed under the terms of the MIT license, see <https://opensource.org/licenses/MIT>.
'''
import numpy as np
def diff(a, b):
N = len(a)
M = len(b)
MAX = max(0, M+N)
V = np.zeros((2*MAX+1), np.int)
dist = -1
for D in range(MAX):
for k in range(-D, D+1, 2):
if k == -D or k != D and V[k-1] < V[k+1]:
x = V[k+1]
else:
x = V[k-1] + 1
y = x - k
while x < N and y < M and (y < 0 or a[x] == b[y]):
x += 1
y += 1
V[k] = x
if x >= N and y >= M:
dist = D
break
if dist != -1:
break
return dist
if __name__ == '__main__':
a = 'abcabba'
b = 'cbabac'
dist = diff(a, b)
assert dist == 5
a = 'abcabc'
b = 'bcbd'
dist = diff(a, b)
assert dist == 4
a = 'abcabc'
b = 'abc'
dist = diff(a, b)
assert dist == 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment