ASKSAGE: Sage Q&A Forum - RSS feedhttps://ask.sagemath.org/questions/Q&A Forum for SageenCopyright Sage, 2010. Some rights reserved under creative commons license.Mon, 16 Apr 2018 19:55:51 +0200Subset functionhttps://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.Mon, 16 Apr 2018 01:46:21 +0200https://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>
https://ask.sagemath.org/question/42033/subset-function/?comment=42043#post-id-42043Welcome to Ask Sage! Thank you for your question!Mon, 16 Apr 2018 10:10:34 +0200https://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>
https://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 19:55:51 +0200https://ask.sagemath.org/question/42033/subset-function/?answer=42050#post-id-42050