Advertisement
Guest User

Untitled

a guest
Mar 1st, 2017
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.19 KB | None | 0 0
  1. # Minimum edit distance algorithm (Wagner-Fischer). Note that this isn't a very efficient algorithm (it runs in
  2. # exponential time, and n^2 space).
  3.  
  4. def minEditDistance(string1, string2):
  5.     # this will be a 2D array to store the distance. Think of it as n*m matrix, which we initially fill with 0s
  6.     array = [[0 for i in range(len(string1)+1)] for j in range(len(string2)+1)];
  7.     # fill the top row of the matrix
  8.     for j in range(len(string1) + 1):
  9.         array[0][j] = j
  10.        
  11.     # fill the first column
  12.     for i in range(len(string2) + 1):
  13.         array[i][0] = i
  14.        
  15.     for i in range(1, len(string2) + 1):
  16.         for j in range(1, len(string1) + 1):
  17.             if string1[j-1] == string2[i-1]:
  18.                 array[i][j] = array[i-1][j-1]
  19.             else:
  20.                 array[i][j] = min (min ((array[i-1][j-1] + 2), (array[i][j-1] + 1)), (array[i-1][j] + 1))
  21.        
  22.     return array[len(string2)][len(string1)]
  23.    
  24. print("to verify the pen and paper exercis:")
  25. print("'refa' to 'fear':    ", minEditDistance("refa", "fear"))
  26. print("'drive' to 'brief':  ", minEditDistance("drive", "brief"))
  27. print("'drive' to 'divers': ", minEditDistance("drive", "divers"))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement