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
lbfeng
V2EX  ›  Python

一道 Python dfs 题

  •  
  •   lbfeng · 2020-02-15 02:59:15 +08:00 · 3102 次点击
    这是一个创建于 1526 天前的主题,其中的信息可能已经有所发展或是发生改变。
    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 条回复    2020-02-15 14:23:01 +08:00
    Xs0ul
        1
    Xs0ul  
       2020-02-15 03:09:57 +08:00   ❤️ 2
    lbfeng
        2
    lbfeng  
    OP
       2020-02-15 03:19:45 +08:00
    so1n
        3
    so1n  
       2020-02-15 03:20:12 +08:00
    可以访问 recursive_dfs.__defaults__ 有绑定动态变量时,每次访问后 recursive_dfs 都会把局部变量保存在__defaults__
    leishi1313
        4
    leishi1313  
       2020-02-15 06:14:53 +08:00 via Android
    你把 3 把 3 个 diff 一下也能发现问题在哪里了,然后顺着看看 python 怎么处理 mutable 默认参数不就明白问题的本质了吗。
    说难听点,不会学习的话趁早放弃编程,或者你试试抄代码学习 https://zhuanlan.zhihu.com/p/31606615
    lbfeng
        5
    lbfeng  
    OP
       2020-02-15 08:42:11 +08:00
    @leishi1313 是是是。应该向您学习,生下来就是大牛。
    kyokuheishin
        6
    kyokuheishin  
       2020-02-15 10:51:05 +08:00
    可变对象造成的问题。
    Keyes
        7
    Keyes  
       2020-02-15 14:13:32 +08:00
    @lbfeng 其实大牛说的没毛病。。。
    poplar50
        8
    poplar50  
       2020-02-15 14:23:01 +08:00 via Android
    一楼说的很详细了 对于函数默认参数使用可变对象的 Python 只会创建一次该对象
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2618 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 15:25 · PVG 23:25 · LAX 08:25 · JFK 11:25
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.