一道 Python dfs 题

2020-02-15 02:59:15 +08:00
 lbfeng
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 个都没发现问题。但正确的只有第一个。

3116 次点击
所在节点    Python
8 条回复
Xs0ul
2020-02-15 03:09:57 +08:00
lbfeng
2020-02-15 03:19:45 +08:00
so1n
2020-02-15 03:20:12 +08:00
可以访问 recursive_dfs.__defaults__ 有绑定动态变量时,每次访问后 recursive_dfs 都会把局部变量保存在__defaults__
leishi1313
2020-02-15 06:14:53 +08:00
你把 3 把 3 个 diff 一下也能发现问题在哪里了,然后顺着看看 python 怎么处理 mutable 默认参数不就明白问题的本质了吗。
说难听点,不会学习的话趁早放弃编程,或者你试试抄代码学习 https://zhuanlan.zhihu.com/p/31606615
lbfeng
2020-02-15 08:42:11 +08:00
@leishi1313 是是是。应该向您学习,生下来就是大牛。
kyokuheishin
2020-02-15 10:51:05 +08:00
可变对象造成的问题。
Keyes
2020-02-15 14:13:32 +08:00
@lbfeng 其实大牛说的没毛病。。。
poplar50
2020-02-15 14:23:01 +08:00
一楼说的很详细了 对于函数默认参数使用可变对象的 Python 只会创建一次该对象

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/644687

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX