我怎样才能找到一个集合的所有子集,正好有 n 个元素? [英] How can I find all the subsets of a set, with exactly n elements?

查看:51
本文介绍了我怎样才能找到一个集合的所有子集,正好有 n 个元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用 Python 编写一个程序,我意识到我需要解决的一个问题需要我,给定一组 Sn 元素 (|S|=n),在特定顺序m(即具有m 个元素)的所有可能子集上测试函数.使用答案产生部分解,然后用下一个顺序重试 m=m+1,直到 m=n.

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

但了解 Python 后,我希望已经有解决方案.

But knowing Python I expected a solution to be already there.

实现这一目标的最佳方法是什么?

What is the best way to accomplish this?

推荐答案

itertools.如果您有 Python 2.6 或更高版本,组合 是您的朋友.否则,请检查等效函数实现的链接.

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:要查找子集的集合
m:子集中元素的个数

S: The set for which you want to find subsets
m: The number of elements in the subset

这篇关于我怎样才能找到一个集合的所有子集,正好有 n 个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆