【问题标题】:using python array in recursive function cause the reference loss在递归函数中使用python数组导致参考损失
【发布时间】:2019-05-06 15:59:37
【问题描述】:

我试图以一种称为电话号码字母组合的递归方式来解决这个问题。

在这个问题中,电话号码被映射到字母,对于给定的数字,询问对应于给定数字的字母组合。

dic = {
    '2': ['a', 'b', 'c'],
    '3': ['d', 'e', 'f'],
    '4': ['g', 'h', 'i'],
    '5': ['j', 'k', 'l'],
    '6': ['m', 'n', 'o'],
    '7': ['p', 'q', 'r', 's'],
    '8': ['t', 'u', 'v'],
    '9': ['w', 'x', 'y', 'z']
}

Input: "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].

我试图用递归函数解决它,但得到了意外的输出[""]

def telephoneHelper(digits, index, ans):
    if(index==len(digits)):
        return ans
    else:
        tmp=[]
        for letter in dic[digits[index]]:
            for an in ans:
                tmp.append(an+letter)
        ans=tmp
        telephoneHelper(digits, index+1, ans)

def telephoneNumberRec(digits):
    ans=[""]
    if(len(digits)!=0):
        telephoneHelper(digits, 0, ans)
    return ans

ans=telephoneNumberRec("23")
print(ans)

我知道有很多与此主题相关的答案,但我试图了解此代码中的问题。

【问题讨论】:

  • telephoneHelper函数中,需要添加return语句:return telephoneHelper(digits, index+1, ans)
  • 因为您的telephoneNumberRec 总是返回ans,它*总是只是ans = [""]。你没有做任何改变ans

标签: python python-3.x recursion combinations


【解决方案1】:

您需要添加两个返回语句(一个在 phoneNumberRec 中,一个在 phoneHelper 函数中)以便递归真正起作用。工作代码如下所示:

dic = {
    '2': ['a', 'b', 'c'],
    '3': ['d', 'e', 'f'],
    '4': ['g', 'h', 'i'],
    '5': ['j', 'k', 'l'],
    '6': ['m', 'n', 'o'],
    '7': ['p', 'q', 'r', 's'],
    '8': ['t', 'u', 'v'],
    '9': ['w', 'x', 'y', 'z']
}
def telephoneHelper(digits, index, ans):
    if(index==len(digits)):
        return ans
    else:
        tmp=[]
        for letter in dic[digits[index]]:
            for an in ans:
                tmp.append(an+letter)
        ans=tmp
        return telephoneHelper(digits, index+1, ans)

def telephoneNumberRec(digits):
    ans=[""]
    if(len(digits)!=0):
        return telephoneHelper(digits, 0, ans)
    return ans

ans=telephoneNumberRec("23")
print(ans)

【讨论】:

    【解决方案2】:
    combinations = []
    def telephoneHelper(digits,index, ans):
        n = len(digits[0])
        for i in range(n):
            item = ans + digits[0][i]
            if (index==len(digits)):
                combinations.append(item)
            else:
                telephoneHelper(digits[1:],index+1, item)
        return(combinations)
    
    
    def telephoneNumberRec(input_):
         a = []
         for letter in input_:
              a.append(dic[letter])
         return (telephoneHelper(a, 0, '')) # a = [['a', 'b', 'c'], ['d', 'e', 'f']]
    
    print (telephoneNumberRec('23'))
    

    输出:

    ['ad', 'ae', 'af', 'bd', 'be', 'bf', 'cd', 'ce', 'cf']
    

    【讨论】:

      猜你喜欢
      • 2021-03-13
      • 1970-01-01
      • 1970-01-01
      • 2017-10-14
      • 2015-04-07
      • 2020-07-08
      • 1970-01-01
      • 1970-01-01
      • 2012-01-17
      相关资源
      最近更新 更多