First time here? Check out the FAQ!

Ask Your Question
2

Subset function

asked 7 years ago

amadeo_ gravatar image

updated 7 years ago

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)
        newSubset.append(L[0])

        TheSubsets.append(newSubset)

    return TheSubsets

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

Preview: (hide)

Comments

Welcome to Ask Sage! Thank you for your question!

slelievre gravatar imageslelievre ( 7 years ago )

1 Answer

Sort by » oldest newest most voted
1

answered 7 years ago

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}]
Preview: (hide)
link

Your Answer

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

Add Answer

Question Tools

Stats

Asked: 7 years ago

Seen: 392 times

Last updated: Apr 16 '18