6
$\begingroup$

I have the following list

set1={-(1/x), -(1/x) + x/2 - 2 Log[x] - Log[x]/x, 1}

How when I am doing

Complement[set1, {-1/x}]

Then it gives

{1, -(1/x) + x/2 - 2 Log[x] - Log[x]/x}

then it rearranges the third element to the second element and vice versa. This is dangerous for my case. How to stop this?

$\endgroup$
1
  • 1
    $\begingroup$ Complement, Union, Intersection treat the list as a set. Hence duplicates are deleted and a sort is performed. $\endgroup$
    – Syed
    Commented Nov 9, 2023 at 9:48

8 Answers 8

10
$\begingroup$

You can use DeleteElements which came with V 13.1:

set1 = {-(1/x), -(1/x) + x/2 - 2 Log[x] - Log[x]/x, 1}

DeleteElements[set1, {-1/x}]

enter image description here

Versions prior to 13.1 could use f.e.

Delete[set1, Position[set1, -1/x, 1]]

or (since V 12.1)

SubsetReplace[set1, {-1/x} -> Nothing]

Both give the expected result:

enter image description here

$\endgroup$
7
$\begingroup$
UniqueElements[{set1,{ -1/x}}][[1]]

(* {-x^(-1)+x/2-2*Log[x]-Log[x]/x,1} *)
$\endgroup$
6
$\begingroup$
set1 = {-1/x, -1/x + x/2 - 2 Log[x] - Log[x]/x, 1};

Fold[DeleteCases, set1, {-1/x}]
(*    {-1/x + x/2 - 2 Log[x] - Log[x]/x, 1}    *)
$\endgroup$
4
$\begingroup$

If I understand correctly, this is what you need

set1 = {-(1/x), -(1/x) + x/2 - 2 Log[x] - Log[x]/x, 1}
SortBy[Complement[set1, {-1/x}], Position[set1, #] &]
$\endgroup$
0
4
$\begingroup$

Instead of applying "Complement" to the whole list set1, you may apply it to the single elements of set1 like:

set1 = {-(1/x), -(1/x) + x/2 - 2 Log[x] - Log[x]/x, 1};
Complement[{#}, {-1/x}] & /@ set1 // Flatten

{-(1/x) + x/2 - 2 Log[x] - Log[x]/x, 1}
$\endgroup$
4
$\begingroup$

or use filter, in Mathematica it's Select

{-(1/x), -(1/x) + x/2 - 2 Log[x] - Log[x]/x, 1} //
Select[# =!= -1/x&]
$\endgroup$
3
$\begingroup$
set1 = {-1/x, -1/x + x/2 - 2  Log[x] - Log[x]/x, 1};

Using DeleteCases with a condition, as follows:

DeleteCases[set1, s_ /; MatchQ[s, -1/x]]

{-(1/x) + x/2 - 2 Log[x] - Log[x]/x, 1}

$\endgroup$
2
$\begingroup$
set1 = {-(1/x), -(1/x) + x/2 - 2 Log[x] - Log[x]/x, 1};

Using UnsortedComplement by George Beck

UnsortedComplement = ResourceFunction["UnsortedComplement"];

UnsortedComplement[set1, {-1/x}]

enter image description here

$\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.