ASKSAGE: Sage Q&A Forum - Individual question feedhttp://ask.sagemath.org/questions/Q&A Forum for SageenCopyright Sage, 2010. Some rights reserved under creative commons license.Mon, 16 Apr 2018 12:55:51 -0500Subset functionhttp://ask.sagemath.org/question/42033/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.Sun, 15 Apr 2018 18:46:21 -0500http://ask.sagemath.org/question/42033/subset-function/Comment by slelievre for <p>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:</p>
<pre><code>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
</code></pre>
<p>...and while MySubsets([]) works, MySubsets([1]) already yields a memory error.</p>
http://ask.sagemath.org/question/42033/subset-function/?comment=42043#post-id-42043Welcome to Ask Sage! Thank you for your question!Mon, 16 Apr 2018 03:10:34 -0500http://ask.sagemath.org/question/42033/subset-function/?comment=42043#post-id-42043Answer by John Palmieri for <p>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:</p>
<pre><code>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
</code></pre>
<p>...and while MySubsets([]) works, MySubsets([1]) already yields a memory error.</p>
http://ask.sagemath.org/question/42033/subset-function/?answer=42050#post-id-42050The 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}]
Mon, 16 Apr 2018 12:55:51 -0500http://ask.sagemath.org/question/42033/subset-function/?answer=42050#post-id-42050