Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # date: 2026.02.27
- # [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)
- d = {
- "1": "abc",
- "2": "def",
- "3": "ghi",
- "4": "jkl",
- "5": "mnop",
- "6": "qrst",
- "7": "uv",
- "8": "wxyz",
- "9": ".;",
- "0": "?!",
- }
- def keypad_combination(d, s, result, indx):
- # print(f"[DEBUG] {indx = }, {result =}")
- if indx == len(s):
- return result
- # after checking `len(s)` because `s[indx]` could raise error
- # key_digit = s[indx]
- # key_chars = d[key_digit]
- # print(f"[DEBUG] {key_digit = }, {key_chars = }")
- if len(result) == 0:
- result.extend(d[s[indx]]) # without `result =`
- # result.extend(key_chars) # without `result =`
- else:
- new_result = [] # create new list which will have more items
- for item in result:
- # for char in d[s[indx]]:
- # new_result.append(item + char)
- new_result.extend([item + char for char in d[s[indx]]])
- # new_result.extend([item + char for char in key_chars])
- result = new_result # replace old `result` with new list
- # print(f"[DEBUG] {result = }")
- # print("[DEBUG] -----")
- return keypad_combination(d, s, result, indx + 1)
- # --- test ---
- result = keypad_combination(d, "573", [], 0)
- print(result)
- # --- result ---
- # ['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