Esercizio 1

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

The difference in speed is due to the number of calculation these alghoritms

perform.Intuitively, the recursive method compute the same calculation a lot


of times unlike the dynamic programming algorithm so, the recursive method
is much more slower then the dynamic method. The dynamic programming
algorithm to compute the edit distance has a computational cost of θ(n · m)
where n is the lenght of the first string and m the lenght of the second one.
Infact,to fulfill the first row or the first column the computational cost is n (
for the row) or m (for the column). The code chunk that matter ( in terms of
computational cost) is the following:

for i in range(1,r):
for j in range(1,c):
if S[i-1]!=T[j-1]:
A[i,j]=min(A[i-1,j],A[i,j-1])+1
else:
A[i,j]=A[i-1,j-1]

Since we move thorugh each elements of the matrix and we compute just simple
operation, the computational cost is θ(n · m).
The recursive alghoritm instead has a computetional cost bigger or equal to
θ(2m ) where m is the lenght of the second string in the worst case (that is when
the two strings have completely different characters). In this case the condition
S[-1]!=T[-1] is always satisfied so, each time the alghoritm must compute the
distance between S[:-1] and T, S and T[:-1] and then find the minumum of these
two values. Therefore the recursive equation is:

T (n, m) = T (n − 1, m) + T (n, m − 1) + θ(1)


T (n, 0) = T (0, m) = θ(1)

Now if we expand the first equation we find:

T (n, m) = T (n − 1, m) + T (n, m − 1) + θ(2)


= T (n, m − 2) + 2T (n − 1, m − 1) + T (n − 2, m) + θ(4)
= T (n, m − 3) + 3T (n − 1, m − 2) + 3T (n − 2, m − 1) + T (n − 3, m) + θ(8)
= T (n, m − 4) + 4T (n − 1, m − 3) + 6T (n − 2, m − 2) + 4T (n − 3, m − 1) + T (n − 4, m) + 16θ(1)
...

We noticed that the coefficients are the same coefficient as (a+b)n . Therefore
at the k-th step we get:
k  
X k
T (n − j, m − k + j) + θ(2k ) (1)
j=0
j

Now, if we suppose that m < n, at the m-th step the equation became:

1
 !
m   m   n−j
X n − j 
X m X m
T (n − j, j) + θ(2m ) =  T (n − j − i, 2j − n + i)  + θ(2m )
j=0
j j=0
j i=0
i
(2)

The second term of the equality is obtained applying"the same line of reasoning
m
n−j #
m n−j
P  P 
to T (n−j, j). Whatever is the computational cost of: j i T (n − j − i, 2j − n + i) ,
j=0 i=0
the computational cost of T (n, m) is at least θ(2m ).

You might also like