-2

The problem set : Letter combinations of a phone

The solution I had in mind:

def letterCombinations(self, digits: str) -> List[str]:
    if not digits: return []
    digit_map = {'2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', 
                 '7': 'pqrs', '8': 'tuv', '9': 'wxyz'}
    result = [""]
    arr = []
    for i in digits:
        for j in digit_map:
            if i==j:
                s = map(str,digit_map[i])
                for x in s:
                    arr.append(x)

After this I was going to use the map() function on arr and then match one alphabet to another. However, this though process was not good enough. I turned to solutions thereafter. The solution I liked best was this one However, in the solution that's provided :

def letterCombinations(self, digits: str) -> List[str]:
    if not digits: return []
    dt = {'2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz'}
    rst = ['']
    for i in digits: rst = [j+k for j in rst for k in dt[i]]
    return rst

I do not understand the for loop on line 5. Could someone destructure it and write it in multiple lines so that the output doesn't change.

I tried to do it myself but the output changed and gave wrong results.

for i in digits:
    tmp = []
    for j in rst:
        for k in dt[i]:
            temp = [j+k] 
    rst += temp
Jerry
  • 366
  • 4
  • 22

2 Answers2

1

This syntax is called list comprehensions. You can read more about it here https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions

That piece can be replaced with these nested for loops

new_rst = []
for j in rst:
  for k in dt[i]:
    new_rst.append(j+k)

rst = new_rst

Sharang Chopra
  • 226
  • 1
  • 10
  • Hi, thank you for your answer. It works well and good and it is exactly what I was looking for. – Jerry Sep 04 '21 at 05:18
1

Your own code had some minor issues, apart from not working:

  • the first parameter is self, suggesting this would be the method of some object, but you're presenting it as a function (and it doesn't actually reference self either)?
  • the name letterCombinations isn't the best, letter_combinations would be better in standard Python, but perhaps that's a requirement of your assignment?
  • your function didn't actually return anything, so even if it worked, you wouldn't be able to tell (note how the found solution does have a return statement)

The reason the code you found works:

for i in digits: rst = [j+k for j in rst for k in dt[i]]

This loops over each digit character i in digits. For each one, it defines the result rst to be a list of every string j already in rst, combined with every character k of the string dt[i], which are the letters corresponding to the digit.

For example, if the function would be called as letterCombinations('12'), this would happen:

  • first character is 1, so i equals '1' during the first iteration.
  • rst contains a single empty string, so each character of dt['1'] is added to that, and the resulting list ['a', 'b', 'c'] is assigned to rst
  • the second character is 2, so i equals '2' during the second iteration.
  • each character of dt['2'] will now be added to every string already in rst, so rst will become ['ad', 'ae', 'af', 'bd', ... , 'cf']

Which is exactly what's needed. The resulting rst is returned after the loop completes its final iteration with return rst.

Note that the part [j+k for j in rst for k in dt[i]] is a so-called list comprehension, which is different from the normal for-loop around it. It creates a list of j+k for each value of j in rst, for each value of k in dt[i].

Grismar
  • 27,561
  • 4
  • 31
  • 54
  • Hi, thankyou for your answer. The detailed explanation is very much appreciated. I can't accept both the answers and the "de-list comprehension (per say)" was what I was looking for. I have upvoted it as deserved. – Jerry Sep 04 '21 at 05:17
  • 1
    That's alright - keep in mind that comprehension are often the better choice for both readability and speed, although they may take some getting used to when coming to Python from other languages. – Grismar Sep 05 '21 at 22:51