Question: How to turn this into a recursive method?(Python) In general, to find the k-subsets of set S: Remove an arbitrary element x S. S is
How to turn this into a recursive method?(Python)
In general, to find the k-subsets of set S:
Remove an arbitrary element x S. S is now smaller by one element.
Consider the k-subsets that do contain x: find all (k 1)-subsets of S, and insert x into each of those subsets.
Consider the k-subsets that dont contain x: find all k-subsets of S.
Combine the k-subsets from above to get the answer.
def k_subsets_better(S,k): if k < 0 or k > len(S): return [] subsets = [[]] for i in range(1, len(S) + 1): subsets = power_set(S)
k_subsets = [] for i in subsets: if len(i) == k: k_subsets.append(i)
return k_subsets
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
