I know Python is working by " pass by reference ". However when I was trapped in a bug with hours I felt like I still didn't understand how things happened. Below is my code, which is using deep first search to implement listing all subset of a set.
def subset_of_unique_dfs(mylist):
"""
:param list: a list of char first assuming the element in the list is unique
:return: list of subset of the input list
we could treated as tree, with ith level represent the ith element is selected or not (binary tree)
when we reach the leafnode of the tree, append the result
so we need to track the level of the tree where we currently at
"""
result_list = []
def helper(thelist, level, curList,result):
print("at level ",level, "curResult is ",curList)
if level == len(thelist):
print type(curList)
result.append(curList)
return
curList.append(thelist[level])
helper(thelist,level + 1,curList,result)
curList.pop()
helper(thelist,level + 1,curList,result)
helper(mylist, 0, [],result_list)
return result_list
print subset_of_unique_dfs(['a','b','c'])
"""
[[], [], [], [], [], [], [], []]
"""
I have been struggling for a while while an empty list was returned. Then I tried to change "result.append(curList)" to "result.append(list(curList))", correct result is returned. May I ask what happened by applying list(curList)? I used to take result.append(curList) as appending the object that binding with curList to result. For example, the below test case actually showed no difference between append(listA) and append(list(listA))
tmp1 = [[1,2],[2,3]]
tmp1_1 = [[1,2],[2,3]]
tmp2 = [3,4]
tmp1.append(tmp2)
tmp1_1.append(list(tmp2))
print tmp1
print tmp1_1
"""
[[1, 2], [2, 3], [3, 4]]
[[1, 2], [2, 3], [3, 4]]
"""