def path_yielder(t, value):
"""Yields all possible paths from the root of t to a node with the label value as a list."""
def dfs(root, path):
path += [root.label]
backup = path[:]
if len(path) and path[-1] == value:
print("debug ", path)
#yield path
#yield path[:]
if root != []:
for branch in root.branches:
**yield from dfs(branch, path)**
path = backup[:]
yield from dfs(t, [])
It's a problem in CS61A, When using generator recursion, the actual value returned by yield from is different from the value returned by base case using yield. The t argument is a data abstraction of Tree, I think it's doesn't matter.
>>> path_to_2 = path_yielder(t2, 2)
>>> sorted(list(path_to_2))
debug [0, 2]
debug [0, 2, 1, 2]
[[0, 2, 1, 2, 3], [0, 2, 1, 2, 3]]
# Error: expected
# [[0, 2], [0, 2, 1, 2]]
# but got
# [[0, 2, 1, 2, 3], [0, 2, 1, 2, 3]]
This is the actually execution result. On the line 7, I print the path array, result show that's [0,2] and[0, 2, 1, 2], but the yield from statement truly return [[0, 2, 1, 2, 3], [0, 2, 1, 2, 3]].
when I use return path[:], I pass the test. So, when the array is returned by yield, if I modify the array again, it will truly change the array I have returned, why? Hasn't this array been returned?
Is this a feature in python about arrays with the same address? The array I return has the same address as the real array. Changing one will change the other at the same time.