python - Enumerating recursively with pass by reference in Python
问题描述
So this is an answer to an interview problem, enumerate all possible mnemonics (possible character sequences given a phone number). Similar to a generate possible permutations problem and things of that sort so question applies there too.
MAPPING = ('0', '1', 'ABC', 'DEF', 'GHI', 'JKL', 'MNO', 'PQRS', 'TUV', 'WXYZ')
def phone_mnemonic(phone_number):
def phone_mnemonic_helper(digit):
if digit == len(phone_number):
# All digits are processed, so add partial_mnemonic to mnemonics.
# (We add a copy since subsequent calls modify partial_mnemonic.)
mnemonics.append(''.join(partial_mnemonic))
else:
# Try all possible characters for this digit.
for c in MAPPING[int(phone_number[digit])]:
partial_mnemonic[digit] = c
phone_mnemonic_helper(digit + 1)
mnemonics, partial_mnemonic = [], [0] * len(phone_number)
phone_mnemonic_helper(0)
return mnemonics
I'm more confused at how this works with regards to pass by value/reference. Since 'partial_mnemonic' is declared at the bottom before the helper function is called and is modified within, in the recursion stack, aren't they operating on the same 'partial_mnemonic' object?
Because we're not passing in a list called 'partial_mnemonic' and simply using the one in the outer scope, why is it that we don't encounter problems modifying the same list?
Think I may be a bit confused on how Python works with regards to pass by value / reference but I'm not too sure why this code works using the same 'partial_mnemonic' list rather than instantiating a new one and passing that in when calling recursively.
解决方案
partial_mnemonic
在进入递归函数之前,您正在创建一个新变量来递归地保存部分助记符。输入递归辅助函数后,代码通过更改 at each 的值在每个数字位置构建助记符partial_mnemonic
,digit
并递归调用以保持构建可能性。一旦递归跟踪partial_mnemonic
达到电话号码的长度,基本情况会将其附加到您的排列列表中。代码将使用for
循环遍历每种可能性,循环再次调用相同的方法,只是partial_mnemonic
列表现在包含部分构建的助记符。没有理由将新列表传递给辅助函数,因为这会消除递归功能。
推荐阅读
- swift - 如何在 NavigationLink 中有多个目的地
- angular - Angular 9 时区 DatePipe
- angular - 使用 angular ivy 创建真正的插件架构
- javascript - 烧瓶上传多个文件
- django - 如果用户未通过 django 身份验证,则显示 404 页面
- python - 在 datalab 中导入 gcsfs 出现错误
- html - 根据高度动态调整图像
- c# - 登录后显示用户信息
- azure-logic-apps - blob 列表中的第一项到文件逻辑应用程序
- python - Keras, AIX360(LIME) - ValueError: input array must be have a shape == (.., ..,[ ..,] 3)), got (28, 28, 1)