V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
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 · 2022-05-01 17:58:35 +08:00 · 1464 次点击
    这是一个创建于 722 天前的主题,其中的信息可能已经有所发展或是发生改变。

    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]
    
    2 条回复
    lixiang2017
        1
    lixiang2017  
       2022-05-01 19:24:46 +08:00 via Android
    insert 里逻辑不对。第二个 if 是干啥的,错的很离谱
    ccvzz
        2
    ccvzz  
       2022-05-01 19:53:01 +08:00
    bug 不止一个。你说的问题是因为:

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

    n1 = Node()
    n2 = Node()
    n1.c is n2.c # True
    ```
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5353 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 09:07 · PVG 17:07 · LAX 02:07 · JFK 05:07
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.