furas

Python - recursion - phone keypad text combinations (Stackoverflow)

Feb 27th, 2026 (edited)
28
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.67 KB | None | 0 0
  1. # date: 2026.02.27
  2.  
  3. # [recursion - Recursive keypad combination not generating correct result in Python - Stack Overflow](https://stackoverflow.com/questions/79897905/recursive-keypad-combination-not-generating-correct-result-in-python)
  4.  
  5.  
  6. d = {
  7.     "1": "abc",
  8.     "2": "def",
  9.     "3": "ghi",
  10.     "4": "jkl",
  11.     "5": "mnop",
  12.     "6": "qrst",
  13.     "7": "uv",
  14.     "8": "wxyz",
  15.     "9": ".;",
  16.     "0": "?!",
  17. }
  18.  
  19.  
  20. def keypad_combination(d, s, result, indx):
  21.     # print(f"[DEBUG] {indx = }, {result =}")
  22.  
  23.     if indx == len(s):
  24.         return result
  25.  
  26.     # after checking `len(s)` because `s[indx]` could raise error
  27.     # key_digit = s[indx]
  28.     # key_chars = d[key_digit]
  29.     # print(f"[DEBUG] {key_digit = }, {key_chars = }")
  30.  
  31.     if len(result) == 0:
  32.         result.extend(d[s[indx]])  # without `result =`
  33.         # result.extend(key_chars)  # without `result =`
  34.     else:
  35.         new_result = []  # create new list which will have more items
  36.  
  37.         for item in result:
  38.             # for char in d[s[indx]]:
  39.             #    new_result.append(item + char)
  40.             new_result.extend([item + char for char in d[s[indx]]])
  41.             # new_result.extend([item + char for char in key_chars])
  42.  
  43.         result = new_result  # replace old `result` with new list
  44.  
  45.     # print(f"[DEBUG] {result = }")
  46.     # print("[DEBUG] -----")
  47.  
  48.     return keypad_combination(d, s, result, indx + 1)
  49.  
  50.  
  51. # --- test ---
  52.  
  53. result = keypad_combination(d, "573", [], 0)
  54. print(result)
  55.  
  56.  
  57. # --- result ---
  58.  
  59. # ['mug', 'muh', 'mui', 'mvg', 'mvh', 'mvi', 'nug', 'nuh', 'nui', 'nvg', 'nvh', 'nvi', 'oug', 'ouh', 'oui', 'ovg', 'ovh', 'ovi', 'pug', 'puh', 'pui', 'pvg', 'pvh', 'pvi']
Advertisement
Add Comment
Please, Sign In to add comment