Ask Your Question
2

Append Set to Set

asked 2022-04-12 17:29:02 +0100

Thrash gravatar image

Consider the sets a={1} and b={2}. As output I want {1,{2}}. I tried

sage: a={1};b={2}
sage: a.add(b)

and

sage: a.union({b})

but both attempts result in an error:

TypeError: unhashable type: 'set'
edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2022-04-12 17:44:17 +0100

rburing gravatar image

updated 2022-04-12 17:52:32 +0100

To circumvent this problem the frozenset (which can't be modified after creation) was invented:

sage: a.add(frozenset(b))
sage: a
{1, frozenset({2})}

Another alternative is to use Sage's Set:

sage: a=Set([1])
sage: b=Set([2])
sage: a.union(Set([b]))
{1, {2}}
edit flag offensive delete link more

Comments

1

How can I remove frozenset in the output?

Thrash gravatar imageThrash ( 2022-04-12 17:46:41 +0100 )edit

You can't really, unless you make a custom type, or call a custom printing function. I offer SageMath's Set as an alternative.

rburing gravatar imagerburing ( 2022-04-12 17:54:11 +0100 )edit
1

SageMath's Set is the solution for me, thank you! I didn't know about these two different functions (set and Set) and thought there was only one.

Thrash gravatar imageThrash ( 2022-04-12 18:00:23 +0100 )edit

Your Answer

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

Add Answer

Question Tools

1 follower

Stats

Asked: 2022-04-12 17:29:02 +0100

Seen: 227 times

Last updated: Apr 12 '22