Simple Python using Itertools


  • 0
    R

    Because all of the possible combinations of the letters is simply a Cartesian product of all of the possible lists of letters, we can use the product method from the itertools library. By first adding each list of letters represented by every digit to a separate list, we can then unpack all of these lists into the product method. Each result from product is a tuple, so to format the output correctly, join them into a string. Add each result to a result list, and return that list.

    from itertools import product
    
    class Solution(object):
        def letterCombinations(self, digits):
            """
            :type digits: str
            :rtype: List[str]
            """
            numToLetters = {"1":[""], "2":["a", "b", "c"], "3":["d","e","f"], "4":["g","h","i"], "5":["j","k","l"], \
                            "6":["m","n","o"], "7":["p","q","r","s"], "8":["t","u","v"], "9":["w","x","y","z"], "0":[" "]}
            
            letterLists = [numToLetters[n] for n in digits]
            letterCombos = []
            
            for cart in product(*letterLists):
                letterCombos.append(''.join(cart))
            
            return letterCombos if digits else []
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.