Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 5ff4571

Browse files
committed
feat: add look_up dict and use caching
1 parent 94fa57b commit 5ff4571

1 file changed

Lines changed: 16 additions & 15 deletions

File tree

core/range_mapper.py

Lines changed: 16 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -7,22 +7,23 @@
77
class RangeMapper(RangeBase):
88
src_range: List[str]
99
to_range: List[str]
10-
11-
10+
_lookup_dict: dict = field(default_factory=dict, init=False)
11+
_cache: dict = field(default_factory=dict, init=False)
12+
13+
14+
def __post_init__(self):
15+
self._lookup_dict = {char: i for i, char in enumerate(self.src_range)}
16+
self._cache = {}
17+
1218
def execute(self, src_string: str) -> str:
13-
result = ''
14-
for src_char in src_string:
15-
index = self._find_index(self.src_range, src_char)
16-
result += self._get_char_from_index(self.to_range, index) if index > -1 else src_char
17-
18-
return result
19+
return ''.join(self.map_char(char) for char in src_string)
20+
21+
def map_char(self, src_char):
22+
if src_char in self._cache:
23+
return self._cache[src_char]
24+
25+
index = self._lookup_dict.get(src_char, -1)
26+
return self._get_char_from_index(self.to_range, index) if index > -1 else src_char
1927

20-
def _find_index(self, range_to_find: List[str], char: str) -> int:
21-
try:
22-
reverse_index = range_to_find[::-1].index(char)
23-
return len(range_to_find) - 1 - reverse_index
24-
except ValueError:
25-
return -1
26-
2728
def _get_char_from_index(self, range_to_get: List[str], index: int) -> str:
2829
return range_to_get[index] if index < len(range_to_get) else range_to_get[-1]

0 commit comments

Comments
 (0)