r/programminghelp • • Aug 05 '20

Python Recursion and syntax help in Letter Combination problem

Hi, I'm trying to understand this working program that solves the Letter Combinations of a Phone Number problem. I get how the answer is achieved, but there are syntax and recursion elements throwing me off. I have a few questions, please excuse me if they're too many.

  1. How does prev = self.letterCombinations(digits[:-1]) work? I'm assuming it's recursively calling self.letterCombinations and, when I used a print statement, prev is doing the combining already. What I don't understand is, in a second iteration, how is it combining letters if it hasn't encountered return [s + c for s in prev for c in additional] yet? I'm not clear on how the recursion is functioning for longer inputs (example: "232").

  2. Why does prev = self.letterCombinations(digits[:-1]) stop at -1 and is not instead [:]?

  3. What's the deal with additional = mapping[digits[-1]]? I don't get why it's added separately.

Program(Python 3):

class Solution:
    # @param {string} digits
    # @return {string[]}
    def letterCombinations(self, digits):
        mapping = {'2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', 
                   '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz'}
        if len(digits) == 0:
            return []
        if len(digits) == 1:
            return list(mapping[digits[0]])
        prev = self.letterCombinations(digits[:-1])
        additional = mapping[digits[-1]]
        return [s + c for s in prev for c in additional]
3 Upvotes

0 comments sorted by