Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I find all the subsets of a set, with exactly n elements?

Tags:

python

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?

like image 363
Pietro Speroni Avatar asked Dec 17 '08 14:12

Pietro Speroni


People also ask

How many subsets a set with n elements has?

Discovered a rule for determining the total number of subsets for a given set: A set with n elements has 2 n subsets.

What is the subset of n element set?

A set of n elements has (n2) subsets of 2 elements, where (n2) is the binomial coefficient n choose 2.

How do you calculate all subsets?

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.


1 Answers

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

like image 137
recursive Avatar answered Oct 19 '22 18:10

recursive