【发布时间】:2016-08-22 14:36:38
【问题描述】:
我正在打印一个我认为是列表的值,但我得到的输出是:
[...]
这代表什么?我该如何测试它?我试过了:
myVar.__repr__() != '[...]'
和
myVar.__repr_() != Ellipsis
但没有骰子...
这是导致问题的代码的删减:
def buildPaths(graph, start, end, path=[], totalPaths=[]):
"""
returns list of all possible paths from start node to the end node
"""
path = path + [start]
if start == end:
return path
for nextNode in graph.childrenOf(start):
if nextNode not in path:
newPath = buildPaths(graph, nextNode, end, path, totalPaths)
if newPath != []: # test
totalPaths.append(newPath)
return totalPaths
totalPaths 包含很多 [...] 所谓的递归列表,但我不明白为什么。我已经更改了 #test 的测试以防止这种情况发生。
我也试过了:
def buildPaths(graph, thisNode, end, path=[], totalPaths=None):
"""
returns list of all possible paths from start node to the end node
"""
path = path + [thisNode]
if thisNode == end:
return path
for nextNode in graph.childrenOf(thisNode):
if nextNode not in path:
newPath = buildPaths(graph, nextNode, end, path, totalPaths)
if newPath != None:
if totalPaths == None:
totalPaths = [newPath]
else:
totalPaths.append(newPath)
return totalPaths
为了为空路径显式返回None。
【问题讨论】:
-
虽然
Ellipsis是python 中的一个东西,但这可能只是告诉你有比它所能显示的更多的东西的任何显示。>>> [...]->[Ellipsis](从 python3 开始) -
您能否提供一个生成此代码的示例?
-
@BrenBarn - 添加示例代码
-
当你做
totalPaths.append(newPath)时,那是在修改传入的列表,所以父递归的totalPaths也被修改了——然后作为newPath返回并附加到自身。 -
谢谢@Izkata - 这就是我要找的解释!
标签: python recursion ellipsis recursive-datastructures