Python passes the lists as a reference to a function. is the behavior any different when calling class function using self pointer? Why the finalResultList is not printing all the values and only empty brackets. Is it something to do with recursion?
Code:
class Solution:
def getAllPermutations(self,nums,index,resultList,finalResultList):
if(index == len(nums)):
finalResultList.append(resultList)
print(finalResultList)
return
for i in range(len(nums)):
if nums[i] not in resultList:
resultList.append(nums[i])
self.getAllPermutations(nums,index 1,resultList,finalResultList)
if(len(resultList) != 0):
resultList.pop(-1)
def permute(self, nums: List[int]) -> List[List[int]]:
resultList = []
finalResultList = []
self.getAllPermutations(nums,0,resultList,finalResultList)
print(finalResultList )
Output :
[[1, 2, 3]]
[[1, 3, 2], [1, 3, 2]]
[[2, 1, 3], [2, 1, 3], [2, 1, 3]]
[[2, 3, 1], [2, 3, 1], [2, 3, 1], [2, 3, 1]]
[[3, 1, 2], [3, 1, 2], [3, 1, 2], [3, 1, 2], [3, 1, 2]]
[[3, 2, 1], [3, 2, 1], [3, 2, 1], [3, 2, 1], [3, 2, 1], [3, 2, 1]]
[[], [], [], [], [], []]
CodePudding user response:
No, the behaviour is the same. When you append the resultList
to your finalResultList
, you're appending the same list each time, and that list still gets changed while your code is running. As you mentioned yourself, you have the same pointer/reference to the resultList
all the way through the code, including what you add to your finalResultList
.
finalResultList.append(resultList)
This part just adds the same list (resultList
) x number of times to the finalResultList, and you keep changing this list.
If you want to add a copy of the list that doesn't get changed, create a new list when adding it to your finalResultList:
finalResultList.append(list(resultList))
.. or use the copy
module to create a copy:
finalResultList.append(copy.copy(resultList))
.. or if the resultList list had been a deep list (i.e. having internal references to other lists as well):
finalResultList.append(copy.deepcopy(resultList))
CodePudding user response:
Instead of appending the resultList list as an object to finalResultList:
finalResultList.append(resultList)
add the resultList object as list:
finalResultList.append(list(resultList))