@@ -38,12 +38,13 @@ class LexicalDistance:
38
38
39
39
_input : str
40
40
_input_lower_case : str
41
- _cells : List [List [int ]]
41
+ _rows : List [List [int ]]
42
42
43
43
def __init__ (self , input_ : str ):
44
44
self ._input = input_
45
45
self ._input_lower_case = input_ .lower ()
46
- self ._cells = []
46
+ row_size = len (input_ ) + 1
47
+ self ._rows = [[0 ] * row_size , [0 ] * row_size , [0 ] * row_size ]
47
48
48
49
def measure (self , option : str ):
49
50
if self ._input == option :
@@ -55,28 +56,32 @@ def measure(self, option: str):
55
56
if self ._input_lower_case == option_lower_case :
56
57
return 1
57
58
58
- d = self ._cells
59
59
a , b = option_lower_case , self ._input_lower_case
60
60
a_len , b_len = len (a ), len (b )
61
61
62
- d = [[ j for j in range ( 0 , b_len + 1 )]]
63
- for i in range (1 , a_len + 1 ):
64
- d . append ([ i ] + [ 0 ] * b_len )
62
+ rows = self . _rows
63
+ for j in range (0 , b_len + 1 ):
64
+ rows [ 0 ][ j ] = j
65
65
66
66
for i in range (1 , a_len + 1 ):
67
+ up_row = rows [(i - 1 ) % 3 ]
68
+ current_row = rows [i % 3 ]
69
+
70
+ current_row [0 ] = i
67
71
for j in range (1 , b_len + 1 ):
68
72
cost = 0 if a [i - 1 ] == b [j - 1 ] else 1
69
73
70
74
current_cell = min (
71
- d [ i - 1 ] [j ] + 1 , # delete
72
- d [ i ] [j - 1 ] + 1 , # insert
73
- d [ i - 1 ] [j - 1 ] + cost , # substitute
75
+ up_row [j ] + 1 , # delete
76
+ current_row [j - 1 ] + 1 , # insert
77
+ up_row [j - 1 ] + cost , # substitute
74
78
)
75
79
76
80
if i > 1 and j > 1 and a [i - 1 ] == b [j - 2 ] and a [i - 2 ] == b [j - 1 ]:
77
81
# transposition
78
- current_cell = min (current_cell , d [i - 2 ][j - 2 ] + 1 )
82
+ double_diagonal_cell = rows [(i - 2 ) % 3 ][j - 2 ]
83
+ current_cell = min (current_cell , double_diagonal_cell + 1 )
79
84
80
- d [ i ] [j ] = current_cell
85
+ current_row [j ] = current_cell
81
86
82
- return d [a_len ][b_len ]
87
+ return rows [a_len % 3 ][b_len ]
0 commit comments