# Subset function

I am new to Sage and trying to define a recursive function that returns the subsets for a given set. I get some sort of memory error for even the smallest sets and I don't know why:

def MySubsets(L):
if L == []:
return [[]]

TheSubsets = MySubsets(L[1:len(L)])

for subset in TheSubsets:
newSubset = copy(subset)
newSubset.append(L[0])

TheSubsets.append(newSubset)

return TheSubsets


...and while MySubsets([]) works, MySubsets([1]) already yields a memory error.

edit retag close merge delete

( 2018-04-16 10:10:34 +0100 )edit

Sort by ยป oldest newest most voted

The problem is that you are looping over the list TheSubset, but your for loop is modifying TheSubset, making it larger, so the loop never ends. If you use instead for subset in copy(TheSubsets):, I think it will work.

Another option, in case you care about sets rather than lists:

sage: S = Set([1,2,3])
sage: S.subsets()
Subsets of {1, 2, 3}
sage: list(S.subsets())
[{}, {1}, {2}, {3}, {1, 2}, {1, 3}, {2, 3}, {1, 2, 3}]

more