Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
178 views
in Technique[技术] by (71.8m points)

recursion - Printing all subsets with only a given length in python

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You are trying to iterate through a list from which you are also removing elements. This messed up the position and index of the list of subsets and gave you the wrong output.

Change the function get_subsets to this:

def get_subsets(nums, k):
    all_subsets = []

    _gen_subsets(nums =nums,curr_idx =0,curr_subset=[],
           all_subsets=all_subsets)

    final_subset = all_subsets.copy()
    for n in all_subsets:
        if len(n) != k:
            final_subset.remove(n)

    return final_subset

Or this:

def get_subsets(nums, k):
    all_subsets = []

    _gen_subsets(nums =nums,curr_idx =0,curr_subset=[],
           all_subsets=all_subsets)

    all_subsets = [n for n in all_subsets if len(n) == k]

    return all_subsets

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...