File tree 2 files changed +49
-0
lines changed
problems/dynamic_programming
tests/dynamic_programming
2 files changed +49
-0
lines changed Original file line number Diff line number Diff line change
1
+ class EditDistance :
2
+ @staticmethod
3
+ def minDistance (word1 : str , word2 : str ) -> int :
4
+ # Lengths of the strings
5
+ m , n = len (word1 ), len (word2 )
6
+ # Lookup table to store minimum operations required
7
+ lookup = [[0 for _ in range (n + 1 )] for _ in range (m + 1 )]
8
+ # Base initialization
9
+ for i in range (m + 1 ):
10
+ lookup [i ][0 ] = i
11
+ for j in range (n + 1 ):
12
+ lookup [0 ][j ] = j
13
+ # Populate the remaining table
14
+ for i in range (1 , m + 1 ):
15
+ for j in range (1 , n + 1 ):
16
+ # If current characters are same, we don't have to
17
+ # do anything
18
+ cost = 0 if word1 [i - 1 ] == word2 [j - 1 ] else 1
19
+ lookup [i ][j ] = min (cost + lookup [i - 1 ][j - 1 ], 1 + lookup [i - 1 ][j ], 1 + lookup [i ][j - 1 ])
20
+
21
+ return lookup [m ][n ]
Original file line number Diff line number Diff line change
1
+ import unittest
2
+
3
+ from problems .dynamic_programming .edit_distance import EditDistance
4
+
5
+
6
+ class TestEditDistance (unittest .TestCase ):
7
+
8
+ def setUp (self ):
9
+ self .edit_distance = EditDistance ()
10
+
11
+ def test_min_distance_empty_strings (self ):
12
+ self .assertEqual (self .edit_distance .minDistance ("" , "" ), 0 )
13
+
14
+ def test_min_distance_one_empty_string (self ):
15
+ self .assertEqual (self .edit_distance .minDistance ("hello" , "" ), 5 )
16
+ self .assertEqual (self .edit_distance .minDistance ("" , "java" ), 4 )
17
+
18
+ def test_min_distance_same_strings (self ):
19
+ self .assertEqual (self .edit_distance .minDistance ("same" , "same" ), 0 )
20
+
21
+ def test_min_distance_different_strings (self ):
22
+ self .assertEqual (self .edit_distance .minDistance ("horse" , "ros" ), 3 )
23
+ self .assertEqual (self .edit_distance .minDistance ("intention" , "execution" ), 5 )
24
+ self .assertEqual (self .edit_distance .minDistance ("flaw" , "lawn" ), 2 )
25
+
26
+
27
+ if __name__ == "__main__" :
28
+ unittest .main ()
You can’t perform that action at this time.
0 commit comments