V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
roundRobin
V2EX  ›  Python

这个 trie 实现有什么问题吗

  •  
  •   roundRobin · May 1, 2022 · 2055 views
    This topic created in 1463 days ago, the information mentioned may be changed or developed.

    leetcode208 很简单的 trie 实现,下面这个 case 在 debug 的时候都是结果是[null, false],但是 submit 之后结果就变成了[null,true],是哪部分代码触发了服务器的异常编译吗?

    class Trie:
        def __init__(self):
            self.root = Node()
    
        def insert(self, word: str) -> None:
            ptr = self.root
            for ch in word:
                if ch not in ptr.child:
                    ptr.child[ch] = Node("")
                if ch == word[-1]:
                    ptr.child[ch].val = ch
                    return
                ptr = ptr.child[ch]
    
        def search(self, word: str) -> bool:
            ptr = self.root
            for ch in word:
                if ch not in ptr.child:
                    return False
                ptr = ptr.child[ch]
            return ptr.val == word[-1]
    
        def startsWith(self, prefix: str) -> bool:
            ptr = self.root
            for ch in prefix:
                if ch not in ptr.child:
                    return False
                ptr = ptr.child[ch]
            return True
        
    class Node:
        def __init__(self, val="", child={}):
            self.child = child
            self.val = val
    
    
    # Your Trie object will be instantiated and called as such:
    # obj = Trie()
    # obj.insert(word)
    # param_2 = obj.search(word)
    # param_3 = obj.startsWith(prefix)
    

    Input:

    ["Trie","startsWith"]
    [[],["a"]]
    

    Output:

    [null,true]
    

    Expect:

    [null,false]
    
    lixiang2017
        1
    lixiang2017  
       May 1, 2022 via Android
    insert 里逻辑不对。第二个 if 是干啥的,错的很离谱
    0xo
        2
    0xo  
       May 1, 2022
    bug 不止一个。你说的问题是因为:

    ```python
    class Node:
    def __init__(self, c={}):
    self.c = c

    n1 = Node()
    n2 = Node()
    n1.c is n2.c # True
    ```
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2220 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 33ms · UTC 16:08 · PVG 00:08 · LAX 09:08 · JFK 12:08
    ♥ Do have faith in what you're doing.