【发布时间】:2020-08-03 12:29:26
【问题描述】:
这是一个理解 Python 列表变异的问题。我解决了这个深度优先搜索问题,我得到了正确的结果。然后我得到了一些反馈,我认为这不应该有效,但它有效。
基本上,如果我使用 path[0] 而不是 current_path (通过切换注释掉和非注释行对中的行),结果是相同的。我试图理解为什么会这样。我了解列表路径中的列表,即路径 [0],没有发生突变。但是,当我将不同的列表分配给路径的第 0 个索引时,列表路径应该会发生变化。然而,它工作得很好。
以下是代码,我留下了文档字符串以进行进一步说明。最后,我粘贴了我玩过的代码以更好地理解列表突变,但这对我没有帮助。有人可以解释一下吗?
# Problem 3b: Implement get_best_path
def get_best_path(digraph, start, end, path, max_dist_outdoors, best_dist,
best_path):
"""
Finds the shortest path between buildings subject to constraints.
digraph: Digraph instance
The graph on which to carry out the search
start: string, Building number at which to start
end: string, Building number at which to end
path: list composed of [[list of strings], int, int]
Represents the current path of nodes being traversed. Contains
a list of node names, total distance traveled, and total
distance outdoors.
max_dist_outdoors: int
Maximum distance spent outdoors on a path
best_dist: int
The smallest distance between the original start and end node
for the initial problem that you are trying to solve
best_path: list of strings
The shortest path found so far between the original start
and end node.
Returns:
A tuple with the shortest-path from start to end, represented by
a list of building numbers (in strings), [n_1, n_2, ..., n_k],
where there exists an edge from n_i to n_(i+1) in digraph,
for all 1 <= i < k and the distance of that path.
If there exists no path that satisfies max_total_dist and
max_dist_outdoors constraints, then return None.
"""
if not digraph.has_node(Node(start)) or not digraph.has_node(Node(end)):
raise ValueError('Start or end node, or both not in graph')
current_path = path[0] + [start]
path[0]="This line doesn't change a thing, if I use 'current_path', but why?!"
# path[0] = path[0] + [start]
if start == end:
return [current_path, path[1], path[2]]
# return path
edges = digraph.get_edges_for_node(Node(start))
for edge in edges:
next_node = str(edge.get_destination())
if next_node not in current_path: #avoiding cycles
# if next_node not in path[0]: #avoiding cycles
new_tot = path[1] + edge.get_total_distance()
new_out = path[2] + edge.get_outdoor_distance()
if (best_dist==None or best_dist>=new_tot) and new_out<=max_dist_outdoors:
new_path=get_best_path(digraph, next_node, end, [current_path,new_tot,new_out], \
# new_path=get_best_path(digraph, next_node, end, [path[0],new_tot,new_out], \
max_dist_outdoors, best_dist, best_path)
if new_path != None:
best_path = new_path[0]
best_dist = new_path[1]
if best_path == None:
return None
return [best_path, best_dist]
我在这里尝试了这个想法,但正如我所料,输入列表发生了变异。那么,为什么大写的“路径”列表没有发生变异?
def foo_mutating(bar):
bar[0] = bar[0] + [1]
print('bar inside foo:', bar)
if len(bar[0]) == 5:
return bar
return foo_mutating(bar)
def foo_nonmut(bar):
temp_bar0 = bar[0]+[1]
print('bar inside foo:', bar)
if len(temp_bar0) == 5:
return [temp_bar0, bar[1], bar[2]]
return foo_nonmut([temp_bar0, bar[1], bar[2]])
def test():
print('-----TESTING NON-MUTATING----')
bar_init = [[], 22, 33]
print('bar_init:', bar_init)
new_bar = foo_nonmut(bar_init)
print('new_bar:', new_bar)
print('bar_init:', bar_init)
print('\n')
print('-----TESTING MUTATING----')
bar_init = [[], 22, 33]
print('bar_init:', bar_init)
new_bar = foo_mutating(bar_init)
print('new_bar:', new_bar)
print('bar_init:', bar_init)
test()
打印:
-----TESTING NON-MUTATING----
bar_init: [[], 22, 33]
bar inside foo: [[], 22, 33]
bar inside foo: [[1], 22, 33]
bar inside foo: [[1, 1], 22, 33]
bar inside foo: [[1, 1, 1], 22, 33]
bar inside foo: [[1, 1, 1, 1], 22, 33]
new_bar: [[1, 1, 1, 1, 1], 22, 33]
bar_init: [[], 22, 33]
-----TESTING MUTATING----
bar_init: [[], 22, 33]
bar inside foo: [[1], 22, 33]
bar inside foo: [[1, 1], 22, 33]
bar inside foo: [[1, 1, 1], 22, 33]
bar inside foo: [[1, 1, 1, 1], 22, 33]
bar inside foo: [[1, 1, 1, 1, 1], 22, 33]
new_bar: [[1, 1, 1, 1, 1], 22, 33]
bar_init: [[1, 1, 1, 1, 1], 22, 33]
【问题讨论】:
-
你有没有机会提供一个更“最小”的minimal reproducible example?我确信有一个更短的代码可以重现您注意到的行为。
-
@DeepSpace ,我只花了 30 分钟试图减少问题,但我最终得到了其他东西,我认为我无法重现这种情况。我现在才学习编程 2-3 个月,所以语法、运算符和对象的更深层次的含义仍然有点模糊,所以我很难重现我不完全理解的东西。但对于未来的任何问题,我一定会牢记这一点。感谢您对问题的反馈!
标签: python list recursion mutation