python实现返回集合的所有子集
返回集合的所有子集
代码很简单,不过想法特别好,在学习python的过程中看见了,于是就把他记录下来。
算法是利用递归的思想来实现返回集合的所有子集(如果想要对子集长度进行限制,参数加个limit就行了)
def allSubsets(s):
if len(s) == 0 :
return [[]]
return allSubsets(s[1:]) + [[s[0]] + r for r in allSubsets(s[1:])]
s=(1,4,5)
x=allSubsets(s)
print(x)
#测试结果:
[[], [5], [4], [4, 5], [1], [1, 5], [1, 4], [1, 4, 5]]
my homepage
ps:过河问题
Don't aim for success if you really want it.Just stick to what you love and believe in.And it will come naturally.