gpt4 book ai didi

python类属性更新问题

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:53:53 25 4
gpt4 key购买 nike

我编写了一个小程序来打印出数组的所有排列 - 假设输入是 [1,2,3]。我正在使用回溯来生成解决方案。

我的问题是我可以看到结果已更新为所需值(基于打印类属性 result 的日志)但未返回。实际上返回的答案是 [[],[],[],[],[],[]] – 这是我不明白的。

class Solution:
def __init__(self):
self.result = []
def permute(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
c = self.permuteHelper(nums, [])
print("finally, result:", self.result)
return self.result

def permuteHelper(self, nums, chosen):
print("permuteHelper: nums", nums, "chosen:", chosen)
if len(nums) == 0:
print("returning:", chosen)
self.result.append(chosen)
print("result:", self.result)
return self.result
index = 0
for n in nums:
nums.pop(index)
chosen.append(n)

c = self.permuteHelper(nums, chosen)

nums.insert(index, n)
chosen.remove(n)
index+=1

这是我得到的输出:

permuteHelper: nums [1, 2, 3] chosen: []
permuteHelper: nums [2, 3] chosen: [1]
permuteHelper: nums [3] chosen: [1, 2]
permuteHelper: nums [] chosen: [1, 2, 3]
returning: [1, 2, 3]
result: [[1, 2, 3]]
permuteHelper: nums [2] chosen: [1, 3]
permuteHelper: nums [] chosen: [1, 3, 2]
returning: [1, 3, 2]
result: [[1, 3, 2], [1, 3, 2]]
permuteHelper: nums [1, 3] chosen: [2]
permuteHelper: nums [3] chosen: [2, 1]
permuteHelper: nums [] chosen: [2, 1, 3]
returning: [2, 1, 3]
result: [[2, 1, 3], [2, 1, 3], [2, 1, 3]]
permuteHelper: nums [1] chosen: [2, 3]
permuteHelper: nums [] chosen: [2, 3, 1]
returning: [2, 3, 1]
result: [[2, 3, 1], [2, 3, 1], [2, 3, 1], [2, 3, 1]]
permuteHelper: nums [1, 2] chosen: [3]
permuteHelper: nums [2] chosen: [3, 1]
permuteHelper: nums [] chosen: [3, 1, 2]
returning: [3, 1, 2]
result: [[3, 1, 2], [3, 1, 2], [3, 1, 2], [3, 1, 2], [3, 1, 2]]
permuteHelper: nums [1] chosen: [3, 2]
permuteHelper: nums [] chosen: [3, 2, 1]
returning: [3, 2, 1]
result: [[3, 2, 1], [3, 2, 1], [3, 2, 1], [3, 2, 1], [3, 2, 1], [3, 2, 1]]
finally, result: [[], [], [], [], [], []]

最佳答案

最简单的修复方法(添加复制):

def permuteHelper(self, nums, chosen):
print("permuteHelper: nums", nums, "chosen:", chosen)
if len(nums) == 0:
print("returning:", chosen)
self.result.append(copy.copy(chosen)) # note!
print("result:", self.result)
return self.result
index = 0
for n in nums:
nums.pop(index)
chosen.append(n)

c = self.permuteHelper(nums, chosen)
nums.insert(index, n)
chosen.remove(n)
print("see what happen in here:", self.result) # error happens here
index += 1

此链接可能有帮助: How do I pass a variable by reference?

关于python类属性更新问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51759995/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com