Help! Please help me find out why my code outputed wrong


  • 0
    D

    Hi there,

    I got error on oj Input: addWord("a"),search(".") Output: [false] Expected: [true], but my code worked just fine on my own and outputed True. Didn't know what happened. Following is my code.

    import collections
    
    class TrieNode:
        # Initialize your data structure here.
        def __init__(self):
            self.child = collections.defaultdict(TrieNode)
            self.val = None
    
    class WordDictionary:
    
        def __init__(self):
            self.root = TrieNode()
    
        # @param {string} word
        # @return {void}
        # Adds a word into the data structure.
        def addWord(self, word):
            cur = self.root
            for c in word:
                cur = cur.child[c]
            cur.val = word
    
        # @param {string} word
        # @return {boolean}
        # Returns if the word is in the data structure. A word could
        # contain the dot character '.' to represent any one letter.
        def search(self, word):
            return self.dfs(self.root, word, 0)
    
        def dfs(self, cur, word, idx):
            if cur.val == word or idx == len(word) and cur.val != None:
                return True
            if idx >= len(word):
                return False
            c = word[idx]
            if c is '.':
                for _c in cur.child:
                    if self.dfs(cur.child[_c], word, idx + 1):
                        return True
            else:
                if c not in cur.child:
                    return False
                if self.dfs(cur.child[c], word, idx + 1):
                    return True
            return False
    
    # Your WordDictionary object will be instantiated and called as such:
    # wordDictionary = WordDictionary()
    # wordDictionary.addWord("word")
    # wordDictionary.search("pattern")
    
    if __name__ == '__main__':
        wordDictionary = WordDictionary()
        wordDictionary.addWord("a")
        # wordDictionary.addWord("world")
        print wordDictionary.search(".")
    

    Anyone could help me to find out what happened? Thanks!!!


  • 0
    D

    The problem lies in the line:

    if c is '.':
    

    change it to:

    if c == '.':
    

    and it passed


Log in to reply
 

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