pythondictionarycode-structure

Destructure a for loop


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

Solution

  • 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