6
6
Note that 1 does not map to any letters.
7
7
"""
8
8
from typing import List
9
+ import itertools
9
10
10
11
11
12
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
+
12
29
def letterCombinations (self , digits : str ) -> List [str ]:
13
30
"""
14
31
all word representations of digits using the direct iterative approach
@@ -17,23 +34,9 @@ def letterCombinations(self, digits: str) -> List[str]:
17
34
"""
18
35
if not digits :
19
36
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
- }
31
37
combos = set (['' , ])
32
38
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 ])
37
40
return list (combos )
38
41
39
42
@@ -50,4 +53,13 @@ def letterCombinations(self, digits: str) -> List[str]:
50
53
pred_ans .sort ()
51
54
corr_ans .sort ()
52
55
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