4
$\begingroup$

I have two subsets and tried this expression with MapThread:

TT := {{{P1}, {P2, P3}}}
XX := {P1, P2, P3, P4}

MapThread[Complement, {{Flatten[XX]}, {Flatten[TT]}}, 1]

{{P4}}

I need the partial sets' complements so that the outcome would be {{P2,P3,P4},{P1,P4}}

$\endgroup$
1
  • $\begingroup$ Please add links to/from Wolfram Community cross-post. That way readers can see all prior responses and avoid duplication. $\endgroup$ Jan 6 at 17:12

3 Answers 3

4
$\begingroup$

You have too many braces in TTt. Note also, you should not use uppercase names, because these are used by the system.

Here is working code:

t = {{P1}, {P2, P3}};
 x = {P1, P2, P3, P4};
Complement[x, #] & /@ t

{{P2, P3, P4}, {P1, P4}}
$\endgroup$
0
4
$\begingroup$

We could also use DeleteElements (new in 13.1)

a = {{P1}, {P2, P3}};
b = {P1, P2, P3, P4};

DeleteElements[b, #] & /@ a

{P2, P3, P4}, {P1, P4, P1}}

Unlike Complement, DeleteElements doesn't sort its output

a = {{P3}, {P2, P1}};
b = {P4, P3, P2, P1};

DeleteElements[b, #] & /@ a

{{P4, P2, P1}, {P4, P3}}

Complement[b, #] & /@ a

{{P1, P2, P4}, {P3, P4}}

Unlike Complement, DeleteElements doesn't automatically delete duplicates. Therefore we must apply DeleteDuplicates to b

a = {{P3}, {P2, P1}};
b = {P4, P3, P2, P1, P1};

DeleteElements[DeleteDuplicates @ b, #] & /@ a

{{P4, P2, P1}, {P4, P3}}

It should also be noted, that DeleteElements is much slower than Complement. But it is useful if we have short lists and want to preserve the original sort order.

$\endgroup$
1
$\begingroup$

Another way to preserve the original order is to use DeleteCases and Alternatives as follows:

a = {{P3}, {P2, P1}};
b = {P4, P3, P2, P1};

DeleteCases[b, Alternatives @@ #] & /@ a

(*{{P4, P2, P1}, {P4, P3}}*)
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.