I have the task to print all subsets of given length, I have created the functions to print out the all the subsets. Everything works fine the subsets are generated, but the output is wrong for each call. For example if I call print(get_subsets([1,2,3],2)) the output is [1,2] [1,3] [2,3] and [3]. Of course 3 is not supposed to be there and I can't figure out why. Any help will be appreciated and feedback of course.
def get_subsets(nums, k):
all_subsets = []
_gen_subsets(nums =nums,curr_idx =0,curr_subset=[],
all_subsets=all_subsets)
for curr_subset in all_subsets:
if len(curr_subset) > k or len(curr_subset) < k:
all_subsets.remove(curr_subset)
return all_subsets
def _gen_subsets(nums,curr_idx, curr_subset, all_subsets):
if curr_idx >= len(nums):
all_subsets.append(curr_subset)
else:
itr_subset = curr_subset.copy()
itr_subset.append(nums[curr_idx])
_gen_subsets(nums=nums,
curr_idx=curr_idx+1,
curr_subset=itr_subset,
all_subsets=all_subsets)
_gen_subsets(nums=nums,
curr_idx=curr_idx+1,
curr_subset=curr_subset,
all_subsets=all_subsets)
question from:
https://stackoverflow.com/questions/65932650/printing-all-subsets-with-only-a-given-length-in-python 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…