r/programminghelp • u/[deleted] • 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.
How does
prev = self.letterCombinations(digits[:-1])work? I'm assuming it's recursively callingself.letterCombinationsand, when I used a print statement,previs doing the combining already. What I don't understand is, in a second iteration, how is it combining letters if it hasn't encounteredreturn [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").Why does
prev = self.letterCombinations(digits[:-1])stop at-1and is not instead [:]?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]
