gpt4 book ai didi

python递归是按引用传递还是按值传递?

转载 作者:搜寻专家 更新时间:2023-10-31 00:56:29 25 4
gpt4 key购买 nike

我正在 leetcode 上解决这个问题:

Given a set of distinct integers, nums, return all possible subsets.
input =[1,2,3]
output =[[],[3],[2],[2,3],[1],[1,3],[1,2],[1,2,3]]

我有被接受的 c++ 解决方案,然后我编写了完全相同的 python 解决方案。

class Solution(object):    
def subsets(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
solutions = []
self._get_subset(nums, 0, [], solutions)

return solutions

@staticmethod
def _get_subset(nums, curr, path, solutions):
if curr>= len(nums):
solutions.append(path)
return

path.append(nums[curr])
Solution._get_subset(nums, curr+1, path, solutions)

path.pop()
Solution._get_subset(nums, curr+1, path, solutions)

现在的输出是: [[],[],[],[],[],[],[],[]]

似乎是 Python 的引用传递/值传递导致了这个问题,但我不知道是怎么回事。相同的 C++ 代码工作正常:

class Solution {
public:
vector<vector<int>> subsets(vector<int>& nums) {
vector<vector<int>> solutions;
vector<int> path;

_get_path(nums, 0, path, solutions);
return solutions;
}

void _get_path(vector<int>& nums,
int curr,
vector<int>& path,
vector< vector<int> > &solutions)
{
if(curr >= nums.size()){
solutions.push_back(path);
return;
}
path.push_back(nums[curr]);
_get_path(nums, curr+1, path, solutions);

path.pop_back();
_get_path(nums, curr+1, path, solutions);
}
};

最佳答案

问题出在这里:

solutions.append(path)

在 C++ 中,vector::push_back 复制了 path(内部)。但在 Python 中,一切都是引用。因此,您将 solutions 构建为对同一 path 的许多引用的列表,最终会减少为空。

你想要一份拷贝:

solutions.append(list(path))

或:

solutions.append(path[:])

关于python递归是按引用传递还是按值传递?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39480782/

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