0

I'm trying to solve a coding challenge in python, but values seem to be changing without me appending them.

Expected behavior:

Input: nums = [1,2,2]

Output: [[],[1],[1,2],[1,2,2],[2],[2,2]]

class Solution:
def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:
    possibleSets = [[]]
    for i in range(len(nums)):
        newSet = []
        newSet.append(nums[i])
        if newSet not in possibleSets:
                possibleSets.append(newSet)
                print('possibleSets 1====>', possibleSets)
        for j in range(len(nums)-1):
            newSet.append(nums[j+1])
            print('newSet====>', newSet)
            print('possibleSets 2====>', possibleSets)
            if newSet not in possibleSets:
                possibleSets.append(newSet)
    return possibleSets  

Prints:

possibleSets 1====> [[], [1]]
newSet====> [1, 2]
possibleSets 2====> [[], [1, 2]]
newSet====> [1, 2, 2]
possibleSets 2====> [[], [1, 2, 2]]
possibleSets 1====> [[], [1, 2, 2], [2]]
newSet====> [2, 2]
possibleSets 2====> [[], [1, 2, 2], [2, 2]]
newSet====> [2, 2, 2]
possibleSets 2====> [[], [1, 2, 2], [2, 2, 2]]
possibleSets 1====> [[], [1, 2, 2], [2, 2, 2], [2]]
newSet====> [2, 2]
possibleSets 2====> [[], [1, 2, 2], [2, 2, 2], [2, 2]]
newSet====> [2, 2, 2]
possibleSets 2====> [[], [1, 2, 2], [2, 2, 2], [2, 2, 2]]

Somehow, between the first and second prints the value of 'possibleSets' is being changed, with the appended value before print 1 being overwritten with by newSet.append(nums[j+1]). This causes the final if-statement to never get executed. Is there something I'm missing?

  • 1
    Assigning a list object or adding it to another list **does not create a copy** of that list. – deceze Aug 05 '21 at 18:13

0 Answers0