Bioinformatics/Biological data analysis
[python] universal set - computing subsets from a set (list)
옥탑방람보
2012. 12. 24. 17:28
def subsets(x):
if x == []:
return [[]]
else:
s = [x]
for elem in x:
tmp = x[:]
tmp.remove(elem)
new_sub = subsets(tmp)
for y in new_sub: # <-- can't just make it a set(), because lists aren't hashable.
if y not in s:
s.append(y)
return s
>>> s = [1,2,3]
>>> subsets(s)
[[1, 2, 3], [2, 3], [3], [], [2], [1, 3], [1], [1, 2]]
if x == []:
return [[]]
else:
s = [x]
for elem in x:
tmp = x[:]
tmp.remove(elem)
new_sub = subsets(tmp)
for y in new_sub: # <-- can't just make it a set(), because lists aren't hashable.
if y not in s:
s.append(y)
return s
>>> s = [1,2,3]
>>> subsets(s)
[[1, 2, 3], [2, 3], [3], [], [2], [1, 3], [1], [1, 2]]
from http://www.daniweb.com/forums/thread89048.html