Home > Blockchain >  Why the added list is empty? [duplicate]
Why the added list is empty? [duplicate]

Time:09-21

I am using python3.9.7 on linux and I met a strange error today when i am doing my algorithm permutations.The error is that the added list is empty.
To be more specific,here is the code:

class Solution:
    def permute(self, nums):
        def backtrace(nums, tmpResult, level):
            if nums == []:
                print(f"{level}: {tmpResult}")
                res.append(tmpResult)
                return
            for i, v in enumerate(nums):
                tmpResult.append(v)
                level  = 1
                backtrace(nums[:i]   nums[i   1 :], tmpResult, level)
                level -= 1
                tmpResult.pop()

        res = []
        tmpResult = []
        backtrace(nums, tmpResult, 1)
        print(res)


if __name__ == "__main__":
    Solution().permute([1, 2, 3])

and the result:

4: [1, 2, 3]
4: [1, 3, 2]
4: [2, 1, 3]
4: [2, 3, 1]
4: [3, 1, 2]
4: [3, 2, 1]
[[], [], [], [], [], []]

and if I change the line 6 to res.append(repr(tmpResult)),the result is:

4: [1, 2, 3]
4: [1, 3, 2]
4: [2, 1, 3]
4: [2, 3, 1]
4: [3, 1, 2]
4: [3, 2, 1]
['[1, 2, 3]', '[1, 3, 2]', '[2, 1, 3]', '[2, 3, 1]', '[3, 1, 2]', '[3, 2, 1]']

Could someone tell me why it happens?

CodePudding user response:

You are adding a reference to the tmpResult list to res. tmpResult ends up as an empty list, so the final result shows you a list of 6 of those empty lists. You should append a copy of the list instead: https://stackoverflow.com/a/2612815/12123296

Line 6 should be something like res.append(tmpResult.copy()).

CodePudding user response:

Because if you copy à list and change the original list after the copy will change as well: List changes unexpectedly after assignment. Why is this and how can I prevent it?

To avoid it you can replace res.append(tmpResult)

By res.append(tmpResult.copy()) Or by res.append([x for x in tmpResult] )

  • Related