1
- from typing import Collection , List
1
+ from typing import Collection , Optional , List
2
2
3
3
__all__ = ["suggestion_list" ]
4
4
@@ -14,9 +14,9 @@ def suggestion_list(input_: str, options: Collection[str]) -> List[str]:
14
14
15
15
input_threshold = len (input_ ) // 2
16
16
for option in options :
17
- distance = lexical_distance .measure (option )
18
17
threshold = max (input_threshold , len (option ) // 2 , 1 )
19
- if distance <= threshold :
18
+ distance = lexical_distance .measure (option , threshold )
19
+ if distance is not None :
20
20
options_by_distance [option ] = distance
21
21
22
22
# noinspection PyShadowingNames
@@ -46,7 +46,7 @@ def __init__(self, input_: str):
46
46
row_size = len (input_ ) + 1
47
47
self ._rows = [[0 ] * row_size , [0 ] * row_size , [0 ] * row_size ]
48
48
49
- def measure (self , option : str ) :
49
+ def measure (self , option : str , threshold : int ) -> Optional [ int ] :
50
50
if self ._input == option :
51
51
return 0
52
52
@@ -59,6 +59,9 @@ def measure(self, option: str):
59
59
a , b = option_lower_case , self ._input_lower_case
60
60
a_len , b_len = len (a ), len (b )
61
61
62
+ if abs (a_len - b_len ) > threshold :
63
+ return None
64
+
62
65
rows = self ._rows
63
66
for j in range (0 , b_len + 1 ):
64
67
rows [0 ][j ] = j
@@ -67,7 +70,7 @@ def measure(self, option: str):
67
70
up_row = rows [(i - 1 ) % 3 ]
68
71
current_row = rows [i % 3 ]
69
72
70
- current_row [0 ] = i
73
+ smallest_cell = current_row [0 ] = i
71
74
for j in range (1 , b_len + 1 ):
72
75
cost = 0 if a [i - 1 ] == b [j - 1 ] else 1
73
76
@@ -82,6 +85,15 @@ def measure(self, option: str):
82
85
double_diagonal_cell = rows [(i - 2 ) % 3 ][j - 2 ]
83
86
current_cell = min (current_cell , double_diagonal_cell + 1 )
84
87
88
+ if current_cell < smallest_cell :
89
+ smallest_cell = current_cell
90
+
85
91
current_row [j ] = current_cell
86
92
87
- return rows [a_len % 3 ][b_len ]
93
+ # Early exit, since distance can't go smaller than smallest element
94
+ # of the previous row.
95
+ if smallest_cell > threshold :
96
+ return None
97
+
98
+ distance = rows [a_len % 3 ][b_len ]
99
+ return distance if distance <= threshold else None
0 commit comments