(Almost) 2-line Python solution

  • 1
    import itertools as its
    class Solution(object):
        def letterCombinations(self, digits):           
            g = map( lambda x: [' ','*','abc','def','ghi','jkl','mno','pqrs','tuv','wxyz'][int(x)], digits )
            return [''.join(i) for i in its.product(*g)] if digits else []

    It's 3-line if the import line is counted. :)

  • 0

    LeetCode imports itertools for us, so if you use it by that name, you don't need to import it here.

    If you write

    return map(''.join, itertools.product(*g)) if digits else []

    then the line doesn't even get longer but shorter.

  • 0

    Or even this:

    return g and map(''.join, itertools.product(*g))

  • 0

    Thank you! I replaced len(digits) by digits so that the solution could be clearer. BTW, where can I find the info about what libs are imported by default?

  • 0

    I don't know about a list, but in my experience, at least all the useful ones are imported.

Log in to reply

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