Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
97 views
in Technique[技术] by (71.8m points)

python - I cant find the out of resources error in my recursive function

I cant seem to find where the bug is in my code that is drawing an infinite recursion, my base case seems fine and I think I am indexing properly.

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']}
question from:https://stackoverflow.com/questions/65851433/i-cant-find-the-out-of-resources-error-in-my-recursive-function

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your helper recursive function should not be called when you are putting the letters in the main list. Move it out of for loop.

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"))

OUTPUT

[['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']]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...