【问题标题】:I cant find the out of resources error in my recursive function我在递归函数中找不到资源不足错误
【发布时间】:2021-04-27 06:58:36
【问题描述】:

我似乎无法在我的代码中找到导致无限递归的错误,我的基本情况似乎很好,我认为我的索引正确。

def phoneNumberMnemonics(phoneNumber):
    returnList = []
    helper(phoneNumber,0,[],returnList)
    return returnList

def helper(phoneNumber,idx,currentList,returnList):
    if idx == len(phoneNumber):
        returnList.append(currentList)
        return
    else:
        digit = phoneNumber[idx]
        letters = hashMap[digit]
        for i in letters:
            currentList.append(i)
            helper(phoneNumber,idx+1,currentList,returnList)    

            
hashMap = {'0':['0'],'1':['1'],'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']}

【问题讨论】:

  • 什么是导致无限递归的测试用例?编辑:我找到了一个
  • phoneNumber = "1905"
  • 那个对我来说运行良好。它非常快,每次我都会得到相同的响应。这真的很奇怪......
  • 试试这个,phoneNumber = "9056661234"
  • @je1013 你有没有看到maximum recursion depth 错误或者你的代码运行了很长时间并且你认为它处于无限循环中?

标签: python recursion hashtable


【解决方案1】:

当您将字母放在主列表中时,不应调用您的辅助递归函数。将其移出for 循环。

def phoneNumberMnemonics(phoneNumber):
    returnList = []
    helper(phoneNumber, 0, [], returnList)
    return returnList


def helper(phoneNumber, idx, currentList, returnList):
    if idx == len(phoneNumber):
        returnList.append(currentList)
        return
    else:
        digit = phoneNumber[idx]
        letters = hashMap[digit]
        for i in letters:
            currentList.append(i)
        # outside for loop
        helper(phoneNumber, idx + 1, currentList, returnList)


hashMap = {'0': ['0'], '1': ['1'], '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']}

print(phoneNumberMnemonics("9056661234"))

输出

[['w', 'x', 'y', 'z', '0', 'j', 'k', 'l', 'm', 'n', 'o', 'm', 'n', 'o', 'm', 'n', 'o', '1', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-17
    • 2011-12-27
    • 1970-01-01
    • 2012-12-02
    • 2016-02-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多