I am new to python. I would like all the python gurus to suggest some ways to make the following code more pythonic and hence more efficient .
Its a simple code to find the edit distance between two words.
P.S. I would like improvements in code, not in the logic or algorithm optimization.
class test:
def __init__(self,a,b,I=1,D=1,R=1):
self.a = a
self.b = b
self.mem = dict()
self.la = len(a)
self.lb = len(b)
self.I = I
self.D = D
self.R = R
def diff(self,i=0,j=0):
T = self.diff
memo = self.mem
if j == self.lb: return self.D * i
if i == self.la: return self.D * j
if (i,j) in memo:
return memo[(i,j)]
if self.a[i] == self.b[j]:
memo[(i,j)] = T( i+1,j+1 )
return memo[ (i,j) ]
memo[(i,j)] = min(self.R + T(i+1,j+1) , self.D + T(i+1,j) , self.I + T(i,j+1) ,
self.D + T(i,j+1) , self.I + T(i+1,j) )
return memo[(i,j)]
Variable explanation:
a,b are two string whose edit distance is to be found.
I,D,R Insertion Deletion and Replace cost of a single letter.
mem is dictionary used to memoize the recursive calls.
i and j are the pointers of the string a and b respectively
Pythonic would be:
a bottleneck and if it is improve the algorithm.
T(i+1, j+1)notT( i+1,j+1 )memo[i,j]notmemo[(i,j)]self.diff(i+1, j+1)notT(i+1,j+1)