Message Boards Message Boards

0
|
2409 Views
|
5 Replies
|
1 Total Likes
View groups...
Share
Share this post:

How to determine whether two sets are equal?

Posted 2 years ago

Based on the comments here and here, I find the following method to determine whether two sets are equal:

a = {1, 2, 3};
b = {1, 3, 2};
If[AllTrue[a, MemberQ[b, #] &] && AllTrue[b, MemberQ[a, #] &], 
 Print["a=b"], Print["a\[NotEqual]b"]]

a=b

But this method seems quite cumbersome. Are there any good suggestions?

Regards, HZ

POSTED BY: Hongyi Zhao
5 Replies

Union[a, b] == Intersection[a, b]

POSTED BY: Robert Nowak
Posted 2 years ago

Thank you for your systematic, insightful and in-depth comments. I will supplement and explain in the future according to the actual situation.

POSTED BY: Hongyi Zhao
Posted 2 years ago

Yes, they all work:

a = {1, 2, 3};
b = {1, 3, 2};
If[AllTrue[a, MemberQ[b, #] &] && AllTrue[b, MemberQ[a, #] &], 
 Print["a=b"], Print["a\[NotEqual]b"]]
If[Sort[a] === Sort[b], Print["a=b"], Print["a\[NotEqual]b"]]

a=b

a=b

But, can we always ensure that these methods are absolutely equivalent?

POSTED BY: Hongyi Zhao

That would depend on internals of MemberQ in terms of how it determines equivalence. But you've posed a question that, as it stands, is not possible to answer. You have neglected to provide any details about the types of sets you will consider for such testing. Are they always symbols? Exact numbers? Real numbers, possibly with different precisions? Perhaps more importantly, do you consider multiplicitiy of elements as meaningful? If not, then Sort won't be the function to use, since for example {a,a,b}=!={a,b}.

POSTED BY: Daniel Lichtblau

Maybe Sort[a]===Sort[b].

POSTED BY: Daniel Lichtblau
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract