Skip to content

Commit baa2cf6

Browse files
Update LC17 - simplified solution and itertools
1 parent c1ba141 commit baa2cf6

File tree

1 file changed

+28
-16
lines changed

1 file changed

+28
-16
lines changed

LC17-Letter-Combinations-of-a-Phone-Number.py

Lines changed: 28 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,26 @@
66
Note that 1 does not map to any letters.
77
"""
88
from typing import List
9+
import itertools
910

1011

1112
class Solution:
13+
mapping = {
14+
'2': ['a', 'b', 'c'],
15+
'3': ['d', 'e', 'f'],
16+
'4': ['g', 'h', 'i'],
17+
'5': ['j', 'k', 'l'],
18+
'6': ['m', 'n', 'o'],
19+
'7': ['p', 'q', 'r', 's'],
20+
'8': ['t', 'u', 'v'],
21+
'9': ['w', 'x', 'y', 'z']
22+
}
23+
def letterCombinationsUsingItertools(self, digits: str) -> List[str]:
24+
if not digits:
25+
return []
26+
27+
return [''.join(combo) for combo in itertools.product(*[self.mapping[digit] for digit in digits])]
28+
1229
def letterCombinations(self, digits: str) -> List[str]:
1330
"""
1431
all word representations of digits using the direct iterative approach
@@ -17,23 +34,9 @@ def letterCombinations(self, digits: str) -> List[str]:
1734
"""
1835
if not digits:
1936
return []
20-
21-
mapping = {
22-
'2': ['a', 'b', 'c'],
23-
'3': ['d', 'e', 'f'],
24-
'4': ['g', 'h', 'i'],
25-
'5': ['j', 'k', 'l'],
26-
'6': ['m', 'n', 'o'],
27-
'7': ['p', 'q', 'r', 's'],
28-
'8': ['t', 'u', 'v'],
29-
'9': ['w', 'x', 'y', 'z']
30-
}
3137
combos = set(['', ])
3238
for digit in digits:
33-
new_combos = set()
34-
for encoded in mapping[digit]:
35-
new_combos = new_combos | set([c + encoded for c in combos])
36-
combos = set(new_combos)
39+
combos = set(c + encoded for c in combos for encoded in self.mapping[digit])
3740
return list(combos)
3841

3942

@@ -50,4 +53,13 @@ def letterCombinations(self, digits: str) -> List[str]:
5053
pred_ans.sort()
5154
corr_ans.sort()
5255
assert pred_ans == corr_ans, f'For input {seq}, got answer {pred_ans}, expected {corr_ans}'
53-
print('All tests passed')
56+
print('All tests passed')
57+
58+
print('Starting tests for itertools solution')
59+
solve = Solution().letterCombinationsUsingItertools
60+
for seq, corr_ans in correct_ans:
61+
pred_ans = solve(seq)
62+
pred_ans.sort()
63+
corr_ans.sort()
64+
assert pred_ans == corr_ans, f'For input {seq}, got answer {pred_ans}, expected {corr_ans}'
65+
print('All tests passed')

0 commit comments

Comments
 (0)