I am writing a program in Python, and I realized that a problem I need to solve requires me, given a set S
with n
elements (|S|=n), to test a function on all possible subsets of a certain order m
(i.e. with m number of elements). To use the answer to produce a partial solution, and then try again with the next order m=m+1, until m=n.
I am on my way to write a solution of the form:
def findsubsets(S, m): subsets = set([]) ... return subsets
But knowing Python I expected a solution to be already there.
What is the best way to accomplish this?
Discovered a rule for determining the total number of subsets for a given set: A set with n elements has 2 n subsets.
A set of n elements has (n2) subsets of 2 elements, where (n2) is the binomial coefficient n choose 2.
If a set contains n elements, then the number of subsets of this set is equal to 2ⁿ - 1 . The only subset which is not proper is the set itself. So, to get the number of proper subsets, you just need to subtract one from the total number of subsets.
itertools.combinations is your friend if you have Python 2.6 or greater. Otherwise, check the link for an implementation of an equivalent function.
import itertools def findsubsets(S,m): return set(itertools.combinations(S, m))
S: The set for which you want to find subsets
m: The number of elements in the subset
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With