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?