Ask Your Question

Subset function

asked 2018-04-15 18:46:21 -0500

amadeo_ gravatar image

updated 2018-04-16 03:09:42 -0500

slelievre gravatar image

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)


    return TheSubsets

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

edit retag flag offensive close merge delete


Welcome to Ask Sage! Thank you for your question!

slelievre gravatar imageslelievre ( 2018-04-16 03:10:34 -0500 )edit

1 answer

Sort by ยป oldest newest most voted

answered 2018-04-16 12:55:51 -0500

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}]
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools


Asked: 2018-04-15 18:46:21 -0500

Seen: 51 times

Last updated: Apr 16