推荐学习书目
› 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
lbfeng
V2EX  ›  Python

一道 Python dfs 题

  •  
  •   lbfeng · Feb 15, 2020 · 4554 views
    This topic created in 2463 days ago, the information mentioned may be changed or developed.
    def recursive_dfs(graph, start, path=None):
        if path is None:
            path = []
        path.append(start)
        for node in graph[start]:
            if not node in path:
                recursive_dfs(graph, node, path)
        return path
    
    def recursive_dfs(graph, start, path=[]):
        path.append(start)
        for node in graph[start]:
            if not node in path:
                recursive_dfs(graph, node, path)
        return path
    
    def recursive_dfs(graph, start, path=list()):
        path.append(start)
        for node in graph[start]:
            if not node in path:
            recursive_dfs(graph, node, path)
        return path
    

    recursive_dfs([[1,2], [0], [3], [1]], 0)

    以上 3 个都没发现问题。但正确的只有第一个。

    8 replies  •  2020-02-15 14:23:01 +08:00
    Xs0ul
    Xs0ul
    Feb 15, 2020❤️2
    1
    so1n
    so1n
    Feb 15, 2020
    3
    可以访问 recursive_dfs.__defaults__ 有绑定动态变量时,每次访问后 recursive_dfs 都会把局部变量保存在__defaults__
    leishi1313
    leishi1313
    Feb 15, 2020 via Android
    4
    你把 3 把 3 个 diff 一下也能发现问题在哪里了,然后顺着看看 python 怎么处理 mutable 默认参数不就明白问题的本质了吗。
    说难听点,不会学习的话趁早放弃编程,或者你试试抄代码学习 https://zhuanlan.zhihu.com/p/31606615
    lbfeng
    lbfeng
    OP
    Feb 15, 2020
    5
    @leishi1313 是是是。应该向您学习,生下来就是大牛。
    kyokuheishin
    kyokuheishin
    Feb 15, 2020
    6
    可变对象造成的问题。
    Keyes
    Keyes
    Feb 15, 2020
    7
    @lbfeng 其实大牛说的没毛病。。。
    poplar50
    poplar50
    Feb 15, 2020 via Android
    8
    一楼说的很详细了 对于函数默认参数使用可变对象的 Python 只会创建一次该对象
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2104 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 41ms · UTC 13:00 · PVG 21:00 · LAX 05:00 · JFK 08:00
    ♥ Do have faith in what you're doing.