首页 > 解决方案 > 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.

标签: pythonlistrecursionpass-by-referencepass-by-value

解决方案


partial_mnemonic在进入递归函数之前,您正在创建一个新变量来递归地保存部分助记符。输入递归辅助函数后,代码通过更改 at each 的值在每个数字位置构建助记符partial_mnemonicdigit并递归调用以保持构建可能性。一旦递归跟踪partial_mnemonic达到电话号码的长度,基本情况会将其附加到您的排列列表中。代码将使用for循环遍历每种可能性,循环再次调用相同的方法,只是partial_mnemonic列表现在包含部分构建的助记符。没有理由将新列表传递给辅助函数,因为这会消除递归功能。


推荐阅读