[Python Resolution] Would Someone tell me Why KeyError


  • 0
    Y
    I have test my code underline several times, and I am quite sure I get the right result. But when I submit, i get a KeyError (┬_┬)
    

    '''
    class Solution(object):
    def findLadders(self,beginWord, endWord, wordList):
    res = []
    path = [endWord]
    wordMap = {} # type wordMap:Dic{string:List[]}
    currentList = [beginWord]
    nextList = []
    while currentList != []:
    # print ('wordList:',wordList)
    # print ('currentList:',currentList)
    for word in currentList :
    for i in range (0,len(word)):
    for j in range (26):
    wordTmp=word[:i]+chr(ord('a')+j)+word[i+1:]

                        if wordTmp in wordList:
                            # record words that can be approach by 'word'
                            nextList.append(wordTmp) if wordTmp not in nextList else None
                            # make relation wordTmp --> word in wordMap
                            if wordTmp not in wordMap:
                                wordMap[wordTmp]=[word]
                            else :
                                wordMap[wordTmp].append(word)
                            
            # update currentList with nextList
            # erase words in nextList from wordList            
            del currentList [:]
            currentList=[word for word in nextList]
            for word in nextList :
                wordList.remove(word)
            del nextList [:]
        self.makePath(endWord,beginWord,wordMap,path,res)
        return res
    
    def makePath(self,beginWord,endWord,wordMap,path,res):
        if beginWord == endWord :
            res.append([x for x in path])
        else :
            for word in wordMap[beginWord]:
                path.insert(0,word)
                self.makePath(word,endWord,wordMap,path,res)
                path.remove(word)
    

    '''


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.