@@ -38,12 +38,13 @@ class LexicalDistance:
3838
3939 _input : str
4040 _input_lower_case : str
41- _cells : List [List [int ]]
41+ _rows : List [List [int ]]
4242
4343 def __init__ (self , input_ : str ):
4444 self ._input = input_
4545 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 ]
4748
4849 def measure (self , option : str ):
4950 if self ._input == option :
@@ -55,28 +56,32 @@ def measure(self, option: str):
5556 if self ._input_lower_case == option_lower_case :
5657 return 1
5758
58- d = self ._cells
5959 a , b = option_lower_case , self ._input_lower_case
6060 a_len , b_len = len (a ), len (b )
6161
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
6565
6666 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
6771 for j in range (1 , b_len + 1 ):
6872 cost = 0 if a [i - 1 ] == b [j - 1 ] else 1
6973
7074 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
7478 )
7579
7680 if i > 1 and j > 1 and a [i - 1 ] == b [j - 2 ] and a [i - 2 ] == b [j - 1 ]:
7781 # 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 )
7984
80- d [ i ] [j ] = current_cell
85+ current_row [j ] = current_cell
8186
82- return d [a_len ][b_len ]
87+ return rows [a_len % 3 ][b_len ]
0 commit comments